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 821efe0b85..0ff03994a6 100644 --- a/src/agent/opencode-v2.ts +++ b/src/agent/opencode-v2.ts @@ -41,7 +41,12 @@ // 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, 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 }; @@ -65,6 +70,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 +92,14 @@ interface V2CatalogModelEntry { export interface V2PluginContext { session?: { hook?: (name: string, cb: (e: V2HttpRequestEvent) => void | Promise) => void | Promise; + synthetic?: (input: { sessionID: string; text: string; description?: string; resume?: boolean }) => 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 }; } @@ -180,10 +202,26 @@ 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) { - 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 }; } }, }); @@ -191,6 +229,81 @@ 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). + 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 { + 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 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 + ? `bili: proxy returned no status panel (${errText})` + : "bili: proxy returned no status panel"; + } + } catch (err) { + text = `bili: /acp failed (${err instanceof Error ? err.message : String(err)})`; + } + } + } + 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). + // 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)}`); + } + }, + }); + }); + 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") { void (async () => { 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-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" }, ); }); diff --git a/tests/opencode-v2.test.ts b/tests/opencode-v2.test.ts index 3023b6327a..493ebd3f51 100644 --- a/tests/opencode-v2.test.ts +++ b/tests/opencode-v2.test.ts @@ -42,6 +42,22 @@ 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("{}"); }); @@ -62,12 +78,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; description?: string; resume?: boolean }> = []; let modelRequestCb: ((e: Record) => void | Promise) | undefined; const disposed: number[] = []; @@ -78,6 +102,10 @@ function makeFakeCtx() { modelRequestCb = cb; return { dispose: () => { disposed.push(1); } }; }, + synthetic: async (input: { sessionID: string; text: string; description?: string; resume?: boolean }) => { + syntheticCalls.push(input); + return {}; + }, }, tool: { transform: async (cb: (editor: { add: (t: FakeAddedTool) => void }) => void) => { @@ -85,6 +113,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 +160,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; }, }; } @@ -249,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(); } @@ -316,6 +359,195 @@ 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].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(); + } + }); + } 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].description!, /no proxy detected/); + assert.match(fake.syntheticCalls[0].text, /not an instruction/); + assert.equal(fake.syntheticCalls[0].resume, false); + } finally { + cleanup(); + } + }); +}); + +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(); + 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; + 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].description!, /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].description!, /no status panel/); + assert.match(fake.syntheticCalls[0].description!, /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"] } },