From 11a82d79e757d12029b2cc19d30610aaf14647fc Mon Sep 17 00:00:00 2001 From: ework-agent Date: Wed, 16 Sep 2026 18:25:44 +0800 Subject: [PATCH 1/7] feat(agent): register /acp command under OpenCode V2 (#809) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The /acp status command was implemented only against the legacy .server() plugin API and orphaned by the V2 migration — OpenCode 2.x loads `{id, setup}` and never calls `.server()`, so /acp never registered (native mode looked "inactive"). Register /acp in the shared createOpencodeV2Setup factory so BOTH launcher and native modes surface it. API verified against @opencode/cli v2.0.3 source: - ctx.command.transform(editor.add({name, description, execute})) — commands carry an execute(input) handler (input.sessionID is provided). - ctx.session.synthetic({sessionID, text}) — inserts a synthetic message that does NOT trigger a model turn (the V2 replacement for the legacy ignored no-reply prompt). /acp fetches /__bili/plugin/status?conversationId=&fallback=latest and renders the panel (or idle/error notice) via synthetic. Inert-safe on surfaces without ctx.command; TUI-only (`run` dispatches no slash commands). - src/agent/opencode-v2.ts: add command seam to V2PluginContext + V2CommandEditor types; register /acp after tool registration. - tests/opencode-v2.test.ts: fake ctx gains command.transform + session.synthetic; fake proxy serves /status; 2 new tests (panel render, no-proxy notice). typecheck clean; full suite 1654 pass / 0 fail / 2 skip (win32-only); build OK; dist markers confirmed in both agent entries. Refs #809. --- src/agent/opencode-v2.ts | 71 ++++++++++++++++++++++++++++++++++++++- tests/opencode-v2.test.ts | 63 ++++++++++++++++++++++++++++++++++ 2 files changed, 133 insertions(+), 1 deletion(-) diff --git a/src/agent/opencode-v2.ts b/src/agent/opencode-v2.ts index 821efe0b85..07b66190fe 100644 --- a/src/agent/opencode-v2.ts +++ b/src/agent/opencode-v2.ts @@ -41,7 +41,7 @@ // available on all observed surfaces. import { ACP_TOOLS_OPENAI, ABSORB_TOOL_OPENAI } from "../compress-tool.js"; -import { forwardTool, proxyBaseFromEnv, proxyBaseFromUrl, reportCompactionBoundary } from "./shared.js"; +import { fetchProxyVersion, forwardTool, proxyBaseFromEnv, proxyBaseFromUrl, reportCompactionBoundary } from "./shared.js"; type V2Registration = { dispose?: () => void | Promise }; @@ -65,6 +65,19 @@ interface V2ToolEditor { }): void; } +interface V2CommandInvocation { + sessionID?: unknown; + [key: string]: unknown; +} + +interface V2CommandEditor { + add(def: { + name: string; + description?: string; + execute: (input: V2CommandInvocation) => Promise; + }): void; +} + interface V2CatalogModelEntry { providerID?: unknown; id?: unknown; @@ -74,10 +87,14 @@ interface V2CatalogModelEntry { export interface V2PluginContext { session?: { hook?: (name: string, cb: (e: V2HttpRequestEvent) => void | Promise) => void | Promise; + synthetic?: (input: { sessionID: string; text: string }) => Promise; }; tool?: { transform?: (cb: (editor: V2ToolEditor) => void) => void | Promise; }; + command?: { + transform?: (cb: (editor: V2CommandEditor) => void) => void | Promise; + }; event?: { subscribe?: (opts?: { signal?: AbortSignal }) => AsyncIterable<{ type?: unknown; data?: Record }> | undefined }; catalog?: { model?: { list?: () => Promise<{ data?: V2CatalogModelEntry[] }> | undefined } | undefined }; } @@ -191,6 +208,58 @@ export function createOpencodeV2Setup(options: OpencodeV2SetupOptions = {}): (ct }); if (toolReg) registrations.push(toolReg); + // /acp status command (#809): registered via the V2 command editor where + // supported (2.0.x stable; inert-safe otherwise) and rendered as a + // synthetic non-model-turn message; TUI-only (`run` dispatches no slash cmds). + const commandReg = await ctx.command?.transform?.((editor) => { + editor.add({ + name: "acp", + description: "Show ACP status (billion-context proxy)", + execute: async (input) => { + const sid = typeof input.sessionID === "string" ? input.sessionID : ""; + let text: string; + if (pluginDisabled()) { + text = "bili: disabled (BILLION_CONTEXT_PLUGIN=0)"; + } else if (!sid) { + return; + } else { + const base = state.proxyBase ?? proxyBaseFromEnv(); + if (!base) { + text = "bili: no proxy detected (launch opencode through `bili opencode`, or point the provider baseURL at the bili proxy)"; + } else { + try { + const res = await fetch(`${base}/__bili/plugin/status?conversationId=${encodeURIComponent(sid)}&fallback=latest`); + const status = (await res.json()) as { ok?: boolean; panel?: string; error?: string }; + if (typeof status.panel === "string" && status.panel.length > 0) { + text = status.panel; + } else if (status.ok === false) { + let version: string | undefined; + try { + version = await fetchProxyVersion(base); + } catch { + version = undefined; + } + text = version !== undefined + ? `billion-context@${version} — proxy connected, no ACP session yet. Send a model request, then run /acp again.` + : "bili: no ACP session yet (send a model request first, then run /acp)"; + } else { + text = "bili: proxy returned no status panel"; + } + } catch (err) { + text = `bili: /acp failed (${err instanceof Error ? err.message : String(err)})`; + } + } + } + try { + await ctx.session?.synthetic?.({ sessionID: sid, text }); + } catch (err) { + console.error(`[bili-opencode] /acp render failed: ${err instanceof Error ? err.message : String(err)}`); + } + }, + }); + }); + if (commandReg) registrations.push(commandReg); + const subscription = ctx.event?.subscribe?.({ signal: ac.signal }); if (subscription && typeof subscription[Symbol.asyncIterator] === "function") { void (async () => { diff --git a/tests/opencode-v2.test.ts b/tests/opencode-v2.test.ts index 3023b6327a..ebdc814566 100644 --- a/tests/opencode-v2.test.ts +++ b/tests/opencode-v2.test.ts @@ -42,6 +42,11 @@ function startFakeProxyV2(): Promise<{ origin: string; toolCalls: Array<{ conver }); return; } + if ((req.url ?? "").startsWith("/__bili/plugin/status")) { + res.writeHead(200, { "content-type": "application/json" }); + res.end(JSON.stringify({ ok: true, panel: "ACP-PANEL-OK" })); + return; + } res.writeHead(404); res.end("{}"); }); @@ -62,12 +67,20 @@ interface FakeAddedTool { execute: (input: Record, ctx: { sessionID: string }) => Promise<{ content: string }>; } +interface FakeAddedCommand { + name: string; + description?: string; + execute: (input: Record) => Promise; +} + function makeFakeCtx() { const eventQueue: Array<{ type?: unknown; data?: Record }> = []; let wake: (() => void) | undefined; let closed = false; let signal: AbortSignal | undefined; const addedTools: FakeAddedTool[] = []; + const addedCommands: FakeAddedCommand[] = []; + const syntheticCalls: Array<{ sessionID: string; text: string }> = []; let modelRequestCb: ((e: Record) => void | Promise) | undefined; const disposed: number[] = []; @@ -78,6 +91,10 @@ function makeFakeCtx() { modelRequestCb = cb; return { dispose: () => { disposed.push(1); } }; }, + synthetic: async (input: { sessionID: string; text: string }) => { + syntheticCalls.push(input); + return {}; + }, }, tool: { transform: async (cb: (editor: { add: (t: FakeAddedTool) => void }) => void) => { @@ -85,6 +102,12 @@ function makeFakeCtx() { return { dispose: () => { disposed.push(2); } }; }, }, + command: { + transform: async (cb: (editor: { add: (c: FakeAddedCommand) => void }) => void) => { + cb({ add: (c) => addedCommands.push(c) }); + return { dispose: () => { disposed.push(3); } }; + }, + }, event: { subscribe: (opts?: { signal?: AbortSignal }) => { signal = opts?.signal; @@ -126,6 +149,8 @@ function makeFakeCtx() { }, pushEvent: (evt: { type?: unknown; data?: Record }) => { eventQueue.push(evt); wake?.(); }, get addedTools() { return addedTools; }, + get addedCommands() { return addedCommands; }, + get syntheticCalls() { return syntheticCalls; }, get disposed() { return disposed; }, }; } @@ -316,6 +341,44 @@ test("v2 setup: cleanup aborts event subscription and disposes registrations", a } }); +test("v2 setup: /acp command registered and renders proxy status panel via synthetic", async () => { + const proxy = await startFakeProxyV2(); + const fake = makeFakeCtx(); + try { + await withEnv({ BILLION_CONTEXT_PROXY: proxy.origin, BILLION_CONTEXT_PLUGIN: undefined }, async () => { + const cleanup = await biliOpencodePlugin.setup(fake.ctx as never); + try { + const acp = fake.addedCommands.find((c) => c.name === "acp"); + assert.ok(acp, "/acp command registered"); + assert.equal(typeof acp!.execute, "function"); + await acp!.execute({ sessionID: "ses_acp_1" }); + await until(() => fake.syntheticCalls.length === 1); + assert.equal(fake.syntheticCalls[0].sessionID, "ses_acp_1"); + assert.match(fake.syntheticCalls[0].text, /ACP-PANEL-OK/); + } finally { + cleanup(); + } + }); + } finally { + await proxy.close(); + } +}); + +test("v2 setup: /acp reports no proxy detected via synthetic when no proxy", async () => { + const fake = makeFakeCtx(); + await withEnv({ BILLION_CONTEXT_PROXY: undefined, BILLION_CONTEXT_PLUGIN: undefined }, async () => { + const cleanup = await biliOpencodePlugin.setup(fake.ctx as never); + try { + const acp = fake.addedCommands.find((c) => c.name === "acp")!; + await acp.execute({ sessionID: "s_nopx" }); + await until(() => fake.syntheticCalls.length === 1); + assert.match(fake.syntheticCalls[0].text, /no proxy detected/); + } finally { + cleanup(); + } + }); +}); + test("fetchManifest openai format maps parameters to inputSchema", async () => { const MANIFEST_OPENAI = [ { name: "compress", description: "Compress a range", parameters: { type: "object", properties: { content: { type: "array" } }, required: ["content"] } }, From f857ff1666dfd3854e114dea5a24b210579cc807 Mon Sep 17 00:00:00 2001 From: ework-agent Date: Wed, 16 Sep 2026 21:57:07 +0800 Subject: [PATCH 2/7] fix(agent): harden /acp under OpenCode V2 (guard order, status timeout, inert-safe registration) F1: check empty-sessionID guard before the disabled branch so a missing id never reaches ctx.session.synthetic with an empty id. F2: read status via shared fetchStatus (5s STATUS_TIMEOUT_MS soft-fail) instead of a bare unbounded fetch. F3: surface status.error in the no-panel fall-through. F4: wrap command registration in its own try/catch so an unsupported editor.add degrades to no-/acp instead of rejecting setup. F5: console.warn on the no-sessionID path so a broken host contract surfaces instead of dead silence. --- src/agent/opencode-v2.ts | 94 +++++++++++++++++++---------------- tests/opencode-v2.test.ts | 100 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 151 insertions(+), 43 deletions(-) diff --git a/src/agent/opencode-v2.ts b/src/agent/opencode-v2.ts index 07b66190fe..b84a5c47a7 100644 --- a/src/agent/opencode-v2.ts +++ b/src/agent/opencode-v2.ts @@ -41,7 +41,7 @@ // available on all observed surfaces. import { ACP_TOOLS_OPENAI, ABSORB_TOOL_OPENAI } from "../compress-tool.js"; -import { fetchProxyVersion, forwardTool, proxyBaseFromEnv, proxyBaseFromUrl, reportCompactionBoundary } from "./shared.js"; +import { fetchProxyVersion, fetchStatus, forwardTool, proxyBaseFromEnv, proxyBaseFromUrl, reportCompactionBoundary } from "./shared.js"; type V2Registration = { dispose?: () => void | Promise }; @@ -211,54 +211,62 @@ export function createOpencodeV2Setup(options: OpencodeV2SetupOptions = {}): (ct // /acp status command (#809): registered via the V2 command editor where // supported (2.0.x stable; inert-safe otherwise) and rendered as a // synthetic non-model-turn message; TUI-only (`run` dispatches no slash cmds). - const commandReg = await ctx.command?.transform?.((editor) => { - editor.add({ - name: "acp", - description: "Show ACP status (billion-context proxy)", - execute: async (input) => { - const sid = typeof input.sessionID === "string" ? input.sessionID : ""; - let text: string; - if (pluginDisabled()) { - text = "bili: disabled (BILLION_CONTEXT_PLUGIN=0)"; - } else if (!sid) { - return; - } else { - const base = state.proxyBase ?? proxyBaseFromEnv(); - if (!base) { - text = "bili: no proxy detected (launch opencode through `bili opencode`, or point the provider baseURL at the bili proxy)"; + try { + const commandReg = await ctx.command?.transform?.((editor) => { + editor.add({ + name: "acp", + description: "Show ACP status (billion-context proxy)", + execute: async (input) => { + const sid = typeof input.sessionID === "string" ? input.sessionID : ""; + if (!sid) { + console.warn("[bili-opencode] /acp invoked without a sessionID; cannot render ACP status"); + return; + } + let text: string; + if (pluginDisabled()) { + text = "bili: disabled (BILLION_CONTEXT_PLUGIN=0)"; } else { - try { - const res = await fetch(`${base}/__bili/plugin/status?conversationId=${encodeURIComponent(sid)}&fallback=latest`); - const status = (await res.json()) as { ok?: boolean; panel?: string; error?: string }; - if (typeof status.panel === "string" && status.panel.length > 0) { - text = status.panel; - } else if (status.ok === false) { - let version: string | undefined; - try { - version = await fetchProxyVersion(base); - } catch { - version = undefined; + const base = state.proxyBase ?? proxyBaseFromEnv(); + if (!base) { + text = "bili: no proxy detected (set BILLION_CONTEXT_PROXY or point the provider at the proxy's /bili/ URL, then run /acp again)"; + } else { + try { + const status = await fetchStatus(base, sid); + if (status && typeof status.panel === "string" && status.panel.length > 0) { + text = status.panel; + } else if (status && status.ok === false) { + let version: string | undefined; + try { + version = await fetchProxyVersion(base); + } catch { + version = undefined; + } + text = version !== undefined + ? `billion-context@${version} — proxy connected, no ACP session yet. Send a model request, then run /acp again.` + : "bili: no ACP session yet (send a model request first, then run /acp)"; + } else { + const errText = status?.error; + text = typeof errText === "string" && errText.length > 0 + ? `bili: proxy returned no status panel (${errText})` + : "bili: proxy returned no status panel"; } - text = version !== undefined - ? `billion-context@${version} — proxy connected, no ACP session yet. Send a model request, then run /acp again.` - : "bili: no ACP session yet (send a model request first, then run /acp)"; - } else { - text = "bili: proxy returned no status panel"; + } catch (err) { + text = `bili: /acp failed (${err instanceof Error ? err.message : String(err)})`; } - } catch (err) { - text = `bili: /acp failed (${err instanceof Error ? err.message : String(err)})`; } } - } - try { - await ctx.session?.synthetic?.({ sessionID: sid, text }); - } catch (err) { - console.error(`[bili-opencode] /acp render failed: ${err instanceof Error ? err.message : String(err)}`); - } - }, + try { + await ctx.session?.synthetic?.({ sessionID: sid, text }); + } catch (err) { + console.error(`[bili-opencode] /acp render failed: ${err instanceof Error ? err.message : String(err)}`); + } + }, + }); }); - }); - if (commandReg) registrations.push(commandReg); + if (commandReg) registrations.push(commandReg); + } catch (err) { + console.warn(`[bili-opencode] /acp command registration unavailable; continuing without it: ${err instanceof Error ? err.message : String(err)}`); + } const subscription = ctx.event?.subscribe?.({ signal: ac.signal }); if (subscription && typeof subscription[Symbol.asyncIterator] === "function") { diff --git a/tests/opencode-v2.test.ts b/tests/opencode-v2.test.ts index ebdc814566..c3b3c7de35 100644 --- a/tests/opencode-v2.test.ts +++ b/tests/opencode-v2.test.ts @@ -379,6 +379,106 @@ test("v2 setup: /acp reports no proxy detected via synthetic when no proxy", asy }); }); +test("v2 /acp: host omits sessionID → warn once, render nothing (never an empty-id synthetic)", async () => { + const warns: string[] = []; + const origWarn = console.warn; + console.warn = (msg?: unknown) => { warns.push(String(msg)); }; + try { + for (const plugin of ["0", undefined]) { + const f = makeFakeCtx(); + await withEnv({ BILLION_CONTEXT_PROXY: undefined, BILLION_CONTEXT_PLUGIN: plugin }, async () => { + const cleanup = await biliOpencodePlugin.setup(f.ctx as never); + try { + const acp = f.addedCommands.find((c) => c.name === "acp")!; + await acp.execute({}); + await new Promise((r) => setTimeout(r, 20)); + assert.equal(f.syntheticCalls.length, 0, `no synthetic for missing sessionID (BILLION_CONTEXT_PLUGIN=${String(plugin)})`); + } finally { + cleanup(); + } + }); + } + assert.equal(warns.filter((w) => w.includes("sessionID")).length, 2, "one warning per no-sessionID invocation"); + } finally { + console.warn = origWarn; + } +}); + +test("v2 /acp: disabled + valid session still renders the 'disabled' notice", async () => { + const fake = makeFakeCtx(); + await withEnv({ BILLION_CONTEXT_PROXY: undefined, BILLION_CONTEXT_PLUGIN: "0" }, async () => { + const cleanup = await biliOpencodePlugin.setup(fake.ctx as never); + try { + const acp = fake.addedCommands.find((c) => c.name === "acp")!; + await acp.execute({ sessionID: "ses_dis" }); + await until(() => fake.syntheticCalls.length === 1); + assert.match(fake.syntheticCalls[0].text, /disabled/); + assert.equal(fake.syntheticCalls[0].sessionID, "ses_dis"); + } finally { + cleanup(); + } + }); +}); + +test("v2 /acp: surfaces status.error when the proxy returns no panel", async () => { + const server = http.createServer((req, res) => { + if ((req.url ?? "").startsWith("/__bili/plugin/status")) { + res.writeHead(200, { "content-type": "application/json" }); + res.end(JSON.stringify({ ok: true, error: "backend-busy" })); + return; + } + res.writeHead(404); + res.end("{}"); + }); + server.listen(0, "127.0.0.1"); + await once(server, "listening"); + const origin = `http://127.0.0.1:${(server.address() as { port: number }).port}`; + const fake = makeFakeCtx(); + try { + await withEnv({ BILLION_CONTEXT_PROXY: origin, BILLION_CONTEXT_PLUGIN: undefined }, async () => { + const cleanup = await biliOpencodePlugin.setup(fake.ctx as never); + try { + const acp = fake.addedCommands.find((c) => c.name === "acp")!; + await acp.execute({ sessionID: "ses_err" }); + await until(() => fake.syntheticCalls.length === 1); + assert.match(fake.syntheticCalls[0].text, /no status panel/); + assert.match(fake.syntheticCalls[0].text, /backend-busy/); + } finally { + cleanup(); + } + }); + } finally { + await new Promise((resolve) => server.close(() => resolve())); + } +}); + +test("v2 /acp: a throwing command editor degrades to no-/acp without killing setup", async () => { + const fake = makeFakeCtx(); + const ctxObj = fake.ctx as unknown as { command?: unknown }; + ctxObj.command = { + transform: async (cb: (editor: { add: (c: unknown) => void }) => void) => { + cb({ add: () => { throw new Error("command editor has no add"); } }); + return { dispose: () => {} }; + }, + }; + const warns: string[] = []; + const origWarn = console.warn; + console.warn = (msg?: unknown) => { warns.push(String(msg)); }; + try { + await withEnv({ BILLION_CONTEXT_PROXY: undefined, BILLION_CONTEXT_PLUGIN: undefined }, async () => { + const cleanup = await biliOpencodePlugin.setup(fake.ctx as never); + try { + assert.ok(typeof cleanup === "function", "setup resolved despite the command editor throwing"); + } finally { + cleanup(); + } + }); + assert.ok(warns.some((w) => w.includes("/acp")), "degradation logged"); + } finally { + console.warn = origWarn; + } +}); + test("fetchManifest openai format maps parameters to inputSchema", async () => { const MANIFEST_OPENAI = [ { name: "compress", description: "Compress a range", parameters: { type: "object", properties: { content: { type: "array" } }, required: ["content"] } }, From d6d60f8d3e55fece71d0764611d41361941bbad6 Mon Sep 17 00:00:00 2001 From: Sisyphus Date: Thu, 17 Sep 2026 10:11:27 +0800 Subject: [PATCH 3/7] fix(agent): /acp must not wake the model under OpenCode V2 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit OpenCode V2's session.synthetic defaults to delivery="steer" and, unless resume:false, calls execution.wake(sessionID) — every /acp invocation started a model turn on behalf of a status query. Observed live in TUI: the model answered its own injected status panel with an unprompted assistant message. Pass resume:false so rendering stays inert. --- src/agent/opencode-v2.ts | 6 ++++-- tests/opencode-v2.test.ts | 6 ++++-- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/src/agent/opencode-v2.ts b/src/agent/opencode-v2.ts index b84a5c47a7..d40508cf08 100644 --- a/src/agent/opencode-v2.ts +++ b/src/agent/opencode-v2.ts @@ -87,7 +87,7 @@ interface V2CatalogModelEntry { export interface V2PluginContext { session?: { hook?: (name: string, cb: (e: V2HttpRequestEvent) => void | Promise) => void | Promise; - synthetic?: (input: { sessionID: string; text: string }) => Promise; + synthetic?: (input: { sessionID: string; text: string; description?: string; resume?: boolean }) => Promise; }; tool?: { transform?: (cb: (editor: V2ToolEditor) => void) => void | Promise; @@ -256,7 +256,9 @@ export function createOpencodeV2Setup(options: OpencodeV2SetupOptions = {}): (ct } } try { - await ctx.session?.synthetic?.({ sessionID: sid, text }); + // resume:false — OpenCode V2 defaults to delivery "steer" + execution.wake(), which would + // start a model turn on every /acp invocation with no user input (spurious empty turns). + await ctx.session?.synthetic?.({ sessionID: sid, text, resume: false }); } catch (err) { console.error(`[bili-opencode] /acp render failed: ${err instanceof Error ? err.message : String(err)}`); } diff --git a/tests/opencode-v2.test.ts b/tests/opencode-v2.test.ts index c3b3c7de35..a38b920088 100644 --- a/tests/opencode-v2.test.ts +++ b/tests/opencode-v2.test.ts @@ -80,7 +80,7 @@ function makeFakeCtx() { let signal: AbortSignal | undefined; const addedTools: FakeAddedTool[] = []; const addedCommands: FakeAddedCommand[] = []; - const syntheticCalls: Array<{ sessionID: string; text: string }> = []; + const syntheticCalls: Array<{ sessionID: string; text: string; description?: string; resume?: boolean }> = []; let modelRequestCb: ((e: Record) => void | Promise) | undefined; const disposed: number[] = []; @@ -91,7 +91,7 @@ function makeFakeCtx() { modelRequestCb = cb; return { dispose: () => { disposed.push(1); } }; }, - synthetic: async (input: { sessionID: string; text: string }) => { + synthetic: async (input: { sessionID: string; text: string; description?: string; resume?: boolean }) => { syntheticCalls.push(input); return {}; }, @@ -355,6 +355,7 @@ test("v2 setup: /acp command registered and renders proxy status panel via synth await until(() => fake.syntheticCalls.length === 1); assert.equal(fake.syntheticCalls[0].sessionID, "ses_acp_1"); assert.match(fake.syntheticCalls[0].text, /ACP-PANEL-OK/); + assert.equal(fake.syntheticCalls[0].resume, false); } finally { cleanup(); } @@ -373,6 +374,7 @@ test("v2 setup: /acp reports no proxy detected via synthetic when no proxy", asy await acp.execute({ sessionID: "s_nopx" }); await until(() => fake.syntheticCalls.length === 1); assert.match(fake.syntheticCalls[0].text, /no proxy detected/); + assert.equal(fake.syntheticCalls[0].resume, false); } finally { cleanup(); } From 304110ad3fa0b93403a349dc2381a474174ef0ef Mon Sep 17 00:00:00 2001 From: Sisyphus Date: Thu, 17 Sep 2026 10:25:25 +0800 Subject: [PATCH 4/7] fix(agent): make opencode v2 /acp status panel visible in the TUI The /acp panel was carried only in the synthetic message's text. OpenCode V2's TUI renders a synthetic message as a Notice row only when its display text fits the timeline cap (~1KB; message-timeline.tsx canRenderImmediately), so real panels were silently dropped: users saw nothing after /acp. The panel now goes to description (verbatim under 1024 chars, leading lines + [panel truncated] above) and the model-facing body is an inert one-line note (V2_SYNTHETIC_TEXT) so the model context never repeats panel content. Verified live in a v2.0.4 TUI: short panels render fully as the notice row, a >1.5KB panel renders its leading lines plus the marker; no model turn is triggered (pairs with the no-wake fix #879). --- src/agent/opencode-v2.ts | 12 +++++++++++- src/agent/shared.ts | 4 ++++ tests/opencode-v2.test.ts | 39 +++++++++++++++++++++++++++++++++------ 3 files changed, 48 insertions(+), 7 deletions(-) diff --git a/src/agent/opencode-v2.ts b/src/agent/opencode-v2.ts index d40508cf08..ecf496dbb8 100644 --- a/src/agent/opencode-v2.ts +++ b/src/agent/opencode-v2.ts @@ -43,6 +43,11 @@ import { ACP_TOOLS_OPENAI, ABSORB_TOOL_OPENAI } from "../compress-tool.js"; import { fetchProxyVersion, fetchStatus, forwardTool, proxyBaseFromEnv, proxyBaseFromUrl, reportCompactionBoundary } from "./shared.js"; +// OpenCode V2 TUI renders a synthetic message as a visible Notice row only when its display text fits the +// timeline cap (~1KB): longer text renders nothing (#880). Panels go to description verbatim under the cap. +import { V2_SYNTHETIC_TEXT } from "./shared.js"; +const V2_SYNTHETIC_VISIBLE_MAX = 1024; + type V2Registration = { dispose?: () => void | Promise }; interface V2Headers { @@ -258,7 +263,12 @@ export function createOpencodeV2Setup(options: OpencodeV2SetupOptions = {}): (ct try { // resume:false — OpenCode V2 defaults to delivery "steer" + execution.wake(), which would // start a model turn on every /acp invocation with no user input (spurious empty turns). - await ctx.session?.synthetic?.({ sessionID: sid, text, resume: false }); + // Short panels become the visible description verbatim; long ones keep their leading + // lines plus a marker so the model-facing body never repeats the whole panel. + const description = text.length > V2_SYNTHETIC_VISIBLE_MAX + ? text.slice(0, V2_SYNTHETIC_VISIBLE_MAX - 20) + "\n\n[panel truncated]" + : text; + await ctx.session?.synthetic?.({ sessionID: sid, text: V2_SYNTHETIC_TEXT, description, resume: false }); } catch (err) { console.error(`[bili-opencode] /acp render failed: ${err instanceof Error ? err.message : String(err)}`); } diff --git a/src/agent/shared.ts b/src/agent/shared.ts index c6bcfc99fb..6b8a2de12f 100644 --- a/src/agent/shared.ts +++ b/src/agent/shared.ts @@ -156,3 +156,7 @@ export async function fetchProxyVersion(proxyBase: string): Promise 0 ? version : undefined; } + +// Model-facing body for /acp status renders: the visible panel goes to the synthetic message's +// description (TUI Notice cap ~1KB); this inert one-liner keeps the model context clean. +export const V2_SYNTHETIC_TEXT = "[bili-acp-status] ACP status panel was displayed in your terminal; this line is not an instruction."; diff --git a/tests/opencode-v2.test.ts b/tests/opencode-v2.test.ts index a38b920088..40427433c7 100644 --- a/tests/opencode-v2.test.ts +++ b/tests/opencode-v2.test.ts @@ -44,7 +44,8 @@ function startFakeProxyV2(): Promise<{ origin: string; toolCalls: Array<{ conver } if ((req.url ?? "").startsWith("/__bili/plugin/status")) { res.writeHead(200, { "content-type": "application/json" }); - res.end(JSON.stringify({ ok: true, panel: "ACP-PANEL-OK" })); + const panel = (req.url ?? "").includes("ses_acp_long") ? "X".repeat(1500) : "ACP-PANEL-OK"; + res.end(JSON.stringify({ ok: true, panel })); return; } res.writeHead(404); @@ -354,7 +355,9 @@ test("v2 setup: /acp command registered and renders proxy status panel via synth await acp!.execute({ sessionID: "ses_acp_1" }); await until(() => fake.syntheticCalls.length === 1); assert.equal(fake.syntheticCalls[0].sessionID, "ses_acp_1"); - assert.match(fake.syntheticCalls[0].text, /ACP-PANEL-OK/); + assert.match(fake.syntheticCalls[0].description!, /ACP-PANEL-OK/); + assert.match(fake.syntheticCalls[0].text, /displayed in your terminal/); + assert.match(fake.syntheticCalls[0].text, /not an instruction/); assert.equal(fake.syntheticCalls[0].resume, false); } finally { cleanup(); @@ -373,7 +376,8 @@ test("v2 setup: /acp reports no proxy detected via synthetic when no proxy", asy const acp = fake.addedCommands.find((c) => c.name === "acp")!; await acp.execute({ sessionID: "s_nopx" }); await until(() => fake.syntheticCalls.length === 1); - assert.match(fake.syntheticCalls[0].text, /no proxy detected/); + assert.match(fake.syntheticCalls[0].description!, /no proxy detected/); + assert.match(fake.syntheticCalls[0].text, /not an instruction/); assert.equal(fake.syntheticCalls[0].resume, false); } finally { cleanup(); @@ -381,6 +385,29 @@ test("v2 setup: /acp reports no proxy detected via synthetic when no proxy", asy }); }); +test("v2 setup: /acp truncates long panels to the TUI notice cap", async () => { + const proxy = await startFakeProxyV2(); + const fake = makeFakeCtx(); + try { + await withEnv({ BILLION_CONTEXT_PROXY: proxy.origin, BILLION_CONTEXT_PLUGIN: undefined }, async () => { + const cleanup = await biliOpencodePlugin.setup(fake.ctx as never); + try { + const acp = fake.addedCommands.find((c) => c.name === "acp")!; + await acp.execute({ sessionID: "ses_acp_long" }); + await until(() => fake.syntheticCalls.length === 1); + const desc = fake.syntheticCalls[0].description ?? ""; + assert.ok(desc.length > 0 && desc.length <= 1024); + assert.match(desc, /\[panel truncated\]$/); + assert.match(fake.syntheticCalls[0].text, /not an instruction/); + } finally { + cleanup(); + } + }); + } finally { + await proxy.close(); + } +}); + test("v2 /acp: host omits sessionID → warn once, render nothing (never an empty-id synthetic)", async () => { const warns: string[] = []; const origWarn = console.warn; @@ -414,7 +441,7 @@ test("v2 /acp: disabled + valid session still renders the 'disabled' notice", as const acp = fake.addedCommands.find((c) => c.name === "acp")!; await acp.execute({ sessionID: "ses_dis" }); await until(() => fake.syntheticCalls.length === 1); - assert.match(fake.syntheticCalls[0].text, /disabled/); + assert.match(fake.syntheticCalls[0].description!, /disabled/); assert.equal(fake.syntheticCalls[0].sessionID, "ses_dis"); } finally { cleanup(); @@ -443,8 +470,8 @@ test("v2 /acp: surfaces status.error when the proxy returns no panel", async () const acp = fake.addedCommands.find((c) => c.name === "acp")!; await acp.execute({ sessionID: "ses_err" }); await until(() => fake.syntheticCalls.length === 1); - assert.match(fake.syntheticCalls[0].text, /no status panel/); - assert.match(fake.syntheticCalls[0].text, /backend-busy/); + assert.match(fake.syntheticCalls[0].description!, /no status panel/); + assert.match(fake.syntheticCalls[0].description!, /backend-busy/); } finally { cleanup(); } From 6d79228fc111c7298ae2629c051cd54fcd828682 Mon Sep 17 00:00:00 2001 From: Sisyphus Date: Thu, 17 Sep 2026 12:13:32 +0800 Subject: [PATCH 5/7] fix(agent): show the idle notice on first opencode v2 /acp before any model request MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Before the conversation's first model request the proxy knows no ACP session; handlePluginStatus answers that with HTTP 404 {ok:false}. shared.fetchStatus() soft-fails every non-2xx into undefined, so the v2 renderer fell through both the panel and the ok===false branches and printed 'proxy returned no status panel' instead of the friendly idle line. Handle the undefined result explicitly: probe the manifest, and when it answers render 'billion-context@ — proxy connected, no ACP session yet…'; when nothing answers, say the proxy is unreachable. Second-and-later calls were already correct (panel or ok:false path). Same soft-fail contract as v1's inline fetch, without changing the endpoint's wire semantics. --- src/agent/opencode-v2.ts | 8 ++++++++ tests/opencode-v2.test.ts | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+) diff --git a/src/agent/opencode-v2.ts b/src/agent/opencode-v2.ts index ecf496dbb8..7ae0ed6bb8 100644 --- a/src/agent/opencode-v2.ts +++ b/src/agent/opencode-v2.ts @@ -249,6 +249,14 @@ export function createOpencodeV2Setup(options: OpencodeV2SetupOptions = {}): (ct text = version !== undefined ? `billion-context@${version} — proxy connected, no ACP session yet. Send a model request, then run /acp again.` : "bili: no ACP session yet (send a model request first, then run /acp)"; + } else if (!status) { + // fetchStatus soft-fails to undefined both when the proxy 404s an absent or + // never-seen conversation and when the proxy is unreachable. Probe the + // manifest to claim "connected" only when it answers. + const version = await fetchProxyVersion(base).catch(() => undefined); + text = version !== undefined + ? `billion-context@${version} — proxy connected, no ACP session yet. Send a model request, then run /acp again.` + : "bili: cannot reach the bili proxy (run `bili start`, then run /acp again)"; } else { const errText = status?.error; text = typeof errText === "string" && errText.length > 0 diff --git a/tests/opencode-v2.test.ts b/tests/opencode-v2.test.ts index 40427433c7..3661ac5c06 100644 --- a/tests/opencode-v2.test.ts +++ b/tests/opencode-v2.test.ts @@ -43,11 +43,21 @@ function startFakeProxyV2(): Promise<{ origin: string; toolCalls: Array<{ conver return; } if ((req.url ?? "").startsWith("/__bili/plugin/status")) { + if ((req.url ?? "").includes("ses_acp_idle")) { + res.writeHead(404, { "content-type": "application/json" }); + res.end(JSON.stringify({ ok: false, error: "unknown plugin conversation" })); + return; + } res.writeHead(200, { "content-type": "application/json" }); const panel = (req.url ?? "").includes("ses_acp_long") ? "X".repeat(1500) : "ACP-PANEL-OK"; res.end(JSON.stringify({ ok: true, panel })); return; } + if ((req.url ?? "") === "/__bili/plugin/manifest") { + res.writeHead(200, { "content-type": "application/json" }); + res.end(JSON.stringify({ version: "9.9.9-test" })); + return; + } res.writeHead(404); res.end("{}"); }); @@ -385,6 +395,29 @@ test("v2 setup: /acp reports no proxy detected via synthetic when no proxy", asy }); }); +test("v2 setup: first /acp before any model request shows the idle notice (proxy 404s the conversation)", async () => { + const proxy = await startFakeProxyV2(); + const fake = makeFakeCtx(); + try { + await withEnv({ BILLION_CONTEXT_PROXY: proxy.origin, BILLION_CONTEXT_PLUGIN: undefined }, async () => { + const cleanup = await biliOpencodePlugin.setup(fake.ctx as never); + try { + const acp = fake.addedCommands.find((c) => c.name === "acp")!; + await acp.execute({ sessionID: "ses_acp_idle" }); + await until(() => fake.syntheticCalls.length === 1); + assert.match(fake.syntheticCalls[0].description!, /billion-context@9\.9\.9-test \u2014 proxy connected, no ACP session yet/); + assert.match(fake.syntheticCalls[0].text, /not an instruction/); + assert.equal(fake.syntheticCalls[0].resume, false); + } finally { + cleanup(); + } + }); + } finally { + await proxy.close(); + } +}); + + test("v2 setup: /acp truncates long panels to the TUI notice cap", async () => { const proxy = await startFakeProxyV2(); const fake = makeFakeCtx(); From 202e8116a91a30a3facc9a893544484c1c031d2b Mon Sep 17 00:00:00 2001 From: Sisyphus Date: Thu, 17 Sep 2026 13:39:56 +0800 Subject: [PATCH 6/7] fix(agent): preset BILLION_CONTEXT_PROXY attaches the opencode v2 native plugin instead of standing down MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The pseudo-attach hole: presetting BILLION_CONTEXT_PROXY and running bare opencode disarmed the native bootstrap entirely (no spawn, no attach) while tools still discovered the proxy through the env — model traffic silently went direct, the proxy never saw the session, and every tool forward 404'd ("unknown plugin conversation"). planNativeOpencode now treats the preset value as an external attach target (probe + rewrite + stamp, same semantics as BILLION_CONTEXT_ATTACH; explicit ATTACH wins when both are set). Kill switches (BILLION_CONTEXT_PLUGIN=0, BILI_NATIVE_OPENCODE=0) and /bili/ launches (BILI_PROVIDER_REWRITES) still stand down; a garbage preset falls back to spawn. Also: the opencode v2 plugin tool forward now returns guided text when the proxy reports the conversation was never registered, instead of surfacing the raw 404 that sent the model down a "refresh/restart" tangent. Verified in-container end-to-end (real qwen upstream) across all four postures: proxy (baseURL), launcher (bili opencode), native spawn (bare opencode + plugin), and preset-env attach — session registration, live conversation, acp_status real execution, /acp panel render. --- src/agent/native-bootstrap.ts | 16 ++++++++++++++++ src/agent/opencode-native.ts | 28 ++++++++++++++++++---------- src/agent/opencode-v2.ts | 6 +++++- tests/opencode-native.test.ts | 25 +++++++++++++++++++++---- 4 files changed, 60 insertions(+), 15 deletions(-) diff --git a/src/agent/native-bootstrap.ts b/src/agent/native-bootstrap.ts index d519b2ef17..6d0a456e5b 100644 --- a/src/agent/native-bootstrap.ts +++ b/src/agent/native-bootstrap.ts @@ -25,6 +25,22 @@ export function nativeBootstrapGate(env: NodeJS.ProcessEnv, optOutKey: string): return true; } +/** Normalize a preset BILLION_CONTEXT_PROXY value (http/https, trailing + * slashes stripped) for attach-style routing. Returns undefined when unset, + * blank, or not a valid http(s) origin. */ +export function proxyEnvOrigin(env: NodeJS.ProcessEnv): string | undefined { + const raw = env.BILLION_CONTEXT_PROXY; + if (raw === undefined) return undefined; + const url = raw.trim(); + if (url.length === 0 || !/^https?:\/\//i.test(url)) return undefined; + try { + new URL(url); + } catch { + return undefined; + } + return url.replace(/\/+$/, ""); +} + /** External-proxy attach signal (#809): when BILLION_CONTEXT_ATTACH holds a * valid http(s) origin, a host-native entry routes model traffic THROUGH that * pre-existing proxy instead of spawning its own — no ownership, no respawn, diff --git a/src/agent/opencode-native.ts b/src/agent/opencode-native.ts index 41903d7a64..b28ef4bbe4 100644 --- a/src/agent/opencode-native.ts +++ b/src/agent/opencode-native.ts @@ -30,9 +30,10 @@ // retries are rate-limited to one attempt per RESPAWN_COOLDOWN_MS so a // persistently failing spawn does not become a per-request spawn storm. // -// Skipped when a proxy is already managed (BILLION_CONTEXT_PROXY set by a -// `bili` launch, or BILI_PROVIDER_REWRITES set by a `bili` /bili/ launch) or -// opted out (BILI_NATIVE_OPENCODE=0 / BILLION_CONTEXT_PLUGIN=0). +// Skipped when opted out (BILI_NATIVE_OPENCODE=0 / BILLION_CONTEXT_PLUGIN=0) +// or when a `bili` /bili/ launch owns routing (BILI_PROVIDER_REWRITES). A +// preset BILLION_CONTEXT_PROXY is treated as an EXTERNAL attach target +// (probe + rewrite + stamp) instead of a stand-down — see planNativeOpencode. // // Deployment: OpenCode 2.x `plugin` entries must be DIRECTORIES whose index.js // is the entrypoint (bare file paths are rejected, #754 probe) — `bili plugin @@ -41,7 +42,7 @@ // src/launcher.ts prepareOpencodeHttpRewrite). import { ensureProxyRunning, LAUNCHER_DEFAULT_HOST } from "../launcher.js"; -import { markNativeHost, nativeAttachOrigin, nativeBootstrapGate, nativeProxyScriptPath, singleFlight } from "./native-bootstrap.js"; +import { markNativeHost, nativeAttachOrigin, nativeBootstrapGate, nativeProxyScriptPath, proxyEnvOrigin, singleFlight } from "./native-bootstrap.js"; import { isModelApiUrl, readyOrigin, type NativeInterceptState } from "./native-intercept.js"; import { createOpencodeV2Setup, type V2HttpRequestEvent, type V2State } from "./opencode-v2.js"; @@ -50,13 +51,20 @@ export function shouldBootstrapNativeOpencode(env: NodeJS.ProcessEnv): boolean { return nativeBootstrapGate(env, "BILI_NATIVE_OPENCODE"); } -/** Decide this process's native posture (#809). Precedence off > attach > - * spawn: a launcher-owned proxy or an opt-out stands us down entirely (even - * over an explicit attach); otherwise attach to BILLION_CONTEXT_ATTACH when - * given, else spawn our own watchdog proxy. */ +/** Decide this process's native posture (#809). Precedence kill-switch > + * /bili/ rewrite launch > attach > spawn. A preset BILLION_CONTEXT_PROXY is + * an ATTACH target, not a stand-down: the pseudo-attach hole (preset env + + * bare opencode) used to disarm routing entirely while tools still found the + * proxy through the env — model traffic went direct, the proxy never saw the + * session, and every tool forward 404'd. Attach keeps the user's intent + * ("route through THIS proxy") and matches BILLION_CONTEXT_ATTACH semantics + * (probe + rewrite + stamp); explicit BILLION_CONTEXT_ATTACH wins when both + * are set. A /bili/ launch (BILI_PROVIDER_REWRITES) still stands us down — + * its URLs are already proxy-shaped and isModelApiUrl skips them. */ export function planNativeOpencode(env: NodeJS.ProcessEnv): { mode: "off" | "attach" | "spawn"; attachOrigin?: string } { - if (!shouldBootstrapNativeOpencode(env)) return { mode: "off" }; - const attachOrigin = nativeAttachOrigin(env); + if (env.BILLION_CONTEXT_PLUGIN === "0" || env.BILI_NATIVE_OPENCODE === "0") return { mode: "off" }; + if (env.BILI_PROVIDER_REWRITES !== undefined) return { mode: "off" }; + const attachOrigin = nativeAttachOrigin(env) ?? proxyEnvOrigin(env); if (attachOrigin !== undefined) return { mode: "attach", attachOrigin }; return { mode: "spawn" }; } diff --git a/src/agent/opencode-v2.ts b/src/agent/opencode-v2.ts index 7ae0ed6bb8..3559b3ea95 100644 --- a/src/agent/opencode-v2.ts +++ b/src/agent/opencode-v2.ts @@ -205,7 +205,11 @@ export function createOpencodeV2Setup(options: OpencodeV2SetupOptions = {}): (ct const result = await forwardTool(base, tctx.sessionID, t.name, args); return { content: result }; } catch (err) { - return { content: err instanceof Error ? err.message : String(err) }; + const msg = err instanceof Error ? err.message : String(err); + if (msg.includes("no model request has arrived with this conversation id yet")) { + return { content: "bili: no ACP state for this session yet — no model request has been routed through the proxy. Tell the user to send one normal message first; ACP activates automatically once model traffic flows through the proxy (verify the provider baseURL goes through bili, or launch via `bili opencode` / the installed plugin)." }; + } + return { content: msg }; } }, }); diff --git a/tests/opencode-native.test.ts b/tests/opencode-native.test.ts index 74fb4e3ef7..df1641dd14 100644 --- a/tests/opencode-native.test.ts +++ b/tests/opencode-native.test.ts @@ -274,11 +274,28 @@ test("nativeAttachOrigin: normalizes a valid http(s) origin (trailing slash stri assert.equal(nativeAttachOrigin({ BILLION_CONTEXT_ATTACH: " https://proxy.example.com/ " }), "https://proxy.example.com"); }); -test("planNativeOpencode: default is spawn; opt-out and launcher-owned are off", () => { +test("planNativeOpencode: default is spawn; opt-out and /bili/ launches are off", () => { assert.deepEqual(planNativeOpencode({}), { mode: "spawn" }); assert.deepEqual(planNativeOpencode({ BILLION_CONTEXT_PLUGIN: "0" }), { mode: "off" }); assert.deepEqual(planNativeOpencode({ BILI_NATIVE_OPENCODE: "0" }), { mode: "off" }); - assert.deepEqual(planNativeOpencode({ BILLION_CONTEXT_PROXY: "http://127.0.0.1:36485" }), { mode: "off" }); + assert.deepEqual(planNativeOpencode({ BILI_PROVIDER_REWRITES: '{"vllm":"http://127.0.0.1:1/bili/http://x"}' }), { mode: "off" }); +}); + +test("planNativeOpencode: a preset BILLION_CONTEXT_PROXY is an attach target, not a stand-down", () => { + assert.deepEqual( + planNativeOpencode({ BILLION_CONTEXT_PROXY: "http://127.0.0.1:36485" }), + { mode: "attach", attachOrigin: "http://127.0.0.1:36485" }, + ); + assert.deepEqual( + planNativeOpencode({ BILLION_CONTEXT_PROXY: "http://127.0.0.1:36485/" }), + { mode: "attach", attachOrigin: "http://127.0.0.1:36485" }, + ); + // kill switches and a /bili/ launch still win over the preset + assert.deepEqual(planNativeOpencode({ BILLION_CONTEXT_PROXY: "http://127.0.0.1:36485", BILLION_CONTEXT_PLUGIN: "0" }), { mode: "off" }); + assert.deepEqual(planNativeOpencode({ BILLION_CONTEXT_PROXY: "http://127.0.0.1:36485", BILI_PROVIDER_REWRITES: "{}" }), { mode: "off" }); + // a garbage preset falls back to spawn (self-managed) rather than dead-off + assert.deepEqual(planNativeOpencode({ BILLION_CONTEXT_PROXY: "garbage" }), { mode: "spawn" }); + assert.deepEqual(planNativeOpencode({ BILLION_CONTEXT_PROXY: " " }), { mode: "spawn" }); }); test("planNativeOpencode: attach wins over spawn when no launcher owns the proxy", () => { @@ -289,10 +306,10 @@ test("planNativeOpencode: attach wins over spawn when no launcher owns the proxy assert.deepEqual(planNativeOpencode({ BILLION_CONTEXT_ATTACH: "garbage" }), { mode: "spawn" }); }); -test("planNativeOpencode: a launcher-owned proxy stands down even over an explicit attach", () => { +test("planNativeOpencode: explicit BILLION_CONTEXT_ATTACH wins over the env preset", () => { assert.deepEqual( planNativeOpencode({ BILLION_CONTEXT_PROXY: "http://127.0.0.1:36485", BILLION_CONTEXT_ATTACH: "http://10.0.0.5:9000" }), - { mode: "off" }, + { mode: "attach", attachOrigin: "http://10.0.0.5:9000" }, ); }); From 96368b24d8a412fefd9106a9a51651af64fe84bc Mon Sep 17 00:00:00 2001 From: Sisyphus Date: Thu, 17 Sep 2026 22:42:14 +0800 Subject: [PATCH 7/7] fix(agent): opencode v2 acp_status renders the status panel (panel-first) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The forwarded kernel acp_status returns the legacy flat report while the /acp command shows the rich status panel — tool and command disagreed. acp_status is read-only, so the plugin now reads the panel from the proxy's status endpoint first and falls back to forwardTool when no panel is served (older proxy, unknown conversation). Fixes #911 --- src/agent/opencode-v2.ts | 12 ++++++++++++ tests/opencode-v2.test.ts | 9 ++++++++- 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/src/agent/opencode-v2.ts b/src/agent/opencode-v2.ts index 3559b3ea95..0ff03994a6 100644 --- a/src/agent/opencode-v2.ts +++ b/src/agent/opencode-v2.ts @@ -202,6 +202,18 @@ export function createOpencodeV2Setup(options: OpencodeV2SetupOptions = {}): (ct const base = state.proxyBase ?? proxyBaseFromEnv(); if (!base) return { content: "bili: no proxy detected (launch opencode through `bili opencode`, or point the provider baseURL at the bili proxy)" }; try { + // Panel-first for acp_status: the proxy's status + // endpoint renders the same rich panel the /acp + // command shows; the forwarded kernel tool returns + // the legacy flat report. acp_status is read-only, + // so reading the panel changes no state. Fall back + // to the tool call when no panel comes back (older + // proxy, unknown conversation). + if (t.name === "acp_status") { + const status = await fetchStatus(base, tctx.sessionID); + const panel = status?.["panel"]; + if (typeof panel === "string" && panel.length > 0) return { content: panel }; + } const result = await forwardTool(base, tctx.sessionID, t.name, args); return { content: result }; } catch (err) { diff --git a/tests/opencode-v2.test.ts b/tests/opencode-v2.test.ts index 3661ac5c06..493ebd3f51 100644 --- a/tests/opencode-v2.test.ts +++ b/tests/opencode-v2.test.ts @@ -285,8 +285,15 @@ test("v2 setup: activates from /bili/ baseURL on round 1, stamps headers, forwar assert.equal(proxy.toolCalls.at(-1)?.conversationId, "ses_v2_1"); assert.equal(proxy.toolCalls.at(-1)?.tool, "compress"); - const statusOut = await fake.addedTools.find((t) => t.name === "acp_status")!.execute({}, { sessionID: "ses_other" }); + // Panel-first: acp_status returns the status panel when the + // proxy serves one for this conversation (ses_other gets the + // generic "ACP-PANEL-OK"), and falls back to the forwarded + // kernel tool when the status endpoint 404s (ses_acp_idle). + const panelOut = await fake.addedTools.find((t) => t.name === "acp_status")!.execute({}, { sessionID: "ses_other" }); + assert.equal(panelOut.content, "ACP-PANEL-OK"); + const statusOut = await fake.addedTools.find((t) => t.name === "acp_status")!.execute({}, { sessionID: "ses_acp_idle" }); assert.equal(statusOut.content, "STATUS-RESULT"); + assert.equal(proxy.toolCalls.at(-1)?.tool, "acp_status"); } finally { cleanup(); }