From 50eb8a7750a42ea5a10b9b555d753a58418f9116 Mon Sep 17 00:00:00 2001 From: Anthony Hausman Date: Sun, 29 Nov 2026 16:29:58 +0100 Subject: [PATCH 01/13] feat(acp): resume stored agy sessions after restart Resume the stored agy session with session/resume when a new process starts and the fingerprint matches, so history is not replayed and the prompt cache survives. Falls back to session/new with full replay when resume fails or the last turn was interrupted. Assisted-by: Claude Opus 5.5 --- docs/acp-spike-findings.md | 10 +++++++++ src/acp/language-model.ts | 14 ++++++++++--- src/acp/live-session.ts | 25 +++++++++++++++++++++- src/acp/process.ts | 28 +++++++++++++++++++------ test/acp/language-model.test.ts | 32 ++++++++++++++++++++++++++-- test/acp/process.test.ts | 37 +++++++++++++++++++++++++++++++++ 6 files changed, 134 insertions(+), 12 deletions(-) diff --git a/docs/acp-spike-findings.md b/docs/acp-spike-findings.md index 6c82e5be..f06c9dea 100644 --- a/docs/acp-spike-findings.md +++ b/docs/acp-spike-findings.md @@ -338,3 +338,13 @@ Date: 2026-11-27. OpenCode 2.4.2. Audited through ACP only (no direct Code Assis - `session/new` `mcpServers` (stdio) was not exposed to the default agent in this run; the provider does not use that path (`mcpServers: []`). - antigravity-cli#1684: `systemPrompt.append` containing `tools.opencode.session_move` still ends with `RESOURCE_EXHAUSTED (code 429)` after about 141 s; `tools.opencode.sessionMove` answers in 5 s. - `MIN_AGY_VERSION` stays `1.5.10`. + +## Session resume across a process restart (agy 1.5.20) + +Spike: `session/new`, two prompts, kill the `agy acp` process, start a new one, `initialize` + `authenticate`, then `session/load` or `session/resume` with the old `sessionId`, `cwd` and `mcpServers: []`, then a prompt that needs the earlier context. + +- Both methods restore the session: the next prompt recalls a code word given before the restart. +- `session/load` replays the history as `user_message_chunk` / `agent_message_chunk` updates before it returns. `session/resume` returns without replaying anything, so it is the one the provider uses. +- Both return `sessionId`, `models`, `modes`, `configOptions` and `_meta`, like `session/new`. +- Google's prompt cache survives the restart: the prompt after `session/resume` reported `cachedReadTokens` 7690 of about 9960 input tokens, the same as a second prompt in the same process (7571). The first prompt of a fresh session reports 0. +- `usage_update` carries `used` (tokens in the session context) and `size` (1048576 for `gemini-3.8-flash-high`). A prompt's `usage` is a per-prompt total, reported once in the `session/prompt` result. diff --git a/src/acp/language-model.ts b/src/acp/language-model.ts index 7397bd8a..869b3f67 100644 --- a/src/acp/language-model.ts +++ b/src/acp/language-model.ts @@ -231,6 +231,10 @@ export class AgyAcpLanguageModel implements LanguageModelV3 { for (;;) { if (deps.pool.get(key)?.dead) await deps.pool.release(key); let created = false; + const record = await deps.store.get(key); + // Resume only a cleanly finished agy session: an interrupted turn may have left partial state. + const resumeId = + record?.fingerprint === fingerprint && !record.interrupted ? record.agySessionId : undefined; const acquired = await waitBounded( deps.pool.acquire(key, fingerprint, () => { created = true; @@ -240,6 +244,7 @@ export class AgyAcpLanguageModel implements LanguageModelV3 { tools: ctx.tools, session: this.sessionParams(ctx, ctx.tools), auth, + ...(resumeId ? { resumeId } : {}), }); }), o.abortSignal, @@ -249,9 +254,10 @@ export class AgyAcpLanguageModel implements LanguageModelV3 { return; } const live = acquired.value; - const record = await deps.store.get(key); - // A new process holds no history: replay everything (unless the config changed, which decideSync reports). - const decision = decideSync(created && record?.fingerprint === fingerprint ? undefined : record, o.prompt, fingerprint); + // A new process holds no history unless it resumed the stored agy session: replay everything + // (unless the config changed, which decideSync reports). + const fresh = created && !live.resumed && record?.fingerprint === fingerprint; + const decision = decideSync(fresh ? undefined : record, o.prompt, fingerprint); const previous = live.turn; if (previous && (decision.kind !== "continue" || decision.blocks.length > 0)) { @@ -265,6 +271,8 @@ export class AgyAcpLanguageModel implements LanguageModelV3 { if (settled.kind === "timeout") { // agy ignored session/cancel: drop the process; the next acquire respawns and replays history. deps.log("warn", "agy-acp: cancelled agy turn did not settle in time; restarting agy"); + // The killed turn may have left partial state: do not resume it. + await this.markInterrupted(live); if (deps.pool.get(key) === live) await deps.pool.release(key); else await live.dispose(); continue; diff --git a/src/acp/live-session.ts b/src/acp/live-session.ts index 52f25c9c..167addc8 100644 --- a/src/acp/live-session.ts +++ b/src/acp/live-session.ts @@ -95,6 +95,8 @@ export interface LiveSessionConfig { tools: BridgeToolDef[]; session: NewSessionParams; auth: AgyAuth; + /** agy session id stored for this OpenCode session; resumed instead of opening a new one when set. */ + resumeId?: string; } function definedOnly(o: T | undefined): Partial { @@ -109,6 +111,8 @@ export class LiveSession implements PoolEntry { turn?: LiveTurn; dead = false; record?: SessionRecord; + /** True while the current agy session was resumed from the store (it already holds the history). */ + resumed = false; readonly claimed = new Set(); readonly callOrder: string[] = []; private readonly toolCalls = new Map(); @@ -160,7 +164,7 @@ export class LiveSession implements PoolEntry { ...(deps.idleTimeoutMs === undefined ? {} : { idleTimeoutMs: deps.idleTimeoutMs }), }); live = new LiveSession(proc, bridge, pending, config, deps.log); - const models = await live.openSession(); + const models = config.resumeId ? await live.resumeOrOpen(config.resumeId) : await live.openSession(); deps.onAuthStatus?.(undefined); deps.onModels?.(models); if (config.tools.length > 0) { @@ -189,9 +193,28 @@ export class LiveSession implements PoolEntry { const res = await this.proc.newSession(this.config.session); this.agySessionId = res.sessionId; this.record = undefined; + this.resumed = false; return res.models; } + /** + * Reattaches the stored agy session so history and prompt cache survive a process restart. + * Falls back to a new session when agy cannot resume it (expired, deleted, other machine). + */ + async resumeOrOpen(sessionId: string): Promise { + try { + const res = await this.proc.resumeSession(sessionId, this.config.session); + this.agySessionId = res.sessionId; + this.resumed = true; + return res.models; + } catch (error) { + if (this.dead) throw error; + const detail = error instanceof Error ? error.message : String(error); + this.log("warn", `agy session/resume failed, opening a new session: ${detail}`); + return this.openSession(); + } + } + private onPermission(req: AcpPermissionRequest): AcpPermissionResponse { const id = req.toolCall?.toolCallId; const toolCall = { ...this.toolCalls.get(id), ...definedOnly(req.toolCall) } as AcpToolCall; diff --git a/src/acp/process.ts b/src/acp/process.ts index 79ed427c..316efca8 100644 --- a/src/acp/process.ts +++ b/src/acp/process.ts @@ -115,6 +115,14 @@ export interface AgyExit { stderrTail: string; } +function sessionParams(p: NewSessionParams): Record { + const params: Record = { cwd: p.cwd, mcpServers: [] }; + if (p.systemPromptAppend) { + params._meta = { antigravity: { systemPrompt: { append: p.systemPromptAppend } } }; + } + return params; +} + const STDERR_TAIL_BYTES = 4096; const KILL_GRACE_MS = 2000; @@ -291,12 +299,20 @@ export class AgyAcpProcess { } async newSession(p: NewSessionParams): Promise { - const params: Record = { cwd: p.cwd, mcpServers: [] }; - if (p.systemPromptAppend) { - params._meta = { antigravity: { systemPrompt: { append: p.systemPromptAppend } } }; - } - const res = await this.rpc("session/new", params); - const sessionId: string = res.sessionId; + const res = await this.rpc("session/new", sessionParams(p)); + return this.applySelections(res.sessionId, res, p); + } + + /** + * Reattaches a session agy persisted earlier (`session/resume` replays no history and keeps the + * prompt cache). Rejects when agy no longer knows the session. + */ + async resumeSession(sessionId: string, p: NewSessionParams): Promise { + const res = await this.rpc("session/resume", { sessionId, ...sessionParams(p) }); + return this.applySelections(sessionId, res ?? {}, p); + } + + private async applySelections(sessionId: string, res: any, p: NewSessionParams): Promise { const models: AcpModelInfo[] = res.models?.availableModels ?? []; const currentModelId: string | undefined = res.models?.currentModelId; diff --git a/test/acp/language-model.test.ts b/test/acp/language-model.test.ts index a03007a1..760d4919 100644 --- a/test/acp/language-model.test.ts +++ b/test/acp/language-model.test.ts @@ -742,16 +742,44 @@ describe("AgyAcpLanguageModel", () => { expect((await h.deps.store.get("ses-1"))!.agySessionId).toBe("s2"); }); - it("respawns when the process died while idle", async () => { + it("resumes the stored agy session when the process died while idle", async () => { const h = harness([INIT, AUTH, NEW, { expect: "session/prompt", reply: END }]); const history = [user("hi")]; await run(h, opts(history)); const live = h.deps.pool.get("ses-1")!; - writeFileSync(path.join(h.dir, "scenario.json"), JSON.stringify([INIT, AUTH, NEW, { expect: "session/prompt", reply: END }])); + writeFileSync( + path.join(h.dir, "scenario.json"), + JSON.stringify([INIT, AUTH, { expect: "session/resume", reply: { models: NEW.reply.models } }, { expect: "session/prompt", reply: END }]), + ); + await live.proc.dispose(); + await run(h, opts([...history, { role: "assistant", content: [{ type: "text", text: "a" }] }, user("again")])); + expect(h.starts()).toHaveLength(2); + expect(h.recv("session/resume")[0].message.params.sessionId).toBe("s1"); + expect(h.recv("session/new")).toHaveLength(1); + expect(promptTexts(h)[1]).toEqual(["again"]); + expect((await h.deps.store.get("ses-1"))!.agySessionId).toBe("s1"); + }); + + it("opens a new session and replays history when resume fails", async () => { + const h = harness([INIT, AUTH, NEW, { expect: "session/prompt", reply: END }]); + const history = [user("hi")]; + await run(h, opts(history)); + const live = h.deps.pool.get("ses-1")!; + writeFileSync( + path.join(h.dir, "scenario.json"), + JSON.stringify([ + INIT, + AUTH, + { expect: "session/resume", error: { code: -32602, message: "unknown session" } }, + { ...NEW, reply: { ...NEW.reply, sessionId: "s2" } }, + { expect: "session/prompt", reply: END }, + ]), + ); await live.proc.dispose(); await run(h, opts([...history, { role: "assistant", content: [{ type: "text", text: "a" }] }, user("again")])); expect(h.starts()).toHaveLength(2); expect(promptTexts(h)[1]![0]).toContain(""); + expect((await h.deps.store.get("ses-1"))!.agySessionId).toBe("s2"); }); it("idle_kill_closes_bridge_and_frees_slot", async () => { diff --git a/test/acp/process.test.ts b/test/acp/process.test.ts index 7e9e875e..adf7497e 100644 --- a/test/acp/process.test.ts +++ b/test/acp/process.test.ts @@ -243,6 +243,43 @@ describe("AgyAcpProcess", () => { expect(t.recv("session/set_config_option")).toHaveLength(1); }); + it("resumes a stored session with the same params and selections", async () => { + const t = setup([ + INIT, + { + expect: "session/resume", + reply: { + models: { currentModelId: "m1", availableModels: [{ modelId: "m1" }] }, + modes: { currentModeId: "auto" }, + }, + }, + { expect: "session/set_model", reply: {} }, + { expect: "session/set_config_option", reply: {} }, + { expect: "session/set_config_option", reply: {} }, + ]); + const p = await t.start(); + const res = await p.resumeSession("old-1", { cwd: "/w", systemPromptAppend: "sys", modelId: "m2", tier: "high" }); + const sent = t.recv("session/resume")[0].message.params; + expect(sent).toEqual({ + sessionId: "old-1", + cwd: "/w", + mcpServers: [], + _meta: { antigravity: { systemPrompt: { append: "sys" } } }, + }); + expect(res).toEqual({ sessionId: "old-1", models: [{ modelId: "m1" }], currentModelId: "m1" }); + expect(t.recv("session/set_model")[0].message.params).toEqual({ sessionId: "old-1", modelId: "m2" }); + expect(t.recv("session/set_config_option").map((e) => e.message.params.configId)).toEqual([ + "thought_level", + "mode", + ]); + }); + + it("rejects when agy cannot resume the session", async () => { + const t = setup([INIT, { expect: "session/resume", error: { code: -32602, message: "unknown session" } }]); + const p = await t.start(); + await expect(p.resumeSession("gone", { cwd: "/w" })).rejects.toThrow(/unknown session/); + }); + it("startup_timeout", async () => { const t = setup([{ expect: "initialize" }], { startupTimeoutMs: 50 }); await expect(AgyAcpProcess.start(t.opts)).rejects.toThrow(/did not start within/); From 63e90116e301ae2f5dd431d5f97e33f35c9c7384 Mon Sep 17 00:00:00 2001 From: Anthony Hausman Date: Sun, 29 Nov 2026 21:30:21 +0100 Subject: [PATCH 02/13] feat(acp): run title and summary side calls in throwaway sessions OpenCode tags each model request with a kind. Non-primary kinds such as title now use a throwaway agy session, so they never reset or pollute the stored primary conversation. Assisted-by: Claude Opus 5.5 --- src/acp/language-model.ts | 8 ++++++-- test/acp/language-model.test.ts | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 2 deletions(-) diff --git a/src/acp/language-model.ts b/src/acp/language-model.ts index 869b3f67..83e75be9 100644 --- a/src/acp/language-model.ts +++ b/src/acp/language-model.ts @@ -8,7 +8,7 @@ import type { LanguageModelV3Usage, SharedV3Warning, } from "@ai-sdk/provider"; -import { AGY_ACP_PROVIDER_ID, CANCEL_SETTLE_TIMEOUT_MS, SESSION_HEADER, type AgyTier } from "./constants"; +import { AGY_ACP_PROVIDER_ID, CANCEL_SETTLE_TIMEOUT_MS, KIND_HEADER, SESSION_HEADER, type AgyTier } from "./constants"; import { AgyAcpError, toAgyError } from "./errors"; import { LiveSession, type AgyAcpDeps, type LiveTurn } from "./live-session"; import type { BridgeToolDef, ToolOutcome } from "./mcp-bridge"; @@ -98,7 +98,11 @@ function prepareCall(o: LanguageModelV3CallOptions): { warnings: SharedV3Warning .join("\n\n"); const rawTier = (o.providerOptions?.[AGY_ACP_PROVIDER_ID] as { tier?: unknown } | undefined)?.tier; const tier = typeof rawTier === "string" && TIERS.has(rawTier) ? (rawTier as AgyTier) : undefined; - return { warnings, ctx: { key: headerValue(o.headers, SESSION_HEADER), system, tools, tier } }; + // Side calls (title, summary, compaction...) run in a throwaway agy session so + // they never touch the stored conversation of the primary session. + const kind = headerValue(o.headers, KIND_HEADER); + const key = kind && kind !== "primary" ? undefined : headerValue(o.headers, SESSION_HEADER); + return { warnings, ctx: { key, system, tools, tier } }; } function cleanBlocks(blocks: AcpContentBlock[]): AcpContentBlock[] { diff --git a/test/acp/language-model.test.ts b/test/acp/language-model.test.ts index 760d4919..998a6b70 100644 --- a/test/acp/language-model.test.ts +++ b/test/acp/language-model.test.ts @@ -591,6 +591,38 @@ describe("AgyAcpLanguageModel", () => { expect(h.recv("session/new")[0].message.params._meta.antigravity.systemPrompt.append).toBe("Generate a title"); }); + it("title_kind_uses_throwaway_even_with_session_header", async () => { + const h = harness([INIT, AUTH, NEW, { expect: "session/prompt", notify: [chunk("Title")], reply: END }, CLOSE], { + deps: { bridgeConnectTimeoutMs: 1 }, + }); + const parts = await run( + h, + opts([system("Generate a title"), user("hello")], { + tools: [READ_TOOL], + headers: { "X-OpenCode-Session-Id": "ses-1", "X-OpenCode-Request-Kind": "title" }, + }), + ); + expect(errorsOf(parts)).toHaveLength(0); + expect(finishOf(parts).finishReason.unified).toBe("stop"); + expect(h.bridge("tools/list")[0].response.result.tools).toEqual([]); + expect(h.recv("session/new")).toHaveLength(1); + expect(h.recv("session/close")).toHaveLength(1); + expect(existsSync(path.join(h.dir, "sessions.json"))).toBe(false); + }); + + it("primary_kind_keeps_the_session", async () => { + const h = harness([INIT, AUTH, NEW, { expect: "session/prompt", notify: [chunk("Hi")], reply: END }]); + const parts = await run( + h, + opts([user("hello")], { + headers: { "X-OpenCode-Session-Id": "ses-1", "X-OpenCode-Request-Kind": "primary" }, + }), + ); + expect(errorsOf(parts)).toHaveLength(0); + expect(h.recv("session/close")).toHaveLength(0); + expect(existsSync(path.join(h.dir, "sessions.json"))).toBe(true); + }); + it("throwaway reports errors and still disposes", async () => { const h = harness([ INIT, From 98aa106ca8643d72b314369270199e8d49f2edaa Mon Sep 17 00:00:00 2001 From: Anthony Hausman Date: Mon, 30 Nov 2026 06:06:05 +0100 Subject: [PATCH 03/13] feat(acp): report agy context use on tool-call steps Tool-call steps finished with zero usage, so the OpenCode context gauge and compaction stayed blind mid-turn. Use the latest usage_update context size as input tokens until agy reports usage. Assisted-by: Claude Opus 5.5 --- src/acp/language-model.ts | 4 +++- src/acp/live-session.ts | 3 +++ test/acp/language-model.test.ts | 24 ++++++++++++++++++++++++ 3 files changed, 30 insertions(+), 1 deletion(-) diff --git a/src/acp/language-model.ts b/src/acp/language-model.ts index 83e75be9..bfd09245 100644 --- a/src/acp/language-model.ts +++ b/src/acp/language-model.ts @@ -366,7 +366,9 @@ export class AgyAcpLanguageModel implements LanguageModelV3 { if (outcome.kind === "detached") return undefined; if (outcome.kind === "tool-calls") { await this.writeRecord(live, o); - out.emit({ type: "finish", finishReason: { unified: "tool-calls", raw: undefined }, usage: mapUsage() }); + // agy reports prompt usage only at the end of the turn; usage_update gives the context in use so far. + const usage = mapUsage(turn.contextUsed !== undefined ? { inputTokens: turn.contextUsed } : undefined); + out.emit({ type: "finish", finishReason: { unified: "tool-calls", raw: undefined }, usage }); return undefined; } turn.detachAbort?.(); diff --git a/src/acp/live-session.ts b/src/acp/live-session.ts index 167addc8..0a8bbb91 100644 --- a/src/acp/live-session.ts +++ b/src/acp/live-session.ts @@ -78,6 +78,8 @@ export class LiveTurn { done: Promise = Promise.resolve(); detachAbort?: () => void; interruptWrite?: Promise; + /** Latest context use agy reported through `usage_update` (tokens). */ + contextUsed?: number; setAbortSignal(signal: AbortSignal | undefined, onAbort: (reason: unknown) => void): void { this.detachAbort?.(); @@ -243,6 +245,7 @@ export class LiveSession implements PoolEntry { const merged = { ...this.toolCalls.get(u.toolCallId), ...definedOnly(u as AcpToolCall) } as AcpToolCall; this.toolCalls.set(u.toolCallId, merged); } + if (u.sessionUpdate === "usage_update" && typeof u.used === "number") turn.contextUsed = u.used; const ev = turn.mapper.map(u); if (ev.bridgeCall) { this.pending.expect(ev.bridgeCall); diff --git a/test/acp/language-model.test.ts b/test/acp/language-model.test.ts index 998a6b70..813b5f66 100644 --- a/test/acp/language-model.test.ts +++ b/test/acp/language-model.test.ts @@ -208,6 +208,30 @@ describe("AgyAcpLanguageModel", () => { expect(record!.messageHashes).toHaveLength(1); }); + it("reports agy context use on tool-call steps from usage_update", async () => { + const h = harness([ + INIT, + AUTH, + NEW, + { + expect: "session/prompt", + notify: [ + { + method: "session/update", + params: { sessionId: "s1", update: { sessionUpdate: "usage_update", used: 4321, size: 1048576 } }, + }, + ], + callMcp: { tool: "read", args: { path: "a" }, toolCallId: "t1" }, + reply: END, + }, + ]); + const parts = await run(h, opts([user("read a")], { tools: [READ_TOOL] })); + const f = finishOf(parts); + expect(f.finishReason.unified).toBe("tool-calls"); + expect(f.usage.inputTokens.total).toBe(4321); + expect(f.usage.outputTokens.total).toBeUndefined(); + }); + it("bridge_tool_round_trip", async () => { const h = harness([ INIT, From c9023aeabeb5fb8d491aa3cdcafa888815871622 Mon Sep 17 00:00:00 2001 From: Anthony Hausman Date: Mon, 30 Nov 2026 06:11:56 +0100 Subject: [PATCH 04/13] feat(acp): report agy 429 as one rate limit error agy reports quota exhaustion as chat text. Drop its retry notices and turn the final give-up line into a rate_limited error. Assisted-by: Claude Opus 5.5 --- src/acp/errors.ts | 1 + src/acp/language-model.ts | 11 +++++++++++ src/acp/stream-map.ts | 16 +++++++++++++++- test/acp/language-model.test.ts | 14 ++++++++++++++ test/acp/stream-map.test.ts | 25 +++++++++++++++++++++++++ 5 files changed, 66 insertions(+), 1 deletion(-) diff --git a/src/acp/errors.ts b/src/acp/errors.ts index 6ca5beda..4707a48d 100644 --- a/src/acp/errors.ts +++ b/src/acp/errors.ts @@ -9,6 +9,7 @@ export type AgyErrorCode = | "plugin_install" | "bridge_unreachable" | "crash" + | "rate_limited" | "other"; export const BRIDGE_NOT_CONNECTED_TEXT = diff --git a/src/acp/language-model.ts b/src/acp/language-model.ts index bfd09245..f2bffdf8 100644 --- a/src/acp/language-model.ts +++ b/src/acp/language-model.ts @@ -400,6 +400,17 @@ export class AgyAcpLanguageModel implements LanguageModelV3 { out.error(error); return undefined; } + const limit = turn.mapper.rateLimit; + if (limit !== undefined) { + await this.markInterrupted(live); + out.error( + new AgyAcpError( + "rate_limited", + `agy reported ${limit} agy already retried; wait for the quota to reset or switch model.`, + ), + ); + return undefined; + } return turn.settled!.result!; } diff --git a/src/acp/stream-map.ts b/src/acp/stream-map.ts index ad7f0880..a9f2fb51 100644 --- a/src/acp/stream-map.ts +++ b/src/acp/stream-map.ts @@ -67,16 +67,30 @@ function resultText(tc: AcpToolCall): string { return ""; } +const AGY_RETRY_LINE = /^\s*⚠ API error \(attempt \d+\): RESOURCE_EXHAUSTED \(code 429\)[^\n]*\s*$/; +const AGY_RATE_LIMIT_LINE = /^\s*⚠ (RESOURCE_EXHAUSTED \(code 429\)[^\n]*?)\s*$/; + export class StreamMapper { private open?: { kind: "text" | "reasoning"; id: string }; private counter = 0; private readonly seen = new Set(); private readonly providerCalls = new Map(); + /** agy's final 429 message, set when agy gave up retrying a rate-limited request. */ + rateLimit?: string; map(update: AcpSessionUpdate): MappedEvent { switch (update.sessionUpdate) { - case "agent_message_chunk": + case "agent_message_chunk": { + // agy reports quota errors as chat text: drop its retry notices, keep the final one as an error. + const text = update.content?.type === "text" ? update.content.text : undefined; + if (text !== undefined && AGY_RETRY_LINE.test(text)) return { parts: [] }; + const final = text === undefined ? null : AGY_RATE_LIMIT_LINE.exec(text); + if (final) { + this.rateLimit = final[1]; + return { parts: [] }; + } return { parts: this.chunk("text", update.content) }; + } case "agent_thought_chunk": return { parts: this.chunk("reasoning", update.content) }; case "tool_call": diff --git a/test/acp/language-model.test.ts b/test/acp/language-model.test.ts index 813b5f66..0f5c42de 100644 --- a/test/acp/language-model.test.ts +++ b/test/acp/language-model.test.ts @@ -352,6 +352,20 @@ describe("AgyAcpLanguageModel", () => { await waitFor(() => h.entries().length > 0); }); + it("reports agy's 429 give-up text as one rate_limited error", async () => { + const retry = "\n⚠ API error (attempt 1): RESOURCE_EXHAUSTED (code 429): Resource has been exhausted (e.g. check quota).\n"; + const final = "\n⚠ RESOURCE_EXHAUSTED (code 429): Resource has been exhausted (e.g. check quota).\n"; + const h = harness([INIT, AUTH, NEW, { expect: "session/prompt", notify: [chunk(retry), chunk(final)], reply: END }]); + const parts = await run(h, opts([user("hi")])); + const errors = errorsOf(parts); + expect(errors).toHaveLength(1); + expect(errors[0].error.code).toBe("rate_limited"); + expect(errors[0].error.message).toContain("RESOURCE_EXHAUSTED (code 429)"); + expect(parts.filter((p: any) => p.type === "text-delta")).toHaveLength(0); + expect(finishOf(parts)).toBeUndefined(); + expect((await h.deps.store.get("ses-1"))?.interrupted).toBe(true); + }); + it("plugin_install_failure_is_error", async () => { const h = harness([INIT, AUTH, NEW], { deps: { ensurePlugin: vi.fn(async () => Promise.reject(new Error("install failed"))) }, diff --git a/test/acp/stream-map.test.ts b/test/acp/stream-map.test.ts index c02bcf8d..6cea8b5b 100644 --- a/test/acp/stream-map.test.ts +++ b/test/acp/stream-map.test.ts @@ -29,6 +29,31 @@ const bridgeCall = (id = "t1"): AcpSessionUpdate => ({ }, }); +describe("agy 429 chat text", () => { + const RETRY = "\n⚠ API error (attempt 1): RESOURCE_EXHAUSTED (code 429): Resource has been exhausted (e.g. check quota).\n"; + const FINAL = "\n⚠ RESOURCE_EXHAUSTED (code 429): Resource has been exhausted (e.g. check quota).\n"; + + it("drops retry lines and keeps text that follows", () => { + const m = new StreamMapper(); + expect(m.map(msg(RETRY)).parts).toEqual([]); + const parts = m.map(msg("Hello")).parts; + expect(parts.map((p) => p.type)).toEqual(["text-start", "text-delta"]); + expect(m.rateLimit).toBeUndefined(); + }); + + it("records the final give-up line instead of emitting it", () => { + const m = new StreamMapper(); + expect(m.map(msg(FINAL)).parts).toEqual([]); + expect(m.rateLimit).toBe("RESOURCE_EXHAUSTED (code 429): Resource has been exhausted (e.g. check quota)."); + }); + + it("leaves ordinary text mentioning 429 alone", () => { + const m = new StreamMapper(); + expect(m.map(msg("HTTP 429 means too many requests")).parts).toHaveLength(2); + expect(m.rateLimit).toBeUndefined(); + }); +}); + describe("text and reasoning blocks", () => { it("groups consecutive chunks and closes on flush", () => { const m = new StreamMapper(); From ee36bd7bee7d73f35174e87b755b1c3ef00f399b Mon Sep 17 00:00:00 2001 From: Anthony Hausman Date: Mon, 30 Nov 2026 19:25:10 +0100 Subject: [PATCH 05/13] feat(acp): pass tool-result images to agy through the bridge Image parts of OpenCode tool results now reach agy as MCP image content, and as ACP image blocks for late results. PDFs and other attachments become short text notes instead of type placeholders. Assisted-by: Claude Opus 5.5 --- src/acp/language-model.ts | 11 +++++++---- src/acp/mcp-bridge.ts | 9 +++++++-- src/acp/session-sync.ts | 25 ++++++++++++++++++------- test/acp/language-model.test.ts | 33 +++++++++++++++++++++++++++++++++ test/acp/mcp-bridge.test.ts | 11 +++++++++++ test/acp/session-sync.test.ts | 26 ++++++++++++++++++++++++++ 6 files changed, 102 insertions(+), 13 deletions(-) diff --git a/src/acp/language-model.ts b/src/acp/language-model.ts index f2bffdf8..ae394d97 100644 --- a/src/acp/language-model.ts +++ b/src/acp/language-model.ts @@ -110,10 +110,13 @@ function cleanBlocks(blocks: AcpContentBlock[]): AcpContentBlock[] { } function lateBlocks(late: Array<{ callId: string; outcome: ToolOutcome }>): AcpContentBlock[] { - return late.map(({ callId, outcome }) => ({ - type: "text", - text: `\n${outcome.text}\n`, - })); + return late.flatMap(({ callId, outcome }): AcpContentBlock[] => [ + { + type: "text", + text: `\n${outcome.text}\n`, + }, + ...(outcome.images ?? []).map((i): AcpContentBlock => ({ type: "image", data: i.data, mimeType: i.mimeType })), + ]); } export class AgyAcpLanguageModel implements LanguageModelV3 { diff --git a/src/acp/mcp-bridge.ts b/src/acp/mcp-bridge.ts index cad1dc6a..2b80807f 100644 --- a/src/acp/mcp-bridge.ts +++ b/src/acp/mcp-bridge.ts @@ -22,7 +22,9 @@ export interface BridgeCall { input: unknown; } -export type ToolOutcome = { text: string; isError: boolean }; +export type ToolImage = { data: string; mimeType: string }; +/** An OpenCode tool result as agy sees it: text plus optional base64 images. */ +export type ToolOutcome = { text: string; isError: boolean; images?: ToolImage[] }; const TOOL_SUMMARY_KEY = "toolSummary"; @@ -251,7 +253,10 @@ export class McpBridge { } const outcome = await pending.claim(name, input); return { - content: [{ type: "text" as const, text: outcome.text }], + content: [ + { type: "text" as const, text: outcome.text }, + ...(outcome.images ?? []).map((i) => ({ type: "image" as const, data: i.data, mimeType: i.mimeType })), + ], ...(outcome.isError ? { isError: true } : {}), }; }); diff --git a/src/acp/session-sync.ts b/src/acp/session-sync.ts index b3722b60..d9289c47 100644 --- a/src/acp/session-sync.ts +++ b/src/acp/session-sync.ts @@ -3,7 +3,7 @@ import fs from "node:fs/promises"; import path from "node:path"; import type { LanguageModelV3Message, LanguageModelV3Prompt } from "@ai-sdk/provider"; import { agyAcpDataDir } from "./constants"; -import type { BridgeToolDef, ToolOutcome } from "./mcp-bridge"; +import type { BridgeToolDef, ToolImage, ToolOutcome } from "./mcp-bridge"; import type { AcpContentBlock } from "./process"; export interface SessionRecord { @@ -184,15 +184,26 @@ function toOutcome(output: any): ToolOutcome { case "execution-denied": return { text: output.reason ?? "Execution denied", isError: true }; default: - return { - text: (output.value as Part[]) - .map((i) => (i.type === "text" ? i.text : `[${i.type}]`)) - .join("\n"), - isError: false, - }; + return contentOutcome(output.value as Part[]); } } +/** Keeps inline images for agy; other attachments become short text notes. */ +function contentOutcome(parts: Part[]): ToolOutcome { + const lines: string[] = []; + const images: ToolImage[] = []; + for (const p of parts) { + const inline = p.type === "image-data" || p.type === "media" || p.type === "file-data"; + if (p.type === "text") lines.push(p.text); + else if (inline && typeof p.mediaType === "string" && p.mediaType.startsWith("image/")) + images.push({ data: String(p.data), mimeType: p.mediaType }); + else if (inline) lines.push(fileNote(p)); + else if (p.type === "image-url") lines.push(`[image url: ${p.url}]`); + else lines.push(`[${p.type}]`); + } + return { text: lines.join("\n"), isError: false, ...(images.length ? { images } : {}) }; +} + export function renderCheckpoint(messages: LanguageModelV3Message[]): string { const entries: string[] = []; for (const m of messages) { diff --git a/test/acp/language-model.test.ts b/test/acp/language-model.test.ts index 0f5c42de..52e1d15b 100644 --- a/test/acp/language-model.test.ts +++ b/test/acp/language-model.test.ts @@ -341,6 +341,39 @@ describe("AgyAcpLanguageModel", () => { expect((await h.deps.store.get("ses-1"))!.interrupted).toBe(false); }); + it("late tool-result images reach agy as image blocks", async () => { + const h = harness( + [ + INIT, + AUTH, + NEW, + { expect: "session/prompt", callMcp: { tool: "read", args: { path: "a" }, toolCallId: "t1" }, reply: END }, + { expect: "session/prompt", reply: END }, + ], + { deps: { softTimeoutMs: 20 } }, + ); + const history = [user("read a")]; + await run(h, opts(history, { tools: [READ_TOOL] })); + await waitFor(() => bridgeTexts(h)[0] === STILL_RUNNING_TEXT); + const imageResult: LanguageModelV3Message = { + role: "tool", + content: [ + { + type: "tool-result", + toolCallId: "t1", + toolName: "read", + output: { type: "content", value: [{ type: "text", text: "pic" }, { type: "image-data", data: "AAA", mediaType: "image/png" }] }, + }, + ], + }; + await run(h, opts([...history, assistantCall("t1", { path: "a" }), imageResult], { tools: [READ_TOOL] })); + const blocks = h.recv("session/prompt")[1]!.message.params.prompt; + expect(blocks.slice(0, 2)).toEqual([ + { type: "text", text: '\npic\n' }, + { type: "image", data: "AAA", mimeType: "image/png" }, + ]); + }); + it("bridge_not_connected_is_error", async () => { const h = harness([INIT, AUTH, NEW], { env: { FAKE_ACP_SKIP_BRIDGE: "1" }, deps: { bridgeConnectTimeoutMs: 50 } }); const parts = await run(h, opts([user("hi")], { tools: [READ_TOOL] })); diff --git a/test/acp/mcp-bridge.test.ts b/test/acp/mcp-bridge.test.ts index 1f83a993..386464d4 100644 --- a/test/acp/mcp-bridge.test.ts +++ b/test/acp/mcp-bridge.test.ts @@ -114,6 +114,17 @@ describe("McpBridge", () => { expect(pending.size).toBe(0); }); + it("returns tool-result images as MCP image content", async () => { + const { pending, client } = await setup(); + pending.expect({ callId: "t1", toolName: "read", input: { path: "a" } }); + pending.resolve("t1", { text: "shot", isError: false, images: [{ data: "AAA", mimeType: "image/png" }] }); + const r = await client.callTool({ name: "read", arguments: { path: "a" } }); + expect(r.content).toEqual([ + { type: "text", text: "shot" }, + { type: "image", data: "AAA", mimeType: "image/png" }, + ]); + }); + it("error_outcome", async () => { const { pending, client } = await setup(); pending.expect({ callId: "t1", toolName: "read", input: { path: "a" } }); diff --git a/test/acp/session-sync.test.ts b/test/acp/session-sync.test.ts index 8069c5b3..5743e249 100644 --- a/test/acp/session-sync.test.ts +++ b/test/acp/session-sync.test.ts @@ -210,6 +210,32 @@ describe("decideSync", () => { ]); }); + it("keeps tool-result images and notes other attachments", () => { + const hist = [user("a")]; + const out = { + type: "content", + value: [ + { type: "text", text: "shot" }, + { type: "image-data", data: "AAA", mediaType: "image/png" }, + { type: "media", data: "BBB", mediaType: "image/jpeg" }, + { type: "file-data", data: "CCC", mediaType: "image/webp" }, + { type: "file-data", data: "DDD", mediaType: "application/pdf", filename: "spec.pdf" }, + { type: "media", data: "EEE", mediaType: "audio/wav" }, + { type: "image-url", url: "https://x/y.png" }, + ], + }; + const d = decideSync(rec(hist), [...hist, toolMsg("c", "n", out)], "fp") as any; + expect(d.toolResults[0].outcome).toEqual({ + text: "shot\n[file omitted: spec.pdf]\n[file omitted: audio/wav]\n[image url: https://x/y.png]", + isError: false, + images: [ + { data: "AAA", mimeType: "image/png" }, + { data: "BBB", mimeType: "image/jpeg" }, + { data: "CCC", mimeType: "image/webp" }, + ], + }); + }); + it("interrupted yields catch-up with checkpoint after prefix", () => { const hist = [user("a")]; const d = decideSync(rec(hist, { interrupted: true }), [sys, ...hist, asst("partial"), user("n")], "fp"); From 5b86c139abed3a7f65d02600487ed4d7a3df1500 Mon Sep 17 00:00:00 2001 From: Anthony Hausman Date: Tue, 1 Dec 2026 12:10:38 +0100 Subject: [PATCH 06/13] fix(acp): allow agy to read OpenCode tool-output files OpenCode points the model at truncated tool output under its tool-output dir; agy asks permission for that read_file and the policy rejected it. Allow reads that resolve inside that dir. Assisted-by: Claude Opus 5.5 --- AGENTS.md | 2 +- src/acp/live-session.ts | 7 +++--- src/acp/permission.ts | 44 ++++++++++++++++++++++++++++++++----- test/acp/permission.test.ts | 42 +++++++++++++++++++++++++++++++++++ 4 files changed, 86 insertions(+), 9 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 9ca0fd7b..85eefb55 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -17,7 +17,7 @@ The former direct Code Assist provider `google-agy` (OAuth, `models.json`, `agy_ | `rpc.ts`, `process.ts` | NDJSON JSON-RPC connection and per-session `agy acp` process pool (startup 30 s, idle kill 5 min). Plain `spawn`, no shell; `session/new` always sends `mcpServers: []` | | `mcp-bridge.ts` + `agy-plugin/bridge-proxy.mjs` | local MCP bridge (127.0.0.1, random port, 32-byte hex bearer token passed to the child only as `AGY_ACP_BRIDGE_URL` / `AGY_ACP_BRIDGE_TOKEN`). agy hard-times MCP calls out at 180 s; the bridge soft-replies at 170 s | | `agy-plugin.ts` | installs the shipped `agy-plugin/` as global agy plugin `opencode-bridge` via `agy plugin install` only (never edits `~/.gemini/config/*` by hand); one-time notice | -| `permission.ts` | `allow_once` for bridge `call_mcp_tool` only, `reject_once` otherwise. Allowed provider-executed built-ins: `read_file`, `list_resources`, `read_resource`, `manage_task`; any other tool name cancels the turn | +| `permission.ts` | `allow_once` for bridge `call_mcp_tool` and for `read_file` of files under OpenCode's `tool-output` dir (symlinks resolved), `reject_once` otherwise. Allowed provider-executed built-ins: `read_file`, `list_resources`, `read_resource`, `manage_task`; any other tool name cancels the turn | | `stream-map.ts`, `language-model.ts`, `live-session.ts`, `session-lock.ts`, `session-sync.ts`, `errors.ts` | ACP update to AI SDK stream mapping, language model, history sync, error classification | | `register-auth.ts`, `register-catalog.ts`, `sdk-placeholder.ts` | auth methods (Gemini API key and Vertex recommended; Google login is external, the plugin never reads agy tokens or the OS keyring), model catalog | | `debug.ts` | opt-in `AGY_ACP_DEBUG` log | diff --git a/src/acp/live-session.ts b/src/acp/live-session.ts index 0a8bbb91..548cab38 100644 --- a/src/acp/live-session.ts +++ b/src/acp/live-session.ts @@ -18,7 +18,7 @@ import { type PromptResult, } from "./process"; import type { SessionRecord, SessionStore } from "./session-sync"; -import { StreamMapper } from "./stream-map"; +import { StreamMapper, classifyToolCall } from "./stream-map"; /** One resolved credential for a call. `identity` is non-secret (never the raw key). */ export interface AgyAuth { @@ -221,10 +221,11 @@ export class LiveSession implements PoolEntry { const id = req.toolCall?.toolCallId; const toolCall = { ...this.toolCalls.get(id), ...definedOnly(req.toolCall) } as AcpToolCall; const { response, allowed } = decidePermission({ ...req, toolCall }); - if (allowed) { + if (allowed && classifyToolCall(toolCall).kind === "bridge") { + // Bridge calls wait on OpenCode; allowed built-ins (read_file) run inside agy. this.turn?.parked.add(id); this.turn?.signal.fire(); - } else { + } else if (!allowed) { this.log("warn", `agy-acp: rejected agy tool ${toolCall.name ?? "(unknown)"} (call ${id})`); } return response; diff --git a/src/acp/permission.ts b/src/acp/permission.ts index 08eda0d1..ee856925 100644 --- a/src/acp/permission.ts +++ b/src/acp/permission.ts @@ -1,18 +1,52 @@ -import type { AcpPermissionOption, AcpPermissionRequest, AcpPermissionResponse } from "./process"; +import { realpathSync, statSync } from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import type { AcpPermissionOption, AcpPermissionRequest, AcpPermissionResponse, AcpToolCall } from "./process"; import { classifyToolCall } from "./stream-map"; const ALLOW_KINDS: readonly AcpPermissionOption["kind"][] = ["allow_once", "allow_always"]; const REJECT_KINDS: readonly AcpPermissionOption["kind"][] = ["reject_once", "reject_always"]; +const PATH_KEYS = ["Path", "AbsolutePath", "path", "absolutePath", "file_path"] as const; + +/** Directory where OpenCode stores full outputs of truncated tool results. */ +export function openCodeToolOutputDir(env: NodeJS.ProcessEnv = process.env): string { + const base = env.XDG_DATA_HOME || path.join(env.HOME || os.homedir(), ".local/share"); + return path.join(base, "opencode", "tool-output"); +} + +/** + * True when agy asks to `read_file` a regular file inside OpenCode's + * tool-output directory (OpenCode tells the model to read truncated outputs + * there). Symlinks are resolved, so links pointing out are rejected. + */ +function isToolOutputRead(toolCall: AcpToolCall, env: NodeJS.ProcessEnv): boolean { + if (toolCall.name !== "read_file") return false; + const input = toolCall.rawInput as Record | undefined; + const target = PATH_KEYS.map((k) => input?.[k]).find((v): v is string => typeof v === "string"); + if (!target || !path.isAbsolute(target)) return false; + try { + const dir = realpathSync(openCodeToolOutputDir(env)); + const file = realpathSync(target); + return file.startsWith(dir + path.sep) && statSync(file).isFile(); + } catch { + return false; + } +} /** - * Allows only `call_mcp_tool` aimed at the OpenCode bridge; rejects everything - * else. Replies `cancelled` only when no option of the needed kind exists. + * Allows `call_mcp_tool` aimed at the OpenCode bridge and `read_file` of + * OpenCode tool-output files; rejects everything else. Replies `cancelled` + * only when no option of the needed kind exists. */ -export function decidePermission(req: AcpPermissionRequest): { +export function decidePermission( + req: AcpPermissionRequest, + env: NodeJS.ProcessEnv = process.env, +): { response: AcpPermissionResponse; allowed: boolean; } { - const allowed = classifyToolCall(req.toolCall ?? { toolCallId: "" }).kind === "bridge"; + const toolCall = req.toolCall ?? { toolCallId: "" }; + const allowed = classifyToolCall(toolCall).kind === "bridge" || isToolOutputRead(toolCall, env); const options = req.options ?? []; for (const kind of allowed ? ALLOW_KINDS : REJECT_KINDS) { const option = options.find((o) => o.kind === kind); diff --git a/test/acp/permission.test.ts b/test/acp/permission.test.ts index 94ff09cf..d9695ebd 100644 --- a/test/acp/permission.test.ts +++ b/test/acp/permission.test.ts @@ -1,3 +1,6 @@ +import { mkdirSync, mkdtempSync, symlinkSync, writeFileSync } from "node:fs"; +import os from "node:os"; +import path from "node:path"; import { describe, expect, it } from "vitest"; import { decidePermission } from "../../src/acp/permission"; import type { AcpPermissionOption, AcpPermissionRequest } from "../../src/acp/process"; @@ -53,6 +56,45 @@ describe("decidePermission", () => { expect(r.response).toEqual({ outcome: { outcome: "selected", optionId: "never" } }); }); + describe("read_file of OpenCode tool-output files", () => { + const data = mkdtempSync(path.join(os.tmpdir(), "agy-perm-")); + const outDir = path.join(data, "opencode", "tool-output"); + mkdirSync(outDir, { recursive: true }); + const inside = path.join(outDir, "tool_abc"); + writeFileSync(inside, "x"); + const outside = path.join(data, "secret.txt"); + writeFileSync(outside, "s"); + const escape = path.join(outDir, "link"); + symlinkSync(outside, escape); + const env = { XDG_DATA_HOME: data }; + const read = (rawInput: unknown) => req({ toolCallId: "r1", name: "read_file", rawInput }); + + it("allows a file inside the tool-output directory", () => { + expect(decidePermission(read({ Path: inside, StartLine: 1, EndLine: 9 }), env)).toEqual({ + response: { outcome: { outcome: "selected", optionId: "allow" } }, + allowed: true, + }); + expect(decidePermission(read({ AbsolutePath: inside }), env).allowed).toBe(true); + expect(decidePermission(read({ path: inside }), env).allowed).toBe(true); + }); + + it("rejects files outside it, escapes and symlinks out", () => { + expect(decidePermission(read({ Path: outside }), env).allowed).toBe(false); + expect(decidePermission(read({ Path: path.join(outDir, "..", "..", "secret.txt") }), env).allowed).toBe(false); + expect(decidePermission(read({ Path: escape }), env).allowed).toBe(false); + expect(decidePermission(read({ Path: outDir }), env).allowed).toBe(false); + expect(decidePermission(read({ Path: path.join(outDir, "missing") }), env).allowed).toBe(false); + expect(decidePermission(read({ Path: "tool_abc" }), env).allowed).toBe(false); + expect(decidePermission(read({}), env).allowed).toBe(false); + expect(decidePermission(read(undefined), env).allowed).toBe(false); + }); + + it("rejects other tools aimed at the tool-output directory", () => { + const r = decidePermission(req({ toolCallId: "w1", name: "write_file", rawInput: { Path: inside } }), env); + expect(r.allowed).toBe(false); + }); + }); + it("treats a missing tool call and options as a violation", () => { const r = decidePermission({ sessionId: "s1" } as unknown as AcpPermissionRequest); expect(r).toEqual({ response: { outcome: { outcome: "cancelled" } }, allowed: false }); From 5d5ee1d99721d571bd163590ba56b86c1929ed5d Mon Sep 17 00:00:00 2001 From: Anthony Hausman Date: Tue, 1 Dec 2026 12:10:58 +0100 Subject: [PATCH 07/13] fix(acp): close unresolved agy tool calls at turn end When agy ends a turn without finishing a provider-executed call, emit an error tool result so OpenCode does not fail the step. Assisted-by: Claude Opus 5.5 --- src/acp/language-model.ts | 4 ++-- src/acp/stream-map.ts | 20 ++++++++++++++++++++ test/acp/stream-map.test.ts | 26 ++++++++++++++++++++++++++ 3 files changed, 48 insertions(+), 2 deletions(-) diff --git a/src/acp/language-model.ts b/src/acp/language-model.ts index ae394d97..5b096101 100644 --- a/src/acp/language-model.ts +++ b/src/acp/language-model.ts @@ -429,11 +429,11 @@ export class AgyAcpLanguageModel implements LanguageModelV3 { } if (turn.aborted !== undefined) return { kind: "aborted" }; if (emitted.length > 0 && (turn.settled || emitted.every((id) => turn.parked.has(id)))) { - out.emit(...turn.mapper.flush()); + out.emit(...(turn.settled ? turn.mapper.finish() : turn.mapper.flush())); return { kind: "tool-calls" }; } if (turn.settled) { - out.emit(...turn.mapper.flush()); + out.emit(...turn.mapper.finish()); return { kind: "settled" }; } await turn.signal.wait(); diff --git a/src/acp/stream-map.ts b/src/acp/stream-map.ts index a9f2fb51..c83bc4b4 100644 --- a/src/acp/stream-map.ts +++ b/src/acp/stream-map.ts @@ -106,6 +106,26 @@ export class StreamMapper { return this.close(); } + /** + * Ends the turn: closes the open text block and gives every provider-executed + * call agy never finished an error result, so OpenCode does not report a + * missing tool result (agy can drop the update after a denied or aborted call). + */ + finish(): LanguageModelV3StreamPart[] { + const parts = this.close(); + for (const [toolCallId, toolName] of this.providerCalls) { + parts.push({ + type: "tool-result", + toolCallId, + toolName, + result: `agy did not report a result for ${toolName}`, + isError: true, + }); + } + this.providerCalls.clear(); + return parts; + } + private close(): LanguageModelV3StreamPart[] { const open = this.open; if (!open) return []; diff --git a/test/acp/stream-map.test.ts b/test/acp/stream-map.test.ts index 6cea8b5b..cbdcc635 100644 --- a/test/acp/stream-map.test.ts +++ b/test/acp/stream-map.test.ts @@ -183,6 +183,32 @@ describe("builtins", () => { expect(m.map({ sessionUpdate: "tool_call_update", toolCallId: "zz", status: "completed" }).parts).toEqual([]); }); + it("closes provider calls agy never finished when the turn ends", () => { + const m = new StreamMapper(); + m.map({ sessionUpdate: "tool_call", toolCallId: "a", name: "read_file" }); + m.map({ sessionUpdate: "tool_call", toolCallId: "b", name: "list_resources" }); + m.map({ sessionUpdate: "tool_call_update", toolCallId: "a", status: "completed", rawOutput: "ok" }); + m.map(msg("done")); + expect(m.finish()).toEqual([ + { type: "text-end", id: "text-0" }, + { + type: "tool-result", + toolCallId: "b", + toolName: "list_resources", + result: "agy did not report a result for list_resources", + isError: true, + }, + ]); + expect(m.finish()).toEqual([]); + }); + + it("keeps provider calls open on a plain flush", () => { + const m = new StreamMapper(); + m.map({ sessionUpdate: "tool_call", toolCallId: "b", name: "read_file" }); + expect(m.flush()).toEqual([]); + expect((m.finish()[0] as any).toolCallId).toBe("b"); + }); + it("does not duplicate a re-sent builtin tool_call", () => { const m = new StreamMapper(); const tc: AcpSessionUpdate = { sessionUpdate: "tool_call", toolCallId: "b", name: "read_file" }; From 08318ef9991f13df9c1923e63714b3ea8841eb82 Mon Sep 17 00:00:00 2001 From: Anthony Hausman Date: Tue, 1 Dec 2026 12:14:37 +0100 Subject: [PATCH 08/13] fix(acp): allow agy to read saved OpenCode shell output OpenCode 2.4 saves truncated shell output under its shell dir, not tool-output, so agy reads there were still rejected. Assisted-by: Claude Opus 5.5 --- AGENTS.md | 2 +- src/acp/permission.ts | 22 ++++++++++++++++++---- test/acp/permission.test.ts | 10 ++++++++++ 3 files changed, 29 insertions(+), 5 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 85eefb55..c105f769 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -17,7 +17,7 @@ The former direct Code Assist provider `google-agy` (OAuth, `models.json`, `agy_ | `rpc.ts`, `process.ts` | NDJSON JSON-RPC connection and per-session `agy acp` process pool (startup 30 s, idle kill 5 min). Plain `spawn`, no shell; `session/new` always sends `mcpServers: []` | | `mcp-bridge.ts` + `agy-plugin/bridge-proxy.mjs` | local MCP bridge (127.0.0.1, random port, 32-byte hex bearer token passed to the child only as `AGY_ACP_BRIDGE_URL` / `AGY_ACP_BRIDGE_TOKEN`). agy hard-times MCP calls out at 180 s; the bridge soft-replies at 170 s | | `agy-plugin.ts` | installs the shipped `agy-plugin/` as global agy plugin `opencode-bridge` via `agy plugin install` only (never edits `~/.gemini/config/*` by hand); one-time notice | -| `permission.ts` | `allow_once` for bridge `call_mcp_tool` and for `read_file` of files under OpenCode's `tool-output` dir (symlinks resolved), `reject_once` otherwise. Allowed provider-executed built-ins: `read_file`, `list_resources`, `read_resource`, `manage_task`; any other tool name cancels the turn | +| `permission.ts` | `allow_once` for bridge `call_mcp_tool` and for `read_file` of files under OpenCode's `tool-output` or `shell` output dirs (symlinks resolved), `reject_once` otherwise. Allowed provider-executed built-ins: `read_file`, `list_resources`, `read_resource`, `manage_task`; any other tool name cancels the turn | | `stream-map.ts`, `language-model.ts`, `live-session.ts`, `session-lock.ts`, `session-sync.ts`, `errors.ts` | ACP update to AI SDK stream mapping, language model, history sync, error classification | | `register-auth.ts`, `register-catalog.ts`, `sdk-placeholder.ts` | auth methods (Gemini API key and Vertex recommended; Google login is external, the plugin never reads agy tokens or the OS keyring), model catalog | | `debug.ts` | opt-in `AGY_ACP_DEBUG` log | diff --git a/src/acp/permission.ts b/src/acp/permission.ts index ee856925..b6a96241 100644 --- a/src/acp/permission.ts +++ b/src/acp/permission.ts @@ -14,10 +14,24 @@ export function openCodeToolOutputDir(env: NodeJS.ProcessEnv = process.env): str return path.join(base, "opencode", "tool-output"); } +/** Directory where OpenCode saves the full output of truncated shell commands. */ +export function openCodeShellOutputDir(env: NodeJS.ProcessEnv = process.env): string { + return path.join(path.dirname(openCodeToolOutputDir(env)), "shell"); +} + +function isInside(dir: string, file: string): boolean { + try { + return file.startsWith(realpathSync(dir) + path.sep); + } catch { + return false; + } +} + /** * True when agy asks to `read_file` a regular file inside OpenCode's - * tool-output directory (OpenCode tells the model to read truncated outputs - * there). Symlinks are resolved, so links pointing out are rejected. + * tool-output or shell output directory (OpenCode tells the model to read + * truncated outputs there). Symlinks are resolved, so links pointing out are + * rejected. */ function isToolOutputRead(toolCall: AcpToolCall, env: NodeJS.ProcessEnv): boolean { if (toolCall.name !== "read_file") return false; @@ -25,9 +39,9 @@ function isToolOutputRead(toolCall: AcpToolCall, env: NodeJS.ProcessEnv): boolea const target = PATH_KEYS.map((k) => input?.[k]).find((v): v is string => typeof v === "string"); if (!target || !path.isAbsolute(target)) return false; try { - const dir = realpathSync(openCodeToolOutputDir(env)); const file = realpathSync(target); - return file.startsWith(dir + path.sep) && statSync(file).isFile(); + const dirs = [openCodeToolOutputDir(env), openCodeShellOutputDir(env)]; + return dirs.some((dir) => isInside(dir, file)) && statSync(file).isFile(); } catch { return false; } diff --git a/test/acp/permission.test.ts b/test/acp/permission.test.ts index d9695ebd..0c532666 100644 --- a/test/acp/permission.test.ts +++ b/test/acp/permission.test.ts @@ -78,6 +78,16 @@ describe("decidePermission", () => { expect(decidePermission(read({ path: inside }), env).allowed).toBe(true); }); + it("allows saved shell output files", () => { + const shellDir = path.join(data, "opencode", "shell", "189d24e8"); + mkdirSync(shellDir, { recursive: true }); + const out = path.join(shellDir, "sh_1.out"); + writeFileSync(out, "1\n2\n"); + expect(decidePermission(read({ Path: out }), env).allowed).toBe(true); + expect(decidePermission(read({ Path: path.join(data, "opencode", "shell") }), env).allowed).toBe(false); + expect(decidePermission(read({ Path: path.join(data, "opencode", "auth.json") }), env).allowed).toBe(false); + }); + it("rejects files outside it, escapes and symlinks out", () => { expect(decidePermission(read({ Path: outside }), env).allowed).toBe(false); expect(decidePermission(read({ Path: path.join(outDir, "..", "..", "secret.txt") }), env).allowed).toBe(false); From 312a26c4101fe67a1f6229740ba71cf8b0bc2f5c Mon Sep 17 00:00:00 2001 From: Anthony Hausman Date: Tue, 1 Dec 2026 16:57:08 +0100 Subject: [PATCH 09/13] fix(acp): keep agy bridge schemas during side calls agy rewrites one shared bridge schema cache on every tools/list, so title and compaction side calls listing no tools wiped the main session schemas. Side calls now list the last tool list and refuse every call. Assisted-by: Claude Opus 5.5 --- src/acp/language-model.ts | 7 +++++- src/acp/live-session.ts | 24 +++++++++++++++--- src/acp/mcp-bridge.ts | 8 ++++++ test/acp/language-model.test.ts | 44 +++++++++++++++++++++++++++++++-- 4 files changed, 77 insertions(+), 6 deletions(-) diff --git a/src/acp/language-model.ts b/src/acp/language-model.ts index 5b096101..59fde133 100644 --- a/src/acp/language-model.ts +++ b/src/acp/language-model.ts @@ -235,6 +235,7 @@ export class AgyAcpLanguageModel implements LanguageModelV3 { const { deps } = this; const auth = await deps.auth(); const fingerprint = fingerprintOf(ctx.system, ctx.tools, auth, this.modelId, ctx.tier); + if (ctx.tools.length > 0) this.deps.lastTools = ctx.tools; for (;;) { if (deps.pool.get(key)?.dead) await deps.pool.release(key); let created = false; @@ -296,10 +297,14 @@ export class AgyAcpLanguageModel implements LanguageModelV3 { private async runThrowaway(o: LanguageModelV3CallOptions, ctx: CallContext, out: Out) { const auth = await this.deps.auth(); + // Advertise a full tool list: agy rewrites one shared schema cache per bridge on + // every tools/list, so an empty list here would wipe the main session's schemas. + const tools = ctx.tools.length > 0 ? ctx.tools : (this.deps.lastTools ?? []); const live = await LiveSession.create(this.deps, { key: undefined, fingerprint: "", - tools: [], + tools, + sideCall: true, session: this.sessionParams(ctx, []), auth, }); diff --git a/src/acp/live-session.ts b/src/acp/live-session.ts index 548cab38..8e35a1ff 100644 --- a/src/acp/live-session.ts +++ b/src/acp/live-session.ts @@ -48,6 +48,11 @@ export interface AgyAcpDeps { cancelSettleTimeoutMs?: number; /** agy idle-kill delay (tests); defaults to IDLE_TIMEOUT_MS. */ idleTimeoutMs?: number; + /** + * Last non-empty tool list of a primary call. Side calls advertise it so their + * agy process does not rewrite agy's shared bridge schema cache with fewer tools. + */ + lastTools?: BridgeToolDef[]; } export type TurnEvent = @@ -95,6 +100,8 @@ export interface LiveSessionConfig { key: string | undefined; fingerprint: string; tools: BridgeToolDef[]; + /** Side call: list the tools for agy's schema cache but refuse every call; no bridge wait. */ + sideCall?: boolean; session: NewSessionParams; auth: AgyAuth; /** agy session id stored for this OpenCode session; resumed instead of opening a new one when set. */ @@ -150,7 +157,12 @@ export class LiveSession implements PoolEntry { softTimeoutMs: deps.softTimeoutMs ?? MCP_SOFT_TIMEOUT_MS, onClaim: (id) => live?.markClaimed(id), }); - const bridge = await McpBridge.start({ tools: config.tools, pending, log: (m) => deps.log("warn", m) }); + const bridge = await McpBridge.start({ + tools: config.tools, + pending, + log: (m) => deps.log("warn", m), + callable: !config.sideCall, + }); let proc: AgyAcpProcess | undefined; try { proc = await AgyAcpProcess.start({ @@ -169,7 +181,7 @@ export class LiveSession implements PoolEntry { const models = config.resumeId ? await live.resumeOrOpen(config.resumeId) : await live.openSession(); deps.onAuthStatus?.(undefined); deps.onModels?.(models); - if (config.tools.length > 0) { + if (config.tools.length > 0 && !config.sideCall) { const connected = await bridge.waitForClient(deps.bridgeConnectTimeoutMs ?? BRIDGE_CONNECT_TIMEOUT_MS); if (!connected) throw new AgyAcpError("bridge_unreachable", BRIDGE_NOT_CONNECTED_TEXT); } @@ -221,8 +233,9 @@ export class LiveSession implements PoolEntry { const id = req.toolCall?.toolCallId; const toolCall = { ...this.toolCalls.get(id), ...definedOnly(req.toolCall) } as AcpToolCall; const { response, allowed } = decidePermission({ ...req, toolCall }); - if (allowed && classifyToolCall(toolCall).kind === "bridge") { + if (allowed && classifyToolCall(toolCall).kind === "bridge" && !this.config.sideCall) { // Bridge calls wait on OpenCode; allowed built-ins (read_file) run inside agy. + // Side-call bridges refuse calls themselves, so nothing waits on OpenCode. this.turn?.parked.add(id); this.turn?.signal.fire(); } else if (!allowed) { @@ -248,6 +261,11 @@ export class LiveSession implements PoolEntry { } if (u.sessionUpdate === "usage_update" && typeof u.used === "number") turn.contextUsed = u.used; const ev = turn.mapper.map(u); + if (ev.bridgeCall && this.config.sideCall) { + // Refused by the side-call bridge: never surface it to OpenCode as a tool call. + ev.parts = ev.parts.filter((p) => !(p.type === "tool-call" && p.toolCallId === ev.bridgeCall!.callId)); + ev.bridgeCall = undefined; + } if (ev.bridgeCall) { this.pending.expect(ev.bridgeCall); this.callOrder.push(ev.bridgeCall.callId); diff --git a/src/acp/mcp-bridge.ts b/src/acp/mcp-bridge.ts index 2b80807f..cf73ad50 100644 --- a/src/acp/mcp-bridge.ts +++ b/src/acp/mcp-bridge.ts @@ -59,6 +59,10 @@ interface Entry { timer?: ReturnType; } +/** Returned when agy calls an OpenCode tool during a side call (title, summary, compaction). */ +export const SIDE_CALL_TOOL_TEXT = + "OpenCode tools are not available in this request. Answer with text only, without calling tools."; + export class PendingTools { private readonly entries = new Map(); private late: Array<{ callId: string; outcome: ToolOutcome }> = []; @@ -207,8 +211,11 @@ export class McpBridge { tools: BridgeToolDef[]; pending: PendingTools; log?: (msg: string) => void; + /** When false, the tools are listed but every call is refused (side calls). Default true. */ + callable?: boolean; }): Promise { const { tools, pending, log } = opts; + const callable = opts.callable ?? true; const ajv = new Ajv({ strict: false, allErrors: true }); const validators = new Map(); for (const tool of tools) { @@ -243,6 +250,7 @@ export class McpBridge { mcp.setRequestHandler(CallToolRequestSchema, async (request) => { const name = request.params.name; if (!tools.some((t) => t.name === name)) return errorResult(`Unknown OpenCode tool: ${name}`); + if (!callable) return errorResult(SIDE_CALL_TOOL_TEXT); const input = stripToolSummary(request.params.arguments ?? {}); const validate = validators.get(name); if (validate && !validate(input)) { diff --git a/test/acp/language-model.test.ts b/test/acp/language-model.test.ts index 52e1d15b..797943de 100644 --- a/test/acp/language-model.test.ts +++ b/test/acp/language-model.test.ts @@ -655,7 +655,7 @@ describe("AgyAcpLanguageModel", () => { const parts = await run(h, opts([system("Generate a title"), user("hello")], { tools: [READ_TOOL] }, "")); expect(errorsOf(parts)).toHaveLength(0); expect(finishOf(parts).finishReason.unified).toBe("stop"); - expect(h.bridge("tools/list")[0].response.result.tools).toEqual([]); + expect(h.bridge("tools/list")[0].response.result.tools.map((t: any) => t.name)).toEqual(["read"]); expect(h.recv("session/new")).toHaveLength(1); expect(h.recv("session/close")).toHaveLength(1); expect(existsSync(path.join(h.dir, "sessions.json"))).toBe(false); @@ -675,12 +675,52 @@ describe("AgyAcpLanguageModel", () => { ); expect(errorsOf(parts)).toHaveLength(0); expect(finishOf(parts).finishReason.unified).toBe("stop"); - expect(h.bridge("tools/list")[0].response.result.tools).toEqual([]); + expect(h.bridge("tools/list")[0].response.result.tools.map((t: any) => t.name)).toEqual(["read"]); expect(h.recv("session/new")).toHaveLength(1); expect(h.recv("session/close")).toHaveLength(1); expect(existsSync(path.join(h.dir, "sessions.json"))).toBe(false); }); + it("side calls advertise the request tools but refuse to run them", async () => { + const h = harness([ + INIT, + AUTH, + NEW, + { + expect: "session/prompt", + callMcp: { tool: "read", args: { path: "a" }, toolCallId: "t1" }, + notify: [chunk("Title")], + reply: END, + }, + CLOSE, + ]); + const parts = await run( + h, + opts([system("Generate a title"), user("hello")], { + tools: [READ_TOOL], + headers: { "X-OpenCode-Session-Id": "ses-1", "X-OpenCode-Request-Kind": "title" }, + }), + ); + expect(errorsOf(parts)).toHaveLength(0); + expect(finishOf(parts).finishReason.unified).toBe("stop"); + expect(h.bridge("tools/list")[0].response.result.tools.map((t: any) => t.name)).toEqual(["read"]); + expect(h.bridge("tools/call")[0].response.result.isError).toBe(true); + expect(bridgeTexts(h)[0]).toContain("not available"); + }); + + it("side calls without tools advertise the last primary tool list", async () => { + const h = harness([INIT, AUTH, NEW, { expect: "session/prompt", notify: [chunk("Title")], reply: END }, CLOSE], { + deps: { lastTools: [{ name: "read", inputSchema: READ_TOOL.inputSchema }] }, + }); + await run( + h, + opts([system("Generate a title"), user("hello")], { + headers: { "X-OpenCode-Session-Id": "ses-1", "X-OpenCode-Request-Kind": "title" }, + }), + ); + expect(h.bridge("tools/list")[0].response.result.tools.map((t: any) => t.name)).toEqual(["read"]); + }); + it("primary_kind_keeps_the_session", async () => { const h = harness([INIT, AUTH, NEW, { expect: "session/prompt", notify: [chunk("Hi")], reply: END }]); const parts = await run( From 5f5b7715c6c1695ce88192b76b8da4fa0f0c10c2 Mon Sep 17 00:00:00 2001 From: Anthony Hausman Date: Tue, 1 Dec 2026 17:01:19 +0100 Subject: [PATCH 10/13] fix(acp): tell agy side calls to answer without tools Title and compaction side calls now append a text-only instruction, so agy writes the summary OpenCode expects instead of looking up tool schemas. Assisted-by: Claude Opus 5.5 --- src/acp/language-model.ts | 12 +++++++++++- test/acp/language-model.test.ts | 11 +++++++++-- 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/src/acp/language-model.ts b/src/acp/language-model.ts index 59fde133..14025d04 100644 --- a/src/acp/language-model.ts +++ b/src/acp/language-model.ts @@ -66,6 +66,15 @@ class Out { } } +/** + * Appended to the agy system prompt of side calls (title, summary, compaction). + * agy's agent otherwise tends to look up tools instead of answering, and OpenCode + * rejects a compaction reply that skips its summary template. + */ +export const SIDE_CALL_SYSTEM_TEXT = + "This request has no tools: do not call tools, look up tool schemas or read files. " + + "Reply with text only, in exactly the format the instructions above ask for."; + interface CallContext { key: string | undefined; system: string; @@ -300,12 +309,13 @@ export class AgyAcpLanguageModel implements LanguageModelV3 { // Advertise a full tool list: agy rewrites one shared schema cache per bridge on // every tools/list, so an empty list here would wipe the main session's schemas. const tools = ctx.tools.length > 0 ? ctx.tools : (this.deps.lastTools ?? []); + const sideCallSystem = [ctx.system, SIDE_CALL_SYSTEM_TEXT].filter(Boolean).join("\n\n"); const live = await LiveSession.create(this.deps, { key: undefined, fingerprint: "", tools, sideCall: true, - session: this.sessionParams(ctx, []), + session: this.sessionParams({ ...ctx, system: sideCallSystem }, []), auth, }); try { diff --git a/test/acp/language-model.test.ts b/test/acp/language-model.test.ts index 797943de..b84ef781 100644 --- a/test/acp/language-model.test.ts +++ b/test/acp/language-model.test.ts @@ -10,7 +10,12 @@ import type { import { afterEach, describe, expect, it, vi } from "vitest"; import { CANCELLED_TEXT, STILL_RUNNING_TEXT } from "../../src/acp/constants"; import { BRIDGE_NOT_CONNECTED_TEXT, TOS_DISABLED_TEXT } from "../../src/acp/errors"; -import { AgyAcpLanguageModel, type AgyAcpDeps, type LiveSession } from "../../src/acp/language-model"; +import { + AgyAcpLanguageModel, + SIDE_CALL_SYSTEM_TEXT, + type AgyAcpDeps, + type LiveSession, +} from "../../src/acp/language-model"; import { AgyProcessPool } from "../../src/acp/process"; import { lockSession } from "../../src/acp/session-lock"; import { SessionStore } from "../../src/acp/session-sync"; @@ -659,7 +664,9 @@ describe("AgyAcpLanguageModel", () => { expect(h.recv("session/new")).toHaveLength(1); expect(h.recv("session/close")).toHaveLength(1); expect(existsSync(path.join(h.dir, "sessions.json"))).toBe(false); - expect(h.recv("session/new")[0].message.params._meta.antigravity.systemPrompt.append).toBe("Generate a title"); + const append = h.recv("session/new")[0].message.params._meta.antigravity.systemPrompt.append; + expect(append.startsWith("Generate a title\n\n")).toBe(true); + expect(append).toContain(SIDE_CALL_SYSTEM_TEXT); }); it("title_kind_uses_throwaway_even_with_session_header", async () => { From 09bec3b01aa67a8fdb8f752be88436697a321997 Mon Sep 17 00:00:00 2001 From: Anthony Hausman Date: Tue, 1 Dec 2026 17:17:43 +0100 Subject: [PATCH 11/13] refactor(acp): drop thought level variants agy model ids now carry the thinking level, and selecting one sets thought_level, so low/medium/high variants were redundant. Assisted-by: Claude Opus 5.5 --- README.md | 2 +- src/acp/constants.ts | 2 -- src/acp/language-model.ts | 11 +++-------- src/acp/process.ts | 10 ---------- src/acp/register-catalog.ts | 11 +++++------ src/acp/session-sync.ts | 2 -- test/acp/language-model.test.ts | 15 ++------------- test/acp/live.test.ts | 11 ++--------- test/acp/process.test.ts | 12 +++--------- test/acp/register.test.ts | 3 +-- test/acp/session-sync.test.ts | 15 +++++++-------- 11 files changed, 24 insertions(+), 70 deletions(-) diff --git a/README.md b/README.md index 9534c7e0..498a309b 100644 --- a/README.md +++ b/README.md @@ -28,7 +28,7 @@ Then connect the `google-agy-acp` provider in OpenCode and pick an authenticatio ## google-agy-acp provider -The provider starts `agy acp --agent opencode` (one process per OpenCode session, no shell) and exposes agy's models in OpenCode. OpenCode keeps ownership of tools: they are presented to agy through a local MCP bridge (127.0.0.1, random port, per-process bearer token) served by an agy plugin named `opencode-bridge`, so file edits and commands still run inside OpenCode with OpenCode's permission prompts. Low, medium and high variants map to agy's `thought_level`. The model list comes from `agy models` shortly after startup and refreshes when agy reports a different list at session start. If `agy models` fails later, the provider keeps the last list that worked for the current account; if agy is missing, too old, or has never answered for that account, the provider lists no models. +The provider starts `agy acp --agent opencode` (one process per OpenCode session, no shell) and exposes agy's models in OpenCode. OpenCode keeps ownership of tools: they are presented to agy through a local MCP bridge (127.0.0.1, random port, per-process bearer token) served by an agy plugin named `opencode-bridge`, so file edits and commands still run inside OpenCode with OpenCode's permission prompts. Model ids carry the thinking level (for example `gemini-4-neon-low`), so models have no variants. The model list comes from `agy models` shortly after startup and refreshes when agy reports a different list at session start. If `agy models` fails later, the provider keeps the last list that worked for the current account; if agy is missing, too old, or has never answered for that account, the provider lists no models. ### Authentication diff --git a/src/acp/constants.ts b/src/acp/constants.ts index 76037e56..cc4e7fd3 100644 --- a/src/acp/constants.ts +++ b/src/acp/constants.ts @@ -35,9 +35,7 @@ export const AGY_API_KEY_ENV = "GEMINI_API_KEY"; export const AGY_API_KEY_OVERRIDE_ENV = "GOOGLE_API_KEY"; export const AGY_ADC_ENV = "AGY_ADC_AUTH"; -export const THOUGHT_LEVEL_CONFIG_ID = "thought_level"; export const MODE_CONFIG_ID = "mode"; -export type AgyTier = "low" | "medium" | "high"; export const STILL_RUNNING_TEXT = "Still running in OpenCode (waiting on execution or user permission); the result will be sent with the next message."; diff --git a/src/acp/language-model.ts b/src/acp/language-model.ts index 14025d04..4a4340b6 100644 --- a/src/acp/language-model.ts +++ b/src/acp/language-model.ts @@ -8,7 +8,7 @@ import type { LanguageModelV3Usage, SharedV3Warning, } from "@ai-sdk/provider"; -import { AGY_ACP_PROVIDER_ID, CANCEL_SETTLE_TIMEOUT_MS, KIND_HEADER, SESSION_HEADER, type AgyTier } from "./constants"; +import { AGY_ACP_PROVIDER_ID, CANCEL_SETTLE_TIMEOUT_MS, KIND_HEADER, SESSION_HEADER } from "./constants"; import { AgyAcpError, toAgyError } from "./errors"; import { LiveSession, type AgyAcpDeps, type LiveTurn } from "./live-session"; import type { BridgeToolDef, ToolOutcome } from "./mcp-bridge"; @@ -28,7 +28,6 @@ type StepOutcome = | { kind: "aborted" } | { kind: "detached" }; -const TIERS: ReadonlySet = new Set(["low", "medium", "high"]); const UNSUPPORTED_SETTINGS = [ "maxOutputTokens", "temperature", @@ -79,7 +78,6 @@ interface CallContext { key: string | undefined; system: string; tools: BridgeToolDef[]; - tier: AgyTier | undefined; } function headerValue(headers: Record | undefined, name: string): string | undefined { @@ -105,13 +103,11 @@ function prepareCall(o: LanguageModelV3CallOptions): { warnings: SharedV3Warning .filter((m) => m.role === "system") .map((m) => m.content as string) .join("\n\n"); - const rawTier = (o.providerOptions?.[AGY_ACP_PROVIDER_ID] as { tier?: unknown } | undefined)?.tier; - const tier = typeof rawTier === "string" && TIERS.has(rawTier) ? (rawTier as AgyTier) : undefined; // Side calls (title, summary, compaction...) run in a throwaway agy session so // they never touch the stored conversation of the primary session. const kind = headerValue(o.headers, KIND_HEADER); const key = kind && kind !== "primary" ? undefined : headerValue(o.headers, SESSION_HEADER); - return { warnings, ctx: { key, system, tools, tier } }; + return { warnings, ctx: { key, system, tools } }; } function cleanBlocks(blocks: AcpContentBlock[]): AcpContentBlock[] { @@ -207,7 +203,6 @@ export class AgyAcpLanguageModel implements LanguageModelV3 { cwd: this.deps.cwd, ...(append ? { systemPromptAppend: append } : {}), modelId: this.modelId, - ...(ctx.tier ? { tier: ctx.tier } : {}), }; } @@ -243,7 +238,7 @@ export class AgyAcpLanguageModel implements LanguageModelV3 { private async runLocked(o: LanguageModelV3CallOptions, ctx: CallContext, key: string, out: Out) { const { deps } = this; const auth = await deps.auth(); - const fingerprint = fingerprintOf(ctx.system, ctx.tools, auth, this.modelId, ctx.tier); + const fingerprint = fingerprintOf(ctx.system, ctx.tools, auth, this.modelId); if (ctx.tools.length > 0) this.deps.lastTools = ctx.tools; for (;;) { if (deps.pool.get(key)?.dead) await deps.pool.release(key); diff --git a/src/acp/process.ts b/src/acp/process.ts index 316efca8..fe124a45 100644 --- a/src/acp/process.ts +++ b/src/acp/process.ts @@ -10,8 +10,6 @@ import { IDLE_TIMEOUT_MS, MODE_CONFIG_ID, STARTUP_TIMEOUT_MS, - THOUGHT_LEVEL_CONFIG_ID, - type AgyTier, } from "./constants"; import { createAgyDebugLog } from "./debug"; import { JsonRpcConnection } from "./rpc"; @@ -70,7 +68,6 @@ export interface NewSessionParams { cwd: string; systemPromptAppend?: string; modelId?: string; - tier?: AgyTier; } export interface NewSessionResult { @@ -319,13 +316,6 @@ export class AgyAcpProcess { if (p.modelId && p.modelId !== currentModelId) { await this.rpc("session/set_model", { sessionId, modelId: p.modelId }); } - if (p.tier) { - await this.rpc("session/set_config_option", { - sessionId, - configId: THOUGHT_LEVEL_CONFIG_ID, - value: p.tier, - }); - } const configMode = Array.isArray(res.configOptions) ? res.configOptions.find((o: any) => o?.id === MODE_CONFIG_ID)?.currentValue : undefined; diff --git a/src/acp/register-catalog.ts b/src/acp/register-catalog.ts index 93395b22..30a684a5 100644 --- a/src/acp/register-catalog.ts +++ b/src/acp/register-catalog.ts @@ -1,9 +1,8 @@ import { existsSync } from "node:fs"; import { fileURLToPath } from "node:url"; -import { AGY_ACP_PROVIDER_ID, type AgyTier } from "./constants"; +import { AGY_ACP_PROVIDER_ID } from "./constants"; import type { AcpModelInfo } from "./process"; -const TIERS: readonly AgyTier[] = ["low", "medium", "high"]; export const AGY_ACP_PROVIDER_NAME = "Antigravity CLI (ACP)"; @@ -74,9 +73,9 @@ export function applyProviderRecord(p: any, pkg: string): void { } /** - * Mutates an OpenCode model record. Variant `settings` become AI SDK - * `providerOptions`, so `providerOptions["google-agy-acp"].tier` reaches the - * language model. Cost is zero: agy bills the Google account, not OpenCode. + * Mutates an OpenCode model record. No variants: agy model ids already carry the + * thinking level (`gemini-4-neon-low`), and selecting one sets agy's + * `thought_level`. Cost is zero: agy bills the Google account, not OpenCode. */ export function applyModelRecord(m: any, model: AcpModelInfo): void { m.id = model.modelId; @@ -87,7 +86,7 @@ export function applyModelRecord(m: any, model: AcpModelInfo): void { m.capabilities = { tools: true, input: ["text", "image"], output: ["text"] }; m.limit = { context: 1_048_576, output: 65_536 }; m.cost = [{ input: 0, output: 0, cache: { read: 0, write: 0 } }]; - m.variants = TIERS.map((tier) => ({ id: tier, settings: { [AGY_ACP_PROVIDER_ID]: { tier } } })); + m.variants = []; m.status = "active"; m.enabled = true; } diff --git a/src/acp/session-sync.ts b/src/acp/session-sync.ts index d9289c47..57b73591 100644 --- a/src/acp/session-sync.ts +++ b/src/acp/session-sync.ts @@ -118,7 +118,6 @@ export function fingerprintOf( tools: BridgeToolDef[], auth: { method: string; identity: string }, modelId: string, - tier: string | undefined, ): string { const sorted = [...tools].sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0)); return sha256( @@ -128,7 +127,6 @@ export function fingerprintOf( authMethod: auth.method, authIdentity: auth.identity, modelId, - tier: tier ?? null, }), ); } diff --git a/test/acp/language-model.test.ts b/test/acp/language-model.test.ts index b84ef781..103d43c9 100644 --- a/test/acp/language-model.test.ts +++ b/test/acp/language-model.test.ts @@ -624,7 +624,7 @@ describe("AgyAcpLanguageModel", () => { expect(h.recv("authenticate")[0].message.params).toEqual({ methodId: "gemini-api-key" }); }); - it("model_and_tier", async () => { + it("selects the model and ignores a tier option", async () => { const onModels = vi.fn(); const h = harness( [ @@ -632,25 +632,14 @@ describe("AgyAcpLanguageModel", () => { AUTH, NEW, { expect: "session/set_model", reply: {} }, - { expect: "session/set_config_option", reply: {} }, { expect: "session/prompt", reply: END }, ], { modelId: "claude-sonnet-4-6", deps: { onModels } }, ); await run(h, opts([user("hi")], { providerOptions: { "google-agy-acp": { tier: "low" } } })); expect(h.recv("session/set_model")[0].message.params).toEqual({ sessionId: "s1", modelId: "claude-sonnet-4-6" }); - expect(h.recv("session/set_config_option")[0].message.params).toEqual({ - sessionId: "s1", - configId: "thought_level", - value: "low", - }); - expect(onModels).toHaveBeenCalledWith(MODELS); - }); - - it("ignores an invalid tier", async () => { - const h = harness([INIT, AUTH, NEW, { expect: "session/prompt", reply: END }]); - await run(h, opts([user("hi")], { providerOptions: { "google-agy-acp": { tier: "ultra" } } })); expect(h.recv("session/set_config_option")).toHaveLength(0); + expect(onModels).toHaveBeenCalledWith(MODELS); }); it("no_session_header_uses_throwaway", async () => { diff --git a/test/acp/live.test.ts b/test/acp/live.test.ts index 84247d5b..9f094be0 100644 --- a/test/acp/live.test.ts +++ b/test/acp/live.test.ts @@ -15,7 +15,7 @@ import { SessionStore } from "../../src/acp/session-sync"; * plugin globally, like a first real turn does. */ const LIVE = process.env.AGY_ACP_LIVE === "1"; -const MODEL = process.env.AGY_ACP_LIVE_MODEL ?? "gemini-3.8-flash-medium"; +const MODEL = process.env.AGY_ACP_LIVE_MODEL ?? "gemini-4-neon-low"; const echoTool = { type: "function" as const, @@ -51,7 +51,7 @@ describe.skipIf(!LIVE)("live agy acp", () => { if (work) rmSync(work, { recursive: true, force: true }); }); - async function modelFor(tier?: string) { + async function modelFor() { let sdkHandler: ((ev: any) => unknown) | undefined; const ctx: any = { provider: { transform: () => undefined }, @@ -86,7 +86,6 @@ describe.skipIf(!LIVE)("live agy acp", () => { prompt, tools, headers: { "x-opencode-session-id": session }, - ...(tier ? { providerOptions: { [AGY_ACP_PROVIDER_ID]: { tier } } } : {}), } as LanguageModelV3CallOptions) .then((r: any) => collect(r.stream)); return call; @@ -148,10 +147,4 @@ describe.skipIf(!LIVE)("live agy acp", () => { expect(succeeded).toEqual([]); expect(existsSync(path.join(work, "should-not-exist.txt"))).toBe(false); }); - - it("starts with a tier variant", { timeout: 180_000 }, async () => { - const call = await modelFor("low"); - const parts = await call("live-4", [user("Reply with the word pong")]); - expect(finishOf(parts)).toBeDefined(); - }); }); diff --git a/test/acp/process.test.ts b/test/acp/process.test.ts index adf7497e..1c52e7d5 100644 --- a/test/acp/process.test.ts +++ b/test/acp/process.test.ts @@ -200,17 +200,15 @@ describe("AgyAcpProcess", () => { }, { expect: "session/set_model", reply: {} }, { expect: "session/set_config_option", reply: {} }, - { expect: "session/set_config_option", reply: {} }, ]); const p = await t.start(); - await p.newSession({ cwd: "/w", modelId: "claude-sonnet-4-6", tier: "low" }); + await p.newSession({ cwd: "/w", modelId: "claude-sonnet-4-6" }); const methods = t .entries() .filter((e) => e.kind === "recv" && e.message.method?.startsWith("session/") && e.message.method !== "session/new") .map((e) => [e.message.method, e.message.params]); expect(methods).toEqual([ ["session/set_model", { sessionId: "s1", modelId: "claude-sonnet-4-6" }], - ["session/set_config_option", { sessionId: "s1", configId: "thought_level", value: "low" }], ["session/set_config_option", { sessionId: "s1", configId: "mode", value: "default" }], ]); }); @@ -255,10 +253,9 @@ describe("AgyAcpProcess", () => { }, { expect: "session/set_model", reply: {} }, { expect: "session/set_config_option", reply: {} }, - { expect: "session/set_config_option", reply: {} }, ]); const p = await t.start(); - const res = await p.resumeSession("old-1", { cwd: "/w", systemPromptAppend: "sys", modelId: "m2", tier: "high" }); + const res = await p.resumeSession("old-1", { cwd: "/w", systemPromptAppend: "sys", modelId: "m2" }); const sent = t.recv("session/resume")[0].message.params; expect(sent).toEqual({ sessionId: "old-1", @@ -268,10 +265,7 @@ describe("AgyAcpProcess", () => { }); expect(res).toEqual({ sessionId: "old-1", models: [{ modelId: "m1" }], currentModelId: "m1" }); expect(t.recv("session/set_model")[0].message.params).toEqual({ sessionId: "old-1", modelId: "m2" }); - expect(t.recv("session/set_config_option").map((e) => e.message.params.configId)).toEqual([ - "thought_level", - "mode", - ]); + expect(t.recv("session/set_config_option").map((e) => e.message.params.configId)).toEqual(["mode"]); }); it("rejects when agy cannot resume the session", async () => { diff --git a/test/acp/register.test.ts b/test/acp/register.test.ts index 1036cf53..2754b040 100644 --- a/test/acp/register.test.ts +++ b/test/acp/register.test.ts @@ -499,8 +499,7 @@ describe("registerAgyAcpProvider: catalog", () => { ]); for (const m of rec.models.values()) { expect(m.providerID).toBe(AGY_ACP_PROVIDER_ID); - expect(m.variants.map((v: any) => v.id)).toEqual(["low", "medium", "high"]); - for (const v of m.variants) expect(v.settings[AGY_ACP_PROVIDER_ID].tier).toBe(v.id); + expect(m.variants).toEqual([]); expect(m.cost.length).toBeGreaterThan(0); for (const c of m.cost) expect([c.input, c.output]).toEqual([0, 0]); } diff --git a/test/acp/session-sync.test.ts b/test/acp/session-sync.test.ts index 5743e249..66f255c2 100644 --- a/test/acp/session-sync.test.ts +++ b/test/acp/session-sync.test.ts @@ -66,14 +66,13 @@ describe("hashMessage / fingerprintOf", () => { const t1 = { name: "a", inputSchema: {} }; const t2 = { name: "b", inputSchema: {} }; const A = { method: "api", identity: "x" }; - const base = fingerprintOf("s", [t1, t2], A, "m", undefined); - expect(fingerprintOf("s", [t2, t1], A, "m", undefined)).toBe(base); - expect(fingerprintOf("s2", [t1, t2], A, "m", undefined)).not.toBe(base); - expect(fingerprintOf("s", [t1], A, "m", undefined)).not.toBe(base); - expect(fingerprintOf("s", [t1, t2], { method: "oauth", identity: "x" }, "m", undefined)).not.toBe(base); - expect(fingerprintOf("s", [t1, t2], A, "m2", undefined)).not.toBe(base); - expect(fingerprintOf("s", [t1, t2], A, "m", "high")).not.toBe(base); - expect(fingerprintOf("s", [t1, t2], { method: "api", identity: "y" }, "m", undefined)).not.toBe(base); + const base = fingerprintOf("s", [t1, t2], A, "m"); + expect(fingerprintOf("s", [t2, t1], A, "m")).toBe(base); + expect(fingerprintOf("s2", [t1, t2], A, "m")).not.toBe(base); + expect(fingerprintOf("s", [t1], A, "m")).not.toBe(base); + expect(fingerprintOf("s", [t1, t2], { method: "oauth", identity: "x" }, "m")).not.toBe(base); + expect(fingerprintOf("s", [t1, t2], A, "m2")).not.toBe(base); + expect(fingerprintOf("s", [t1, t2], { method: "api", identity: "y" }, "m")).not.toBe(base); }); }); From 3cfae19454c378e8d95878af8b3c3ef34cad55c6 Mon Sep 17 00:00:00 2001 From: Anthony Hausman Date: Tue, 1 Dec 2026 18:33:12 +0100 Subject: [PATCH 12/13] fix(acp): report thinking-only agy turns as errors agy can end a turn with reasoning only, which OpenCode took as an empty answer and compaction rejected. Side calls retry once in a fresh agy session, other turns get an empty_reply error. Assisted-by: Claude Opus 5.5 --- src/acp/errors.ts | 1 + src/acp/language-model.ts | 70 ++++++++++++++++++------- src/acp/live-session.ts | 2 + test/acp/language-model.test.ts | 87 +++++++++++++++++++++++++------- test/acp/register.test.ts | 21 ++++++-- test/fixtures/fake-acp-agent.mjs | 13 ++++- 6 files changed, 152 insertions(+), 42 deletions(-) diff --git a/src/acp/errors.ts b/src/acp/errors.ts index 4707a48d..e896812c 100644 --- a/src/acp/errors.ts +++ b/src/acp/errors.ts @@ -10,6 +10,7 @@ export type AgyErrorCode = | "bridge_unreachable" | "crash" | "rate_limited" + | "empty_reply" | "other"; export const BRIDGE_NOT_CONNECTED_TEXT = diff --git a/src/acp/language-model.ts b/src/acp/language-model.ts index 4a4340b6..dc18b04b 100644 --- a/src/acp/language-model.ts +++ b/src/acp/language-model.ts @@ -28,6 +28,9 @@ type StepOutcome = | { kind: "aborted" } | { kind: "detached" }; +/** `"empty"`: agy ended the turn with thinking only and the caller asked to retry. */ +type StepResult = "empty" | undefined; + const UNSUPPORTED_SETTINGS = [ "maxOutputTokens", "temperature", @@ -74,8 +77,13 @@ export const SIDE_CALL_SYSTEM_TEXT = "This request has no tools: do not call tools, look up tool schemas or read files. " + "Reply with text only, in exactly the format the instructions above ask for."; +/** Shown when agy ends a turn with thinking only: no answer text and no tool call. */ +export const EMPTY_REPLY_TEXT = + "agy ended the turn without an answer (thinking only, no text or tool call). Retry the request."; + interface CallContext { key: string | undefined; + kind: string | undefined; system: string; tools: BridgeToolDef[]; } @@ -107,7 +115,7 @@ function prepareCall(o: LanguageModelV3CallOptions): { warnings: SharedV3Warning // they never touch the stored conversation of the primary session. const kind = headerValue(o.headers, KIND_HEADER); const key = kind && kind !== "primary" ? undefined : headerValue(o.headers, SESSION_HEADER); - return { warnings, ctx: { key, system, tools } }; + return { warnings, ctx: { key, kind, system, tools } }; } function cleanBlocks(blocks: AcpContentBlock[]): AcpContentBlock[] { @@ -304,21 +312,33 @@ export class AgyAcpLanguageModel implements LanguageModelV3 { // Advertise a full tool list: agy rewrites one shared schema cache per bridge on // every tools/list, so an empty list here would wipe the main session's schemas. const tools = ctx.tools.length > 0 ? ctx.tools : (this.deps.lastTools ?? []); - const sideCallSystem = [ctx.system, SIDE_CALL_SYSTEM_TEXT].filter(Boolean).join("\n\n"); - const live = await LiveSession.create(this.deps, { - key: undefined, - fingerprint: "", - tools, - sideCall: true, - session: this.sessionParams({ ...ctx, system: sideCallSystem }, []), - auth, - }); - try { - await this.step(o, live, decideSync(undefined, o.prompt, "").blocks, out); - } finally { - live.turn?.detachAbort?.(); - await live.proc.closeSession(live.agySessionId!); - await live.dispose(); + const sideCallSystem = [ + ctx.system, + SIDE_CALL_SYSTEM_TEXT, + ] + .filter(Boolean) + .join("\n\n"); + const blocks = decideSync(undefined, o.prompt, "").blocks; + // agy sometimes ends a side call with thinking only; one retry in a fresh session usually answers. + for (let attempt = 0; ; attempt++) { + const live = await LiveSession.create(this.deps, { + key: undefined, + fingerprint: "", + tools, + sideCall: true, + session: this.sessionParams({ ...ctx, system: sideCallSystem }, []), + auth, + }); + let outcome: StepResult; + try { + outcome = await this.step(o, live, blocks, out, attempt === 0); + } finally { + live.turn?.detachAbort?.(); + await live.proc.closeSession(live.agySessionId!); + await live.dispose(); + } + if (outcome !== "empty") return; + this.deps.log("warn", `agy-acp: agy answered the ${ctx.kind ?? "side"} call with thinking only; retrying once`); } } @@ -338,7 +358,13 @@ export class AgyAcpLanguageModel implements LanguageModelV3 { } /** Drains the open turn (if any), then sends the next prompt when there is something to send. */ - private async step(o: LanguageModelV3CallOptions, live: LiveSession, decisionBlocks: AcpContentBlock[], out: Out) { + private async step( + o: LanguageModelV3CallOptions, + live: LiveSession, + decisionBlocks: AcpContentBlock[], + out: Out, + retryEmpty = false, + ): Promise { let last: PromptResult | undefined; if (live.turn) { const settled = await this.drive(o, live, live.turn, out); @@ -355,8 +381,15 @@ export class AgyAcpLanguageModel implements LanguageModelV3 { }); return; } - const result = await this.drive(o, live, live.startTurn(blocks), out); + const turn = live.startTurn(blocks); + const result = await this.drive(o, live, turn, out); if (!result) return; + if (!turn.answered) { + await this.markInterrupted(live); + if (retryEmpty) return "empty"; + out.error(new AgyAcpError("empty_reply", EMPTY_REPLY_TEXT)); + return; + } await this.writeRecord(live, o); out.emit({ type: "finish", finishReason: mapStopReason(result.stopReason), usage: mapUsage(result.usage) }); } @@ -435,6 +468,7 @@ export class AgyAcpLanguageModel implements LanguageModelV3 { const ev = turn.queue.shift()!; if (ev.kind === "violation") return { kind: "violation", toolName: ev.toolName }; out.emit(ev.part); + if (ev.part.type === "text-delta" || ev.part.type === "tool-call") turn.answered = true; if (ev.bridgeCallId) emitted.push(ev.bridgeCallId); } if (turn.aborted !== undefined) return { kind: "aborted" }; diff --git a/src/acp/live-session.ts b/src/acp/live-session.ts index 8e35a1ff..721fafe3 100644 --- a/src/acp/live-session.ts +++ b/src/acp/live-session.ts @@ -83,6 +83,8 @@ export class LiveTurn { done: Promise = Promise.resolve(); detachAbort?: () => void; interruptWrite?: Promise; + /** True once agy streamed answer text or a tool call (thinking alone does not count). */ + answered = false; /** Latest context use agy reported through `usage_update` (tokens). */ contextUsed?: number; diff --git a/test/acp/language-model.test.ts b/test/acp/language-model.test.ts index 103d43c9..6d53a550 100644 --- a/test/acp/language-model.test.ts +++ b/test/acp/language-model.test.ts @@ -40,6 +40,8 @@ const READ_TOOL: LanguageModelV3FunctionTool = { inputSchema: { type: "object", properties: { path: { type: "string" } }, required: ["path"] }, }; +/** A prompt step that answers with text (a thinking-only turn is an error). */ +const PROMPT_OK = { expect: "session/prompt", notify: [chunk("ok")], reply: END }; const user = (text: string): LanguageModelV3Message => ({ role: "user", content: [{ type: "text", text }] }); const system = (content: string): LanguageModelV3Message => ({ role: "system", content }); const assistantCall = (id: string, input: unknown, toolName = "read"): LanguageModelV3Message => ({ @@ -353,7 +355,7 @@ describe("AgyAcpLanguageModel", () => { AUTH, NEW, { expect: "session/prompt", callMcp: { tool: "read", args: { path: "a" }, toolCallId: "t1" }, reply: END }, - { expect: "session/prompt", reply: END }, + PROMPT_OK, ], { deps: { softTimeoutMs: 20 } }, ); @@ -426,7 +428,7 @@ describe("AgyAcpLanguageModel", () => { callMcp: { tool: "read", args: { path: "a" }, toolCallId: "t1" }, reply: { stopReason: "cancelled" }, }, - { expect: "session/prompt", reply: END }, + PROMPT_OK, ]); const ac = new AbortController(); const history = [user("read a")]; @@ -613,7 +615,7 @@ describe("AgyAcpLanguageModel", () => { }); it("api_key_env", async () => { - const h = harness([INIT, { expect: "authenticate", reply: {} }, NEW, { expect: "session/prompt", reply: END }], { + const h = harness([INIT, { expect: "authenticate", reply: {} }, NEW, PROMPT_OK], { env: { GOOGLE_API_KEY: "g" }, deps: { auth: async () => ({ method: "gemini-api-key", apiKey: "k", identity: "key:c1" }) }, }); @@ -632,7 +634,7 @@ describe("AgyAcpLanguageModel", () => { AUTH, NEW, { expect: "session/set_model", reply: {} }, - { expect: "session/prompt", reply: END }, + PROMPT_OK, ], { modelId: "claude-sonnet-4-6", deps: { onModels } }, ); @@ -677,6 +679,55 @@ describe("AgyAcpLanguageModel", () => { expect(existsSync(path.join(h.dir, "sessions.json"))).toBe(false); }); + const THINK_ONLY = { expect: "session/prompt", notify: [chunk("hmm", "agent_thought_chunk")], reply: END }; + const SIDE = (kind: string) => ({ headers: { "X-OpenCode-Session-Id": "ses-1", "X-OpenCode-Request-Kind": kind } }); + const textOf = (parts: LanguageModelV3StreamPart[]) => + parts + .filter((p) => p.type === "text-delta") + .map((p: any) => p.delta) + .join(""); + + it("retries a side call once in a fresh agy session when agy answers with thinking only", async () => { + const h = harness( + { + runs: [ + [INIT, AUTH, NEW, THINK_ONLY, CLOSE], + [INIT, AUTH, NEW, { expect: "session/prompt", notify: [chunk("Title")], reply: END }, CLOSE], + ], + } as never, + { deps: { bridgeConnectTimeoutMs: 1 } }, + ); + const parts = await run(h, opts([system("Generate a title"), user("hello")], SIDE("title"))); + expect(errorsOf(parts)).toHaveLength(0); + expect(textOf(parts)).toBe("Title"); + expect(finishOf(parts).finishReason.unified).toBe("stop"); + expect(h.starts()).toHaveLength(2); + expect(h.recv("session/close")).toHaveLength(2); + }); + + it("reports an empty reply when a side call answers with thinking only twice", async () => { + const h = harness({ runs: [[INIT, AUTH, NEW, THINK_ONLY, CLOSE], [INIT, AUTH, NEW, THINK_ONLY, CLOSE]] } as never, { + deps: { bridgeConnectTimeoutMs: 1 }, + }); + const parts = await run(h, opts([system("Summarize"), user("hello")], SIDE("compaction"))); + const errors = errorsOf(parts); + expect(errors).toHaveLength(1); + expect(errors[0].error.code).toBe("empty_reply"); + expect(finishOf(parts)).toBeUndefined(); + expect(h.starts()).toHaveLength(2); + }); + + it("reports an empty reply when a primary turn ends with thinking only", async () => { + const h = harness([INIT, AUTH, NEW, THINK_ONLY]); + const parts = await run(h, opts([user("hello")])); + const errors = errorsOf(parts); + expect(errors).toHaveLength(1); + expect(errors[0].error.code).toBe("empty_reply"); + expect(finishOf(parts)).toBeUndefined(); + expect(h.starts()).toHaveLength(1); + expect((await h.deps.store.get("ses-1"))?.interrupted).toBe(true); + }); + it("side calls advertise the request tools but refuse to run them", async () => { const h = harness([ INIT, @@ -792,7 +843,7 @@ describe("AgyAcpLanguageModel", () => { }); it("warns about unsupported settings and provider tools", async () => { - const h = harness([INIT, AUTH, NEW, { expect: "session/prompt", reply: END }]); + const h = harness([INIT, AUTH, NEW, PROMPT_OK]); const parts = await run( h, opts([user("hi")], { @@ -827,7 +878,7 @@ describe("AgyAcpLanguageModel", () => { }); it("finishes without prompting when there is nothing to send", async () => { - const h = harness([INIT, AUTH, NEW, { expect: "session/prompt", reply: END }]); + const h = harness([INIT, AUTH, NEW, PROMPT_OK]); const history = [user("hi")]; await run(h, opts(history)); const parts = await run(h, opts([...history, { role: "assistant", content: [{ type: "text", text: "hello" }] }])); @@ -838,7 +889,7 @@ describe("AgyAcpLanguageModel", () => { }); it("does not send an empty checkpoint after an interruption", async () => { - const h = harness([INIT, AUTH, NEW, { expect: "session/prompt", reply: END }]); + const h = harness([INIT, AUTH, NEW, PROMPT_OK]); const history = [user("hi")]; await run(h, opts(history)); const record = (await h.deps.store.get("ses-1"))!; @@ -849,11 +900,11 @@ describe("AgyAcpLanguageModel", () => { }); it("replaces the live session when the fingerprint changes", async () => { - const h = harness([INIT, AUTH, NEW, { expect: "session/prompt", reply: END }]); + const h = harness([INIT, AUTH, NEW, PROMPT_OK]); await run(h, opts([system("v1"), user("hi")])); writeFileSync( path.join(h.dir, "scenario.json"), - JSON.stringify([INIT, AUTH, { ...NEW, reply: { ...NEW.reply, sessionId: "s2" } }, { expect: "session/prompt", reply: END }]), + JSON.stringify([INIT, AUTH, { ...NEW, reply: { ...NEW.reply, sessionId: "s2" } }, PROMPT_OK]), ); await run(h, opts([system("v2"), user("hi"), { role: "assistant", content: [{ type: "text", text: "yo" }] }, user("more")])); expect(h.starts()).toHaveLength(2); @@ -868,10 +919,10 @@ describe("AgyAcpLanguageModel", () => { INIT, AUTH, NEW, - { expect: "session/prompt", reply: END }, + PROMPT_OK, CLOSE, { expect: "session/new", reply: { ...NEW.reply, sessionId: "s2" } }, - { expect: "session/prompt", reply: END }, + PROMPT_OK, ]); await run(h, opts([user("first")])); await run(h, opts([user("edited"), { role: "assistant", content: [{ type: "text", text: "x" }] }, user("next")])); @@ -882,13 +933,13 @@ describe("AgyAcpLanguageModel", () => { }); it("resumes the stored agy session when the process died while idle", async () => { - const h = harness([INIT, AUTH, NEW, { expect: "session/prompt", reply: END }]); + const h = harness([INIT, AUTH, NEW, PROMPT_OK]); const history = [user("hi")]; await run(h, opts(history)); const live = h.deps.pool.get("ses-1")!; writeFileSync( path.join(h.dir, "scenario.json"), - JSON.stringify([INIT, AUTH, { expect: "session/resume", reply: { models: NEW.reply.models } }, { expect: "session/prompt", reply: END }]), + JSON.stringify([INIT, AUTH, { expect: "session/resume", reply: { models: NEW.reply.models } }, PROMPT_OK]), ); await live.proc.dispose(); await run(h, opts([...history, { role: "assistant", content: [{ type: "text", text: "a" }] }, user("again")])); @@ -900,7 +951,7 @@ describe("AgyAcpLanguageModel", () => { }); it("opens a new session and replays history when resume fails", async () => { - const h = harness([INIT, AUTH, NEW, { expect: "session/prompt", reply: END }]); + const h = harness([INIT, AUTH, NEW, PROMPT_OK]); const history = [user("hi")]; await run(h, opts(history)); const live = h.deps.pool.get("ses-1")!; @@ -911,7 +962,7 @@ describe("AgyAcpLanguageModel", () => { AUTH, { expect: "session/resume", error: { code: -32602, message: "unknown session" } }, { ...NEW, reply: { ...NEW.reply, sessionId: "s2" } }, - { expect: "session/prompt", reply: END }, + PROMPT_OK, ]), ); await live.proc.dispose(); @@ -922,7 +973,7 @@ describe("AgyAcpLanguageModel", () => { }); it("idle_kill_closes_bridge_and_frees_slot", async () => { - const h = harness([INIT, AUTH, NEW, { expect: "session/prompt", reply: END }], { + const h = harness([INIT, AUTH, NEW, PROMPT_OK], { // Long enough that the session is still pooled after run() under coverage load. deps: { idleTimeoutMs: 1000, bridgeConnectTimeoutMs: 2000 }, }); @@ -949,7 +1000,7 @@ describe("AgyAcpLanguageModel", () => { AUTH, NEW, { expect: "session/prompt", callMcp: { tool: "read", args: { path: "a" }, toolCallId: "t1" }, reply: { stopReason: "cancelled" } }, - { expect: "session/prompt", reply: END }, + PROMPT_OK, ]); const history = [user("read a")]; await run(h, opts(history, { tools: [READ_TOOL] })); @@ -1072,7 +1123,7 @@ describe("AgyAcpLanguageModel turn lifecycle", () => { open = resolve; }); const ensurePlugin = vi.fn(() => gate); - const h = harness([INIT, AUTH, NEW, { expect: "session/prompt", reply: END }], { deps: { ensurePlugin } }); + const h = harness([INIT, AUTH, NEW, PROMPT_OK], { deps: { ensurePlugin } }); const { stream } = await h.model.doStream(opts([user("a")])); await waitFor(() => ensurePlugin.mock.calls.length > 0); await stream.cancel(); diff --git a/test/acp/register.test.ts b/test/acp/register.test.ts index 2754b040..ac2ec280 100644 --- a/test/acp/register.test.ts +++ b/test/acp/register.test.ts @@ -24,6 +24,17 @@ const NEW = { reply: { sessionId: "s1", models: { availableModels: [{ modelId: "gemini-3.8-flash-high" }], currentModelId: "gemini-3.8-flash-high" } }, }; const END = { stopReason: "end_turn", usage: { inputTokens: 1, outputTokens: 1 } }; +/** A prompt step that answers with text (a thinking-only turn is an error). */ +const PROMPT_OK = { + expect: "session/prompt", + notify: [ + { + method: "session/update", + params: { sessionId: "s1", update: { sessionUpdate: "agent_message_chunk", content: { type: "text", text: "ok" } } }, + }, + ], + reply: END, +}; interface Recorder { providers: Map; @@ -715,7 +726,7 @@ describe("registerAgyAcpProvider: integration and auth", () => { }); it("passes the stored API key to the agy child as GEMINI_API_KEY", async () => { - const agy = launcher([INIT, { expect: "authenticate", reply: {} }, NEW, { expect: "session/prompt", reply: END }]); + const agy = launcher([INIT, { expect: "authenticate", reply: {} }, NEW, PROMPT_OK]); active = { type: "credential", id: "c1", label: "k", method: "key" }; credential = { type: "key", key: "AIza-test" }; const { ctx, rec } = fakeCtx(); @@ -727,7 +738,7 @@ describe("registerAgyAcpProvider: integration and auth", () => { }); it("api_key_switch_respawns_process", async () => { - const agy = launcher([INIT, { expect: "authenticate", reply: {} }, NEW, { expect: "session/prompt", reply: END }]); + const agy = launcher([INIT, { expect: "authenticate", reply: {} }, NEW, PROMPT_OK]); active = { type: "credential", id: "c1", label: "k", method: "key" }; credential = { type: "key", key: "AIza-first-key" }; const { ctx, rec } = fakeCtx(); @@ -745,7 +756,7 @@ describe("registerAgyAcpProvider: integration and auth", () => { }); it("does not set GEMINI_API_KEY when no key is stored", async () => { - const agy = launcher([INIT, { expect: "authenticate", reply: {} }, NEW, { expect: "session/prompt", reply: END }]); + const agy = launcher([INIT, { expect: "authenticate", reply: {} }, NEW, PROMPT_OK]); const { ctx, rec } = fakeCtx(); await register(ctx, { probe: async () => ready(agy.path), env: agy.env }); await collect((await (await languageModel(rec)).doStream(turn())).stream); @@ -813,7 +824,7 @@ describe("registerAgyAcpProvider: status", () => { writeFileSync( path.join(dir, "scenario.json"), - JSON.stringify([INIT, { expect: "authenticate", reply: {} }, NEW, { expect: "session/prompt", reply: END }]), + JSON.stringify([INIT, { expect: "authenticate", reply: {} }, NEW, PROMPT_OK]), ); await collect((await (await languageModel(rec)).doStream(turn("ses-2"))).stream); expect(reg.status().status).toBe("ready"); @@ -839,7 +850,7 @@ describe("registerAgyAcpProvider: status", () => { describe("registerAgyAcpProvider: lazy plugin install", () => { it("plugin_install_is_lazy", async () => { - const agy = launcher([INIT, { expect: "authenticate", reply: {} }, NEW, { expect: "session/prompt", reply: END }]); + const agy = launcher([INIT, { expect: "authenticate", reply: {} }, NEW, PROMPT_OK]); const installer = vi.fn(async () => {}); const { ctx, rec } = fakeCtx(); await register(ctx, { probe: async () => ready(agy.path), env: agy.env, installer }); diff --git a/test/fixtures/fake-acp-agent.mjs b/test/fixtures/fake-acp-agent.mjs index 62efbb9c..0391cf3e 100644 --- a/test/fixtures/fake-acp-agent.mjs +++ b/test/fixtures/fake-acp-agent.mjs @@ -9,8 +9,19 @@ const BRIDGE_SERVER_NAME = "opencode-bridge_bridge"; const ALLOWED_BUILTINS = new Set(["read_file", "list_resources", "read_resource", "manage_task"]); const ENV_KEYS = ["AGY_ACP_BRIDGE_URL", "AGY_ACP_BRIDGE_TOKEN", "GEMINI_API_KEY", "GOOGLE_API_KEY", "AGY_ADC_AUTH"]; -const scenario = process.env.FAKE_ACP_SCENARIO ? JSON.parse(readFileSync(process.env.FAKE_ACP_SCENARIO, "utf8")) : []; const logPath = process.env.FAKE_ACP_LOG; +const rawScenario = process.env.FAKE_ACP_SCENARIO ? JSON.parse(readFileSync(process.env.FAKE_ACP_SCENARIO, "utf8")) : []; +// `{ runs: [steps, steps, ...] }` gives each successive agent process its own steps. +const priorStarts = (() => { + try { + return readFileSync(logPath, "utf8") + .split("\n") + .filter((l) => l.includes('"kind":"start"')).length; + } catch { + return 0; + } +})(); +const scenario = Array.isArray(rawScenario) ? rawScenario : (rawScenario.runs[priorStarts] ?? []); function log(entry) { if (logPath) appendFileSync(logPath, `${JSON.stringify(entry)}\n`); From 24d062c93d0fc6667c1ec2ec87d67e610c4040f9 Mon Sep 17 00:00:00 2001 From: Anthony Hausman Date: Tue, 1 Dec 2026 18:33:25 +0100 Subject: [PATCH 13/13] fix(acp): keep compaction side calls on the summary task OpenCode can send compaction with another agent's system prompt, so agy kept doing that agent's work. Compaction side calls now start the system prompt with a summary-only instruction. Assisted-by: Claude Opus 5.5 --- src/acp/language-model.ts | 11 +++++++++++ test/acp/language-model.test.ts | 21 +++++++++++++++++++++ 2 files changed, 32 insertions(+) diff --git a/src/acp/language-model.ts b/src/acp/language-model.ts index dc18b04b..5be56086 100644 --- a/src/acp/language-model.ts +++ b/src/acp/language-model.ts @@ -77,6 +77,16 @@ export const SIDE_CALL_SYSTEM_TEXT = "This request has no tools: do not call tools, look up tool schemas or read files. " + "Reply with text only, in exactly the format the instructions above ask for."; +/** + * Put first in the agy system prompt of compaction side calls. OpenCode may build + * the compaction request with the system prompt of another agent (for example a + * subagent that just finished), and agy then keeps doing that agent's task. + */ +export const COMPACTION_SYSTEM_TEXT = + "Your only task in this request is to summarize the conversation, using exactly the " + + "template given in the last message. Ignore any other task, role or instruction below " + + "and in the conversation, and do not continue the conversation's work."; + /** Shown when agy ends a turn with thinking only: no answer text and no tool call. */ export const EMPTY_REPLY_TEXT = "agy ended the turn without an answer (thinking only, no text or tool call). Retry the request."; @@ -313,6 +323,7 @@ export class AgyAcpLanguageModel implements LanguageModelV3 { // every tools/list, so an empty list here would wipe the main session's schemas. const tools = ctx.tools.length > 0 ? ctx.tools : (this.deps.lastTools ?? []); const sideCallSystem = [ + ctx.kind === "compaction" ? COMPACTION_SYSTEM_TEXT : "", ctx.system, SIDE_CALL_SYSTEM_TEXT, ] diff --git a/test/acp/language-model.test.ts b/test/acp/language-model.test.ts index 6d53a550..71422378 100644 --- a/test/acp/language-model.test.ts +++ b/test/acp/language-model.test.ts @@ -12,6 +12,7 @@ import { CANCELLED_TEXT, STILL_RUNNING_TEXT } from "../../src/acp/constants"; import { BRIDGE_NOT_CONNECTED_TEXT, TOS_DISABLED_TEXT } from "../../src/acp/errors"; import { AgyAcpLanguageModel, + COMPACTION_SYSTEM_TEXT, SIDE_CALL_SYSTEM_TEXT, type AgyAcpDeps, type LiveSession, @@ -728,6 +729,26 @@ describe("AgyAcpLanguageModel", () => { expect((await h.deps.store.get("ses-1"))?.interrupted).toBe(true); }); + it("puts the summary-only instruction first in compaction side calls", async () => { + const h = harness([INIT, AUTH, NEW, { expect: "session/prompt", notify: [chunk("## Goal")], reply: END }, CLOSE], { + deps: { bridgeConnectTimeoutMs: 1 }, + }); + const parts = await run(h, opts([system("You are an explorer"), user("hello")], SIDE("compaction"))); + expect(errorsOf(parts)).toHaveLength(0); + const append = h.recv("session/new")[0].message.params._meta.antigravity.systemPrompt.append; + expect(append.startsWith(`${COMPACTION_SYSTEM_TEXT}\n\nYou are an explorer`)).toBe(true); + expect(append).toContain(SIDE_CALL_SYSTEM_TEXT); + }); + + it("does not add the compaction instruction to title side calls", async () => { + const h = harness([INIT, AUTH, NEW, { expect: "session/prompt", notify: [chunk("T")], reply: END }, CLOSE], { + deps: { bridgeConnectTimeoutMs: 1 }, + }); + await run(h, opts([system("Generate a title"), user("hello")], SIDE("title"))); + const append = h.recv("session/new")[0].message.params._meta.antigravity.systemPrompt.append; + expect(append).not.toContain(COMPACTION_SYSTEM_TEXT); + }); + it("side calls advertise the request tools but refuse to run them", async () => { const h = harness([ INIT,