From b3278048fa76f22ed748d467da515d08c33aa7d3 Mon Sep 17 00:00:00 2001 From: Oliver Mee <102673257+oliver-mee@users.noreply.github.com> Date: Sun, 1 Nov 2026 22:28:42 +0800 Subject: [PATCH 1/5] feat(opencode): add read-only diagnostics and intentional commit controls (cherry picked from commit c2b8db25db4aaeb21f6ee7eb19eb163efb7ef9dd) --- agent-plugins/servers/shared/ov-http.mjs | 8 +- .../hosts/codebuddy/plugin.json | 2 +- .../hosts/cursor/openviking.integration.json | 2 +- .../hosts/kimicode/kimi.plugin.json | 2 +- .../kimicode/openviking.integration.json | 2 +- .../agent-hook-plugin/hosts/qoder/plugin.json | 2 +- .../hosts/trae/openviking.integration.json | 2 +- .../hosts/zcode/openviking.integration.json | 2 +- examples/agent-hook-plugin/plugin.json | 2 +- .../.claude-plugin/plugin.json | 2 +- .../claude-code-memory-plugin/package.json | 2 +- .../scripts/shared/doctor-core.mjs | 4 +- .../scripts/shared/ov-http.mjs | 8 +- .../scripts/shared/pending-queue.mjs | 32 +++++ .../scripts/shared/plugin-config.mjs | 13 ++- .../.codex-plugin/plugin.json | 2 +- .../scripts/shared/doctor-core.mjs | 4 +- .../scripts/shared/ov-http.mjs | 8 +- .../scripts/shared/pending-queue.mjs | 32 +++++ .../scripts/shared/plugin-config.mjs | 13 ++- examples/dsh-memory-plugin/package-lock.json | 4 +- examples/dsh-memory-plugin/package.json | 2 +- examples/magpie-memory-plugin/package.json | 2 +- .../memory-plugin-shared/lib/doctor-core.mjs | 4 +- examples/memory-plugin-shared/lib/ov-http.mjs | 8 +- .../lib/pending-queue.mjs | 32 +++++ .../lib/plugin-config.mjs | 13 ++- .../plugin-config.test.mjs | 23 +++- examples/opencode-plugin/README.md | 35 ++++++ examples/opencode-plugin/lib/config.mjs | 3 +- examples/opencode-plugin/lib/diagnostics.mjs | 109 ++++++++++++++++++ .../opencode-plugin/lib/memory-session.mjs | 57 +++++++-- examples/opencode-plugin/lib/v2-controls.mjs | 48 ++++++++ examples/opencode-plugin/lib/v2-plugin.mjs | 16 ++- examples/opencode-plugin/package.json | 4 +- .../scripts/ov-memory-doctor.mjs | 11 ++ .../tests/diagnostics.test.mjs | 109 ++++++++++++++++++ .../tests/memory-session.test.mjs | 67 +++++++++++ .../package-lock.json | 4 +- .../pi-coding-agent-extension/package.json | 2 +- 40 files changed, 633 insertions(+), 64 deletions(-) create mode 100644 examples/opencode-plugin/lib/diagnostics.mjs create mode 100644 examples/opencode-plugin/lib/v2-controls.mjs create mode 100644 examples/opencode-plugin/scripts/ov-memory-doctor.mjs create mode 100644 examples/opencode-plugin/tests/diagnostics.test.mjs diff --git a/agent-plugins/servers/shared/ov-http.mjs b/agent-plugins/servers/shared/ov-http.mjs index f1bc32d2d91..f5c691a1428 100644 --- a/agent-plugins/servers/shared/ov-http.mjs +++ b/agent-plugins/servers/shared/ov-http.mjs @@ -70,6 +70,9 @@ export function createOvHttp(cfg = {}, { return async function fetchJSON(path, init = {}, options = {}) { const timeoutMs = Math.max(MIN_TIMEOUT_MS, Number(options.timeoutMs) || Number(defaultTimeoutMs) || 0); const controller = new AbortController(); + const callerAbort = () => controller.abort(init.signal.reason); + if (init.signal?.aborted) callerAbort(); + else init.signal?.addEventListener("abort", callerAbort, { once: true }); let timedOut = false; const timer = setTimeout(() => { timedOut = true; @@ -123,14 +126,13 @@ export function createOvHttp(cfg = {}, { return { ok: true, status: response.status, result: body?.result ?? body ?? {}, traceId }; } catch (error) { const message = error?.message || String(error); - // This module owns the controller, so it says a timeout was a timeout - // rather than leaving callers to guess it from whatever fetch threw. - const failure = timedOut + const failure = timedOut || init.signal?.aborted ? { name: "AbortError", aborted: true, message } : { message }; return { ok: false, status: 0, result: null, error: failure }; } finally { clearTimeout(timer); + init.signal?.removeEventListener("abort", callerAbort); } }; } diff --git a/examples/agent-hook-plugin/hosts/codebuddy/plugin.json b/examples/agent-hook-plugin/hosts/codebuddy/plugin.json index 06aa27b7a6d..9061866cf2d 100644 --- a/examples/agent-hook-plugin/hosts/codebuddy/plugin.json +++ b/examples/agent-hook-plugin/hosts/codebuddy/plugin.json @@ -1,6 +1,6 @@ { "name": "openviking-memory", - "version": "0.5.34", + "version": "0.5.35", "description": "Long-term semantic memory for the CodeBuddy Code CLI, powered by OpenViking. Injects relevant context at session start and on each prompt, and captures the conversation back into OpenViking.", "author": { "name": "OpenViking", diff --git a/examples/agent-hook-plugin/hosts/cursor/openviking.integration.json b/examples/agent-hook-plugin/hosts/cursor/openviking.integration.json index e649048de66..b5e7b63074e 100644 --- a/examples/agent-hook-plugin/hosts/cursor/openviking.integration.json +++ b/examples/agent-hook-plugin/hosts/cursor/openviking.integration.json @@ -1,7 +1,7 @@ { "schemaVersion": 1, "id": "openviking-memory", - "version": "0.5.34", + "version": "0.5.35", "clients": [ "cursor" ], diff --git a/examples/agent-hook-plugin/hosts/kimicode/kimi.plugin.json b/examples/agent-hook-plugin/hosts/kimicode/kimi.plugin.json index f45badc20d3..54f71076c94 100644 --- a/examples/agent-hook-plugin/hosts/kimicode/kimi.plugin.json +++ b/examples/agent-hook-plugin/hosts/kimicode/kimi.plugin.json @@ -1,6 +1,6 @@ { "name": "openviking-memory", - "version": "0.5.34", + "version": "0.5.35", "description": "Long-term semantic memory for Kimi Code CLI, powered by OpenViking.", "author": { "name": "OpenViking", diff --git a/examples/agent-hook-plugin/hosts/kimicode/openviking.integration.json b/examples/agent-hook-plugin/hosts/kimicode/openviking.integration.json index e00590f9e5b..457c56f7fd8 100644 --- a/examples/agent-hook-plugin/hosts/kimicode/openviking.integration.json +++ b/examples/agent-hook-plugin/hosts/kimicode/openviking.integration.json @@ -1,7 +1,7 @@ { "schemaVersion": 1, "id": "openviking-memory", - "version": "0.5.34", + "version": "0.5.35", "clients": [ "kimicode" ], diff --git a/examples/agent-hook-plugin/hosts/qoder/plugin.json b/examples/agent-hook-plugin/hosts/qoder/plugin.json index 53fa7f4a0f1..537097780f9 100644 --- a/examples/agent-hook-plugin/hosts/qoder/plugin.json +++ b/examples/agent-hook-plugin/hosts/qoder/plugin.json @@ -1,6 +1,6 @@ { "name": "openviking-memory", - "version": "0.5.34", + "version": "0.5.35", "description": "Long-term semantic memory for the Qoder CLI, powered by OpenViking. Injects relevant context at session start and on each prompt, and captures the conversation back into OpenViking.", "author": { "name": "OpenViking", diff --git a/examples/agent-hook-plugin/hosts/trae/openviking.integration.json b/examples/agent-hook-plugin/hosts/trae/openviking.integration.json index a109fea2ebf..e4602d62ee1 100644 --- a/examples/agent-hook-plugin/hosts/trae/openviking.integration.json +++ b/examples/agent-hook-plugin/hosts/trae/openviking.integration.json @@ -1,7 +1,7 @@ { "schemaVersion": 1, "id": "openviking-memory", - "version": "0.5.34", + "version": "0.5.35", "clients": [ "trae", "trae-cn" diff --git a/examples/agent-hook-plugin/hosts/zcode/openviking.integration.json b/examples/agent-hook-plugin/hosts/zcode/openviking.integration.json index 437dd1240f7..019b972d33e 100644 --- a/examples/agent-hook-plugin/hosts/zcode/openviking.integration.json +++ b/examples/agent-hook-plugin/hosts/zcode/openviking.integration.json @@ -1,7 +1,7 @@ { "schemaVersion": 1, "id": "openviking-memory", - "version": "0.5.34", + "version": "0.5.35", "clients": [ "zcode" ], diff --git a/examples/agent-hook-plugin/plugin.json b/examples/agent-hook-plugin/plugin.json index 02166a71fbc..33ec273bbb3 100644 --- a/examples/agent-hook-plugin/plugin.json +++ b/examples/agent-hook-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "agent-hook-plugin", - "version": "0.5.34", + "version": "0.5.35", "description": "Long-term semantic memory for Cursor, TRAE, TRAE CN, ZCode, Kimi Code, CodeBuddy Code, Qoder CLI and Antigravity — powered by OpenViking. Auto-recall relevant memories and capture the conversation as it happens.", "author": { "name": "OpenViking", diff --git a/examples/claude-code-memory-plugin/.claude-plugin/plugin.json b/examples/claude-code-memory-plugin/.claude-plugin/plugin.json index dd1c19afe70..d4b12d31580 100644 --- a/examples/claude-code-memory-plugin/.claude-plugin/plugin.json +++ b/examples/claude-code-memory-plugin/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "openviking-memory", - "version": "0.7.25", + "version": "0.7.26", "description": "Long-term semantic memory for Claude Code, powered by OpenViking. Auto-recall relevant memories at session start and capture important information during conversations.", "author": { "name": "OpenViking", diff --git a/examples/claude-code-memory-plugin/package.json b/examples/claude-code-memory-plugin/package.json index c19a689e349..8993ccf2378 100644 --- a/examples/claude-code-memory-plugin/package.json +++ b/examples/claude-code-memory-plugin/package.json @@ -1,6 +1,6 @@ { "name": "claude-code-openviking-memory", - "version": "0.7.25", + "version": "0.7.26", "description": "OpenViking memory plugin for Claude Code — semantic long-term memory", "type": "module", "scripts": { diff --git a/examples/claude-code-memory-plugin/scripts/shared/doctor-core.mjs b/examples/claude-code-memory-plugin/scripts/shared/doctor-core.mjs index f1278aff762..c5faf452a90 100644 --- a/examples/claude-code-memory-plugin/scripts/shared/doctor-core.mjs +++ b/examples/claude-code-memory-plugin/scripts/shared/doctor-core.mjs @@ -491,7 +491,7 @@ export async function httpProbe({ url, method = "GET", headers = {}, body, timeo // A connection record carries no `sendIdentityHeaders`: the doctor asks with // the identity and reports whatever the server echoes back. function authHeaders(conn, { identity = true } = {}) { - return buildOvHeaders(conn, { actorPeerId: conn.peerId, identityHeaders: identity }); + return buildOvHeaders(conn, { actorPeerId: conn.peerId, identityHeaders: identity, extraHeaders: conn.extraHeaders }); } export function serverErrorMessage(probe) { @@ -518,7 +518,7 @@ export async function probeOpenViking(conn, { timeoutMs = 5000, mcp = true } = { // Hard network failure: the rest of the ladder would fail identically. return out; } - if (conn.apiKey || conn.account || conn.user) { + if (conn.apiKey || conn.account || conn.user || Object.keys(conn.extraHeaders ?? {}).length) { out.healthAuth = await httpProbe({ url: `${base}/health`, timeoutMs, headers: authHeaders(conn) }); } out.systemStatus = await httpProbe({ url: `${base}/api/v1/system/status`, timeoutMs, headers: authHeaders(conn) }); diff --git a/examples/claude-code-memory-plugin/scripts/shared/ov-http.mjs b/examples/claude-code-memory-plugin/scripts/shared/ov-http.mjs index f1bc32d2d91..f5c691a1428 100644 --- a/examples/claude-code-memory-plugin/scripts/shared/ov-http.mjs +++ b/examples/claude-code-memory-plugin/scripts/shared/ov-http.mjs @@ -70,6 +70,9 @@ export function createOvHttp(cfg = {}, { return async function fetchJSON(path, init = {}, options = {}) { const timeoutMs = Math.max(MIN_TIMEOUT_MS, Number(options.timeoutMs) || Number(defaultTimeoutMs) || 0); const controller = new AbortController(); + const callerAbort = () => controller.abort(init.signal.reason); + if (init.signal?.aborted) callerAbort(); + else init.signal?.addEventListener("abort", callerAbort, { once: true }); let timedOut = false; const timer = setTimeout(() => { timedOut = true; @@ -123,14 +126,13 @@ export function createOvHttp(cfg = {}, { return { ok: true, status: response.status, result: body?.result ?? body ?? {}, traceId }; } catch (error) { const message = error?.message || String(error); - // This module owns the controller, so it says a timeout was a timeout - // rather than leaving callers to guess it from whatever fetch threw. - const failure = timedOut + const failure = timedOut || init.signal?.aborted ? { name: "AbortError", aborted: true, message } : { message }; return { ok: false, status: 0, result: null, error: failure }; } finally { clearTimeout(timer); + init.signal?.removeEventListener("abort", callerAbort); } }; } diff --git a/examples/claude-code-memory-plugin/scripts/shared/pending-queue.mjs b/examples/claude-code-memory-plugin/scripts/shared/pending-queue.mjs index e86f59b00ed..04d5fe4236d 100644 --- a/examples/claude-code-memory-plugin/scripts/shared/pending-queue.mjs +++ b/examples/claude-code-memory-plugin/scripts/shared/pending-queue.mjs @@ -230,6 +230,38 @@ export async function enqueue(type, sessionId, payload, options = {}) { return { ok: false, error: `pending file exists but dedup entry was not readable: ${filename}`, dedupKey }; } +/** True if this session has a queued or in-flight write. Never claim or replay it. */ +export async function hasPendingSessionWrites(sessionId) { + if (!sessionId) return false; + const dir = getPendingDir(); + let files; + try { + files = await readdir(dir); + } catch (error) { + if (error.code === "ENOENT") return false; + throw error; + } + for (const name of files) { + if (!/\.(json|processing)$/.test(name)) continue; + // A drainer may have just claimed a file from this listing. Inspect the + // claimed spelling too; if it was removed, the drainer finished it. + let entry; + try { + entry = await readEntry(dir, name); + } catch (error) { + if (error.code !== "ENOENT") throw error; + const counterpart = name.endsWith(".json") ? processingFilename(name) : pendingFromProcessingFilename(name); + try { + entry = await readEntry(dir, counterpart); + } catch (retryError) { + if (retryError.code !== "ENOENT") throw retryError; + } + } + if (entry?.sessionId === sessionId) return true; + } + return false; +} + /** * List all pending queue entries. * Returns array of { filename, entry } sorted by createdAt ascending. diff --git a/examples/claude-code-memory-plugin/scripts/shared/plugin-config.mjs b/examples/claude-code-memory-plugin/scripts/shared/plugin-config.mjs index f60c3bca8b5..69c72623c14 100644 --- a/examples/claude-code-memory-plugin/scripts/shared/plugin-config.mjs +++ b/examples/claude-code-memory-plugin/scripts/shared/plugin-config.mjs @@ -99,9 +99,9 @@ export function loadPluginSettings(harness, env = process.env, options = {}) { * callers still need to know a value came from ovcli.conf rather than ov.conf. */ export function resolveSettings(harness, options = {}) { - const { env = process.env, cwd = "", legacy = {}, clientVersion = "", cliFile = null } = options; + const { env = process.env, cwd = "", legacy = {}, clientVersion = "", cliFile = null, readOnly = false } = options; const key = harnessKey(harness); - const plugin = loadPluginSettings(key, env, { cwd, clientVersion, cliFile }); + const plugin = loadPluginSettings(key, env, { cwd, clientVersion, cliFile, readOnly }); const { settings, configured, sources } = resolveKnobs({ harness: key, layers: [ @@ -120,7 +120,7 @@ export function resolveSettings(harness, options = {}) { * level, before the payload on stdin has said which directory the session is * actually in — the caller resolves this again once it knows. */ -export function resolveWorkspaceSettings(cwd, env = process.env, { clientVersion = "" } = {}) { +export function resolveWorkspaceSettings(cwd, env = process.env, { clientVersion = "", readOnly = false } = {}) { const empty = { settings: {}, root: "", provenance: {}, warnings: [], announced: [] }; try { const { root } = findWorkspaceRoot(cwd, env); @@ -129,7 +129,7 @@ export function resolveWorkspaceSettings(cwd, env = process.env, { clientVersion const { layers, warnings } = loadWorkspaceLayers(root, { clientVersion }); // The identity is what makes the registry's negative evidence work: without // it a directory reused by a different repository inherits the old peer. - const identity = resolveWorkspaceIdentity({ cwd, env }); + const identity = resolveWorkspaceIdentity({ cwd, env, cache: !readOnly }); const registry = readEntry(root, { identity, env }); warnings.push(...registry.warnings); if (registry.entry?.settings) layers.push({ layer: "registry", data: registry.entry.settings }); @@ -197,6 +197,7 @@ export function buildPluginConfig(harness, { logFile = "", rootKeyFallback = false, deriveEffectivePeer = false, + readOnly = false, } = {}) { const name = String(harness || ""); const key = harnessKey(name); @@ -211,6 +212,7 @@ export function buildPluginConfig(harness, { legacy: legacy || ovConfSection(files.ovFile, key), cliFile: files.cliFile, clientVersion, + readOnly, }); const connection = resolveConnection(key, { env, files, hostInput, rootKeyFallback }); const { baseUrl, account, user } = connection; @@ -279,7 +281,8 @@ export function buildPluginConfig(harness, { // it per session, against the directory the payload names, and an MCP proxy // must not derive one from wherever it happened to be launched. if (deriveEffectivePeer) { - const effectivePeer = resolveEffectivePeerId({ cfg: config, cwd: workspaceCwd, env }); + const identity = readOnly ? resolveWorkspaceIdentity({ cwd: workspaceCwd, env, cache: false }) : null; + const effectivePeer = resolveEffectivePeerId({ cfg: config, cwd: workspaceCwd, env, identity }); config.effectivePeer = effectivePeer; config.legacyPeerId = effectivePeer.legacyPeerId; } diff --git a/examples/codex-memory-plugin/.codex-plugin/plugin.json b/examples/codex-memory-plugin/.codex-plugin/plugin.json index 7a35009a464..8a417956a07 100644 --- a/examples/codex-memory-plugin/.codex-plugin/plugin.json +++ b/examples/codex-memory-plugin/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "openviking-memory", - "version": "0.11.23", + "version": "0.11.24", "description": "Long-term semantic memory for Codex, powered by OpenViking. Recall on UserPromptSubmit, incremental add_message on Stop (per turn), commit on SessionEnd (Codex >= 0.145) and on PreCompact, with an idle/ended sweep on SessionStart as the fallback for signals, crashes and older Codex builds. Includes a local stdio MCP proxy that reads OpenViking credentials from env/ovcli.conf.", "author": { "name": "OpenViking", diff --git a/examples/codex-memory-plugin/scripts/shared/doctor-core.mjs b/examples/codex-memory-plugin/scripts/shared/doctor-core.mjs index f1278aff762..c5faf452a90 100644 --- a/examples/codex-memory-plugin/scripts/shared/doctor-core.mjs +++ b/examples/codex-memory-plugin/scripts/shared/doctor-core.mjs @@ -491,7 +491,7 @@ export async function httpProbe({ url, method = "GET", headers = {}, body, timeo // A connection record carries no `sendIdentityHeaders`: the doctor asks with // the identity and reports whatever the server echoes back. function authHeaders(conn, { identity = true } = {}) { - return buildOvHeaders(conn, { actorPeerId: conn.peerId, identityHeaders: identity }); + return buildOvHeaders(conn, { actorPeerId: conn.peerId, identityHeaders: identity, extraHeaders: conn.extraHeaders }); } export function serverErrorMessage(probe) { @@ -518,7 +518,7 @@ export async function probeOpenViking(conn, { timeoutMs = 5000, mcp = true } = { // Hard network failure: the rest of the ladder would fail identically. return out; } - if (conn.apiKey || conn.account || conn.user) { + if (conn.apiKey || conn.account || conn.user || Object.keys(conn.extraHeaders ?? {}).length) { out.healthAuth = await httpProbe({ url: `${base}/health`, timeoutMs, headers: authHeaders(conn) }); } out.systemStatus = await httpProbe({ url: `${base}/api/v1/system/status`, timeoutMs, headers: authHeaders(conn) }); diff --git a/examples/codex-memory-plugin/scripts/shared/ov-http.mjs b/examples/codex-memory-plugin/scripts/shared/ov-http.mjs index f1bc32d2d91..f5c691a1428 100644 --- a/examples/codex-memory-plugin/scripts/shared/ov-http.mjs +++ b/examples/codex-memory-plugin/scripts/shared/ov-http.mjs @@ -70,6 +70,9 @@ export function createOvHttp(cfg = {}, { return async function fetchJSON(path, init = {}, options = {}) { const timeoutMs = Math.max(MIN_TIMEOUT_MS, Number(options.timeoutMs) || Number(defaultTimeoutMs) || 0); const controller = new AbortController(); + const callerAbort = () => controller.abort(init.signal.reason); + if (init.signal?.aborted) callerAbort(); + else init.signal?.addEventListener("abort", callerAbort, { once: true }); let timedOut = false; const timer = setTimeout(() => { timedOut = true; @@ -123,14 +126,13 @@ export function createOvHttp(cfg = {}, { return { ok: true, status: response.status, result: body?.result ?? body ?? {}, traceId }; } catch (error) { const message = error?.message || String(error); - // This module owns the controller, so it says a timeout was a timeout - // rather than leaving callers to guess it from whatever fetch threw. - const failure = timedOut + const failure = timedOut || init.signal?.aborted ? { name: "AbortError", aborted: true, message } : { message }; return { ok: false, status: 0, result: null, error: failure }; } finally { clearTimeout(timer); + init.signal?.removeEventListener("abort", callerAbort); } }; } diff --git a/examples/codex-memory-plugin/scripts/shared/pending-queue.mjs b/examples/codex-memory-plugin/scripts/shared/pending-queue.mjs index e86f59b00ed..04d5fe4236d 100644 --- a/examples/codex-memory-plugin/scripts/shared/pending-queue.mjs +++ b/examples/codex-memory-plugin/scripts/shared/pending-queue.mjs @@ -230,6 +230,38 @@ export async function enqueue(type, sessionId, payload, options = {}) { return { ok: false, error: `pending file exists but dedup entry was not readable: ${filename}`, dedupKey }; } +/** True if this session has a queued or in-flight write. Never claim or replay it. */ +export async function hasPendingSessionWrites(sessionId) { + if (!sessionId) return false; + const dir = getPendingDir(); + let files; + try { + files = await readdir(dir); + } catch (error) { + if (error.code === "ENOENT") return false; + throw error; + } + for (const name of files) { + if (!/\.(json|processing)$/.test(name)) continue; + // A drainer may have just claimed a file from this listing. Inspect the + // claimed spelling too; if it was removed, the drainer finished it. + let entry; + try { + entry = await readEntry(dir, name); + } catch (error) { + if (error.code !== "ENOENT") throw error; + const counterpart = name.endsWith(".json") ? processingFilename(name) : pendingFromProcessingFilename(name); + try { + entry = await readEntry(dir, counterpart); + } catch (retryError) { + if (retryError.code !== "ENOENT") throw retryError; + } + } + if (entry?.sessionId === sessionId) return true; + } + return false; +} + /** * List all pending queue entries. * Returns array of { filename, entry } sorted by createdAt ascending. diff --git a/examples/codex-memory-plugin/scripts/shared/plugin-config.mjs b/examples/codex-memory-plugin/scripts/shared/plugin-config.mjs index f60c3bca8b5..69c72623c14 100644 --- a/examples/codex-memory-plugin/scripts/shared/plugin-config.mjs +++ b/examples/codex-memory-plugin/scripts/shared/plugin-config.mjs @@ -99,9 +99,9 @@ export function loadPluginSettings(harness, env = process.env, options = {}) { * callers still need to know a value came from ovcli.conf rather than ov.conf. */ export function resolveSettings(harness, options = {}) { - const { env = process.env, cwd = "", legacy = {}, clientVersion = "", cliFile = null } = options; + const { env = process.env, cwd = "", legacy = {}, clientVersion = "", cliFile = null, readOnly = false } = options; const key = harnessKey(harness); - const plugin = loadPluginSettings(key, env, { cwd, clientVersion, cliFile }); + const plugin = loadPluginSettings(key, env, { cwd, clientVersion, cliFile, readOnly }); const { settings, configured, sources } = resolveKnobs({ harness: key, layers: [ @@ -120,7 +120,7 @@ export function resolveSettings(harness, options = {}) { * level, before the payload on stdin has said which directory the session is * actually in — the caller resolves this again once it knows. */ -export function resolveWorkspaceSettings(cwd, env = process.env, { clientVersion = "" } = {}) { +export function resolveWorkspaceSettings(cwd, env = process.env, { clientVersion = "", readOnly = false } = {}) { const empty = { settings: {}, root: "", provenance: {}, warnings: [], announced: [] }; try { const { root } = findWorkspaceRoot(cwd, env); @@ -129,7 +129,7 @@ export function resolveWorkspaceSettings(cwd, env = process.env, { clientVersion const { layers, warnings } = loadWorkspaceLayers(root, { clientVersion }); // The identity is what makes the registry's negative evidence work: without // it a directory reused by a different repository inherits the old peer. - const identity = resolveWorkspaceIdentity({ cwd, env }); + const identity = resolveWorkspaceIdentity({ cwd, env, cache: !readOnly }); const registry = readEntry(root, { identity, env }); warnings.push(...registry.warnings); if (registry.entry?.settings) layers.push({ layer: "registry", data: registry.entry.settings }); @@ -197,6 +197,7 @@ export function buildPluginConfig(harness, { logFile = "", rootKeyFallback = false, deriveEffectivePeer = false, + readOnly = false, } = {}) { const name = String(harness || ""); const key = harnessKey(name); @@ -211,6 +212,7 @@ export function buildPluginConfig(harness, { legacy: legacy || ovConfSection(files.ovFile, key), cliFile: files.cliFile, clientVersion, + readOnly, }); const connection = resolveConnection(key, { env, files, hostInput, rootKeyFallback }); const { baseUrl, account, user } = connection; @@ -279,7 +281,8 @@ export function buildPluginConfig(harness, { // it per session, against the directory the payload names, and an MCP proxy // must not derive one from wherever it happened to be launched. if (deriveEffectivePeer) { - const effectivePeer = resolveEffectivePeerId({ cfg: config, cwd: workspaceCwd, env }); + const identity = readOnly ? resolveWorkspaceIdentity({ cwd: workspaceCwd, env, cache: false }) : null; + const effectivePeer = resolveEffectivePeerId({ cfg: config, cwd: workspaceCwd, env, identity }); config.effectivePeer = effectivePeer; config.legacyPeerId = effectivePeer.legacyPeerId; } diff --git a/examples/dsh-memory-plugin/package-lock.json b/examples/dsh-memory-plugin/package-lock.json index 3093889171f..6669c7b8e52 100644 --- a/examples/dsh-memory-plugin/package-lock.json +++ b/examples/dsh-memory-plugin/package-lock.json @@ -1,12 +1,12 @@ { "name": "@openviking/dsh-memory-plugin", - "version": "0.5.38", + "version": "0.5.39", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@openviking/dsh-memory-plugin", - "version": "0.5.38", + "version": "0.5.39", "license": "Apache-2.0", "devDependencies": { "@deepseek-ai/dsh-llm": "0.1.0-rc.6", diff --git a/examples/dsh-memory-plugin/package.json b/examples/dsh-memory-plugin/package.json index 66c9b958e52..cbe066aa888 100644 --- a/examples/dsh-memory-plugin/package.json +++ b/examples/dsh-memory-plugin/package.json @@ -1,6 +1,6 @@ { "name": "@openviking/dsh-memory-plugin", - "version": "0.5.38", + "version": "0.5.39", "description": "OpenViking memory and context bundle for DeepSeek Harness", "icon": "./icon.svg", "type": "module", diff --git a/examples/magpie-memory-plugin/package.json b/examples/magpie-memory-plugin/package.json index 2317627e1d4..8ac72b54778 100644 --- a/examples/magpie-memory-plugin/package.json +++ b/examples/magpie-memory-plugin/package.json @@ -1,6 +1,6 @@ { "name": "@openviking/magpie-plugin", - "version": "0.2.2", + "version": "0.2.3", "description": "OpenViking integration for Magpie: memory recall/capture and model switching with automatic restart.", "author": "OpenViking", "homepage": "https://github.com/volcengine/OpenViking/tree/main/examples/magpie-memory-plugin", diff --git a/examples/memory-plugin-shared/lib/doctor-core.mjs b/examples/memory-plugin-shared/lib/doctor-core.mjs index 0a22efe3a21..c39c3a52db4 100644 --- a/examples/memory-plugin-shared/lib/doctor-core.mjs +++ b/examples/memory-plugin-shared/lib/doctor-core.mjs @@ -490,7 +490,7 @@ export async function httpProbe({ url, method = "GET", headers = {}, body, timeo // A connection record carries no `sendIdentityHeaders`: the doctor asks with // the identity and reports whatever the server echoes back. function authHeaders(conn, { identity = true } = {}) { - return buildOvHeaders(conn, { actorPeerId: conn.peerId, identityHeaders: identity }); + return buildOvHeaders(conn, { actorPeerId: conn.peerId, identityHeaders: identity, extraHeaders: conn.extraHeaders }); } export function serverErrorMessage(probe) { @@ -517,7 +517,7 @@ export async function probeOpenViking(conn, { timeoutMs = 5000, mcp = true } = { // Hard network failure: the rest of the ladder would fail identically. return out; } - if (conn.apiKey || conn.account || conn.user) { + if (conn.apiKey || conn.account || conn.user || Object.keys(conn.extraHeaders ?? {}).length) { out.healthAuth = await httpProbe({ url: `${base}/health`, timeoutMs, headers: authHeaders(conn) }); } out.systemStatus = await httpProbe({ url: `${base}/api/v1/system/status`, timeoutMs, headers: authHeaders(conn) }); diff --git a/examples/memory-plugin-shared/lib/ov-http.mjs b/examples/memory-plugin-shared/lib/ov-http.mjs index b359783916d..79fd49aa02e 100644 --- a/examples/memory-plugin-shared/lib/ov-http.mjs +++ b/examples/memory-plugin-shared/lib/ov-http.mjs @@ -69,6 +69,9 @@ export function createOvHttp(cfg = {}, { return async function fetchJSON(path, init = {}, options = {}) { const timeoutMs = Math.max(MIN_TIMEOUT_MS, Number(options.timeoutMs) || Number(defaultTimeoutMs) || 0); const controller = new AbortController(); + const callerAbort = () => controller.abort(init.signal.reason); + if (init.signal?.aborted) callerAbort(); + else init.signal?.addEventListener("abort", callerAbort, { once: true }); let timedOut = false; const timer = setTimeout(() => { timedOut = true; @@ -122,14 +125,13 @@ export function createOvHttp(cfg = {}, { return { ok: true, status: response.status, result: body?.result ?? body ?? {}, traceId }; } catch (error) { const message = error?.message || String(error); - // This module owns the controller, so it says a timeout was a timeout - // rather than leaving callers to guess it from whatever fetch threw. - const failure = timedOut + const failure = timedOut || init.signal?.aborted ? { name: "AbortError", aborted: true, message } : { message }; return { ok: false, status: 0, result: null, error: failure }; } finally { clearTimeout(timer); + init.signal?.removeEventListener("abort", callerAbort); } }; } diff --git a/examples/memory-plugin-shared/lib/pending-queue.mjs b/examples/memory-plugin-shared/lib/pending-queue.mjs index 83ec54d71d2..ef04c8e21a3 100644 --- a/examples/memory-plugin-shared/lib/pending-queue.mjs +++ b/examples/memory-plugin-shared/lib/pending-queue.mjs @@ -229,6 +229,38 @@ export async function enqueue(type, sessionId, payload, options = {}) { return { ok: false, error: `pending file exists but dedup entry was not readable: ${filename}`, dedupKey }; } +/** True if this session has a queued or in-flight write. Never claim or replay it. */ +export async function hasPendingSessionWrites(sessionId) { + if (!sessionId) return false; + const dir = getPendingDir(); + let files; + try { + files = await readdir(dir); + } catch (error) { + if (error.code === "ENOENT") return false; + throw error; + } + for (const name of files) { + if (!/\.(json|processing)$/.test(name)) continue; + // A drainer may have just claimed a file from this listing. Inspect the + // claimed spelling too; if it was removed, the drainer finished it. + let entry; + try { + entry = await readEntry(dir, name); + } catch (error) { + if (error.code !== "ENOENT") throw error; + const counterpart = name.endsWith(".json") ? processingFilename(name) : pendingFromProcessingFilename(name); + try { + entry = await readEntry(dir, counterpart); + } catch (retryError) { + if (retryError.code !== "ENOENT") throw retryError; + } + } + if (entry?.sessionId === sessionId) return true; + } + return false; +} + /** * List all pending queue entries. * Returns array of { filename, entry } sorted by createdAt ascending. diff --git a/examples/memory-plugin-shared/lib/plugin-config.mjs b/examples/memory-plugin-shared/lib/plugin-config.mjs index 3ae1399920b..82fbcab66ec 100644 --- a/examples/memory-plugin-shared/lib/plugin-config.mjs +++ b/examples/memory-plugin-shared/lib/plugin-config.mjs @@ -98,9 +98,9 @@ export function loadPluginSettings(harness, env = process.env, options = {}) { * callers still need to know a value came from ovcli.conf rather than ov.conf. */ export function resolveSettings(harness, options = {}) { - const { env = process.env, cwd = "", legacy = {}, clientVersion = "", cliFile = null } = options; + const { env = process.env, cwd = "", legacy = {}, clientVersion = "", cliFile = null, readOnly = false } = options; const key = harnessKey(harness); - const plugin = loadPluginSettings(key, env, { cwd, clientVersion, cliFile }); + const plugin = loadPluginSettings(key, env, { cwd, clientVersion, cliFile, readOnly }); const { settings, configured, sources } = resolveKnobs({ harness: key, layers: [ @@ -119,7 +119,7 @@ export function resolveSettings(harness, options = {}) { * level, before the payload on stdin has said which directory the session is * actually in — the caller resolves this again once it knows. */ -export function resolveWorkspaceSettings(cwd, env = process.env, { clientVersion = "" } = {}) { +export function resolveWorkspaceSettings(cwd, env = process.env, { clientVersion = "", readOnly = false } = {}) { const empty = { settings: {}, root: "", provenance: {}, warnings: [], announced: [] }; try { const { root } = findWorkspaceRoot(cwd, env); @@ -128,7 +128,7 @@ export function resolveWorkspaceSettings(cwd, env = process.env, { clientVersion const { layers, warnings } = loadWorkspaceLayers(root, { clientVersion }); // The identity is what makes the registry's negative evidence work: without // it a directory reused by a different repository inherits the old peer. - const identity = resolveWorkspaceIdentity({ cwd, env }); + const identity = resolveWorkspaceIdentity({ cwd, env, cache: !readOnly }); const registry = readEntry(root, { identity, env }); warnings.push(...registry.warnings); if (registry.entry?.settings) layers.push({ layer: "registry", data: registry.entry.settings }); @@ -196,6 +196,7 @@ export function buildPluginConfig(harness, { logFile = "", rootKeyFallback = false, deriveEffectivePeer = false, + readOnly = false, } = {}) { const name = String(harness || ""); const key = harnessKey(name); @@ -210,6 +211,7 @@ export function buildPluginConfig(harness, { legacy: legacy || ovConfSection(files.ovFile, key), cliFile: files.cliFile, clientVersion, + readOnly, }); const connection = resolveConnection(key, { env, files, hostInput, rootKeyFallback }); const { baseUrl, account, user } = connection; @@ -278,7 +280,8 @@ export function buildPluginConfig(harness, { // it per session, against the directory the payload names, and an MCP proxy // must not derive one from wherever it happened to be launched. if (deriveEffectivePeer) { - const effectivePeer = resolveEffectivePeerId({ cfg: config, cwd: workspaceCwd, env }); + const identity = readOnly ? resolveWorkspaceIdentity({ cwd: workspaceCwd, env, cache: false }) : null; + const effectivePeer = resolveEffectivePeerId({ cfg: config, cwd: workspaceCwd, env, identity }); config.effectivePeer = effectivePeer; config.legacyPeerId = effectivePeer.legacyPeerId; } diff --git a/examples/memory-plugin-shared/plugin-config.test.mjs b/examples/memory-plugin-shared/plugin-config.test.mjs index 7b83e0a4a08..da5e8a0d627 100644 --- a/examples/memory-plugin-shared/plugin-config.test.mjs +++ b/examples/memory-plugin-shared/plugin-config.test.mjs @@ -1,5 +1,5 @@ import assert from "node:assert/strict"; -import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import test from "node:test"; @@ -398,3 +398,24 @@ for (const [name, loader] of Object.entries(LOADERS)) { }); }); } + + +test("readOnly config preserves effective values without cold identity cache writes", () => { + const dir = mkdtempSync(join(tmpdir(), "ov-config-readonly-")); + try { + for (const [name, contents] of [["absent", null], ["valid", '{"url":"http://localhost:1933","plugin":{"opencode":{"autoCapture":false}}}'], ["malformed", "{broken"]]) { + const cwd = join(dir, name); + const state = join(cwd, "state"); + mkdirSync(join(cwd, ".openviking"), { recursive: true }); + writeFileSync(join(cwd, ".openviking", "config.json"), '{"version":1,"peer":{"id":"fixture"}}'); + const cliPath = join(cwd, "ovcli.conf"); + if (contents !== null) writeFileSync(cliPath, contents); + const env = { OPENVIKING_CLI_CONFIG_FILE: cliPath, OPENVIKING_CONFIG_FILE: join(cwd, "absent-ov.conf"), OPENVIKING_STATE_DIR: state, HOME: cwd }; + const readonly = buildPluginConfig("opencode", { cwd, env, deriveEffectivePeer: true, readOnly: true }); + assert.equal(existsSync(state), false, name); + const normal = buildPluginConfig("opencode", { cwd, env, deriveEffectivePeer: true }); + assert.deepEqual(readonly, normal, name); + assert.ok(readdirSync(state).some((file) => file.startsWith("ws-identity-")), name); + } + } finally { rmSync(dir, { recursive: true, force: true }); } +}); diff --git a/examples/opencode-plugin/README.md b/examples/opencode-plugin/README.md index 973ac8b6d2f..c699f6b6a2c 100644 --- a/examples/opencode-plugin/README.md +++ b/examples/opencode-plugin/README.md @@ -267,3 +267,38 @@ Registry failures stop the workflow instead of treating an unavailable registry an unused version. Only upstream `main` can publish the official npm `latest` tag. Manual dispatch on `main` retries a failed release using the existing npm credentials or Trusted Publishing configuration. + +## Read-only diagnostics (OpenCode V2) + +Run `node scripts/ov-memory-doctor.mjs --json` from the installed plugin directory. +Use `--offline` to skip server probes. The CLI resolves the same OpenViking configuration +as the plugin, reads capture metadata without transcript bodies, and reuses the shared +memory doctor's authenticated HTTP/MCP probes and verdicts. It never repairs configuration, +replays pending writes, or commits a session. Native plugin/MCP/skill inventories require +an active OpenCode host; the standalone CLI labels them `unsupported`. + +The V2 server registers RPC `openviking.controls` for a native TUI/client consumer: + +| Method | Input | Result | +| --- | --- | --- | +| `status`, `doctor` | `{ "offline": true }` (optional boolean) | `schemaVersion: 1`, installation, MCP, skills, connection, capture, effective config, findings (`sections`), `text`, `exitCode` | +| `commit` | `{ "sessionID": "" }` | `status`, `traceId` when available, `extraction` | + +Read methods return only selected configuration fields and redact credentials. Inventory +states distinguish disabled, unsupported, missing and failed registration. In particular, +connected MCP with missing bundled native skills is a diagnostic failure. Capture timestamps +record local activity and commit acceptance; they do not prove completed extraction. + +Commit is an intentional write. The caller must pass its current OpenCode session ID, +never an OpenViking session ID. The server checks location ownership, respects capture and +child-session privacy settings, waits for serialized capture, sends current-session messages +before committing, and refuses to overtake queued capture. `pending_capture` requires normal +recovery before retrying. Auth/network errors remain failures (`operation_failed` over RPC), +and HTTP acceptance returns `extraction: "not_verified"`, never completed extraction. +Automatic lifecycle commits retain their existing retry behavior. + +Visible `/ov status`, `/ov doctor` and `/ov commit` controls require the TUI consumer. +OpenCode V2 server command callbacks return no display value; writing a synthetic session +message merely to show diagnostics would alter conversation history and contaminate capture. +The server therefore exposes RPC rather than registering silent commands. The consumer +should show read results in native UI and invoke `commit` only after intentional user action. diff --git a/examples/opencode-plugin/lib/config.mjs b/examples/opencode-plugin/lib/config.mjs index 4847d96317f..48dfc7c3393 100644 --- a/examples/opencode-plugin/lib/config.mjs +++ b/examples/opencode-plugin/lib/config.mjs @@ -23,13 +23,14 @@ function expandHome(value) { return value } -export function loadConfig(pluginRoot, projectDirectory, { env = process.env } = {}) { +export function loadConfig(pluginRoot, projectDirectory, { env = process.env, readOnly = false } = {}) { const config = buildPluginConfig("opencode", { cwd: projectDirectory, env, manifestUrl: MANIFEST_URL, logFile: "opencode-plugin.log", deriveEffectivePeer: true, + readOnly, }) return { diff --git a/examples/opencode-plugin/lib/diagnostics.mjs b/examples/opencode-plugin/lib/diagnostics.mjs new file mode 100644 index 00000000000..f8709ca275d --- /dev/null +++ b/examples/opencode-plugin/lib/diagnostics.mjs @@ -0,0 +1,109 @@ +import { readFile } from "node:fs/promises" +import { join } from "node:path" +import { parseExtraHeaders } from "./shared/mcp-proxy-config.mjs" +import { resolveDataDir } from "./config.mjs" +import { isCaptureEnabled } from "./shared/capture-utils.mjs" +import { assessProbes, createReport, describeApiKey, probeOpenViking } from "./shared/doctor-core.mjs" + +export const BUNDLED_SKILLS = ["openviking-memory", "openviking-skills", "ov-experience-memory", "openviking-rule-search"] + +// Select fields rather than serializing effective config, skill bodies or transcripts. +export async function diagnoseOpenCode({ ctx, config, pluginRoot = "", offline = false, timeoutMs = 5000 }) { + const report = createReport() + const extraHeaders = config.extraHeaders ?? parseExtraHeaders(process.env.OPENVIKING_EXTRA_HEADERS) + const redact = (text) => sanitizeDiagnosticText(config, text) + const inventory = async (domain) => { + if (!domain?.list) return { state: "unsupported" } + try { + const { data } = await domain.list() + if (!Array.isArray(data)) throw new Error("Unexpected OpenCode inventory response") + return { state: "ok", data } + } catch (error) { + return { state: "error", error: redact(error.message ?? error) } + } + } + const [plugins, servers, skills] = await Promise.all([inventory(ctx?.plugin), inventory(ctx?.mcp), inventory(ctx?.skill)]) + report.section("OpenCode installation") + const instances = plugins.data?.filter((p) => p.id === "openviking" || p.source?.target?.includes("@openviking/opencode-plugin") || /openviking/i.test(p.source?.path || "")) + const installation = { state: plugins.state, hostVersion: ctx?.app?.version ?? null, + instances: instances?.map((p) => ({ id: p.id, source: p.source.type, version: p.source.version ?? null, state: p.state.status })), + ...(plugins.error ? { error: plugins.error } : {}) } + try { + installation.packageVersion = JSON.parse(await readFile(join(pluginRoot, "package.json"), "utf8")).version + } catch { installation.packageVersion = null } + report.info(`OpenCode ${installation.hostVersion || "(not in host)"}; plugin ${installation.packageVersion || "(unknown version)"}`) + if (instances) { + installation.state = instances.length === 1 && instances[0].state.status === "active" ? "ok" : "error" + report[installation.state === "ok" ? "ok" : "fail"](`OpenViking plugin instances: ${instances.length}`, "Multiple sources can indicate duplicate discovery; inspect the OpenCode plugin inventory") + } else report.info(`Native plugin inventory: ${plugins.state}`) + + const server = servers.data?.find((s) => s.name === "openviking") + const mcp = !config.mcp?.enabled ? { state: "disabled" } + : servers.state !== "ok" ? { state: servers.state, ...(servers.error ? { error: servers.error } : {}) } + : { state: server?.status?.status ?? "missing", ...(server?.status?.error ? { error: redact(server.status.error) } : {}) } + const missing = BUNDLED_SKILLS.filter((name) => !skills.data?.some((s) => s.name === name)) + const skillState = (!config.mcp?.enabled || mcp.state === "disabled") ? { state: "disabled" } + : skills.state !== "ok" ? { state: skills.state, ...(skills.error ? { error: skills.error } : {}) } + : { state: missing.length ? "error" : "ok", missing, registered: BUNDLED_SKILLS.filter((s) => !missing.includes(s)) } + report.section("Native registration") + report[["connected", "disabled", "unsupported"].includes(mcp.state) ? "info" : "fail"](`MCP: ${mcp.state}`, mcp.error) + report[skillState.state === "error" ? "fail" : "info"](`Skills: ${skillState.state}`, skillState.missing?.join(", ") || skillState.error) + + report.section("Connection") + let connection = { state: offline ? "disabled" : "ok" } + if (!offline) { + const conn = { baseUrl: config.baseUrl, apiKey: config.apiKey, account: config.sendIdentityHeaders ? config.accountId : "", user: config.sendIdentityHeaders ? config.userId : "", peerId: config.effectivePeer?.peerId || config.peerId, userAgent: config.userAgent } + const probes = await probeOpenViking({ ...conn, extraHeaders }, { timeoutMs, mcp: mcp.state !== "disabled" }) + const summary = assessProbes(report, probes, conn, describeApiKey(config.apiKey)) + connection = { state: summary.authOk ? "ok" : "error", reachable: summary.reachable, authOk: summary.authOk, version: summary.version, + mcpHttpStatus: probes.mcp?.status ?? null } + } else report.info("Network probes disabled (--offline)") + + report.section("Capture activity") + const capture = await inspectCapture(config, pluginRoot) + report[capture.state === "error" ? "fail" : "info"](`Capture: ${capture.state}`, capture.error) + let endpoint + try { const url = new URL(config.baseUrl); url.username = ""; url.password = ""; url.search = ""; url.hash = ""; endpoint = url.href } catch { endpoint = "(invalid URL)" } + const result = { schemaVersion: 1, installation, mcp, skills: skillState, connection, capture, + effective: { enabled: config.enabled !== false, baseUrl: endpoint, apiKeyConfigured: Boolean(config.apiKey), peerId: config.effectivePeer?.peerId || config.peerId || null, autoRecall: config.autoRecall, mcpEnabled: config.mcp?.enabled, autoCapture: isCaptureEnabled(config), captureAssistantTurns: config.captureAssistantTurns, skipSubagentSessions: config.skipSubagentSessions, captureRedact: config.captureRedact }, + exitCode: report.exitCode(), ...report.toJSON(), text: report.render() } + // Sanitize values before JSON serialization so quotes and other special + // characters in credentials cannot corrupt the result or evade redaction. + function sanitize(value) { + if (typeof value === "string") return redact(value) + if (Array.isArray(value)) return value.map(sanitize) + if (value && typeof value === "object") return Object.fromEntries(Object.entries(value).map(([key, v]) => [key, sanitize(v)])) + return value + } + return sanitize(result) +} + +export function sanitizeDiagnosticText(config, text) { + const extras = config.extraHeaders ?? parseExtraHeaders(process.env.OPENVIKING_EXTRA_HEADERS) + const secrets = [config.apiKey, ...Object.values(extras)].filter((v) => typeof v === "string" && v) + return secrets.reduce((value, secret) => value.replaceAll(secret, "[redacted]"), String(text)) + .replace(/https?:[^\s"'<>]+/g, (value) => { + try { + const url = new URL(value) + url.username = "" + url.password = "" + url.search = "" + url.hash = "" + return url.href + } catch { return "[URL]" } + }) +} + +async function inspectCapture(config, pluginRoot) { + if (!isCaptureEnabled(config)) return { state: "disabled" } + try { + const data = JSON.parse(await readFile(join(resolveDataDir(pluginRoot, config), "openviking-session-state.json"), "utf8")) + const sessions = Object.values(data.sessions || {}) + return { state: "ok", sessions: sessions.length, + pendingMessages: sessions.reduce((n, s) => n + (s.messages || []).filter(([, m]) => !m.captured).length, 0), + lastActivityAt: sessions.reduce((n, s) => Math.max(n, s.lastActivityAt ?? 0), 0), + lastCommitAcceptedAt: sessions.reduce((n, s) => Math.max(n, s.lastCommitTime ?? 0), 0) } + } catch (error) { + return error.code === "ENOENT" ? { state: "no_activity" } : { state: "error", error: "Cannot read capture state: " + error.message } + } +} diff --git a/examples/opencode-plugin/lib/memory-session.mjs b/examples/opencode-plugin/lib/memory-session.mjs index a187c9d992e..4c66e7dfc4d 100644 --- a/examples/opencode-plugin/lib/memory-session.mjs +++ b/examples/opencode-plugin/lib/memory-session.mjs @@ -10,6 +10,7 @@ import { } from "./shared/session-model.mjs" import { enqueue, + hasPendingSessionWrites, replayPending, } from "./shared/pending-queue.mjs" import { @@ -350,12 +351,35 @@ export function createMemorySessionManager({ config, pluginRoot }) { return commitOvSession(sessionId, { force: true, abortSignal, reason: "tool" }) } + // User-requested commits must not hide failed capture behind offline replay. + // Existing lifecycle/tool commits retain their queueing behavior. + async function commitCurrentSession(opencodeSessionId, abortSignal) { + if (!isCaptureEnabled(config)) return { status: "disabled" } + const state = sessions.get(opencodeSessionId) + if (!state) return { status: "no_activity" } + if (shouldSkipSubagentSession(state)) return { status: "disabled" } + const run = (state.flushChain ?? Promise.resolve()).then(async () => { + // Previously queued messages are marked captured locally. Do not commit + // ahead of their delivery, or replay any unrelated session as a side effect. + if (await hasPendingSessionWrites(state.ovSessionId)) return { status: "pending_capture" } + abortSignal?.throwIfAborted() + await flushPendingMessages(opencodeSessionId, state, { strict: true, abortSignal }) + abortSignal?.throwIfAborted() + const result = await commitOvSession(state.ovSessionId, { force: true, reason: "intentional", abortSignal, queueOnFailure: false }) + await enqueueSave() + return result + }) + state.flushChain = run.catch(() => {}) + return run + } + return { init, waitForBackground, handleEvent, getMappedSessionId, commitSession, + commitCurrentSession, flushAll, flushSession, } @@ -445,7 +469,7 @@ export function createMemorySessionManager({ config, pluginRoot }) { return body } - async function flushPendingMessages(opencodeSessionId, state) { + async function flushPendingMessages(opencodeSessionId, state, { strict = false, abortSignal } = {}) { if (!isCaptureEnabled(config)) return 0 // Recovery/replay paths (idle flush, dispose flushAll, tool commit, a // state file reloaded after a restart) come through here too, so the @@ -465,8 +489,11 @@ export function createMemorySessionManager({ config, pluginRoot }) { if (toSend.length === 0) return 0 let added = 0 - const health = await fetchJSON(config, "/health", {}, { timeoutMs: 5000 }) - if (!health.ok) { + abortSignal?.throwIfAborted() + const health = await fetchJSON(config, "/health", { signal: abortSignal }, { timeoutMs: 5000 }) + abortSignal?.throwIfAborted() + if (!health.ok && strict) throw new Error("Capture failed before commit: OpenViking health check failed") + if (!health.ok && !strict) { for (const item of toSend) { const queued = await enqueue("addMessage", state.ovSessionId, item.body) if (!queued.ok) break @@ -474,17 +501,31 @@ export function createMemorySessionManager({ config, pluginRoot }) { added += 1 } } else { + let sent = 0 const res = await sendSessionMessages( - (endpoint, init = {}, options = {}) => fetchJSON(config, endpoint, init, { timeoutMs: 10000, ...options }), + (endpoint, init = {}, options = {}) => { + abortSignal?.throwIfAborted() + return fetchJSON(config, endpoint, { ...init, signal: abortSignal }, { timeoutMs: 10000, ...options }) + }, state.ovSessionId, toSend.map((item) => item.body), - { enqueueOnRetryable: true }, + { + enqueueOnRetryable: !strict, + onSent: strict ? (count) => { + for (const item of toSend.slice(sent, sent + count)) item.message.captured = true + sent += count + state.lastActivityAt = Date.now() + debouncedSaveState() + } : undefined, + }, ) + abortSignal?.throwIfAborted() added = res.sent + res.queued for (const item of toSend.slice(0, added)) { item.message.captured = true } if (res.failed > 0 || res.enqueueFailed > 0) { + if (strict) throw new Error(`Capture failed before commit: ${res.lastError?.message || JSON.stringify(res.lastError)}`) log("ERROR", "message", "Failed to add message to OpenViking session", { openviking_session: state.ovSessionId, status: res.lastError?.status, @@ -516,7 +557,8 @@ export function createMemorySessionManager({ config, pluginRoot }) { return commitOvSession(state.ovSessionId, { force: true, reason: "threshold" }) } - async function commitOvSession(ovSessionId, { force = false, reason = "manual", abortSignal } = {}) { + async function commitOvSession(ovSessionId, { force = false, reason = "manual", abortSignal, queueOnFailure = true } = {}) { + abortSignal?.throwIfAborted() if (!force && config.commitTokenThreshold <= 0) return { status: "skipped" } const body = { keep_recent_count: 0 } const res = await fetchJSON(config, `/api/v1/sessions/${encodeURIComponent(ovSessionId)}/commit`, { @@ -536,7 +578,8 @@ export function createMemorySessionManager({ config, pluginRoot }) { }) return { status: "accepted", result: res.result, traceId } } - if (isRetryableFailure(res)) { + abortSignal?.throwIfAborted() + if (queueOnFailure && isRetryableFailure(res)) { await enqueue("commitSession", ovSessionId, body) log("WARN", "session", "Queued OpenViking session commit", { openviking_session: ovSessionId, diff --git a/examples/opencode-plugin/lib/v2-controls.mjs b/examples/opencode-plugin/lib/v2-controls.mjs new file mode 100644 index 00000000000..0885a6a7365 --- /dev/null +++ b/examples/opencode-plugin/lib/v2-controls.mjs @@ -0,0 +1,48 @@ +import { diagnoseOpenCode, sanitizeDiagnosticText } from "./diagnostics.mjs" +import { isCaptureEnabled } from "./shared/capture-utils.mjs" + +const sessionInput = { type: "object", properties: { sessionID: { type: "string", minLength: 1 } }, required: ["sessionID"], additionalProperties: false } +const readInput = { type: "object", properties: { offline: { type: "boolean" } }, additionalProperties: false } +// JSON Schema is the portable definition accepted by both plugin hosts. +export const OPENVIKING_CONTROLS = { + id: "openviking.controls", + methods: { + status: { input: readInput, output: { type: "object" } }, + doctor: { input: readInput, output: { type: "object" } }, + commit: { input: sessionInput, output: { type: "object" }, errors: { operation_failed: { type: "object" } } }, + }, + events: {}, +} + +export async function registerV2Controls(ctx, runtime, { pluginRoot, serializeSession, captureCurrent }) { + if (!ctx?.rpc?.register) return + const diagnose = async (input = {}) => diagnoseOpenCode({ ctx, config: runtime.config, pluginRoot, offline: input.offline === true }) + await ctx.rpc.register(OPENVIKING_CONTROLS, { + status: diagnose, + doctor: diagnose, + commit: async ({ sessionID }, { signal, error: rpcError } = {}) => { + try { + signal?.throwIfAborted() + if (!isCaptureEnabled(runtime.config)) return { status: "disabled", extraction: "not_started" } + // Caller selects its current session; never flushAll or accept an OV id. + const session = await ctx.session.get({ sessionID }) + if (session.location.directory !== ctx.location.directory || + (ctx.location.project?.id && session.projectID !== ctx.location.project.id)) throw new Error("Session belongs to another OpenCode location") + if (runtime.config.skipSubagentSessions && session.parentID) return { status: "disabled", extraction: "not_started" } + return await serializeSession(async () => { + await runtime.ready + signal?.throwIfAborted() + // Capture reads the host context and uses the existing privacy filters. + await captureCurrent(sessionID, signal) + const result = await runtime.sessionManager.commitCurrentSession(sessionID, signal) + return { status: result.status, traceId: result.traceId ?? null, + extraction: result.status === "accepted" ? "not_verified" : "not_started" } + }) + } catch (error) { + if (!rpcError) throw error + const message = sanitizeDiagnosticText(runtime.config, error.message ?? error) + return rpcError("operation_failed", message, {}) + } + }, + }) +} diff --git a/examples/opencode-plugin/lib/v2-plugin.mjs b/examples/opencode-plugin/lib/v2-plugin.mjs index 5888f244ac3..f68d9677acb 100644 --- a/examples/opencode-plugin/lib/v2-plugin.mjs +++ b/examples/opencode-plugin/lib/v2-plugin.mjs @@ -4,6 +4,7 @@ import { isRecallEnabled } from "./shared/recall-core.mjs" import { createOpenVikingV2McpConfig, openVikingSkillsDir } from "./mcp-config.mjs" import { contextMessageEvents, normalizeV2LifecycleEvent } from "./v2-events.mjs" import { log } from "./utils.mjs" +import { registerV2Controls } from "./v2-controls.mjs" const METADATA_KEY = "openviking" const CURSOR_KEY_PREFIX = "capture-cursor/" @@ -38,6 +39,12 @@ export async function startV2Plugin(ctx, runtime, { pluginRoot }) { } const directory = ctx?.location?.project?.directory || ctx?.location?.directory + await registerV2Controls(ctx, runtime, { + pluginRoot, + serializeSession, + captureCurrent: (sessionID, signal) => captureV2Context(ctx, sessionManager, captureCursors, sessionID, { signal }), + }) + if (config.mcp.enabled && ctx?.mcp?.transform) { let registered = false await ctx.mcp.transform((editor) => { @@ -278,15 +285,20 @@ function sameLocation(ref, location) { return !ref.workspaceID || !location.workspaceID || ref.workspaceID === location.workspaceID } -export async function captureV2Context(ctx, sessionManager, cursors, sessionID) { +export async function captureV2Context(ctx, sessionManager, cursors, sessionID, { signal } = {}) { const messages = await ctx.session.context({ sessionID }) - if (!Array.isArray(messages)) return + signal?.throwIfAborted() + if (!Array.isArray(messages)) { + if (signal) throw new Error("Cannot read the current OpenCode session context") + return + } // The cursor lives in host storage because the session state file is shared // by every location instance and cannot prove what was already captured. const cursor = cursors.get(sessionID) ?? await readCursor(ctx, sessionID) const cursorIndex = cursor ? messages.findIndex((message) => message?.id === cursor) : -1 const pending = cursorIndex >= 0 ? messages.slice(cursorIndex + 1) : messages for (const message of pending) { + signal?.throwIfAborted() for (const normalized of contextMessageEvents(sessionID, message)) { await sessionManager.handleEvent(normalized) } diff --git a/examples/opencode-plugin/package.json b/examples/opencode-plugin/package.json index 4b1ee9458ff..584ccedc7a4 100644 --- a/examples/opencode-plugin/package.json +++ b/examples/opencode-plugin/package.json @@ -1,6 +1,6 @@ { "name": "@openviking/opencode-plugin", - "version": "0.5.28", + "version": "0.5.29", "author": "@openviking", "description": "Unified OpenCode plugin for OpenViking repository retrieval and long-term memory", "type": "module", @@ -25,7 +25,7 @@ ], "scripts": { "prepack": "node ../memory-plugin-shared/sync.mjs", - "check": "node --check index.mjs && node --check lib/config.mjs && node --check lib/mcp-config.mjs && node --check lib/runtime.mjs && node --check lib/plugin-runtime.mjs && node --check lib/v2-events.mjs && node --check lib/v2-plugin.mjs && node --check lib/repo-context.mjs && node --check lib/memory-session.mjs && node --check lib/memory-recall.mjs && node --check lib/session-inject.mjs && node --check lib/viking-uri-guard.mjs && node --check lib/utils.mjs && node --check lib/shared/*.mjs && node --check servers/mcp-proxy.mjs && node --check scripts/setup.mjs && node --check tests/*.test.mjs", + "check": "node --check index.mjs && node --check lib/config.mjs && node --check lib/mcp-config.mjs && node --check lib/runtime.mjs && node --check lib/plugin-runtime.mjs && node --check lib/v2-events.mjs && node --check lib/diagnostics.mjs && node --check lib/v2-controls.mjs && node --check scripts/ov-memory-doctor.mjs && node --check lib/v2-plugin.mjs && node --check lib/repo-context.mjs && node --check lib/memory-session.mjs && node --check lib/memory-recall.mjs && node --check lib/session-inject.mjs && node --check lib/viking-uri-guard.mjs && node --check lib/utils.mjs && node --check lib/shared/*.mjs && node --check servers/mcp-proxy.mjs && node --check scripts/setup.mjs && node --check tests/*.test.mjs", "test": "node --test tests/*.test.mjs" }, "dependencies": {}, diff --git a/examples/opencode-plugin/scripts/ov-memory-doctor.mjs b/examples/opencode-plugin/scripts/ov-memory-doctor.mjs new file mode 100644 index 00000000000..8094b8a2b8f --- /dev/null +++ b/examples/opencode-plugin/scripts/ov-memory-doctor.mjs @@ -0,0 +1,11 @@ +#!/usr/bin/env node +import { fileURLToPath } from "node:url" +import { loadConfig } from "../lib/config.mjs" +import { diagnoseOpenCode } from "../lib/diagnostics.mjs" +import { parseArgs } from "../lib/shared/doctor-core.mjs" + +const pluginRoot = fileURLToPath(new URL("../", import.meta.url)) +const opts = parseArgs(process.argv.slice(2)) +const result = await diagnoseOpenCode({ config: loadConfig(pluginRoot, process.cwd(), { readOnly: true }), pluginRoot, offline: opts.offline, timeoutMs: opts.timeoutMs }) +console.log(opts.json ? JSON.stringify(result, null, 2) : result.text) +process.exitCode = result.exitCode diff --git a/examples/opencode-plugin/tests/diagnostics.test.mjs b/examples/opencode-plugin/tests/diagnostics.test.mjs new file mode 100644 index 00000000000..ffb0efd978a --- /dev/null +++ b/examples/opencode-plugin/tests/diagnostics.test.mjs @@ -0,0 +1,109 @@ +import test from "node:test" +import assert from "node:assert/strict" +import { diagnoseOpenCode } from "../lib/diagnostics.mjs" + +const config = { enabled: true, autoCapture: true, mcp: { enabled: true }, baseUrl: "http://localhost:1933", apiKey: "secret-fixture-key", runtime: { dataDir: "/nonexistent/ov-diagnostics" } } +const ctx = { + app: { version: "2.3.0" }, + plugin: { list: async () => ({ data: [{ id: "openviking", source: { type: "package", target: "@openviking/opencode-plugin", version: "0.5.23" }, state: { status: "active" } }] }) }, + mcp: { list: async () => ({ data: [{ name: "openviking", status: { status: "connected" } }] }) }, + skill: { list: async () => ({ data: [] }) }, +} + +test("connected MCP with missing native skills is a failure, without capture or repair", async () => { + const result = await diagnoseOpenCode({ ctx, config, pluginRoot: "/nonexistent", offline: true }) + assert.equal(result.mcp.state, "connected") + assert.equal(result.skills.state, "error") + assert.deepEqual(result.skills.missing, ["openviking-memory", "openviking-skills", "ov-experience-memory", "openviking-rule-search"]) + assert.equal(result.exitCode, 1) + assert.doesNotMatch(JSON.stringify(result), /secret-fixture-key/) +}) + +test("disabled, unsupported and failed native inventories remain distinct", async () => { + const disabled = await diagnoseOpenCode({ ctx, config: { ...config, mcp: { enabled: false }, autoCapture: false }, offline: true }) + assert.equal(disabled.mcp.state, "disabled") + assert.equal(disabled.skills.state, "disabled") + assert.equal(disabled.capture.state, "disabled") + const unsupported = await diagnoseOpenCode({ config, offline: true }) + assert.equal(unsupported.skills.state, "unsupported") + const failed = await diagnoseOpenCode({ ctx: { ...ctx, skill: { list: async () => { throw new Error("permission denied secret-fixture-key") } } }, config, offline: true }) + assert.equal(failed.skills.state, "error") + assert.match(failed.skills.error, /permission denied/) + assert.doesNotMatch(JSON.stringify(failed), /secret-fixture-key/) +}) + +import { registerV2Controls, OPENVIKING_CONTROLS } from "../lib/v2-controls.mjs" + +test("RPC read controls never create messages or commit; intentional commit scopes and awaits capture", async () => { + let handlers + const writes = [] + const runtime = { config, ready: Promise.resolve(), sessionManager: { commitCurrentSession: async (id) => { writes.push(`commit:${id}`); return { status: "accepted", result: { completed: true }, traceId: "trace-1" } } } } + const native = { ...ctx, location: { directory: "/project", project: { id: "project", directory: "/project" } }, rpc: { register: async (definition, callbacks) => { assert.equal(definition, OPENVIKING_CONTROLS); handlers = callbacks } }, session: { get: async () => ({ location: { directory: "/project" }, projectID: "project" }) } } + await registerV2Controls(native, runtime, { serializeSession: (op) => op(), captureCurrent: async (id) => { await Promise.resolve(); writes.push(`capture:${id}`) } }) + await handlers.status({ offline: true }) + await handlers.doctor({ offline: true }) + assert.deepEqual(writes, []) + assert.deepEqual(await handlers.commit({ sessionID: "current" }), { status: "accepted", traceId: "trace-1", extraction: "not_verified" }) + assert.deepEqual(writes, ["capture:current", "commit:current"]) + runtime.config = { ...config, autoCapture: false } + assert.equal((await handlers.commit({ sessionID: "current" })).status, "disabled") + assert.equal(writes.length, 2) + runtime.config = config + native.session.get = async () => ({ location: { directory: "/other" } }) + await assert.rejects(handlers.commit({ sessionID: "foreign" }), /another OpenCode location/) + native.session.get = async () => ({ location: { directory: "/project" }, projectID: "other" }) + await assert.rejects(handlers.commit({ sessionID: "foreign-project" }), /another OpenCode location/) + native.session.get = async () => ({ location: { directory: "/project" }, projectID: "project" }) + runtime.sessionManager.commitCurrentSession = async () => { throw new Error("401 denied") } + await assert.rejects(handlers.commit({ sessionID: "current" }), /401 denied/) +}) + +import { createServer } from "node:http" + +test("doctor probes authenticated MCP read operations and redacts effective config", async () => { + const requests = [] + const server = createServer((req, res) => { + requests.push({ method: req.method, url: req.url, auth: req.headers.authorization, gateway: req.headers["x-gateway"] }) + res.setHeader("Content-Type", "application/json") + if (!req.headers["x-gateway"]) { + res.statusCode = 401 + return res.end(JSON.stringify({ status: "error", error: { message: "gateway required" } })) + } + if (req.url === "/mcp") return res.end(JSON.stringify({ jsonrpc: "2.0", id: 1, result: { tools: [] } })) + if (req.url === "/health") return res.end(JSON.stringify({ status: "ok", version: "fixture", auth_mode: "api_key", role: "user", user_id: "fixture" })) + res.end(JSON.stringify({ status: "ok", result: { entries: [] } })) + }) + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)) + try { + const result = await diagnoseOpenCode({ ctx, config: { ...config, baseUrl: `http://127.0.0.1:${server.address().port}`, extraHeaders: { "X-Gateway": 'secret-"gateway"' } } }) + assert.equal(result.connection.mcpHttpStatus, 200) + assert.equal(result.connection.authOk, true) + assert.ok(requests.some((r) => r.url === "/mcp" && r.auth === "Bearer secret-fixture-key" && r.gateway === 'secret-"gateway"' )) + assert.ok(requests.every((r) => r.method === "GET" || r.url === "/mcp")) + assert.doesNotMatch(JSON.stringify(result), /secret-fixture-key/) + assert.doesNotMatch(JSON.stringify(result), /secret-[\\"]*gateway/) + } finally { await new Promise((resolve) => server.close(resolve)) } +}) + +import { mkdtemp, mkdir, readdir, rm, writeFile } from "node:fs/promises" +import { tmpdir } from "node:os" +import { join, resolve } from "node:path" +import { spawnSync } from "node:child_process" + +test("standalone offline doctor never writes a cold workspace identity cache", async () => { + const dir = await mkdtemp(join(tmpdir(), "ov-doctor-readonly-")) + try { + const home = join(dir, "home") + const workspace = join(dir, "workspace") + await mkdir(home) + await mkdir(join(workspace, ".openviking"), { recursive: true }) + await writeFile(join(workspace, ".openviking", "config.json"), JSON.stringify({ version: 1, peer: { id: "doctor-fixture" } })) + const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => !key.startsWith("OPENVIKING_"))) + Object.assign(env, { HOME: home, XDG_CONFIG_HOME: join(home, "config"), XDG_DATA_HOME: join(home, "data"), XDG_CACHE_HOME: join(home, "cache") }) + const run = spawnSync(process.execPath, [resolve(import.meta.dirname, "../scripts/ov-memory-doctor.mjs"), "--json", "--offline"], { env, cwd: workspace, encoding: "utf8" }) + assert.equal(run.status, 0, run.stderr) + assert.equal(JSON.parse(run.stdout).skills.state, "unsupported") + assert.deepEqual(await readdir(home), []) + assert.deepEqual(await readdir(join(workspace, ".openviking")), ["config.json"]) + } finally { await rm(dir, { recursive: true, force: true }) } +}) diff --git a/examples/opencode-plugin/tests/memory-session.test.mjs b/examples/opencode-plugin/tests/memory-session.test.mjs index d24240603b4..9c19aa4f3f9 100644 --- a/examples/opencode-plugin/tests/memory-session.test.mjs +++ b/examples/opencode-plugin/tests/memory-session.test.mjs @@ -876,3 +876,70 @@ test("commit of a session the server no longer has drops the stale local mapping await new Promise((resolve) => server.close(resolve)) } }) +test("intentional commit sends current capture first, preserves failures and obeys privacy", async () => { + await withTempDir("ov-oc-explicit-", async (dir) => { + const requests = [] + let failCapture = false + let failCommit = false + let cancelCapture + const server = createServer(async (req, res) => { + let body = "" + for await (const chunk of req) body += chunk + requests.push({ url: req.url, body }) + if (cancelCapture && req.url.endsWith("/messages/batch")) { + cancelCapture.abort() + return + } + res.setHeader("Content-Type", "application/json") + const failed = (failCapture && req.url.endsWith("/messages/batch")) || (failCommit && req.url.endsWith("/commit")) + res.statusCode = failed ? 401 : 200 + res.end(JSON.stringify(failed ? { status: "error", error: { message: "fixture auth denied" } } : { status: "ok", result: { job_id: "job-1" } })) + }) + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)) + const config = { ...baseConfig(`http://127.0.0.1:${server.address().port}`), commitTokenThreshold: 0 } + const previousPending = process.env.OPENVIKING_PENDING_DIR + process.env.OPENVIKING_PENDING_DIR = join(dir, "pending") + const manager = createMemorySessionManager({ config, pluginRoot: dir }) + const add = async (id, message) => { + for (const event of contextMessageEvents(id, { id: message, type: "user", text: "A useful capture fixture message" })) await manager.handleEvent(event) + } + try { + await add("current", "m1") + await add("other", "m2") + assert.equal((await manager.commitCurrentSession("current")).status, "accepted") + const batch = requests.findIndex((r) => r.url.endsWith("/messages/batch")) + const commit = requests.findIndex((r) => r.url.endsWith("/commit")) + assert.ok(batch >= 0 && commit > batch) + assert.equal(requests.filter((r) => r.url.endsWith("/commit")).length, 1) + assert.equal(requests.some((r) => r.url.includes("oc-other")), false) + failCapture = true + await add("current", "m3") + await assert.rejects(manager.commitCurrentSession("current"), /Capture failed.*auth denied/) + assert.equal(requests.filter((r) => r.url.endsWith("/commit")).length, 1) + failCapture = false + failCommit = true + await assert.rejects(manager.commitCurrentSession("current"), /auth denied/) + fs.mkdirSync(process.env.OPENVIKING_PENDING_DIR) + fs.writeFileSync(join(process.env.OPENVIKING_PENDING_DIR, "queued.json"), JSON.stringify({ sessionId: manager.getMappedSessionId("current"), type: "addMessage" })) + const queuedBefore = requests.length + assert.equal((await manager.commitCurrentSession("current")).status, "pending_capture") + assert.equal(requests.length, queuedBefore) + const before = requests.length + config.autoCapture = false + assert.equal((await manager.commitCurrentSession("current")).status, "disabled") + assert.equal(requests.length, before) + config.autoCapture = true + await add("cancelled", "m4") + cancelCapture = new AbortController() + const cancelStart = requests.length + await assert.rejects(manager.commitCurrentSession("cancelled", cancelCapture.signal), { name: "AbortError" }) + assert.deepEqual(requests.slice(cancelStart).map(({ url }) => url.split("/").at(-1)), ["health", "batch"]) + } finally { + config.autoCapture = false + await manager.flushAll() + if (previousPending === undefined) delete process.env.OPENVIKING_PENDING_DIR + else process.env.OPENVIKING_PENDING_DIR = previousPending + await new Promise((resolve) => server.close(resolve)) + } + }) +}) diff --git a/examples/pi-coding-agent-extension/package-lock.json b/examples/pi-coding-agent-extension/package-lock.json index b3200467b6b..06ecb8227c0 100644 --- a/examples/pi-coding-agent-extension/package-lock.json +++ b/examples/pi-coding-agent-extension/package-lock.json @@ -1,12 +1,12 @@ { "name": "openviking-pi-extension", - "version": "0.4.31", + "version": "0.4.32", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "openviking-pi-extension", - "version": "0.4.31", + "version": "0.4.32", "dependencies": { "@modelcontextprotocol/client": "2.0.0" }, diff --git a/examples/pi-coding-agent-extension/package.json b/examples/pi-coding-agent-extension/package.json index 40b3ec3ca27..c28eb00d32e 100644 --- a/examples/pi-coding-agent-extension/package.json +++ b/examples/pi-coding-agent-extension/package.json @@ -1,6 +1,6 @@ { "name": "openviking-pi-extension", - "version": "0.4.31", + "version": "0.4.32", "description": "OpenViking memory and context extension for the pi coding agent", "private": true, "type": "module", From 89598b09ef0b7d977523c7d33784a979d16b7791 Mon Sep 17 00:00:00 2001 From: Oliver Mee <102673257+oliver-mee@users.noreply.github.com> Date: Wed, 18 Nov 2026 13:16:16 +0800 Subject: [PATCH 2/5] fix(opencode): emit JSON-only diagnostics over native RPC --- examples/opencode-plugin/lib/diagnostics.mjs | 2 +- examples/opencode-plugin/tests/diagnostics.test.mjs | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/examples/opencode-plugin/lib/diagnostics.mjs b/examples/opencode-plugin/lib/diagnostics.mjs index f8709ca275d..658bc0c5e49 100644 --- a/examples/opencode-plugin/lib/diagnostics.mjs +++ b/examples/opencode-plugin/lib/diagnostics.mjs @@ -72,7 +72,7 @@ export async function diagnoseOpenCode({ ctx, config, pluginRoot = "", offline = function sanitize(value) { if (typeof value === "string") return redact(value) if (Array.isArray(value)) return value.map(sanitize) - if (value && typeof value === "object") return Object.fromEntries(Object.entries(value).map(([key, v]) => [key, sanitize(v)])) + if (value && typeof value === "object") return Object.fromEntries(Object.entries(value).filter(([, v]) => v !== undefined).map(([key, v]) => [key, sanitize(v)])) return value } return sanitize(result) diff --git a/examples/opencode-plugin/tests/diagnostics.test.mjs b/examples/opencode-plugin/tests/diagnostics.test.mjs index ffb0efd978a..035e1cf1514 100644 --- a/examples/opencode-plugin/tests/diagnostics.test.mjs +++ b/examples/opencode-plugin/tests/diagnostics.test.mjs @@ -26,6 +26,7 @@ test("disabled, unsupported and failed native inventories remain distinct", asyn assert.equal(disabled.capture.state, "disabled") const unsupported = await diagnoseOpenCode({ config, offline: true }) assert.equal(unsupported.skills.state, "unsupported") + assert.deepEqual(unsupported, JSON.parse(JSON.stringify(unsupported)), "native RPC output must contain only JSON values") const failed = await diagnoseOpenCode({ ctx: { ...ctx, skill: { list: async () => { throw new Error("permission denied secret-fixture-key") } } }, config, offline: true }) assert.equal(failed.skills.state, "error") assert.match(failed.skills.error, /permission denied/) From c37ddf0a60f87bb63526d95d747974064703227a Mon Sep 17 00:00:00 2001 From: Oliver Mee <102673257+oliver-mee@users.noreply.github.com> Date: Wed, 18 Nov 2026 13:11:20 +0800 Subject: [PATCH 3/5] feat(opencode): add native terminal controls for OpenViking --- examples/opencode-plugin/README.md | 33 +++- .../opencode-plugin/lib/controls-contract.mjs | 13 ++ examples/opencode-plugin/lib/tui-controls.mjs | 151 ++++++++++++++++++ examples/opencode-plugin/lib/v2-controls.mjs | 35 ++-- .../lib/v2-recall-inspector.mjs | 46 ++++++ examples/opencode-plugin/package.json | 11 +- .../opencode-plugin/scripts/check-tui.mjs | 14 ++ .../tests/tui-controls.test.mjs | 136 ++++++++++++++++ examples/opencode-plugin/tui.tsx | 27 ++++ 9 files changed, 443 insertions(+), 23 deletions(-) create mode 100644 examples/opencode-plugin/lib/controls-contract.mjs create mode 100644 examples/opencode-plugin/lib/tui-controls.mjs create mode 100644 examples/opencode-plugin/lib/v2-recall-inspector.mjs create mode 100644 examples/opencode-plugin/scripts/check-tui.mjs create mode 100644 examples/opencode-plugin/tests/tui-controls.test.mjs create mode 100644 examples/opencode-plugin/tui.tsx diff --git a/examples/opencode-plugin/README.md b/examples/opencode-plugin/README.md index c699f6b6a2c..66890496831 100644 --- a/examples/opencode-plugin/README.md +++ b/examples/opencode-plugin/README.md @@ -282,6 +282,7 @@ The V2 server registers RPC `openviking.controls` for a native TUI/client consum | Method | Input | Result | | --- | --- | --- | | `status`, `doctor` | `{ "offline": true }` (optional boolean) | `schemaVersion: 1`, installation, MCP, skills, connection, capture, effective config, findings (`sections`), `text`, `exitCode` | +| `recall` | `{ "sessionID": "" }` | Stored OpenViking prompt context with source references, where available | | `commit` | `{ "sessionID": "" }` | `status`, `traceId` when available, `extraction` | Read methods return only selected configuration fields and redact credentials. Inventory @@ -297,8 +298,30 @@ recovery before retrying. Auth/network errors remain failures (`operation_failed and HTTP acceptance returns `extraction: "not_verified"`, never completed extraction. Automatic lifecycle commits retain their existing retry behavior. -Visible `/ov status`, `/ov doctor` and `/ov commit` controls require the TUI consumer. -OpenCode V2 server command callbacks return no display value; writing a synthetic session -message merely to show diagnostics would alter conversation history and contaminate capture. -The server therefore exposes RPC rather than registering silent commands. The consumer -should show read results in native UI and invoke `commit` only after intentional user action. +### Terminal companion (OpenCode V2) + +The package exports an optional `./tui` part. OpenCode loads it alongside the server +part in its terminal UI. Headless clients use the server entrypoint without UI imports. +OpenCode supplies the Solid/OpenTUI runtime. + +- `/ov` opens the control picker. +- `/ov status` and `/ov doctor` show read-only, scrollable native dialogs. +- `/ov recall` shows recent OpenViking context stored with the current session. +- `/ov commit` confirms before sending current-session activity to OpenViking. + Changing sessions dismisses the original intent. + +The footer shows the last requested connection/capture result. It starts `unchecked`; +run status or Doctor to refresh it. No diagnostics are added to chat history. + +The recall inspector reads saved prompt metadata or the plugin's replay ledger when +available. It exposes at most ten recent records, bounded text and source references. +Stored context can be absent or incomplete and does not prove what reached a model. +Live pending requests, wait budgets and runtime errors are unavailable here. + +To disable just the terminal companion, add the following filter to OpenCode's `cli.json`: + +```json +{ "plugins": ["*", "-openviking.tui"] } +``` + +Run `pnpm run check:tui` for a Bun TSX build and `pnpm test` for command/RPC coverage. diff --git a/examples/opencode-plugin/lib/controls-contract.mjs b/examples/opencode-plugin/lib/controls-contract.mjs new file mode 100644 index 00000000000..c566c5671a2 --- /dev/null +++ b/examples/opencode-plugin/lib/controls-contract.mjs @@ -0,0 +1,13 @@ +const sessionInput = { type: "object", properties: { sessionID: { type: "string", minLength: 1 } }, required: ["sessionID"], additionalProperties: false } +const readInput = { type: "object", properties: { offline: { type: "boolean" } }, additionalProperties: false } +// JSON Schema is the portable definition accepted by both plugin hosts. +export const OPENVIKING_CONTROLS = { + id: "openviking.controls", + methods: { + status: { input: readInput, output: { type: "object" } }, + doctor: { input: readInput, output: { type: "object" } }, + recall: { input: sessionInput, output: { type: "object" }, errors: { operation_failed: { type: "object" } } }, + commit: { input: sessionInput, output: { type: "object" }, errors: { operation_failed: { type: "object" } } }, + }, + events: {}, +} diff --git a/examples/opencode-plugin/lib/tui-controls.mjs b/examples/opencode-plugin/lib/tui-controls.mjs new file mode 100644 index 00000000000..9ce12cf0ae1 --- /dev/null +++ b/examples/opencode-plugin/lib/tui-controls.mjs @@ -0,0 +1,151 @@ +import { OPENVIKING_CONTROLS } from "./controls-contract.mjs" + +const ACTIONS = ["status", "doctor", "recall", "commit"] +const COMMIT_MESSAGES = { + accepted: "Commit accepted. Memory extraction completion has not been verified.", + disabled: "Capture is disabled for this session. Nothing was committed.", + no_activity: "No captured activity for this session. Nothing was committed.", + pending_capture: "Capture delivery is pending. Resolve it before committing again.", + queued: "Commit queued for retry. Memory extraction has not started.", + not_found: "The OpenViking session was not found. Nothing was committed.", + skipped: "Commit skipped. Memory extraction has not started.", +} + +// UI text must never interpret terminal controls or echo arbitrary RPC errors. +export function displayText(value) { + return String(value ?? "").replace(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/g, "") +} + +export function statusText(report) { + return [ + `Connection: ${report.connection.state}`, + `Plugin: ${report.installation.state}; MCP: ${report.mcp.state}; skills: ${report.skills.state}`, + `Capture: ${report.capture.state} (persisted activity across this location)`, + `Pending messages: ${report.capture.pendingMessages ?? "unavailable"}`, + `Last accepted commit: ${report.capture.lastCommitAcceptedAt ? new Date(report.capture.lastCommitAcceptedAt).toISOString() : "unavailable"}`, + "An accepted commit does not establish completed memory extraction.", + "Use /ov doctor for checks or /ov recall for stored context.", + ].join("\n") +} + +export function recallText(view) { + const lines = [ + `Session: ${view.sessionID}`, + `Recall: ${view.state}; source: ${view.source ?? "unavailable"}`, + `Pending: ${view.pending === null ? "unavailable" : JSON.stringify(view.pending)}`, + "Live runtime error: unavailable", + ...(view.error ? [`Inspection error: ${view.error}`] : []), + ...(view.limitations ?? []), + ] + for (const turn of view.turns ?? []) { + lines.push("", `Turn: ${turn.messageID}${turn.truncated ? " (truncated)" : ""}${turn.redacted ? " (credentials redacted)" : ""}`, + `Sources: ${turn.sources?.join(", ") || "not recorded"}`, turn.text) + } + return lines.join("\n") +} + +/** TUI-local commands; every mutation requires the current session and confirmation. */ +export function startTuiControls(context, { renderDialog, renderStatus, updateStatus }) { + const rpc = context.client.rpc(OPENVIKING_CONTROLS) + const controller = new AbortController() + let active = false + let disposed = false + let generation = 0 + let dialogOwned = false + let dialogOpen = false + let dialogID = 0 + const location = () => context.location ?? context.data.location.default() + const currentSession = () => { + const route = context.ui.router.current() + return route.type === "session" ? route.sessionID : undefined + } + const show = (title, text) => { + if (disposed) return + const id = ++dialogID + dialogOwned = true + dialogOpen = true + context.ui.dialog.show(() => renderDialog(title, displayText(text)), () => { + if (id !== dialogID) return + dialogOpen = false + dialogOwned = false + }) + context.ui.dialog.set({ size: "large" }) + } + const call = (action, input) => rpc[action](input, { location: location(), signal: controller.signal }) + const run = async (action) => { + if (disposed || active) return + if (!ACTIONS.includes(action)) { + show("OpenViking", "Use /ov status, /ov doctor, /ov recall or /ov commit.") + return + } + active = true + const request = ++generation + try { + const sessionID = currentSession() + if ((action === "commit" || action === "recall") && !sessionID) { + show("OpenViking", "Open a session first. This control only applies to the current session.") + return + } + if (action === "commit") { + dialogID++ + dialogOpen = false + dialogOwned = true + const confirmed = await context.ui.dialog.confirm({ title: "Commit current session?", + message: "Send eligible captured activity from this session to OpenViking for memory extraction? This writes to the server.", + label: { confirm: "Commit", cancel: "Cancel" } }) + dialogOwned = false + if (disposed || !confirmed) return + if (currentSession() !== sessionID) { + show("OpenViking", "The current session changed. Run /ov commit again in the intended session.") + return + } + } + show(`OpenViking ${action}`, "Loading…") + updateStatus(`OV: ${action}…`) + const result = await call(action, action === "recall" || action === "commit" ? { sessionID } : {}) + if (disposed || request !== generation) return + updateStatus(action === "status" || action === "doctor" + ? `OV: ${result.connection.state} · capture ${result.capture.state}` : "OV: /ov status to refresh") + // A dismissed dialog must not reopen when its network request finishes. + if (!dialogOpen || ((action === "recall" || action === "commit") && currentSession() !== sessionID)) return + show(`OpenViking ${action}`, action === "status" ? statusText(result) + : action === "doctor" ? result.text + : action === "recall" ? recallText(result) + : COMMIT_MESSAGES[result.status] ?? "Commit returned an unsupported result. Run /ov doctor.") + } catch (error) { + if (disposed || controller.signal.aborted) return + updateStatus("OV: unavailable · /ov doctor") + if (dialogOpen) { + const kind = ["operation_failed", "rpc.not_found", "rpc.method_not_found"].includes(error?.type) ? ` (${error.type})` : "" + show("OpenViking unavailable", `The OpenViking control could not complete${kind}. Check that the server plugin is enabled and connected, then run /ov doctor. No extraction completion is implied.`) + } + } finally { + active = false + } + } + context.keymap.layer(() => ({ + commands: [{ id: "openviking.controls", title: "OpenViking controls", group: "OpenViking", palette: true, + slash: { name: "ov", arguments: true }, run: async (input) => { + if (disposed || active) return + const action = input?.trim() + if (action) return run(action) + dialogID++ + dialogOpen = false + dialogOwned = true + const selected = await context.ui.dialog.select({ title: "OpenViking", options: ACTIONS.map((value) => ({ + title: value === "commit" ? "Commit current session…" : value[0].toUpperCase() + value.slice(1), value, + })) }) + dialogOwned = false + if (selected) await run(selected) + } }], + })) + const stopStatus = context.ui.slot({ append: "prompt.footer.status", render: renderStatus }) + return () => { + disposed = true + generation++ + controller.abort() + stopStatus() + if (dialogOwned) context.ui.dialog.clear() + // OpenCode owns the keymap layer and removes it on reload/disable. + } +} diff --git a/examples/opencode-plugin/lib/v2-controls.mjs b/examples/opencode-plugin/lib/v2-controls.mjs index 0885a6a7365..1b9729add9a 100644 --- a/examples/opencode-plugin/lib/v2-controls.mjs +++ b/examples/opencode-plugin/lib/v2-controls.mjs @@ -1,17 +1,17 @@ import { diagnoseOpenCode, sanitizeDiagnosticText } from "./diagnostics.mjs" import { isCaptureEnabled } from "./shared/capture-utils.mjs" -const sessionInput = { type: "object", properties: { sessionID: { type: "string", minLength: 1 } }, required: ["sessionID"], additionalProperties: false } -const readInput = { type: "object", properties: { offline: { type: "boolean" } }, additionalProperties: false } -// JSON Schema is the portable definition accepted by both plugin hosts. -export const OPENVIKING_CONTROLS = { - id: "openviking.controls", - methods: { - status: { input: readInput, output: { type: "object" } }, - doctor: { input: readInput, output: { type: "object" } }, - commit: { input: sessionInput, output: { type: "object" }, errors: { operation_failed: { type: "object" } } }, - }, - events: {}, +import { inspectV2Recall } from "./v2-recall-inspector.mjs" +import { OPENVIKING_CONTROLS } from "./controls-contract.mjs" +export { OPENVIKING_CONTROLS } from "./controls-contract.mjs" + +async function getOwnedSession(ctx, sessionID) { + const session = await ctx.session.get({ sessionID }) + if (session?.location?.directory !== ctx.location.directory || + (ctx.location.project?.id && session.projectID !== ctx.location.project.id)) { + throw new Error("Session belongs to another OpenCode location") + } + return session } export async function registerV2Controls(ctx, runtime, { pluginRoot, serializeSession, captureCurrent }) { @@ -20,14 +20,21 @@ export async function registerV2Controls(ctx, runtime, { pluginRoot, serializeSe await ctx.rpc.register(OPENVIKING_CONTROLS, { status: diagnose, doctor: diagnose, + recall: async ({ sessionID }, { error: rpcError } = {}) => { + try { + await getOwnedSession(ctx, sessionID) + return await inspectV2Recall(ctx, runtime.config, sessionID) + } catch (error) { + if (!rpcError) throw error + return rpcError("operation_failed", "Could not inspect this session's stored OpenViking prompt context", {}) + } + }, commit: async ({ sessionID }, { signal, error: rpcError } = {}) => { try { signal?.throwIfAborted() if (!isCaptureEnabled(runtime.config)) return { status: "disabled", extraction: "not_started" } // Caller selects its current session; never flushAll or accept an OV id. - const session = await ctx.session.get({ sessionID }) - if (session.location.directory !== ctx.location.directory || - (ctx.location.project?.id && session.projectID !== ctx.location.project.id)) throw new Error("Session belongs to another OpenCode location") + const session = await getOwnedSession(ctx, sessionID) if (runtime.config.skipSubagentSessions && session.parentID) return { status: "disabled", extraction: "not_started" } return await serializeSession(async () => { await runtime.ready diff --git a/examples/opencode-plugin/lib/v2-recall-inspector.mjs b/examples/opencode-plugin/lib/v2-recall-inspector.mjs new file mode 100644 index 00000000000..8317909ba85 --- /dev/null +++ b/examples/opencode-plugin/lib/v2-recall-inspector.mjs @@ -0,0 +1,46 @@ +import { sanitizeDiagnosticText } from "./diagnostics.mjs" + +/** Inspect only the context OpenViking already stored for this session. */ +export async function inspectV2Recall(ctx, config, sessionID) { + const view = { schemaVersion: 1, sessionID, state: "unavailable", source: null, + turns: [], pending: null, error: null, + limitations: ["Live pending requests, wait budgets and runtime errors are not exposed.", + "Only stored context is shown; the latest unsaved turn may be absent."] } + + let entries + try { + const ledger = await ctx.storage?.get?.(`recall-ledger/${sessionID}`) + if (ledger != null) { + if (ledger.version !== 1 || !Array.isArray(ledger.entries) || ledger.entries.some((entry) => + !Array.isArray(entry) || typeof entry[0] !== "string" || typeof entry[1] !== "string")) { + return { ...view, state: "error", error: "Unsupported or invalid replay ledger." } + } + entries = ledger.entries.slice(-10) + view.source = "persisted_replay_ledger" + } else if (ctx.session?.context) { + const messages = await ctx.session.context({ sessionID }) + if (!Array.isArray(messages)) throw new Error("Unexpected session context") + entries = messages.filter((message) => message.type === "user" && typeof message.id === "string" && + Array.isArray(message.metadata?.openviking?.context)).slice(-10).map((message) => + [message.id, message.metadata.openviking.context.filter((block) => typeof block === "string").join("\n\n")]) + view.source = "stored_prompt_metadata" + } + } catch { + return { ...view, state: "error", error: "Cannot read stored OpenViking prompt context." } + } + if (!entries?.length) { + view.limitations.push("No stored context is available for this session. This does not establish what the model received.") + return view + } + let budget = 60000 + view.turns = entries.map(([messageID, original]) => { + const redacted = sanitizeDiagnosticText(config, original) + const text = redacted.slice(0, Math.min(12000, budget)) + budget -= text.length + return { messageID, text, redacted: redacted !== original, truncated: text.length < redacted.length, + sources: [...new Set(text.match(/viking:\/\/[^\s<>"'`\]\)]+/g) ?? [])] } + }) + view.state = "available" + view.limitations.push("At most the latest 10 persisted turns and 60,000 characters are shown; configured credentials are redacted.") + return view +} diff --git a/examples/opencode-plugin/package.json b/examples/opencode-plugin/package.json index 584ccedc7a4..ee807508ada 100644 --- a/examples/opencode-plugin/package.json +++ b/examples/opencode-plugin/package.json @@ -1,6 +1,6 @@ { "name": "@openviking/opencode-plugin", - "version": "0.5.29", + "version": "0.5.30", "author": "@openviking", "description": "Unified OpenCode plugin for OpenViking repository retrieval and long-term memory", "type": "module", @@ -11,10 +11,12 @@ ], "exports": { ".": "./index.mjs", - "./servers/mcp-proxy.mjs": "./servers/mcp-proxy.mjs" + "./servers/mcp-proxy.mjs": "./servers/mcp-proxy.mjs", + "./tui": "./tui.tsx" }, "files": [ "index.mjs", + "tui.tsx", "lib/", "servers/", "skills/", @@ -25,8 +27,9 @@ ], "scripts": { "prepack": "node ../memory-plugin-shared/sync.mjs", - "check": "node --check index.mjs && node --check lib/config.mjs && node --check lib/mcp-config.mjs && node --check lib/runtime.mjs && node --check lib/plugin-runtime.mjs && node --check lib/v2-events.mjs && node --check lib/diagnostics.mjs && node --check lib/v2-controls.mjs && node --check scripts/ov-memory-doctor.mjs && node --check lib/v2-plugin.mjs && node --check lib/repo-context.mjs && node --check lib/memory-session.mjs && node --check lib/memory-recall.mjs && node --check lib/session-inject.mjs && node --check lib/viking-uri-guard.mjs && node --check lib/utils.mjs && node --check lib/shared/*.mjs && node --check servers/mcp-proxy.mjs && node --check scripts/setup.mjs && node --check tests/*.test.mjs", - "test": "node --test tests/*.test.mjs" + "check": "node --check index.mjs && node --check lib/config.mjs && node --check lib/mcp-config.mjs && node --check lib/runtime.mjs && node --check lib/plugin-runtime.mjs && node --check lib/v2-events.mjs && node --check lib/diagnostics.mjs && node --check lib/v2-controls.mjs && node --check lib/controls-contract.mjs && node --check lib/tui-controls.mjs && node --check lib/v2-recall-inspector.mjs && node --check scripts/ov-memory-doctor.mjs && node --check lib/v2-plugin.mjs && node --check lib/repo-context.mjs && node --check lib/memory-session.mjs && node --check lib/memory-recall.mjs && node --check lib/session-inject.mjs && node --check lib/viking-uri-guard.mjs && node --check lib/utils.mjs && node --check lib/shared/*.mjs && node --check servers/mcp-proxy.mjs && node --check scripts/setup.mjs && node --check tests/*.test.mjs", + "test": "node --test tests/*.test.mjs", + "check:tui": "node scripts/check-tui.mjs" }, "dependencies": {}, "publishConfig": { diff --git a/examples/opencode-plugin/scripts/check-tui.mjs b/examples/opencode-plugin/scripts/check-tui.mjs new file mode 100644 index 00000000000..35a882f927b --- /dev/null +++ b/examples/opencode-plugin/scripts/check-tui.mjs @@ -0,0 +1,14 @@ +// OpenCode supplies Solid/OpenTUI at runtime; syntax-check without bundling them. +import { mkdtemp, rm } from "node:fs/promises" +import { tmpdir } from "node:os" +import { join } from "node:path" +import { fileURLToPath } from "node:url" +import { spawnSync } from "node:child_process" + +const output = await mkdtemp(join(tmpdir(), "ov-tui-build-")) +try { + const result = spawnSync("bun", ["build", fileURLToPath(new URL("../tui.tsx", import.meta.url)), + "--target=bun", "--external=*", `--outfile=${join(output, "tui.js")}`], { stdio: "inherit" }) + if (result.error) throw result.error + process.exitCode = result.status ?? 1 +} finally { await rm(output, { recursive: true, force: true }) } diff --git a/examples/opencode-plugin/tests/tui-controls.test.mjs b/examples/opencode-plugin/tests/tui-controls.test.mjs new file mode 100644 index 00000000000..494f9c6318b --- /dev/null +++ b/examples/opencode-plugin/tests/tui-controls.test.mjs @@ -0,0 +1,136 @@ +import test from "node:test" +import assert from "node:assert/strict" +import { startTuiControls, displayText } from "../lib/tui-controls.mjs" +import { inspectV2Recall } from "../lib/v2-recall-inspector.mjs" +import { registerV2Controls } from "../lib/v2-controls.mjs" + +function fixture(methods = {}) { + const calls = [], dialogs = [], slots = [], layers = [] + let close, sessionID = "current", confirmed = true + const report = { connection: { state: "error" }, installation: { state: "ok" }, mcp: { state: "disabled" }, + skills: { state: "disabled" }, capture: { state: "disabled" }, text: "Doctor: disconnected", effective: { apiKey: "must-not-render" } } + const rpc = Object.fromEntries(["status", "doctor", "commit", "recall"].map((action) => [action, async (input, options) => { + calls.push({ action, input, options }) + return methods[action]?.(input, options) ?? (action === "commit" ? { status: "accepted", extraction: "not_verified" } : report) + }])) + const context = { options: {}, location: { directory: "/fixture" }, client: { rpc: () => rpc }, + keymap: { layer: (fn) => layers.push(fn()) }, + ui: { router: { current: () => sessionID ? { type: "session", sessionID } : { type: "home" } }, + slot: (slot) => { slots.push(slot); return () => slots.splice(slots.indexOf(slot), 1) }, + dialog: { set: () => {}, show: (render, onClose) => { close?.(); dialogs.push(render()); close = onClose }, + clear: () => { close?.(); close = undefined }, confirm: async () => typeof confirmed === "function" ? confirmed() : confirmed, + select: async () => "status" } } } + const start = () => startTuiControls(context, { renderDialog: (title, text) => ({ title, text }), renderStatus: () => "status", updateStatus: () => {} }) + const run = (input) => layers.at(-1).commands[0].run(input) + return { context, calls, dialogs, slots, layers, run, start, + session: (id) => { sessionID = id }, confirm: (value) => { confirmed = value }, dismiss: () => context.ui.dialog.clear() } +} + +test("TUI reads are native dialogs, disconnected/disabled states stay visible without configuration output", async () => { + const f = fixture(); const stop = f.start() + assert.deepEqual(f.layers[0].commands[0].slash, { name: "ov", arguments: true }) + await f.run("status") + assert.match(f.dialogs.at(-1).text, /Connection: error/) + assert.match(f.dialogs.at(-1).text, /MCP: disabled/) + assert.doesNotMatch(JSON.stringify(f.dialogs), /must-not-render/) + await f.run("doctor") + assert.equal(f.dialogs.at(-1).text, "Doctor: disconnected") + assert.deepEqual(f.calls.map((c) => c.action), ["status", "doctor"]) + assert.deepEqual(f.calls[0].options.location, f.context.location) + stop(); assert.equal(f.slots.length, 0) + assert.ok(f.calls[0].options.signal.aborted) +}) + +test("commit needs explicit confirmation, stays on current session, and only reports acceptance", async () => { + const f = fixture(); f.start(); f.confirm(false) + await f.run("commit"); assert.equal(f.calls.length, 0) + f.confirm(() => { f.session("changed"); return true }) + await f.run("commit"); assert.equal(f.calls.length, 0) + f.confirm(true) + await f.run("commit") + assert.deepEqual(f.calls[0].input, { sessionID: "changed" }) + assert.match(f.dialogs.at(-1).text, /accepted.*completion has not been verified/s) + f.session(null); await f.run("commit"); await f.run("recall") + assert.equal(f.calls.length, 1) +}) + +test("reload/disable abort requests, remove slot, and never resurrect dismissed dialogs", async () => { + let resolve + const f = fixture({ doctor: () => new Promise((done) => { resolve = done }) }) + const stop = f.start(); const pending = f.run("doctor") + await Promise.resolve(); f.dismiss() + resolve({ text: "late", connection: { state: "ok" }, capture: { state: "ok" } }) + await pending; assert.equal(f.dialogs.length, 1) + stop() + await f.run("status"); assert.equal(f.calls.length, 1) + // The real host disposes its keymap scope on reload; a new setup gets one layer. + f.layers.length = 0; const stopAgain = f.start() + assert.equal(f.layers.length, 1); assert.equal(f.slots.length, 1); stopAgain() + assert.equal(f.slots.length, 0) +}) + +test("disabling while commit confirmation is open prevents a late confirmation from writing", async () => { + const f = fixture(); let confirm + f.confirm(() => new Promise((resolve) => { confirm = resolve })) + const stop = f.start(); const pending = f.run("commit") + stop(); confirm(true); await pending + assert.equal(f.calls.length, 0) +}) + +test("RPC failures do not echo arbitrary error secrets or terminal escape controls", async () => { + const f = fixture({ doctor: () => { throw { type: "operation_failed", message: "Bearer secret-value" } } }) + f.start(); await f.run("doctor") + assert.match(f.dialogs.at(-1).text, /operation_failed/) + assert.doesNotMatch(JSON.stringify(f.dialogs), /secret-value/) + assert.equal(displayText("\x1b]52;clipboard\x07\nreadable"), "]52;clipboard\nreadable") +}) + +test("recall inspector reads exact persisted context with turn/source and explicit live-state limits", async () => { + const original = "Source viking://user/fixture/memories/test.md\nactual injected secret-key" + const ctx = { storage: { get: async (key) => { + assert.equal(key, "recall-ledger/current") + return { version: 1, entries: [["turn-1", original]] } + } } } + const view = await inspectV2Recall(ctx, { apiKey: "secret-key" }, "current") + assert.equal(view.state, "available"); assert.equal(view.pending, null); assert.equal(view.error, null) + assert.equal(view.turns[0].messageID, "turn-1") + assert.equal(view.turns[0].text, original.replace("secret-key", "[redacted]")) + assert.deepEqual(view.turns[0].sources, ["viking://user/fixture/memories/test.md"]) + const f = fixture({ recall: () => view }); f.start(); await f.run("recall") + assert.match(f.dialogs.at(-1).text, /Turn: turn-1/) + assert.match(f.dialogs.at(-1).text, /Pending: unavailable/) + assert.match(f.dialogs.at(-1).text, /latest unsaved turn may be absent/) + assert.equal((await inspectV2Recall({}, {}, "current")).state, "unavailable") + assert.equal((await inspectV2Recall({ storage: { get: async () => ({ version: 2 }) } }, {}, "current")).state, "error") + const bounded = await inspectV2Recall({ storage: { get: async () => ({ version: 1, entries: Array.from({ length: 40 }, (_, i) => [`turn-${i}`, "x".repeat(15000)]) }) } }, {}, "current") + assert.equal(bounded.turns.length, 10) + assert.ok(bounded.turns.reduce((n, t) => n + t.text.length, 0) <= 60000) +}) + +test("recall RPC rejects foreign sessions before reading ledger and never captures or commits", async () => { + let handlers, reads = 0 + const ctx = { location: { directory: "/here", project: { id: "a" } }, + rpc: { register: async (_, value) => { handlers = value } }, + session: { get: async () => ({ location: { directory: "/here" }, projectID: "b" }) }, + storage: { get: async () => { reads++; return undefined } } } + await registerV2Controls(ctx, { config: {} }, {}) + await assert.rejects(handlers.recall({ sessionID: "foreign" }), /another OpenCode location/) + assert.equal(reads, 0) + ctx.session.get = async () => ({ location: ctx.location, projectID: "a" }) + const view = await handlers.recall({ sessionID: "current" }) + assert.equal(view.state, "unavailable"); assert.equal(reads, 1) +}) + + +test("recall inspector uses stored prompt metadata on hosts without a replay ledger", async () => { + const view = await inspectV2Recall({ session: { context: async ({ sessionID }) => { + assert.equal(sessionID, "current") + return [ + { id: "msg_1", type: "user", text: "transcript must not surface", metadata: { openviking: { context: ["saved prompt context"] } } }, + { id: "msg_2", type: "assistant", metadata: { openviking: { context: ["assistant text"] } } }, + ] + } } }, {}, "current") + assert.equal(view.source, "stored_prompt_metadata") + assert.deepEqual(view.turns.map(({ messageID, text }) => [messageID, text]), [["msg_1", "saved prompt context"]]) + assert.doesNotMatch(JSON.stringify(view), /transcript must not surface|assistant text/) +}) diff --git a/examples/opencode-plugin/tui.tsx b/examples/opencode-plugin/tui.tsx new file mode 100644 index 00000000000..4aace5df93f --- /dev/null +++ b/examples/opencode-plugin/tui.tsx @@ -0,0 +1,27 @@ +import { Plugin } from "@opencode/plugin/tui" +import { createSignal } from "solid-js" +import { useTerminalDimensions } from "@opentui/solid" +import { startTuiControls } from "./lib/tui-controls.mjs" + +export default Plugin.define({ + id: "openviking.tui", + setup(context) { + const [status, setStatus] = createSignal("OV: unchecked · /ov") + return startTuiControls(context, { + updateStatus: setStatus, + renderStatus: () => {status()}, + renderDialog: (title: string, text: string) => { + const dimensions = useTerminalDimensions() + return ( + + {title} + + {text} + + Scroll to read · esc to close + + ) + }, + }) + }, +}) From c43b250a3f57de1d001024dd43822f11acae8ac1 Mon Sep 17 00:00:00 2001 From: Oliver Mee <102673257+oliver-mee@users.noreply.github.com> Date: Wed, 18 Nov 2026 17:18:06 +0800 Subject: [PATCH 4/5] fix(opencode): make the native OpenViking picker draft safe --- .../scripts/shared/doctor-core.mjs | 22 +++-- .../scripts/shared/doctor-core.mjs | 22 +++-- .../memory-plugin-shared/lib/doctor-core.mjs | 22 +++-- examples/opencode-plugin/README.md | 13 ++- examples/opencode-plugin/lib/diagnostics.mjs | 20 +++-- examples/opencode-plugin/lib/tui-controls.mjs | 81 ++++++++----------- examples/opencode-plugin/lib/v2-controls.mjs | 4 +- .../lib/v2-recall-inspector.mjs | 12 +-- .../tests/diagnostics.test.mjs | 42 ++++++++++ .../tests/tui-controls.test.mjs | 32 ++++---- examples/opencode-plugin/tui.tsx | 4 - 11 files changed, 160 insertions(+), 114 deletions(-) diff --git a/examples/claude-code-memory-plugin/scripts/shared/doctor-core.mjs b/examples/claude-code-memory-plugin/scripts/shared/doctor-core.mjs index c5faf452a90..01848a2cb1e 100644 --- a/examples/claude-code-memory-plugin/scripts/shared/doctor-core.mjs +++ b/examples/claude-code-memory-plugin/scripts/shared/doctor-core.mjs @@ -453,13 +453,13 @@ export function classifyFetchError(err) { return { kind: "other", hint: message }; } -export async function httpProbe({ url, method = "GET", headers = {}, body, timeoutMs = 5000 }) { +export async function httpProbe({ url, method = "GET", headers = {}, body, timeoutMs = 5000, signal }) { const controller = new AbortController(); const timer = setTimeout(() => controller.abort(), timeoutMs); const t0 = Date.now(); const out = { url, method, ok: false, status: 0, latencyMs: 0, text: "", json: null, headers: {}, error: "", errorKind: "", errorHint: "" }; try { - const res = await fetch(url, { method, headers, body, signal: controller.signal, redirect: "manual" }); + const res = await fetch(url, { method, headers, body, signal: signal ? AbortSignal.any([signal, controller.signal]) : controller.signal, redirect: "manual" }); out.status = res.status; out.ok = res.ok; out.latencyMs = Date.now() - t0; @@ -510,25 +510,31 @@ export function serverErrorMessage(probe) { * fsLs GET /api/v1/fs/ls?uri=viking://~/memories — tenant-data authorization + resolved user space * mcp POST /mcp tools/list — what the MCP proxy forwards */ -export async function probeOpenViking(conn, { timeoutMs = 5000, mcp = true } = {}) { +export async function probeOpenViking(conn, { timeoutMs = 5000, mcp = true, signal } = {}) { + const probe = async (params) => { + signal?.throwIfAborted(); + const result = await httpProbe({ ...params, signal }); + signal?.throwIfAborted(); + return result; + }; const base = String(conn.baseUrl || "").replace(/\/+$/, ""); const out = {}; - out.health = await httpProbe({ url: `${base}/health`, timeoutMs, headers: conn.userAgent ? { "User-Agent": conn.userAgent } : {} }); + out.health = await probe({ url: `${base}/health`, timeoutMs, headers: conn.userAgent ? { "User-Agent": conn.userAgent } : {} }); if (out.health.error && out.health.errorKind !== "other") { // Hard network failure: the rest of the ladder would fail identically. return out; } if (conn.apiKey || conn.account || conn.user || Object.keys(conn.extraHeaders ?? {}).length) { - out.healthAuth = await httpProbe({ url: `${base}/health`, timeoutMs, headers: authHeaders(conn) }); + out.healthAuth = await probe({ url: `${base}/health`, timeoutMs, headers: authHeaders(conn) }); } - out.systemStatus = await httpProbe({ url: `${base}/api/v1/system/status`, timeoutMs, headers: authHeaders(conn) }); - out.fsLs = await httpProbe({ + out.systemStatus = await probe({ url: `${base}/api/v1/system/status`, timeoutMs, headers: authHeaders(conn) }); + out.fsLs = await probe({ url: `${base}/api/v1/fs/ls?uri=${encodeURIComponent("viking://~/memories")}&output=original`, timeoutMs, headers: authHeaders(conn), }); if (mcp) { - out.mcp = await httpProbe({ + out.mcp = await probe({ url: `${base}/mcp`, method: "POST", timeoutMs: Math.max(timeoutMs, 8000), diff --git a/examples/codex-memory-plugin/scripts/shared/doctor-core.mjs b/examples/codex-memory-plugin/scripts/shared/doctor-core.mjs index c5faf452a90..01848a2cb1e 100644 --- a/examples/codex-memory-plugin/scripts/shared/doctor-core.mjs +++ b/examples/codex-memory-plugin/scripts/shared/doctor-core.mjs @@ -453,13 +453,13 @@ export function classifyFetchError(err) { return { kind: "other", hint: message }; } -export async function httpProbe({ url, method = "GET", headers = {}, body, timeoutMs = 5000 }) { +export async function httpProbe({ url, method = "GET", headers = {}, body, timeoutMs = 5000, signal }) { const controller = new AbortController(); const timer = setTimeout(() => controller.abort(), timeoutMs); const t0 = Date.now(); const out = { url, method, ok: false, status: 0, latencyMs: 0, text: "", json: null, headers: {}, error: "", errorKind: "", errorHint: "" }; try { - const res = await fetch(url, { method, headers, body, signal: controller.signal, redirect: "manual" }); + const res = await fetch(url, { method, headers, body, signal: signal ? AbortSignal.any([signal, controller.signal]) : controller.signal, redirect: "manual" }); out.status = res.status; out.ok = res.ok; out.latencyMs = Date.now() - t0; @@ -510,25 +510,31 @@ export function serverErrorMessage(probe) { * fsLs GET /api/v1/fs/ls?uri=viking://~/memories — tenant-data authorization + resolved user space * mcp POST /mcp tools/list — what the MCP proxy forwards */ -export async function probeOpenViking(conn, { timeoutMs = 5000, mcp = true } = {}) { +export async function probeOpenViking(conn, { timeoutMs = 5000, mcp = true, signal } = {}) { + const probe = async (params) => { + signal?.throwIfAborted(); + const result = await httpProbe({ ...params, signal }); + signal?.throwIfAborted(); + return result; + }; const base = String(conn.baseUrl || "").replace(/\/+$/, ""); const out = {}; - out.health = await httpProbe({ url: `${base}/health`, timeoutMs, headers: conn.userAgent ? { "User-Agent": conn.userAgent } : {} }); + out.health = await probe({ url: `${base}/health`, timeoutMs, headers: conn.userAgent ? { "User-Agent": conn.userAgent } : {} }); if (out.health.error && out.health.errorKind !== "other") { // Hard network failure: the rest of the ladder would fail identically. return out; } if (conn.apiKey || conn.account || conn.user || Object.keys(conn.extraHeaders ?? {}).length) { - out.healthAuth = await httpProbe({ url: `${base}/health`, timeoutMs, headers: authHeaders(conn) }); + out.healthAuth = await probe({ url: `${base}/health`, timeoutMs, headers: authHeaders(conn) }); } - out.systemStatus = await httpProbe({ url: `${base}/api/v1/system/status`, timeoutMs, headers: authHeaders(conn) }); - out.fsLs = await httpProbe({ + out.systemStatus = await probe({ url: `${base}/api/v1/system/status`, timeoutMs, headers: authHeaders(conn) }); + out.fsLs = await probe({ url: `${base}/api/v1/fs/ls?uri=${encodeURIComponent("viking://~/memories")}&output=original`, timeoutMs, headers: authHeaders(conn), }); if (mcp) { - out.mcp = await httpProbe({ + out.mcp = await probe({ url: `${base}/mcp`, method: "POST", timeoutMs: Math.max(timeoutMs, 8000), diff --git a/examples/memory-plugin-shared/lib/doctor-core.mjs b/examples/memory-plugin-shared/lib/doctor-core.mjs index c39c3a52db4..3e7caa63b96 100644 --- a/examples/memory-plugin-shared/lib/doctor-core.mjs +++ b/examples/memory-plugin-shared/lib/doctor-core.mjs @@ -452,13 +452,13 @@ export function classifyFetchError(err) { return { kind: "other", hint: message }; } -export async function httpProbe({ url, method = "GET", headers = {}, body, timeoutMs = 5000 }) { +export async function httpProbe({ url, method = "GET", headers = {}, body, timeoutMs = 5000, signal }) { const controller = new AbortController(); const timer = setTimeout(() => controller.abort(), timeoutMs); const t0 = Date.now(); const out = { url, method, ok: false, status: 0, latencyMs: 0, text: "", json: null, headers: {}, error: "", errorKind: "", errorHint: "" }; try { - const res = await fetch(url, { method, headers, body, signal: controller.signal, redirect: "manual" }); + const res = await fetch(url, { method, headers, body, signal: signal ? AbortSignal.any([signal, controller.signal]) : controller.signal, redirect: "manual" }); out.status = res.status; out.ok = res.ok; out.latencyMs = Date.now() - t0; @@ -509,25 +509,31 @@ export function serverErrorMessage(probe) { * fsLs GET /api/v1/fs/ls?uri=viking://~/memories — tenant-data authorization + resolved user space * mcp POST /mcp tools/list — what the MCP proxy forwards */ -export async function probeOpenViking(conn, { timeoutMs = 5000, mcp = true } = {}) { +export async function probeOpenViking(conn, { timeoutMs = 5000, mcp = true, signal } = {}) { + const probe = async (params) => { + signal?.throwIfAborted(); + const result = await httpProbe({ ...params, signal }); + signal?.throwIfAborted(); + return result; + }; const base = String(conn.baseUrl || "").replace(/\/+$/, ""); const out = {}; - out.health = await httpProbe({ url: `${base}/health`, timeoutMs, headers: conn.userAgent ? { "User-Agent": conn.userAgent } : {} }); + out.health = await probe({ url: `${base}/health`, timeoutMs, headers: conn.userAgent ? { "User-Agent": conn.userAgent } : {} }); if (out.health.error && out.health.errorKind !== "other") { // Hard network failure: the rest of the ladder would fail identically. return out; } if (conn.apiKey || conn.account || conn.user || Object.keys(conn.extraHeaders ?? {}).length) { - out.healthAuth = await httpProbe({ url: `${base}/health`, timeoutMs, headers: authHeaders(conn) }); + out.healthAuth = await probe({ url: `${base}/health`, timeoutMs, headers: authHeaders(conn) }); } - out.systemStatus = await httpProbe({ url: `${base}/api/v1/system/status`, timeoutMs, headers: authHeaders(conn) }); - out.fsLs = await httpProbe({ + out.systemStatus = await probe({ url: `${base}/api/v1/system/status`, timeoutMs, headers: authHeaders(conn) }); + out.fsLs = await probe({ url: `${base}/api/v1/fs/ls?uri=${encodeURIComponent("viking://~/memories")}&output=original`, timeoutMs, headers: authHeaders(conn), }); if (mcp) { - out.mcp = await httpProbe({ + out.mcp = await probe({ url: `${base}/mcp`, method: "POST", timeoutMs: Math.max(timeoutMs, 8000), diff --git a/examples/opencode-plugin/README.md b/examples/opencode-plugin/README.md index 66890496831..9ed1c5bac15 100644 --- a/examples/opencode-plugin/README.md +++ b/examples/opencode-plugin/README.md @@ -304,14 +304,11 @@ The package exports an optional `./tui` part. OpenCode loads it alongside the se part in its terminal UI. Headless clients use the server entrypoint without UI imports. OpenCode supplies the Solid/OpenTUI runtime. -- `/ov` opens the control picker. -- `/ov status` and `/ov doctor` show read-only, scrollable native dialogs. -- `/ov recall` shows recent OpenViking context stored with the current session. -- `/ov commit` confirms before sending current-session activity to OpenViking. - Changing sessions dismisses the original intent. - -The footer shows the last requested connection/capture result. It starts `unchecked`; -run status or Doctor to refresh it. No diagnostics are added to chat history. +Select `/ov` from slash completion in the full terminal UI, or search for +**OpenViking controls** in the command palette. The picker offers **Doctor** +(Esc cancels a pending check), **View saved recall** (newest first), and +**Commit current session…** (requires confirmation in that session). +Diagnostics are not added to chat history. The recall inspector reads saved prompt metadata or the plugin's replay ledger when available. It exposes at most ten recent records, bounded text and source references. diff --git a/examples/opencode-plugin/lib/diagnostics.mjs b/examples/opencode-plugin/lib/diagnostics.mjs index 658bc0c5e49..47dd7132c64 100644 --- a/examples/opencode-plugin/lib/diagnostics.mjs +++ b/examples/opencode-plugin/lib/diagnostics.mjs @@ -8,14 +8,17 @@ import { assessProbes, createReport, describeApiKey, probeOpenViking } from "./s export const BUNDLED_SKILLS = ["openviking-memory", "openviking-skills", "ov-experience-memory", "openviking-rule-search"] // Select fields rather than serializing effective config, skill bodies or transcripts. -export async function diagnoseOpenCode({ ctx, config, pluginRoot = "", offline = false, timeoutMs = 5000 }) { +export async function diagnoseOpenCode({ ctx, config, pluginRoot = "", offline = false, timeoutMs = 5000, signal }) { + const deadline = AbortSignal.timeout(timeoutMs) + const bounded = signal ? AbortSignal.any([signal, deadline]) : deadline + bounded.throwIfAborted() const report = createReport() const extraHeaders = config.extraHeaders ?? parseExtraHeaders(process.env.OPENVIKING_EXTRA_HEADERS) const redact = (text) => sanitizeDiagnosticText(config, text) const inventory = async (domain) => { if (!domain?.list) return { state: "unsupported" } try { - const { data } = await domain.list() + const { data } = await domain.list(undefined, { signal: bounded }) if (!Array.isArray(data)) throw new Error("Unexpected OpenCode inventory response") return { state: "ok", data } } catch (error) { @@ -23,8 +26,10 @@ export async function diagnoseOpenCode({ ctx, config, pluginRoot = "", offline = } } const [plugins, servers, skills] = await Promise.all([inventory(ctx?.plugin), inventory(ctx?.mcp), inventory(ctx?.skill)]) + bounded.throwIfAborted() report.section("OpenCode installation") - const instances = plugins.data?.filter((p) => p.id === "openviking" || p.source?.target?.includes("@openviking/opencode-plugin") || /openviking/i.test(p.source?.path || "")) + const instances = plugins.data?.filter(({ id, source }) => + id === "openviking" || /^@openviking\/opencode-plugin(?:@.+)?$/.test(source?.target ?? "")) const installation = { state: plugins.state, hostVersion: ctx?.app?.version ?? null, instances: instances?.map((p) => ({ id: p.id, source: p.source.type, version: p.source.version ?? null, state: p.state.status })), ...(plugins.error ? { error: plugins.error } : {}) } @@ -53,14 +58,15 @@ export async function diagnoseOpenCode({ ctx, config, pluginRoot = "", offline = let connection = { state: offline ? "disabled" : "ok" } if (!offline) { const conn = { baseUrl: config.baseUrl, apiKey: config.apiKey, account: config.sendIdentityHeaders ? config.accountId : "", user: config.sendIdentityHeaders ? config.userId : "", peerId: config.effectivePeer?.peerId || config.peerId, userAgent: config.userAgent } - const probes = await probeOpenViking({ ...conn, extraHeaders }, { timeoutMs, mcp: mcp.state !== "disabled" }) + const probes = await probeOpenViking({ ...conn, extraHeaders }, { timeoutMs, mcp: mcp.state !== "disabled", signal: bounded }) const summary = assessProbes(report, probes, conn, describeApiKey(config.apiKey)) connection = { state: summary.authOk ? "ok" : "error", reachable: summary.reachable, authOk: summary.authOk, version: summary.version, mcpHttpStatus: probes.mcp?.status ?? null } } else report.info("Network probes disabled (--offline)") report.section("Capture activity") - const capture = await inspectCapture(config, pluginRoot) + const capture = await inspectCapture(config, pluginRoot, bounded) + bounded.throwIfAborted() report[capture.state === "error" ? "fail" : "info"](`Capture: ${capture.state}`, capture.error) let endpoint try { const url = new URL(config.baseUrl); url.username = ""; url.password = ""; url.search = ""; url.hash = ""; endpoint = url.href } catch { endpoint = "(invalid URL)" } @@ -94,10 +100,10 @@ export function sanitizeDiagnosticText(config, text) { }) } -async function inspectCapture(config, pluginRoot) { +async function inspectCapture(config, pluginRoot, signal) { if (!isCaptureEnabled(config)) return { state: "disabled" } try { - const data = JSON.parse(await readFile(join(resolveDataDir(pluginRoot, config), "openviking-session-state.json"), "utf8")) + const data = JSON.parse(await readFile(join(resolveDataDir(pluginRoot, config), "openviking-session-state.json"), { encoding: "utf8", signal })) const sessions = Object.values(data.sessions || {}) return { state: "ok", sessions: sessions.length, pendingMessages: sessions.reduce((n, s) => n + (s.messages || []).filter(([, m]) => !m.captured).length, 0), diff --git a/examples/opencode-plugin/lib/tui-controls.mjs b/examples/opencode-plugin/lib/tui-controls.mjs index 9ce12cf0ae1..0128f5781fb 100644 --- a/examples/opencode-plugin/lib/tui-controls.mjs +++ b/examples/opencode-plugin/lib/tui-controls.mjs @@ -1,6 +1,6 @@ import { OPENVIKING_CONTROLS } from "./controls-contract.mjs" -const ACTIONS = ["status", "doctor", "recall", "commit"] +const ACTIONS = { doctor: "Doctor", recall: "View saved recall", commit: "Commit current session…" } const COMMIT_MESSAGES = { accepted: "Commit accepted. Memory extraction completion has not been verified.", disabled: "Capture is disabled for this session. Nothing was committed.", @@ -16,24 +16,10 @@ export function displayText(value) { return String(value ?? "").replace(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/g, "") } -export function statusText(report) { - return [ - `Connection: ${report.connection.state}`, - `Plugin: ${report.installation.state}; MCP: ${report.mcp.state}; skills: ${report.skills.state}`, - `Capture: ${report.capture.state} (persisted activity across this location)`, - `Pending messages: ${report.capture.pendingMessages ?? "unavailable"}`, - `Last accepted commit: ${report.capture.lastCommitAcceptedAt ? new Date(report.capture.lastCommitAcceptedAt).toISOString() : "unavailable"}`, - "An accepted commit does not establish completed memory extraction.", - "Use /ov doctor for checks or /ov recall for stored context.", - ].join("\n") -} - export function recallText(view) { const lines = [ `Session: ${view.sessionID}`, `Recall: ${view.state}; source: ${view.source ?? "unavailable"}`, - `Pending: ${view.pending === null ? "unavailable" : JSON.stringify(view.pending)}`, - "Live runtime error: unavailable", ...(view.error ? [`Inspection error: ${view.error}`] : []), ...(view.limitations ?? []), ] @@ -45,9 +31,8 @@ export function recallText(view) { } /** TUI-local commands; every mutation requires the current session and confirmation. */ -export function startTuiControls(context, { renderDialog, renderStatus, updateStatus }) { - const rpc = context.client.rpc(OPENVIKING_CONTROLS) - const controller = new AbortController() +export function startTuiControls(context, { renderDialog }) { + let controller let active = false let disposed = false let generation = 0 @@ -59,7 +44,7 @@ export function startTuiControls(context, { renderDialog, renderStatus, updateSt const route = context.ui.router.current() return route.type === "session" ? route.sessionID : undefined } - const show = (title, text) => { + const show = (title, text, onClose) => { if (disposed) return const id = ++dialogID dialogOwned = true @@ -68,18 +53,15 @@ export function startTuiControls(context, { renderDialog, renderStatus, updateSt if (id !== dialogID) return dialogOpen = false dialogOwned = false + onClose?.() }) context.ui.dialog.set({ size: "large" }) } - const call = (action, input) => rpc[action](input, { location: location(), signal: controller.signal }) const run = async (action) => { if (disposed || active) return - if (!ACTIONS.includes(action)) { - show("OpenViking", "Use /ov status, /ov doctor, /ov recall or /ov commit.") - return - } active = true const request = ++generation + let operation try { const sessionID = currentSession() if ((action === "commit" || action === "recall") && !sessionID) { @@ -96,55 +78,56 @@ export function startTuiControls(context, { renderDialog, renderStatus, updateSt dialogOwned = false if (disposed || !confirmed) return if (currentSession() !== sessionID) { - show("OpenViking", "The current session changed. Run /ov commit again in the intended session.") + show("OpenViking", "The current session changed. Open the picker again in the intended session.") return } } - show(`OpenViking ${action}`, "Loading…") - updateStatus(`OV: ${action}…`) - const result = await call(action, action === "recall" || action === "commit" ? { sessionID } : {}) - if (disposed || request !== generation) return - updateStatus(action === "status" || action === "doctor" - ? `OV: ${result.connection.state} · capture ${result.capture.state}` : "OV: /ov status to refresh") + operation = controller = new AbortController() + show(`OpenViking: ${ACTIONS[action]}`, "Loading…", () => { + // A confirmed commit may already be accepted; closing its dialog only hides the result. + if (action === "commit") return + operation.abort() + if (request === generation) active = false + }) + const rpc = context.client.rpc(OPENVIKING_CONTROLS) + const result = await rpc[action](action === "recall" || action === "commit" ? { sessionID } : {}, + { location: location(), signal: operation.signal }) + if (disposed || request !== generation || operation.signal.aborted) return // A dismissed dialog must not reopen when its network request finishes. if (!dialogOpen || ((action === "recall" || action === "commit") && currentSession() !== sessionID)) return - show(`OpenViking ${action}`, action === "status" ? statusText(result) - : action === "doctor" ? result.text + show(`OpenViking: ${ACTIONS[action]}`, action === "doctor" ? result.text : action === "recall" ? recallText(result) - : COMMIT_MESSAGES[result.status] ?? "Commit returned an unsupported result. Run /ov doctor.") + : COMMIT_MESSAGES[result.status] ?? "Commit returned an unsupported result. Run Doctor from the OpenViking picker.") } catch (error) { - if (disposed || controller.signal.aborted) return - updateStatus("OV: unavailable · /ov doctor") + if (disposed || request !== generation || operation?.signal.aborted) return if (dialogOpen) { const kind = ["operation_failed", "rpc.not_found", "rpc.method_not_found"].includes(error?.type) ? ` (${error.type})` : "" - show("OpenViking unavailable", `The OpenViking control could not complete${kind}. Check that the server plugin is enabled and connected, then run /ov doctor. No extraction completion is implied.`) + show("OpenViking unavailable", `The OpenViking control could not complete${kind}. Check that the server plugin is enabled and connected, then retry from the picker.`) } } finally { - active = false + if (controller === operation) controller = undefined + if (request === generation) active = false } } context.keymap.layer(() => ({ - commands: [{ id: "openviking.controls", title: "OpenViking controls", group: "OpenViking", palette: true, - slash: { name: "ov", arguments: true }, run: async (input) => { - if (disposed || active) return - const action = input?.trim() - if (action) return run(action) + mode: "global", + commands: [{ id: "openviking.controls", title: "OpenViking controls (/ov)", group: "OpenViking", palette: true, + slash: { name: "ov" }, run: async () => { + if (disposed || active || dialogOwned) return dialogID++ dialogOpen = false dialogOwned = true - const selected = await context.ui.dialog.select({ title: "OpenViking", options: ACTIONS.map((value) => ({ - title: value === "commit" ? "Commit current session…" : value[0].toUpperCase() + value.slice(1), value, + const selected = await context.ui.dialog.select({ title: "OpenViking", options: Object.entries(ACTIONS).map(([value, title]) => ({ + title, value, })) }) dialogOwned = false - if (selected) await run(selected) + if (Object.hasOwn(ACTIONS, selected)) await run(selected) } }], })) - const stopStatus = context.ui.slot({ append: "prompt.footer.status", render: renderStatus }) return () => { disposed = true generation++ - controller.abort() - stopStatus() + controller?.abort() if (dialogOwned) context.ui.dialog.clear() // OpenCode owns the keymap layer and removes it on reload/disable. } diff --git a/examples/opencode-plugin/lib/v2-controls.mjs b/examples/opencode-plugin/lib/v2-controls.mjs index 1b9729add9a..991634ed4fa 100644 --- a/examples/opencode-plugin/lib/v2-controls.mjs +++ b/examples/opencode-plugin/lib/v2-controls.mjs @@ -16,7 +16,9 @@ async function getOwnedSession(ctx, sessionID) { export async function registerV2Controls(ctx, runtime, { pluginRoot, serializeSession, captureCurrent }) { if (!ctx?.rpc?.register) return - const diagnose = async (input = {}) => diagnoseOpenCode({ ctx, config: runtime.config, pluginRoot, offline: input.offline === true }) + const diagnose = async (input = {}, { signal } = {}) => diagnoseOpenCode({ + ctx, config: runtime.config, pluginRoot, offline: input.offline === true, signal, + }) await ctx.rpc.register(OPENVIKING_CONTROLS, { status: diagnose, doctor: diagnose, diff --git a/examples/opencode-plugin/lib/v2-recall-inspector.mjs b/examples/opencode-plugin/lib/v2-recall-inspector.mjs index 8317909ba85..f373eb27248 100644 --- a/examples/opencode-plugin/lib/v2-recall-inspector.mjs +++ b/examples/opencode-plugin/lib/v2-recall-inspector.mjs @@ -33,14 +33,16 @@ export async function inspectV2Recall(ctx, config, sessionID) { return view } let budget = 60000 - view.turns = entries.map(([messageID, original]) => { + for (const [messageID, original] of entries.reverse()) { + if (budget <= 0) break const redacted = sanitizeDiagnosticText(config, original) const text = redacted.slice(0, Math.min(12000, budget)) + if (!text.trim()) continue budget -= text.length - return { messageID, text, redacted: redacted !== original, truncated: text.length < redacted.length, - sources: [...new Set(text.match(/viking:\/\/[^\s<>"'`\]\)]+/g) ?? [])] } - }) - view.state = "available" + view.turns.push({ messageID, text, redacted: redacted !== original, truncated: text.length < redacted.length, + sources: [...new Set(text.match(/viking:\/\/[^\s<>"'`\]\)]+/g) ?? [])] }) + } + if (view.turns.length) view.state = "available" view.limitations.push("At most the latest 10 persisted turns and 60,000 characters are shown; configured credentials are redacted.") return view } diff --git a/examples/opencode-plugin/tests/diagnostics.test.mjs b/examples/opencode-plugin/tests/diagnostics.test.mjs index 035e1cf1514..11021d37ebb 100644 --- a/examples/opencode-plugin/tests/diagnostics.test.mjs +++ b/examples/opencode-plugin/tests/diagnostics.test.mjs @@ -19,6 +19,23 @@ test("connected MCP with missing native skills is a failure, without capture or assert.doesNotMatch(JSON.stringify(result), /secret-fixture-key/) }) +test("Doctor matches plugin identity without counting unrelated parent paths", async () => { + const local = { id: "openviking", source: { type: "local", path: "/plugins/openviking/index.mjs" }, state: { status: "active" } } + const companion = { id: "mee-toolkit", source: { type: "local", path: "/state/openviking-parity/toolkit/index.mjs" }, state: { status: "active" } } + const lookalike = { id: "lookalike", source: { type: "package", target: "@openviking/opencode-plugin-helper" }, state: { status: "active" } } + const duplicate = { id: "openviking-package", source: { type: "package", target: "@openviking/opencode-plugin@0.5.29" }, state: { status: "active" } } + const plugins = [local, companion, lookalike] + const inventory = { ...ctx, plugin: { list: async () => ({ data: plugins }) } } + const diagnose = () => diagnoseOpenCode({ ctx: inventory, config, offline: true }) + const initial = (await diagnose()).installation + assert.equal(initial.state, "ok") + assert.deepEqual(initial.instances.map(({ id }) => id), ["openviking"]) + plugins.push(duplicate) + const withDuplicate = (await diagnose()).installation + assert.equal(withDuplicate.state, "error") + assert.deepEqual(withDuplicate.instances.map(({ id }) => id), ["openviking", "openviking-package"]) +}) + test("disabled, unsupported and failed native inventories remain distinct", async () => { const disabled = await diagnoseOpenCode({ ctx, config: { ...config, mcp: { enabled: false }, autoCapture: false }, offline: true }) assert.equal(disabled.mcp.state, "disabled") @@ -61,6 +78,31 @@ test("RPC read controls never create messages or commit; intentional commit scop import { createServer } from "node:http" +test("cancelling Doctor closes the active probe and does not start another", async () => { + const requests = [] + let started, closed + const ready = new Promise((resolve) => { started = resolve }) + const disconnected = new Promise((resolve) => { closed = resolve }) + const server = createServer((req, res) => { + requests.push(req.url) + res.once("close", closed) + started() + }) + await new Promise((resolve) => server.listen(0, "localhost", resolve)) + try { + const controller = new AbortController() + const result = diagnoseOpenCode({ ctx, config: { ...config, baseUrl: `http://localhost:${server.address().port}` }, signal: controller.signal }) + await ready + controller.abort() + await assert.rejects(result, { name: "AbortError" }) + await disconnected + assert.deepEqual(requests, ["/health"]) + } finally { + server.closeAllConnections() + await new Promise((resolve) => server.close(resolve)) + } +}) + test("doctor probes authenticated MCP read operations and redacts effective config", async () => { const requests = [] const server = createServer((req, res) => { diff --git a/examples/opencode-plugin/tests/tui-controls.test.mjs b/examples/opencode-plugin/tests/tui-controls.test.mjs index 494f9c6318b..cc58d4e0660 100644 --- a/examples/opencode-plugin/tests/tui-controls.test.mjs +++ b/examples/opencode-plugin/tests/tui-controls.test.mjs @@ -6,7 +6,7 @@ import { registerV2Controls } from "../lib/v2-controls.mjs" function fixture(methods = {}) { const calls = [], dialogs = [], slots = [], layers = [] - let close, sessionID = "current", confirmed = true + let close, sessionID = "current", confirmed = true, choice const report = { connection: { state: "error" }, installation: { state: "ok" }, mcp: { state: "disabled" }, skills: { state: "disabled" }, capture: { state: "disabled" }, text: "Doctor: disconnected", effective: { apiKey: "must-not-render" } } const rpc = Object.fromEntries(["status", "doctor", "commit", "recall"].map((action) => [action, async (input, options) => { @@ -19,26 +19,24 @@ function fixture(methods = {}) { slot: (slot) => { slots.push(slot); return () => slots.splice(slots.indexOf(slot), 1) }, dialog: { set: () => {}, show: (render, onClose) => { close?.(); dialogs.push(render()); close = onClose }, clear: () => { close?.(); close = undefined }, confirm: async () => typeof confirmed === "function" ? confirmed() : confirmed, - select: async () => "status" } } } - const start = () => startTuiControls(context, { renderDialog: (title, text) => ({ title, text }), renderStatus: () => "status", updateStatus: () => {} }) - const run = (input) => layers.at(-1).commands[0].run(input) + select: async () => { context.ui.dialog.clear(); return choice } } } } + const start = () => startTuiControls(context, { renderDialog: (title, text) => ({ title, text }) }) + const run = (input) => { choice = input; return layers.at(-1).commands[0].run() } return { context, calls, dialogs, slots, layers, run, start, session: (id) => { sessionID = id }, confirm: (value) => { confirmed = value }, dismiss: () => context.ui.dialog.clear() } } test("TUI reads are native dialogs, disconnected/disabled states stay visible without configuration output", async () => { const f = fixture(); const stop = f.start() - assert.deepEqual(f.layers[0].commands[0].slash, { name: "ov", arguments: true }) - await f.run("status") - assert.match(f.dialogs.at(-1).text, /Connection: error/) - assert.match(f.dialogs.at(-1).text, /MCP: disabled/) - assert.doesNotMatch(JSON.stringify(f.dialogs), /must-not-render/) + assert.deepEqual(f.layers[0].commands[0].slash, { name: "ov" }) + assert.equal(f.layers[0].mode, "global") + assert.match(f.layers[0].commands[0].title, /\/ov/) await f.run("doctor") assert.equal(f.dialogs.at(-1).text, "Doctor: disconnected") - assert.deepEqual(f.calls.map((c) => c.action), ["status", "doctor"]) + assert.doesNotMatch(JSON.stringify(f.dialogs), /must-not-render/) + assert.deepEqual(f.calls.map((c) => c.action), ["doctor"]) assert.deepEqual(f.calls[0].options.location, f.context.location) stop(); assert.equal(f.slots.length, 0) - assert.ok(f.calls[0].options.signal.aborted) }) test("commit needs explicit confirmation, stays on current session, and only reports acceptance", async () => { @@ -46,11 +44,12 @@ test("commit needs explicit confirmation, stays on current session, and only rep await f.run("commit"); assert.equal(f.calls.length, 0) f.confirm(() => { f.session("changed"); return true }) await f.run("commit"); assert.equal(f.calls.length, 0) + f.dismiss() f.confirm(true) await f.run("commit") assert.deepEqual(f.calls[0].input, { sessionID: "changed" }) assert.match(f.dialogs.at(-1).text, /accepted.*completion has not been verified/s) - f.session(null); await f.run("commit"); await f.run("recall") + f.dismiss(); f.session(null); await f.run("commit"); f.dismiss(); await f.run("recall") assert.equal(f.calls.length, 1) }) @@ -59,20 +58,21 @@ test("reload/disable abort requests, remove slot, and never resurrect dismissed const f = fixture({ doctor: () => new Promise((done) => { resolve = done }) }) const stop = f.start(); const pending = f.run("doctor") await Promise.resolve(); f.dismiss() + assert.equal(f.calls[0].options.signal.aborted, true) resolve({ text: "late", connection: { state: "ok" }, capture: { state: "ok" } }) await pending; assert.equal(f.dialogs.length, 1) stop() await f.run("status"); assert.equal(f.calls.length, 1) // The real host disposes its keymap scope on reload; a new setup gets one layer. f.layers.length = 0; const stopAgain = f.start() - assert.equal(f.layers.length, 1); assert.equal(f.slots.length, 1); stopAgain() + assert.equal(f.layers.length, 1); assert.equal(f.slots.length, 0); stopAgain() assert.equal(f.slots.length, 0) }) test("disabling while commit confirmation is open prevents a late confirmation from writing", async () => { const f = fixture(); let confirm f.confirm(() => new Promise((resolve) => { confirm = resolve })) - const stop = f.start(); const pending = f.run("commit") + const stop = f.start(); const pending = f.run("commit"); await Promise.resolve() stop(); confirm(true); await pending assert.equal(f.calls.length, 0) }) @@ -98,12 +98,12 @@ test("recall inspector reads exact persisted context with turn/source and explic assert.deepEqual(view.turns[0].sources, ["viking://user/fixture/memories/test.md"]) const f = fixture({ recall: () => view }); f.start(); await f.run("recall") assert.match(f.dialogs.at(-1).text, /Turn: turn-1/) - assert.match(f.dialogs.at(-1).text, /Pending: unavailable/) assert.match(f.dialogs.at(-1).text, /latest unsaved turn may be absent/) assert.equal((await inspectV2Recall({}, {}, "current")).state, "unavailable") assert.equal((await inspectV2Recall({ storage: { get: async () => ({ version: 2 }) } }, {}, "current")).state, "error") const bounded = await inspectV2Recall({ storage: { get: async () => ({ version: 1, entries: Array.from({ length: 40 }, (_, i) => [`turn-${i}`, "x".repeat(15000)]) }) } }, {}, "current") - assert.equal(bounded.turns.length, 10) + assert.equal(bounded.turns[0].messageID, "turn-39") + assert.ok(bounded.turns.every(({ text }) => text.length > 0)) assert.ok(bounded.turns.reduce((n, t) => n + t.text.length, 0) <= 60000) }) diff --git a/examples/opencode-plugin/tui.tsx b/examples/opencode-plugin/tui.tsx index 4aace5df93f..01e814a13e9 100644 --- a/examples/opencode-plugin/tui.tsx +++ b/examples/opencode-plugin/tui.tsx @@ -1,15 +1,11 @@ import { Plugin } from "@opencode/plugin/tui" -import { createSignal } from "solid-js" import { useTerminalDimensions } from "@opentui/solid" import { startTuiControls } from "./lib/tui-controls.mjs" export default Plugin.define({ id: "openviking.tui", setup(context) { - const [status, setStatus] = createSignal("OV: unchecked · /ov") return startTuiControls(context, { - updateStatus: setStatus, - renderStatus: () => {status()}, renderDialog: (title: string, text: string) => { const dimensions = useTerminalDimensions() return ( From d2840f4fba10d6b4bd4e9da86233902b6729c9d4 Mon Sep 17 00:00:00 2001 From: Oliver Mee <102673257+oliver-mee@users.noreply.github.com> Date: Thu, 19 Nov 2026 13:19:46 +0800 Subject: [PATCH 5/5] fix(opencode): load packaged TUI with the host Solid runtime --- examples/opencode-plugin/README.md | 5 +++- examples/opencode-plugin/package.json | 4 +-- .../opencode-plugin/scripts/check-tui.mjs | 24 ++++++++--------- examples/opencode-plugin/tui.mjs | 27 +++++++++++++++++++ examples/opencode-plugin/tui.tsx | 23 ---------------- 5 files changed, 45 insertions(+), 38 deletions(-) create mode 100644 examples/opencode-plugin/tui.mjs delete mode 100644 examples/opencode-plugin/tui.tsx diff --git a/examples/opencode-plugin/README.md b/examples/opencode-plugin/README.md index 9ed1c5bac15..af46bb90e3e 100644 --- a/examples/opencode-plugin/README.md +++ b/examples/opencode-plugin/README.md @@ -321,4 +321,7 @@ To disable just the terminal companion, add the following filter to OpenCode's ` { "plugins": ["*", "-openviking.tui"] } ``` -Run `pnpm run check:tui` for a Bun TSX build and `pnpm test` for command/RPC coverage. +The packaged `./tui` entry uses OpenCode's OpenTUI Solid runtime directly. Run +`pnpm run check:tui` to check the export and `pnpm test` for command/RPC coverage. +After packaging changes, install the package in a clean OpenCode home and open +`/ov` → **Doctor** to verify the terminal client can render the dialog. diff --git a/examples/opencode-plugin/package.json b/examples/opencode-plugin/package.json index ee807508ada..86431324407 100644 --- a/examples/opencode-plugin/package.json +++ b/examples/opencode-plugin/package.json @@ -12,11 +12,11 @@ "exports": { ".": "./index.mjs", "./servers/mcp-proxy.mjs": "./servers/mcp-proxy.mjs", - "./tui": "./tui.tsx" + "./tui": "./tui.mjs" }, "files": [ "index.mjs", - "tui.tsx", + "tui.mjs", "lib/", "servers/", "skills/", diff --git a/examples/opencode-plugin/scripts/check-tui.mjs b/examples/opencode-plugin/scripts/check-tui.mjs index 35a882f927b..bbad5c3d66a 100644 --- a/examples/opencode-plugin/scripts/check-tui.mjs +++ b/examples/opencode-plugin/scripts/check-tui.mjs @@ -1,14 +1,14 @@ -// OpenCode supplies Solid/OpenTUI at runtime; syntax-check without bundling them. -import { mkdtemp, rm } from "node:fs/promises" -import { tmpdir } from "node:os" -import { join } from "node:path" -import { fileURLToPath } from "node:url" +// Git installs this entrypoint under node_modules without running a JSX build. +import assert from "node:assert/strict" +import { readFile } from "node:fs/promises" import { spawnSync } from "node:child_process" +import { fileURLToPath } from "node:url" -const output = await mkdtemp(join(tmpdir(), "ov-tui-build-")) -try { - const result = spawnSync("bun", ["build", fileURLToPath(new URL("../tui.tsx", import.meta.url)), - "--target=bun", "--external=*", `--outfile=${join(output, "tui.js")}`], { stdio: "inherit" }) - if (result.error) throw result.error - process.exitCode = result.status ?? 1 -} finally { await rm(output, { recursive: true, force: true }) } +const { exports, files } = JSON.parse(await readFile(new URL("../package.json", import.meta.url))) +const entry = exports["./tui"] +assert.ok(files.includes(entry.slice(2)), "Include ./tui in the package files") +const result = spawnSync("bun", ["build", fileURLToPath(new URL(`../${entry}`, import.meta.url)), + "--target=bun", "--external=*"], { encoding: "utf8" }) +if (result.error) throw result.error +assert.equal(result.status, 0, result.stderr) +assert.doesNotMatch(result.stdout, /["'](?:react|@opentui\/react)(?:\/[^"']*)?["']/) diff --git a/examples/opencode-plugin/tui.mjs b/examples/opencode-plugin/tui.mjs new file mode 100644 index 00000000000..5ec2cda92c3 --- /dev/null +++ b/examples/opencode-plugin/tui.mjs @@ -0,0 +1,27 @@ +import { Plugin } from "@opencode/plugin/tui" +import { useTerminalDimensions } from "@opentui/solid" +import { jsx } from "@opentui/solid/jsx-runtime" +import { startTuiControls } from "./lib/tui-controls.mjs" + +export default Plugin.define({ + id: "openviking.tui", + setup(context) { + return startTuiControls(context, { + renderDialog(title, text) { + const dimensions = useTerminalDimensions() + return jsx("box", { + flexDirection: "column", gap: 1, paddingLeft: 2, paddingRight: 2, paddingBottom: 1, + children: [ + jsx("text", { fg: context.theme.text.base, children: title }), + jsx("scrollbox", { + get maxHeight() { return Math.max(3, Math.min(20, dimensions().height - 12)) }, + focused: true, + children: jsx("text", { fg: context.theme.text.base, wrapMode: "word", children: text }), + }), + jsx("text", { fg: context.theme.text.muted, children: "Scroll to read · esc to close" }), + ], + }) + }, + }) + }, +}) diff --git a/examples/opencode-plugin/tui.tsx b/examples/opencode-plugin/tui.tsx deleted file mode 100644 index 01e814a13e9..00000000000 --- a/examples/opencode-plugin/tui.tsx +++ /dev/null @@ -1,23 +0,0 @@ -import { Plugin } from "@opencode/plugin/tui" -import { useTerminalDimensions } from "@opentui/solid" -import { startTuiControls } from "./lib/tui-controls.mjs" - -export default Plugin.define({ - id: "openviking.tui", - setup(context) { - return startTuiControls(context, { - renderDialog: (title: string, text: string) => { - const dimensions = useTerminalDimensions() - return ( - - {title} - - {text} - - Scroll to read · esc to close - - ) - }, - }) - }, -})