Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
10 changes: 10 additions & 0 deletions docs/acp-spike-findings.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
2 changes: 0 additions & 2 deletions src/acp/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.";
Expand Down
2 changes: 2 additions & 0 deletions src/acp/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ export type AgyErrorCode =
| "plugin_install"
| "bridge_unreachable"
| "crash"
| "rate_limited"
| "empty_reply"
| "other";

export const BRIDGE_NOT_CONNECTED_TEXT =
Expand Down
149 changes: 116 additions & 33 deletions src/acp/language-model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand All @@ -28,7 +28,9 @@ type StepOutcome =
| { kind: "aborted" }
| { kind: "detached" };

const TIERS: ReadonlySet<string> = 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",
Expand Down Expand Up @@ -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<string, string | undefined> | undefined, name: string): string | undefined {
Expand All @@ -96,20 +121,25 @@ 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[] {
return blocks.filter((b) => b.type !== "text" || (b.text.trim() !== "" && !EMPTY_CHECKPOINT.test(b.text)));
}

function lateBlocks(late: Array<{ callId: string; outcome: ToolOutcome }>): AcpContentBlock[] {
return late.map(({ callId, outcome }) => ({
type: "text",
text: `<tool-result id="${callId}"${outcome.isError ? ' error="true"' : ""}>\n${outcome.text}\n</tool-result>`,
}));
return late.flatMap(({ callId, outcome }): AcpContentBlock[] => [
{
type: "text",
text: `<tool-result id="${callId}"${outcome.isError ? ' error="true"' : ""}>\n${outcome.text}\n</tool-result>`,
},
...(outcome.images ?? []).map((i): AcpContentBlock => ({ type: "image", data: i.data, mimeType: i.mimeType })),
]);
}

export class AgyAcpLanguageModel implements LanguageModelV3 {
Expand Down Expand Up @@ -191,7 +221,6 @@ export class AgyAcpLanguageModel implements LanguageModelV3 {
cwd: this.deps.cwd,
...(append ? { systemPromptAppend: append } : {}),
modelId: this.modelId,
...(ctx.tier ? { tier: ctx.tier } : {}),
};
}

Expand Down Expand Up @@ -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;
Expand All @@ -240,6 +274,7 @@ export class AgyAcpLanguageModel implements LanguageModelV3 {
tools: ctx.tools,
session: this.sessionParams(ctx, ctx.tools),
auth,
...(resumeId ? { resumeId } : {}),
});
}),
o.abortSignal,
Expand All @@ -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)) {
Expand All @@ -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;
Expand All @@ -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`);
}
}

Expand All @@ -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<StepResult> {
let last: PromptResult | undefined;
if (live.turn) {
const settled = await this.drive(o, live, live.turn, out);
Expand All @@ -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) });
}
Expand All @@ -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?.();
Expand Down Expand Up @@ -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!;
}

Expand All @@ -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();
Expand Down
Loading