diff --git a/AGENTS.md b/AGENTS.md index 9ca0fd7b..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` 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` 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/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/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/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/errors.ts b/src/acp/errors.ts index 6ca5beda..e896812c 100644 --- a/src/acp/errors.ts +++ b/src/acp/errors.ts @@ -9,6 +9,8 @@ export type AgyErrorCode = | "plugin_install" | "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 7397bd8a..5be56086 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 } 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,9 @@ type StepOutcome = | { kind: "aborted" } | { kind: "detached" }; -const TIERS: ReadonlySet = new Set(["low", "medium", "high"]); +/** `"empty"`: agy ended the turn with thinking only and the caller asked to retry. */ +type StepResult = "empty" | undefined; + const UNSUPPORTED_SETTINGS = [ "maxOutputTokens", "temperature", @@ -66,11 +68,34 @@ 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."; + +/** + * 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."; + interface CallContext { key: string | undefined; + kind: string | undefined; system: string; tools: BridgeToolDef[]; - tier: AgyTier | undefined; } function headerValue(headers: Record | undefined, name: string): string | undefined { @@ -96,9 +121,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; - 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, kind, system, tools } }; } function cleanBlocks(blocks: AcpContentBlock[]): AcpContentBlock[] { @@ -106,10 +133,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 { @@ -191,7 +221,6 @@ export class AgyAcpLanguageModel implements LanguageModelV3 { cwd: this.deps.cwd, ...(append ? { systemPromptAppend: append } : {}), modelId: this.modelId, - ...(ctx.tier ? { tier: ctx.tier } : {}), }; } @@ -227,10 +256,15 @@ 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); 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 +274,7 @@ export class AgyAcpLanguageModel implements LanguageModelV3 { tools: ctx.tools, session: this.sessionParams(ctx, ctx.tools), auth, + ...(resumeId ? { resumeId } : {}), }); }), o.abortSignal, @@ -249,9 +284,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 +301,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; @@ -281,19 +319,37 @@ export class AgyAcpLanguageModel implements LanguageModelV3 { private async runThrowaway(o: LanguageModelV3CallOptions, ctx: CallContext, out: Out) { const auth = await this.deps.auth(); - const live = await LiveSession.create(this.deps, { - key: undefined, - fingerprint: "", - tools: [], - session: this.sessionParams(ctx, []), - 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(); + // 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.kind === "compaction" ? COMPACTION_SYSTEM_TEXT : "", + 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`); } } @@ -313,7 +369,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); @@ -330,8 +392,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) }); } @@ -354,7 +423,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?.(); @@ -386,6 +457,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!; } @@ -397,15 +479,16 @@ 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" }; 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/live-session.ts b/src/acp/live-session.ts index 52f25c9c..721fafe3 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 { @@ -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 = @@ -78,6 +83,10 @@ 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; setAbortSignal(signal: AbortSignal | undefined, onAbort: (reason: unknown) => void): void { this.detachAbort?.(); @@ -93,8 +102,12 @@ 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. */ + resumeId?: string; } function definedOnly(o: T | undefined): Partial { @@ -109,6 +122,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(); @@ -144,7 +159,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({ @@ -160,10 +180,10 @@ 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) { + 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); } @@ -189,17 +209,38 @@ 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; const { response, allowed } = decidePermission({ ...req, toolCall }); - if (allowed) { + 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 { + } else if (!allowed) { this.log("warn", `agy-acp: rejected agy tool ${toolCall.name ?? "(unknown)"} (call ${id})`); } return response; @@ -220,7 +261,13 @@ 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.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 cad1dc6a..cf73ad50 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"; @@ -57,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 }> = []; @@ -205,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) { @@ -241,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)) { @@ -251,7 +261,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/permission.ts b/src/acp/permission.ts index 08eda0d1..b6a96241 100644 --- a/src/acp/permission.ts +++ b/src/acp/permission.ts @@ -1,18 +1,66 @@ -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"); +} + +/** 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 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; + 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 file = realpathSync(target); + const dirs = [openCodeToolOutputDir(env), openCodeShellOutputDir(env)]; + return dirs.some((dir) => isInside(dir, file)) && 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/src/acp/process.ts b/src/acp/process.ts index 79ed427c..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 { @@ -115,6 +112,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,25 +296,26 @@ 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; 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 b3722b60..57b73591 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 { @@ -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, }), ); } @@ -184,15 +182,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/src/acp/stream-map.ts b/src/acp/stream-map.ts index ad7f0880..c83bc4b4 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": @@ -92,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/language-model.test.ts b/test/acp/language-model.test.ts index a03007a1..71422378 100644 --- a/test/acp/language-model.test.ts +++ b/test/acp/language-model.test.ts @@ -10,7 +10,13 @@ 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, + COMPACTION_SYSTEM_TEXT, + 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"; @@ -35,6 +41,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 => ({ @@ -208,6 +216,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, @@ -317,6 +349,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 }, + PROMPT_OK, + ], + { 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] })); @@ -328,6 +393,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"))) }, @@ -350,7 +429,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")]; @@ -537,7 +616,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" }) }, }); @@ -548,7 +627,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( [ @@ -556,25 +635,14 @@ describe("AgyAcpLanguageModel", () => { AUTH, NEW, { expect: "session/set_model", reply: {} }, - { expect: "session/set_config_option", reply: {} }, - { expect: "session/prompt", reply: END }, + PROMPT_OK, ], { 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 () => { @@ -584,11 +652,154 @@ 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); + 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 () => { + 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.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); - expect(h.recv("session/new")[0].message.params._meta.antigravity.systemPrompt.append).toBe("Generate a title"); + }); + + 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("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, + 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( + 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 () => { @@ -653,7 +864,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")], { @@ -688,7 +899,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" }] }])); @@ -699,7 +910,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"))!; @@ -710,11 +921,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); @@ -729,10 +940,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")])); @@ -742,20 +953,48 @@ describe("AgyAcpLanguageModel", () => { expect((await h.deps.store.get("ses-1"))!.agySessionId).toBe("s2"); }); - it("respawns when the process died while idle", async () => { - const h = harness([INIT, AUTH, NEW, { expect: "session/prompt", reply: END }]); + it("resumes the stored agy session when the process died while idle", async () => { + 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 } }, PROMPT_OK]), + ); + 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, 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, NEW, { expect: "session/prompt", reply: END }])); + 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" } }, + PROMPT_OK, + ]), + ); 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 () => { - 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 }, }); @@ -782,7 +1021,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] })); @@ -905,7 +1144,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/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/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/permission.test.ts b/test/acp/permission.test.ts index 94ff09cf..0c532666 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,55 @@ 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("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); + 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 }); diff --git a/test/acp/process.test.ts b/test/acp/process.test.ts index 7e9e875e..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" }], ]); }); @@ -243,6 +241,39 @@ 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: {} }, + ]); + const p = await t.start(); + 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", + 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(["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/); diff --git a/test/acp/register.test.ts b/test/acp/register.test.ts index 1036cf53..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; @@ -499,8 +510,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]); } @@ -716,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(); @@ -728,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(); @@ -746,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); @@ -814,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"); @@ -840,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/acp/session-sync.test.ts b/test/acp/session-sync.test.ts index 8069c5b3..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); }); }); @@ -210,6 +209,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"); diff --git a/test/acp/stream-map.test.ts b/test/acp/stream-map.test.ts index c02bcf8d..cbdcc635 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(); @@ -158,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" }; 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`);