diff --git a/.github/workflows/upstream-drift.yml b/.github/workflows/upstream-drift.yml new file mode 100644 index 000000000..b1909f731 --- /dev/null +++ b/.github/workflows/upstream-drift.yml @@ -0,0 +1,51 @@ +name: Upstream Drift + +# Versions we pin by hand in code (Antigravity, managed Node.js, the ACP and +# Codex protocol schemas) that Dependabot can't see. Opens one issue per pin +# that is behind its vendor, keeps it current, and closes it once we catch up. +# See scripts/check-upstream-drift.ts. + +on: + schedule: + # Mondays 12:23 UTC: 07:23 ET in winter, 08:23 in summer. Off the hour + # because GitHub queues top-of-the-hour crons the longest. + - cron: "23 12 * * 1" + workflow_dispatch: + +permissions: + contents: read + issues: write + +concurrency: + group: upstream-drift + cancel-in-progress: false + +jobs: + check: + name: Check pinned versions + runs-on: ubuntu-latest + timeout-minutes: 15 + steps: + # Always the default branch, even when run by hand from another one: + # a pin bumped on an unmerged branch must not close its issue. + - name: Checkout + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ github.event.repository.default_branch }} + + - name: Setup Vite+ + uses: voidzero-dev/setup-vp@cab1ab9eaff52d4857875f4f2c016e36af8f2c76 # v1.22.0 + with: + node-version: "24" + cache: true + run-install: false + + # The script imports the server modules that hold two of the pins. + - name: Install dependencies + run: vp install --frozen-lockfile + + - name: Check pins and sync issues + env: + GH_TOKEN: ${{ github.token }} + GH_REPO: ${{ github.repository }} + run: node scripts/check-upstream-drift.ts --apply diff --git a/apps/server/scripts/acp-mock-agent.ts b/apps/server/scripts/acp-mock-agent.ts index 093096e57..eba63655f 100644 --- a/apps/server/scripts/acp-mock-agent.ts +++ b/apps/server/scripts/acp-mock-agent.ts @@ -28,6 +28,10 @@ const failSetConfigOption = process.env.T3_ACP_FAIL_SET_CONFIG_OPTION === "1"; const authRequiredOnSetConfigOption = process.env.T3_ACP_FAIL_SET_CONFIG_OPTION === "auth"; const exitOnSetConfigOption = process.env.T3_ACP_EXIT_ON_SET_CONFIG_OPTION === "1"; const promptResponseText = process.env.T3_ACP_PROMPT_RESPONSE_TEXT; +/** Refuses to reopen a saved session, as an agent that no longer has it does. */ +const failLoadSession = process.env.T3_ACP_FAIL_LOAD_SESSION === "1"; +/** `agentInfo` to report on `initialize`, as JSON (`{"name":…,"version":…}`). */ +const agentInfo = process.env.T3_ACP_AGENT_INFO; /** Refuses the first prompt it gets, as an agent that errors before taking it does. */ let failFirstPrompt = process.env.T3_ACP_FAIL_FIRST_PROMPT === "1"; /** Ends every prompt with this stop reason and no reply, as a refusing model does. */ @@ -266,6 +270,7 @@ const program = Effect.gen(function* () { request.clientCapabilities.elicitation.url !== null; return { protocolVersion: 1, + ...(agentInfo ? { agentInfo: JSON.parse(agentInfo) as AcpSchema.Implementation } : {}), agentCapabilities: { loadSession: true, ...(advertiseHttpMcp ? { mcpCapabilities: { http: true } } : {}), @@ -342,20 +347,22 @@ const program = Effect.gen(function* () { ); yield* agent.handleLoadSession((request) => - agent.client - .sessionUpdate({ - sessionId: String(request.sessionId ?? sessionId), - update: { - sessionUpdate: "user_message_chunk", - content: { type: "text", text: "replay" }, - }, - }) - .pipe( - Effect.as({ - modes: modeState(), - configOptions: configOptions(), - }), - ), + failLoadSession + ? Effect.fail(AcpError.AcpRequestError.invalidParams("Session not found", {})) + : agent.client + .sessionUpdate({ + sessionId: String(request.sessionId ?? sessionId), + update: { + sessionUpdate: "user_message_chunk", + content: { type: "text", text: "replay" }, + }, + }) + .pipe( + Effect.as({ + modes: modeState(), + configOptions: configOptions(), + }), + ), ); yield* agent.handleSetSessionConfigOption((request) => diff --git a/apps/server/scripts/antigravity-mock-agent.ts b/apps/server/scripts/antigravity-mock-agent.ts new file mode 100644 index 000000000..249d27951 --- /dev/null +++ b/apps/server/scripts/antigravity-mock-agent.ts @@ -0,0 +1,1018 @@ +#!/usr/bin/env node +// @effect-diagnostics nodeBuiltinImport:off +/** + * An `agy acp` 1.5 stand-in for tests: what the Antigravity descriptor and + * the generic ACP core react to around a turn's end, as Google's changelog + * and T3 Code's fixtures describe it. `AGYMOCK_SCENARIO` picks the prompt's + * behaviour (the launcher drops `AGY_` and `ANTIGRAVITY_` variables, so the + * names avoid both); every frame the client sends is appended to + * `AGYMOCK_LOG` as JSON lines. + * + * - `simple`: replies and ends. + * - `background`: starts a command, ends its prompt, and when the command + * finishes replies by itself (1.5.10), then a `usage_update` ends the reply. + * - `hang`: starts a command that never finishes; a cancel fails it, then + * the CLI's cancellation notice follows. + * - `exit`: starts a command, ends its prompt, then the process exits. + * - `ignore-cancel`: never answers its prompt, a cancel included. + * - `schedule`: sets a timer (a `Running schedule` call that stays as it + * started), ends its prompt, and replies when the timer fires. + * - `subagents`: launches two subagents in one batch call; their reports come + * 3 seconds apart. + * - `cost`: reports a running USD cost before its answer and more after its + * own reply once a command ends. + * - `steer-late-log-error`: as `steer`, but the first prompt writes its + * error to the log only once the steer has arrived. + * - `subagent-quiet`: launches one subagent whose report never sends the + * closing `usage_update`. + * - `permission-second`: answers its first prompt at once; a second asks + * for a permission before it replies. + * - `steer-log-error`: as `steer`, but the first prompt's log ends in an + * error before the steer comes; the second answers cleanly. + * - `steer-own-log-error`: as `steer`, but the steer fails upstream: its + * error is logged before the first prompt answers, and nothing after it. + * - `subagent`: launches a subagent, ends its prompt, and replies with the + * subagent's report later. It writes no subagent records. + * - `subagent-records`: as `subagents`, with the children's records (as + * 1.5.12+ keeps them under `brain/`) and their reports in them. + * - `tools`: an MCP call through `call_mcp_tool`, a long command line, and + * a screenshot in a tool's content. + * - `mcp-permission`: asks to run a real `call_mcp_tool` call, then a + * command whose input also names an MCP tool. + * - `mcp-lossy`: an MCP-looking call with big arguments and a field no + * wrapper has, after them. + * - `mcp-then-location`: an MCP call whose later update names a file. + * - `permission-partial`: a command update, then a permission request that + * names the call by its id alone. + * - `permission-reask`: asks for an MCP call; while it waits, an update shows + * the call runs a command. + * - `permission-edit-changed`: asks for an edit; while it waits, the edit's + * replacement text changes and nothing else. + * - `plan-file-permission`: asks for a command naming the plan file, then + * for an edit of the plan file. + * - `plan-file-foreign`: asks to write another session's plan, then a + * `plan.md ` with a trailing space, then its own plan. It writes no subagent records. + * - `records-one-reply`: as `subagent-records`, but both children report + * before the agent wakes, and it answers both in one reply. + * - `records-killed`: as `subagent-records`, but in the reply to the first + * child's report the agent kills the second (its record says so). + * - `wake`: ends its prompt with nothing running, then replies by itself. + * - `background-quick`: as `background`, but the command ends 20 ms after + * the answer, and the wake's reply streams in two parts 300 ms apart. + * - `quiet-activity`: starts a command that never ends; 100 ms after the + * answer an update about it shows nothing new. + * - `stuck`: starts a command that never ends, and ignores a cancel. + * - `wake-permission-reask`: a command ends after the answer; the wake asks + * for an MCP call, and an update while it waits has it asked again. + * - `deaf`: closes its stdin once the session is up, and stays running. + * - `mode-fails-once`: the first switch back to the `default` mode fails; + * later ones work. + * - `steer`: holds its first prompt until a second arrives, answers the first + * `end_turn`, and replies to the second. + * - `log-error`: ends `end_turn`, its log's last step an upstream 502 error. + * - `quota`: fails the prompt with Google's quota error (1.5.9). + * - `lost-signature`: fails the prompt with the refused-thinking error. + * + * Every new session lists its slash commands right after it opens + * (`available_commands_update`), as the 1.5 CLI does. Under `flapping` it + * then changes the list ten times in a row. + */ +import { appendFileSync, closeSync, mkdirSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +import { DatabaseSync } from "node:sqlite"; + +import * as NodeRuntime from "@effect/platform-node/NodeRuntime"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import * as Deferred from "effect/Deferred"; +import * as Effect from "effect/Effect"; +import * as EffectAcpAgent from "effect-acp/agent"; +import * as AcpError from "effect-acp/errors"; +import type * as AcpSchema from "effect-acp/schema"; + +const scenario = process.env.AGYMOCK_SCENARIO ?? "simple"; +const logPath = process.env.AGYMOCK_LOG; +const profileDir = process.env.GEMINI_HOME; +let sessionCount = 0; + +const QUOTA_ERROR = + "Error 429, Message: Quota exhausted for gemini-4-argon., Status: RESOURCE_EXHAUSTED, Details: [map[@type:type.googleapis.com/google.rpc.ErrorInfo domain:googleapis.com metadata:map[quotaResetDelay:3600s quotaResetTimeStamp:2026-11-24T01:05:00Z] reason:QUOTA_EXHAUSTED]]"; +const GATEWAY_ERROR = + "Error 502, Message: Bad Gateway: Failed to connect to backend API, Status: 502 Bad Gateway, Details: []"; +const LOST_SIGNATURE_ERROR = + 'Error 400, Message: {"type":"error","error":{"type":"invalid_request_error","message":"messages.1.content.0.thinking.signature: Field required"}}, Status: INVALID_ARGUMENT, Details: []'; + +/** Appends steps to the session's log, as the CLI keeps it (step 15 a reply, 17 an error). */ +function appendLogSteps(sessionId: string, steps: ReadonlyArray) { + if (profileDir === undefined) return; + const dir = join(profileDir, "antigravity-acp", "conversations"); + mkdirSync(dir, { recursive: true }); + const database = new DatabaseSync(join(dir, `${sessionId}.db`)); + try { + database.exec( + "CREATE TABLE IF NOT EXISTS steps (idx INTEGER PRIMARY KEY, step_type INTEGER, step_payload BLOB)", + ); + const insert = database.prepare("INSERT INTO steps (step_type, step_payload) VALUES (?, ?)"); + for (const [type, payload] of steps) insert.run(type, Buffer.from(payload)); + } finally { + database.close(); + } +} + +/** Writes one of the CLI's JSON records under `brain/` in the profile. */ +function writeBrainRecord(segments: ReadonlyArray, value: unknown) { + if (profileDir === undefined) return; + const file = join(profileDir, "antigravity-acp", "brain", ...segments); + mkdirSync(join(file, ".."), { recursive: true }); + writeFileSync(file, typeof value === "string" ? value : JSON.stringify(value)); +} + +/** A child's records as `invoke_subagent` leaves them: its entry, its launch, its steps. */ +function recordChild(input: { + readonly parent: string; + readonly child: string; + readonly callId: string; + readonly role: string; + readonly prompt: string; + readonly state: string; +}) { + writeBrainRecord([input.parent, ".system_generated", "subagents", `${input.child}.json`], { + conversationId: input.child, + subagentDescriptor: { typeName: "research", role: input.role }, + state: input.state, + }); + writeBrainRecord([input.child, ".system_generated", "messages", "launch.json"], { + sender: input.parent, + content: input.prompt, + sourceMetadata: { + tool: { + conversationId: input.parent, + toolCall: { + id: input.callId, + name: "invoke_subagent", + argumentsJson: JSON.stringify({ Role: input.role, Prompt: input.prompt }), + }, + }, + }, + }); + writeBrainRecord( + [input.child, ".system_generated", "logs", "transcript.jsonl"], + [ + { + step_index: 0, + type: "SYSTEM_MESSAGE", + status: "DONE", + content: `\n[Message] sender=${input.parent} content=${input.prompt}\n`, + }, + { + step_index: 1, + type: "PLANNER_RESPONSE", + status: "DONE", + tool_calls: [{ name: "view_file", args: { AbsolutePath: '"/project/api.test.ts"' } }], + }, + { step_index: 2, type: "VIEW_FILE", status: "DONE", content: "1: it.skip('flaky')" }, + { step_index: 3, type: "PLANNER_RESPONSE", status: "DONE", content: "Found it." }, + ] + .map((line) => JSON.stringify(line)) + .join("\n") + "\n", + ); +} + +/** A child's report, in the parent's inbox. */ +function recordReport(parent: string, child: string, content: string) { + writeBrainRecord([parent, ".system_generated", "messages", `${child}-report.json`], { + sender: child, + content, + priority: "MESSAGE_PRIORITY_HIGH", + }); +} + +const textOf = (prompt: ReadonlyArray) => + prompt.flatMap((block) => (block.type === "text" ? [block.text] : [])).join("\n"); + +const program = Effect.gen(function* () { + const agent = yield* EffectAcpAgent.AcpAgent; + const secondPrompt = yield* Deferred.make(); + let promptsSeen = 0; + + const update = (sessionId: string, value: AcpSchema.SessionUpdate) => + agent.client.sessionUpdate({ sessionId, update: value }); + const say = (sessionId: string, text: string) => + update(sessionId, { sessionUpdate: "agent_message_chunk", content: { type: "text", text } }); + // The context grows with each model call, as the CLI reports it. + let contextUsed = 8_000; + const modelCallEnds = (sessionId: string) => + Effect.suspend(() => { + contextUsed += 1_000; + return update(sessionId, { + sessionUpdate: "usage_update", + used: contextUsed, + size: 1_048_576, + }); + }); + const command = { + toolCallId: "call_build", + title: "Running node build.mjs", + kind: "execute" as const, + rawInput: { CommandLine: "node build.mjs" }, + }; + + yield* agent.handleInitialize(() => + Effect.succeed({ + protocolVersion: 1, + agentInfo: { name: "agy", title: "Antigravity", version: "1.5.14" }, + agentCapabilities: { + loadSession: true, + sessionCapabilities: { resume: {} }, + promptCapabilities: { image: true, audio: true, embeddedContext: true }, + }, + }), + ); + yield* agent.handleCreateSession(() => + Effect.gen(function* () { + sessionCount += 1; + // Unique per process, as the CLI's are: two threads never share one. + const sessionId = `agy-${process.pid}-${sessionCount}`; + if (scenario === "deaf") { + // Closes its stdin once the session is up (the descriptor itself: + // destroying the stream leaves the pipe open); stdout stays open. + yield* Effect.sleep("100 millis").pipe( + Effect.andThen( + Effect.sync(() => { + process.stdin.destroy(); + closeSync(0); + }), + ), + Effect.forkDetach, + ); + } + // After the answer, as the CLI sends it. + yield* Effect.sleep("20 millis").pipe( + Effect.andThen( + update(sessionId, { + sessionUpdate: "available_commands_update", + availableCommands: [ + { name: "goal", description: "Work toward a goal", input: { hint: "objective" } }, + { name: "compact", description: "Summarize the conversation" }, + { name: "plan", description: "Plan before acting" }, + { name: "logout", description: "Sign out" }, + ], + }), + ), + Effect.andThen( + scenario === "flapping" + ? Effect.forEach( + Array.from({ length: 10 }, (_, index) => index), + (index) => + update(sessionId, { + sessionUpdate: "available_commands_update", + availableCommands: [{ name: "goal", description: `Version ${index}` }], + }).pipe(Effect.andThen(Effect.sleep("10 millis"))), + { discard: true }, + ) + : Effect.void, + ), + Effect.forkDetach, + ); + return { + sessionId, + modes: { + currentModeId: "default", + availableModes: [ + { id: "default", name: "Default" }, + { id: "accept-edits", name: "Accept edits" }, + { id: "plan", name: "Plan" }, + ], + }, + }; + }), + ); + // A mode switch, either way the client sends it. In `mode-fails-once` + // the first switch back to `default` fails. + let modeFailed = false; + const switchMode = (modeId: unknown) => { + if (scenario === "mode-fails-once" && modeId === "default" && !modeFailed) { + modeFailed = true; + return Effect.fail(AcpError.AcpRequestError.internalError("Could not switch mode.")); + } + return Effect.void; + }; + yield* agent.handleUnknownExtRequest((method, params) => + method === "session/set_mode" + ? switchMode((params as { readonly modeId?: unknown }).modeId).pipe(Effect.as({})) + : Effect.fail(AcpError.AcpRequestError.methodNotFound(method)), + ); + yield* agent.handleSetSessionConfigOption((request) => + switchMode(request.value).pipe(Effect.as({ configOptions: [] })), + ); + yield* agent.handleResumeSession(() => Effect.succeed({})); + yield* agent.handleLoadSession(() => Effect.succeed({})); + yield* agent.handleCancel(({ sessionId }) => + Effect.gen(function* () { + // 1.5.10: a cancel stops the session's commands too. + if (scenario === "hang") { + yield* update(String(sessionId), { + sessionUpdate: "tool_call_update", + toolCallId: command.toolCallId, + status: "failed", + }); + // The notice lands after the turn was stopped. + yield* Effect.gen(function* () { + yield* Effect.sleep("150 millis"); + yield* say(String(sessionId), "The request was cancelled by the client."); + }).pipe(Effect.forkDetach); + } + }), + ); + + yield* agent.handlePrompt((request) => + Effect.gen(function* () { + const sessionId = String(request.sessionId); + promptsSeen += 1; + if (scenario === "ignore-cancel") { + yield* say(sessionId, "Thinking hard."); + return yield* Effect.never; + } + if (scenario === "permission-partial" || scenario === "permission-reask") { + const options = [ + { optionId: "allow", name: "Allow", kind: "allow_once" as const }, + { optionId: "deny", name: "Deny", kind: "reject_once" as const }, + ]; + if (scenario === "permission-partial") { + yield* update(sessionId, { + sessionUpdate: "tool_call", + toolCallId: "call_rm", + title: "Running rm -rf build", + kind: "execute", + status: "pending", + rawInput: { CommandLine: "rm -rf build" }, + }); + // The request names the call by its id alone. + yield* agent.client.requestPermission({ + sessionId, + toolCall: { toolCallId: "call_rm" }, + options, + }); + yield* update(sessionId, { + sessionUpdate: "tool_call_update", + toolCallId: "call_rm", + status: "failed", + }); + } else { + // Asked as an MCP call; an update while it waits shows a command. + yield* Effect.gen(function* () { + yield* Effect.sleep("300 millis"); + yield* update(sessionId, { + sessionUpdate: "tool_call_update", + toolCallId: "call_mcp", + status: "pending", + rawInput: { CommandLine: "rm -rf build" }, + }); + }).pipe(Effect.forkDetach); + yield* agent.client.requestPermission({ + sessionId, + toolCall: { + toolCallId: "call_mcp", + title: "MCP Tool list_issues", + kind: "execute", + status: "pending", + rawInput: { ServerName: "github", ToolName: "list_issues", Arguments: {} }, + }, + options, + }); + } + yield* say(sessionId, "Asked."); + yield* modelCallEnds(sessionId); + return { stopReason: "end_turn" as const }; + } + if (scenario === "permission-edit-changed") { + const edit = (newText: string) => ({ + toolCallId: "call_config", + title: "Edit config.json", + kind: "edit" as const, + status: "pending" as const, + content: [{ type: "diff" as const, path: "/repo/config.json", oldText: "{}", newText }], + locations: [{ path: "/repo/config.json" }], + }); + yield* update(sessionId, { sessionUpdate: "tool_call", ...edit('{"a":1}') }); + // While the approval waits, the edit changes only its replacement text. + yield* Effect.gen(function* () { + yield* Effect.sleep("300 millis"); + yield* update(sessionId, { sessionUpdate: "tool_call_update", ...edit('{"a":2}') }); + }).pipe(Effect.forkDetach); + yield* agent.client.requestPermission({ + sessionId, + toolCall: edit('{"a":1}'), + options: [ + { optionId: "allow", name: "Allow", kind: "allow_once" }, + { optionId: "deny", name: "Deny", kind: "reject_once" }, + ], + }); + yield* update(sessionId, { + sessionUpdate: "tool_call_update", + toolCallId: "call_config", + status: "failed", + }); + yield* say(sessionId, "Asked."); + yield* modelCallEnds(sessionId); + return { stopReason: "end_turn" as const }; + } + if (scenario === "plan-file-foreign") { + const brain = join(profileDir ?? "", "antigravity-acp", "brain"); + const options = [ + { optionId: "allow", name: "Allow", kind: "allow_once" as const }, + { optionId: "deny", name: "Deny", kind: "reject_once" as const }, + ]; + const writePlan = (toolCallId: string, path: string) => + agent.client.requestPermission({ + sessionId, + toolCall: { + toolCallId, + title: "Write plan.md", + kind: "edit", + status: "pending", + content: [{ type: "diff", path, newText: "# Plan\n" }], + }, + options, + }); + // Another session's plan, and a file whose name only looks like it. + yield* writePlan("call_other", join(brain, "other-session", "plan.md")); + yield* writePlan("call_padded", join(brain, sessionId, "plan.md ")); + // This session's own plan needs no approval. + yield* writePlan("call_own", join(brain, sessionId, "plan.md")); + yield* say(sessionId, "Planned."); + yield* modelCallEnds(sessionId); + return { stopReason: "end_turn" as const }; + } + if (scenario === "plan-file-permission") { + const plan = join(profileDir ?? "", "antigravity-acp", "brain", sessionId, "plan.md"); + const options = [ + { optionId: "allow", name: "Allow", kind: "allow_once" as const }, + { optionId: "deny", name: "Deny", kind: "reject_once" as const }, + ]; + // A command that names the plan file is still a command. + yield* agent.client.requestPermission({ + sessionId, + toolCall: { + toolCallId: "call_shell", + title: "Running cat plan.md", + kind: "execute", + status: "pending", + rawInput: { CommandLine: `cat ${plan}` }, + locations: [{ path: plan }], + }, + options, + }); + // Writing the plan file itself needs no approval. + yield* agent.client.requestPermission({ + sessionId, + toolCall: { + toolCallId: "call_plan", + title: "Write plan.md", + kind: "edit", + status: "pending", + content: [{ type: "diff", path: plan, newText: "# Plan\n" }], + }, + options, + }); + yield* say(sessionId, "Planned."); + yield* modelCallEnds(sessionId); + return { stopReason: "end_turn" as const }; + } + if (scenario === "mcp-lossy") { + // Big arguments, then a field no wrapper has: bounding could drop it. + yield* update(sessionId, { + sessionUpdate: "tool_call", + toolCallId: "call_lossy", + kind: "execute", + title: "MCP Tool list_issues", + status: "completed", + rawInput: { + ServerName: "github", + ToolName: "list_issues", + Arguments: Object.fromEntries( + Array.from({ length: 600 }, (_, index) => [`k${index}`, index]), + ), + Cwd: "/", + }, + }); + yield* say(sessionId, "Done."); + yield* modelCallEnds(sessionId); + return { stopReason: "end_turn" as const }; + } + if (scenario === "mcp-then-location") { + yield* update(sessionId, { + sessionUpdate: "tool_call", + toolCallId: "call_wrapped", + kind: "execute", + title: "MCP Tool list_issues", + status: "in_progress", + rawInput: { ServerName: "github", ToolName: "list_issues", Arguments: {} }, + }); + // A later update that names a file: not an MCP call after all. + yield* update(sessionId, { + sessionUpdate: "tool_call_update", + toolCallId: "call_wrapped", + status: "in_progress", + locations: [{ path: "/tmp/agy-target" }], + }); + yield* say(sessionId, "Done."); + yield* update(sessionId, { + sessionUpdate: "tool_call_update", + toolCallId: "call_wrapped", + status: "completed", + }); + yield* modelCallEnds(sessionId); + return { stopReason: "end_turn" as const }; + } + if (scenario === "mcp-permission") { + const ask = (toolCall: AcpSchema.ToolCallUpdate) => + agent.client.requestPermission({ + sessionId, + toolCall, + options: [ + { optionId: "allow", name: "Allow", kind: "allow_once" }, + { optionId: "deny", name: "Deny", kind: "reject_once" }, + ], + }); + // A real `call_mcp_tool` call. + yield* ask({ + toolCallId: "call_mcp", + title: "MCP Tool list_issues", + kind: "execute", + status: "pending", + rawInput: { ServerName: "github", ToolName: "list_issues", Arguments: { repo: "x/y" } }, + }); + // A command that also names an MCP tool: it is still a command. + yield* ask({ + toolCallId: "call_spoof", + title: "MCP Tool list_issues", + kind: "execute", + status: "pending", + rawInput: { ServerName: "github", ToolName: "list_issues", CommandLine: "rm -rf build" }, + }); + yield* say(sessionId, "Asked twice."); + yield* modelCallEnds(sessionId); + return { stopReason: "end_turn" as const }; + } + if (scenario === "permission-second") { + if (promptsSeen === 1) { + yield* say(sessionId, "First done."); + yield* modelCallEnds(sessionId); + return { stopReason: "end_turn" as const }; + } + yield* agent.client.requestPermission({ + sessionId, + toolCall: { + toolCallId: "call_rm", + title: "Running rm -rf build", + kind: "execute", + status: "pending", + rawInput: { CommandLine: "rm -rf build" }, + }, + options: [ + { optionId: "allow", name: "Allow", kind: "allow_once" }, + { optionId: "deny", name: "Deny", kind: "reject_once" }, + ], + }); + yield* say(sessionId, "Second done."); + yield* modelCallEnds(sessionId); + return { stopReason: "end_turn" as const }; + } + if ( + scenario === "steer" || + scenario === "steer-log-error" || + scenario === "steer-late-log-error" || + scenario === "steer-own-log-error" + ) { + if (promptsSeen === 1) { + if (scenario === "steer-log-error") appendLogSteps(sessionId, [[17, GATEWAY_ERROR]]); + yield* say(sessionId, "Working on it."); + // Answered once the steer arrives, as 1.5.11 does. + yield* Deferred.await(secondPrompt); + // Its error written only now, while the steer is under way. + if (scenario === "steer-late-log-error") { + appendLogSteps(sessionId, [[17, GATEWAY_ERROR]]); + } + return { + stopReason: "end_turn" as const, + usage: { inputTokens: 100, outputTokens: 5, totalTokens: 105 }, + }; + } + // The steer's own upstream error, logged before the first prompt answers. + if (scenario === "steer-own-log-error") appendLogSteps(sessionId, [[17, GATEWAY_ERROR]]); + yield* Deferred.succeed(secondPrompt, undefined); + yield* Effect.sleep("50 millis"); + if (scenario === "steer-own-log-error") { + yield* say(sessionId, "API error: the request failed."); + return { stopReason: "end_turn" as const }; + } + // The CLI logs the model's reply to the steer as a step of its own. + appendLogSteps(sessionId, [[15, `Steered: ${textOf(request.prompt)}`]]); + yield* say(sessionId, `Steered: ${textOf(request.prompt)}`); + yield* modelCallEnds(sessionId); + return { + stopReason: "end_turn" as const, + usage: { inputTokens: 300, outputTokens: 20, totalTokens: 320 }, + }; + } + if (scenario === "quota") { + return yield* AcpError.AcpRequestError.internalError(QUOTA_ERROR); + } + if (scenario === "lost-signature") { + return yield* AcpError.AcpRequestError.internalError(LOST_SIGNATURE_ERROR); + } + if (scenario === "log-error") { + appendLogSteps(sessionId, [ + [14, textOf(request.prompt)], + [17, GATEWAY_ERROR], + ]); + yield* say(sessionId, "API error: the request failed."); + return { stopReason: "end_turn" as const }; + } + if (scenario === "schedule") { + const timer = { + toolCallId: "call_timer", + kind: "other" as const, + title: "Running schedule", + }; + yield* update(sessionId, { sessionUpdate: "tool_call", ...timer, status: "in_progress" }); + yield* say(sessionId, "Timer set."); + yield* modelCallEnds(sessionId); + yield* Effect.gen(function* () { + yield* Effect.sleep("3000 millis"); + yield* update(sessionId, { + sessionUpdate: "tool_call_update", + toolCallId: timer.toolCallId, + status: "completed", + }); + yield* say(sessionId, "Timer fired."); + yield* modelCallEnds(sessionId); + }).pipe(Effect.forkDetach); + return { stopReason: "end_turn" as const }; + } + if (scenario === "subagents" || scenario === "subagent-quiet") { + // `subagents` launches both in one batch call. + yield* update(sessionId, { + sessionUpdate: "tool_call", + toolCallId: "call_launch", + kind: "other", + title: "Running invoke_subagent", + status: "completed", + rawInput: + scenario === "subagents" + ? { + Subagents: [ + { Role: "Researcher", Prompt: "Work as Researcher" }, + { Role: "Tester", Prompt: "Work as Tester" }, + ], + } + : { Role: "Researcher", Prompt: "Work as Researcher" }, + }); + yield* say(sessionId, "Subagents are on it."); + yield* modelCallEnds(sessionId); + yield* Effect.gen(function* () { + yield* Effect.sleep("1000 millis"); + yield* say(sessionId, "The researcher reported."); + if (scenario === "subagent-quiet") return; + yield* modelCallEnds(sessionId); + yield* Effect.sleep("3000 millis"); + yield* say(sessionId, "The tester reported."); + yield* modelCallEnds(sessionId); + }).pipe(Effect.forkDetach); + return { stopReason: "end_turn" as const }; + } + if (scenario === "cost") { + // A running cost on the context fill, as fx sends it: 2 cents by the + // answer, 5 once the agent's own reply after the command is done. + yield* update(sessionId, { + sessionUpdate: "tool_call", + ...command, + status: "in_progress", + }); + yield* update(sessionId, { + sessionUpdate: "usage_update", + used: 9_000, + size: 1_048_576, + cost: { amount: 0.02, currency: "USD" }, + }); + yield* Effect.gen(function* () { + yield* Effect.sleep("300 millis"); + yield* update(sessionId, { + sessionUpdate: "tool_call_update", + toolCallId: command.toolCallId, + status: "completed", + }); + yield* say(sessionId, "Done."); + yield* update(sessionId, { + sessionUpdate: "usage_update", + used: 9_500, + size: 1_048_576, + cost: { amount: 0.05, currency: "USD" }, + }); + }).pipe(Effect.forkDetach); + return { + stopReason: "end_turn" as const, + usage: { inputTokens: 400, outputTokens: 10, totalTokens: 410 }, + }; + } + if (scenario === "background" || scenario === "hang" || scenario === "exit") { + yield* update(sessionId, { sessionUpdate: "tool_call", ...command, status: "in_progress" }); + yield* say(sessionId, "I'll report once the build finishes."); + yield* modelCallEnds(sessionId); + if (scenario === "exit") { + yield* Effect.gen(function* () { + yield* Effect.sleep("400 millis"); + yield* Effect.sync((): void => process.exit(1)); + }).pipe(Effect.forkDetach); + } + if (scenario === "background") { + yield* Effect.gen(function* () { + yield* Effect.sleep("400 millis"); + yield* update(sessionId, { + sessionUpdate: "tool_call_update", + toolCallId: command.toolCallId, + status: "completed", + rawOutput: { output: "Command exited with code 0.", exit_code: 0 }, + }); + yield* Effect.sleep("100 millis"); + yield* say(sessionId, "The build passed."); + yield* modelCallEnds(sessionId); + }).pipe(Effect.forkDetach); + } + return { + stopReason: "end_turn" as const, + usage: { + inputTokens: 1_000, + cachedReadTokens: 4_000, + outputTokens: 50, + thoughtTokens: 20, + totalTokens: 5_050, + }, + }; + } + if (scenario === "subagent") { + yield* update(sessionId, { + sessionUpdate: "tool_call", + toolCallId: "call_research", + kind: "other", + title: "Running invoke_subagent", + status: "completed", + rawInput: { Role: "Researcher", Prompt: "Find the flaky test" }, + }); + yield* say(sessionId, "A researcher is on it."); + yield* modelCallEnds(sessionId); + yield* Effect.gen(function* () { + yield* Effect.sleep("2500 millis"); + yield* say(sessionId, "The researcher found it."); + yield* modelCallEnds(sessionId); + }).pipe(Effect.forkDetach); + return { stopReason: "end_turn" as const }; + } + if (scenario === "records-one-reply" || scenario === "records-killed") { + const launch = (callId: string, child: string, role: string, prompt: string) => + Effect.gen(function* () { + recordChild({ + parent: sessionId, + child, + callId, + role, + prompt, + state: "SUBAGENT_STATE_ALIVE", + }); + yield* update(sessionId, { + sessionUpdate: "tool_call", + toolCallId: callId, + kind: "other", + // How agy 1.5 titles a launch it ran without asking. + title: "Run invoke_subagent", + status: "completed", + rawInput: { Role: role, Prompt: prompt }, + }); + }); + yield* launch("call_research", "child-research", "Researcher", "Find the flaky test"); + yield* launch("call_review", "child-review", "Reviewer", "Review the fix"); + yield* say(sessionId, "Two agents are on it."); + yield* modelCallEnds(sessionId); + yield* Effect.gen(function* () { + yield* Effect.sleep("400 millis"); + recordReport(sessionId, "child-research", "The flaky test is api.test.ts."); + if (scenario === "records-one-reply") { + recordReport(sessionId, "child-review", "The fix looks right."); + yield* say(sessionId, " Both agents reported."); + } else { + // The kill only rewrites the child's entry. + recordChild({ + parent: sessionId, + child: "child-review", + callId: "call_review", + role: "Reviewer", + prompt: "Review the fix", + state: "SUBAGENT_STATE_KILLED", + }); + yield* say(sessionId, " The researcher found it, so I stopped the reviewer."); + } + yield* modelCallEnds(sessionId); + }).pipe(Effect.forkDetach); + return { stopReason: "end_turn" as const }; + } + if (scenario === "subagent-records") { + const launch = (callId: string, child: string, role: string, prompt: string) => + Effect.gen(function* () { + recordChild({ + parent: sessionId, + child, + callId, + role, + prompt, + state: "SUBAGENT_STATE_ALIVE", + }); + yield* update(sessionId, { + sessionUpdate: "tool_call", + toolCallId: callId, + kind: "other", + // The title the turn's hold counts; agy 1.5 also sends "Run invoke_subagent". + title: "Running invoke_subagent", + status: "completed", + rawInput: { Role: role, Prompt: prompt }, + }); + }); + yield* launch("call_research", "child-research", "Researcher", "Find the flaky test"); + yield* launch("call_review", "child-review", "Reviewer", "Review the fix"); + yield* say(sessionId, "Two agents are on it."); + yield* modelCallEnds(sessionId); + yield* Effect.gen(function* () { + yield* Effect.sleep("400 millis"); + recordReport(sessionId, "child-research", "The flaky test is api.test.ts."); + yield* say(sessionId, " The researcher found it."); + yield* modelCallEnds(sessionId); + // Longer than a held turn's settle: only the records hold it. + yield* Effect.sleep("3000 millis"); + recordReport(sessionId, "child-review", "The fix looks right."); + yield* say(sessionId, " The reviewer agreed."); + yield* modelCallEnds(sessionId); + }).pipe(Effect.forkDetach); + return { stopReason: "end_turn" as const }; + } + if (scenario === "tools") { + yield* update(sessionId, { + sessionUpdate: "tool_call", + toolCallId: "call_mcp", + kind: "execute", + title: "MCP Tool list_issues", + status: "completed", + rawInput: { ServerName: "github", ToolName: "list_issues", Arguments: { repo: "x/y" } }, + rawOutput: "[]", + }); + yield* update(sessionId, { + sessionUpdate: "tool_call", + toolCallId: "call_long", + kind: "execute", + title: "Running long command", + status: "completed", + rawInput: { CommandLine: `echo start ${"x".repeat(9_000)} 😀 end` }, + rawOutput: { output: `${"y".repeat(9_000)}tail`, exit_code: 0 }, + }); + yield* update(sessionId, { + sessionUpdate: "tool_call", + toolCallId: "call_shot", + kind: "other", + title: "Took a screenshot", + status: "completed", + content: [ + { + type: "content", + content: { type: "image", data: "aGVsbG8=", mimeType: "image/png" }, + }, + { type: "content", content: { type: "text", text: "Screenshot taken." } }, + ], + }); + yield* say(sessionId, "Done."); + yield* modelCallEnds(sessionId); + return { stopReason: "end_turn" as const }; + } + if (scenario === "wake") { + yield* say(sessionId, "Timer set."); + yield* modelCallEnds(sessionId); + yield* Effect.gen(function* () { + yield* Effect.sleep("3000 millis"); + yield* say(sessionId, "Woke up by myself."); + yield* modelCallEnds(sessionId); + }).pipe(Effect.forkDetach); + return { stopReason: "end_turn" as const }; + } + if (scenario === "wake-permission-reask") { + yield* update(sessionId, { sessionUpdate: "tool_call", ...command, status: "in_progress" }); + yield* say(sessionId, "I'll report once the build finishes."); + yield* modelCallEnds(sessionId); + yield* Effect.gen(function* () { + yield* Effect.sleep("100 millis"); + yield* update(sessionId, { + sessionUpdate: "tool_call_update", + toolCallId: command.toolCallId, + status: "completed", + rawOutput: { output: "Command exited with code 0.", exit_code: 0 }, + }); + // Woken by the build, it asks to run an MCP tool; an update while + // it waits shows the call is a command, so it is asked again. + yield* Effect.gen(function* () { + yield* Effect.sleep("300 millis"); + yield* update(sessionId, { + sessionUpdate: "tool_call_update", + toolCallId: "call_mcp", + status: "pending", + rawInput: { CommandLine: "rm -rf build" }, + }); + }).pipe(Effect.forkDetach); + yield* agent.client.requestPermission({ + sessionId, + toolCall: { + toolCallId: "call_mcp", + title: "MCP Tool list_issues", + kind: "execute", + status: "pending", + rawInput: { ServerName: "github", ToolName: "list_issues", Arguments: {} }, + }, + options: [ + { optionId: "allow", name: "Allow", kind: "allow_once" }, + { optionId: "deny", name: "Deny", kind: "reject_once" }, + ], + }); + yield* say(sessionId, "Done after asking."); + yield* modelCallEnds(sessionId); + }).pipe(Effect.forkDetach); + return { stopReason: "end_turn" as const }; + } + if ( + scenario === "background-quick" || + scenario === "quiet-activity" || + scenario === "stuck" + ) { + yield* update(sessionId, { sessionUpdate: "tool_call", ...command, status: "in_progress" }); + yield* say(sessionId, "I'll report once the build finishes."); + yield* modelCallEnds(sessionId); + yield* Effect.gen(function* () { + yield* Effect.sleep(scenario === "quiet-activity" ? "100 millis" : "20 millis"); + if (scenario === "quiet-activity") { + // An update about the command that shows nothing new. + yield* update(sessionId, { + sessionUpdate: "tool_call_update", + toolCallId: command.toolCallId, + status: "in_progress", + }); + return; + } + if (scenario === "stuck") return; + yield* update(sessionId, { + sessionUpdate: "tool_call_update", + toolCallId: command.toolCallId, + status: "completed", + rawOutput: { output: "Command exited with code 0.", exit_code: 0 }, + }); + yield* say(sessionId, "The build"); + yield* Effect.sleep("300 millis"); + yield* say(sessionId, " passed."); + yield* modelCallEnds(sessionId); + }).pipe(Effect.forkDetach); + return { + stopReason: "end_turn" as const, + usage: { inputTokens: 700, outputTokens: 30, totalTokens: 730 }, + }; + } + yield* say(sessionId, "hello from agy"); + yield* modelCallEnds(sessionId); + return { + stopReason: "end_turn" as const, + usage: { inputTokens: 10, outputTokens: 3, totalTokens: 13 }, + }; + }), + ); + + return yield* Effect.never; +}).pipe( + Effect.provide( + EffectAcpAgent.layerStdio( + logPath + ? { + logIncoming: true, + logger: (event) => + event.direction === "incoming" && + event.stage === "raw" && + typeof event.payload === "string" + ? Effect.sync(() => { + const payload = event.payload as string; + appendFileSync( + logPath, + payload.endsWith("\n") ? payload : `${payload}\n`, + "utf8", + ); + }) + : Effect.void, + } + : {}, + ), + ), + Effect.scoped, + Effect.provide(NodeServices.layer), +); + +NodeRuntime.runMain(program); diff --git a/apps/server/src/guide/topics.ts b/apps/server/src/guide/topics.ts index cdec6a023..5aae2bc98 100644 --- a/apps/server/src/guide/topics.ts +++ b/apps/server/src/guide/topics.ts @@ -313,7 +313,11 @@ While this computer is asleep or Threadlines is closed, assistants are told it's Claude's models come from Claude Code itself, so a new one shows up without a Threadlines update. A model Threadlines has no settings of its own for starts on Default reasoning: no level is sent and Claude Code picks one. When Claude Code stops listing a model, the picker stops offering it, but a thread, room agent or setting already on it keeps it. -How much of each plan you've used is on {place:usage}. The ring beside the composer's send button shows the same limits when you hover or tap it; a short upright tick on each bar marks how much of that limit's window has passed (hover the tick for the exact share, "55% of the week has passed"), so a bar filled past its tick is on track to run out before the reset, and its line says "ahead of pace" once it is clearly past. The same ticks show on a provider's Usage tab in Settings › Providers. Clicking a limit there opens {place:usage}. +Antigravity runs Google's Antigravity CLI (agy), which Threadlines downloads and checks itself; it needs 1.5.14 or newer, for a custom path too. New models arrive with a newer Antigravity: when Google publishes one, the Antigravity card offers Update, and the picker lists the new models after it, with the reasoning level as its own choice. An Antigravity installed before the move to the CLI shows Update, and a Google sign-in from then needs one more sign-in. Signing in with Google opens Google's page on the device you started from; paste the code the Antigravity page shows into the box Threadlines shows. Sign out removes only that account's sign-in; your own agy in a terminal stays signed in. While Antigravity waits on a command, a timer or a subagent it started, its turn stays working with Stop, and its reply when that work ends lands in the same turn; Stop ends the turn and that work. A message sent while it answers waits for the turn to end; one sent while it only waits on that work ends the turn and goes at once. Each subagent Antigravity launches shows like other agents' subagents, with its role, prompt, report and recent steps. Images and audio go to Antigravity inline, PDFs and text files as documents, other files as a path. Its turns count on {place:usage}. + +Each Antigravity account brings in your own rules and skills from ~/.gemini at every start (AGENTS.md, GEMINI.md, config/rules, and the config/skills and antigravity-cli/skills folders with skills.json); your sign-in, hooks, plugins and MCP servers stay out. Antigravity runs a skill or one of its own commands (such as /goal or /compact, when it offers them) when a message starts with / and its name, so typing / in the composer lists its skills, and while Antigravity runs in that thread, the commands it offers there. A message whose typed words start with one of those goes to Antigravity alone and as typed, even in plan mode; the context Threadlines would put in front of it waits for the next ordinary message. Editing an earlier message stops anything Antigravity still runs before the files are restored, and starts it over with only the turns before it, since it can't rewind its own conversation. + +How much of each plan you've used is on {place:usage}. The ring beside the composer's send button shows the same limits when you hover or tap it; a short upright tick on each bar marks how much of that limit's window has passed (hover the tick for the exact share, "55% of the week has passed"), so a bar filled past its tick is on track to run out before the reset, and its line says "ahead of pace" once it is clearly past. The same ticks show on a provider's Usage tab in Settings › Providers. Clicking a limit there opens {place:usage}. An Antigravity account signed in with Google shows a 5-hour and a weekly limit for each group of models Google meters apart (Gemini, each Gemini 4 model with its own limit, and Claude & GPT together), read from Google every few minutes; each model in the picker shows its own group's limit. Google renews that sign-in only while Antigravity runs, so when it has lapsed the last numbers stay, with their age and a line saying a chat refreshes them. API-key and Vertex AI accounts have no plan limits to show. An agent's row that says Can't start means its program is on this computer but fails to launch, usually because an update stopped partway. It is not a sign-in problem: the sign-in is still saved. The row has Reinstall when Threadlines can put that same copy back: with npm, bun or Homebrew for a copy they installed, or with the agent's own installer for a copy sitting where that installer puts it (Claude, OpenCode, Cursor, fx, Muse Code, and Codex on Windows). For Pi it reinstalls an npm copy, or installs Threadlines' own copy of Pi. There is no Reinstall for a copy from pnpm, Scoop, winget or Nix, for one at a custom path, or for Grok from xAI's installer (it would switch the release channel); reinstall those the way they were installed. An update that leaves an agent unable to start runs that reinstall once on its own before reporting. Community agents are installed by Threadlines itself and have Install again instead. Antigravity is downloaded and checked by Threadlines, so it isn't covered. @@ -329,7 +333,7 @@ When Claude Code refuses to start (a settings file that is not valid JSON, a bad If Codex's sign-in goes stale in a chat before it has started on your message, Threadlines restarts Codex and sends the message again, once, with a note in the chat. If that fails too, the chat asks you to sign in. -When a Claude or Codex usage limit stops a thread, the notice above the composer says which limit and when it resets. Its Continue at reset switch sends "Continue where you left off." a minute after the reset, from the computer the thread runs on (a Mac that wakes only briefly for upkeep waits until it's fully awake), or within a few minutes of the limit resetting early because the user spent a limit reset, and {place:threads.continueAfterUsageLimits} turns it on for every limit. With it on, a thread another thread's agent started on this computer also waits for the reset instead of failing, and its answer goes back once it continues; so does a thread hearing back from one it started. Stop ends the wait, and a turn you stopped never comes back by itself. If you added another account of the same agent that still has room, the notice offers it by name. Threadlines never switches accounts on its own.`, +When a Claude, Codex or Antigravity usage limit stops a thread, the notice above the composer says which limit and when it resets. Its Continue at reset switch sends "Continue where you left off." a minute after the reset, from the computer the thread runs on (a Mac that wakes only briefly for upkeep waits until it's fully awake), or within a few minutes of the limit resetting early because the user spent a limit reset, and {place:threads.continueAfterUsageLimits} turns it on for every limit. With it on, a thread another thread's agent started on this computer also waits for the reset instead of failing, and its answer goes back once it continues; so does a thread hearing back from one it started. Stop ends the wait, and a turn you stopped never comes back by itself. If you added another account of the same agent that still has room, the notice offers it by name. Threadlines never switches accounts on its own.`, }, { id: "plugins-skills-instructions", diff --git a/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts b/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts index a1daa1a74..cc4141983 100644 --- a/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts +++ b/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts @@ -68,6 +68,7 @@ import { checkpointRefForThreadTurn, } from "../../checkpointing/Utils.ts"; import { ServerConfig } from "../../config.ts"; +import { ProviderAdapterRequestError } from "../../provider/Errors.ts"; import { WorkspaceEntriesLive } from "../../workspace/Layers/WorkspaceEntries.ts"; import { WorkspacePathsLive } from "../../workspace/Layers/WorkspacePaths.ts"; @@ -94,6 +95,8 @@ function createProviderServiceHarness( sessionCwd = cwd, providerName: ProviderSession["provider"] = ProviderDriverKind.make("codex"), extraSessions: ReadonlyArray = [], + conversationRollback?: "native" | "none" | "new-session", + capabilitiesFail = false, ) { const now = "2026-01-01T00:00:00.000Z"; const runtimeEventPubSub = Effect.runSync(PubSub.unbounded()); @@ -102,7 +105,8 @@ function createProviderServiceHarness( readonly threadId: ThreadId; readonly numTurns: number; readonly targetUserMessageId?: MessageId; - }) => Effect.succeed({ conversationRolledBack: true }), + }): Effect.Effect<{ conversationRolledBack: boolean }, ProviderAdapterRequestError> => + Effect.succeed({ conversationRolledBack: true }), ); const unsupported = () => @@ -161,7 +165,20 @@ function createProviderServiceHarness( adoptNativeSession: () => Effect.void, forgetNativeSession: () => Effect.void, dropResumeCursor: () => Effect.void, - getCapabilities: () => Effect.succeed({ sessionModelSwitch: "in-session" }), + noteHistoryDelivered: () => Effect.void, + getCapabilities: () => + capabilitiesFail + ? Effect.fail( + new ProviderAdapterRequestError({ + provider: "antigravity", + method: "getCapabilities", + detail: "the instance is not reachable", + }), + ) + : Effect.succeed({ + sessionModelSwitch: "in-session", + ...(conversationRollback !== undefined ? { conversationRollback } : {}), + }), getInstanceInfo: (instanceId) => Effect.succeed({ instanceId, @@ -366,6 +383,8 @@ describe("CheckpointReactor", () => { readonly includeConcurrentSession?: boolean; readonly extraProviderSessions?: ReadonlyArray; readonly gitStatusRefreshCalls?: Array; + readonly conversationRollback?: "native" | "none" | "new-session"; + readonly capabilitiesFail?: boolean; }) { const cwd = createGitRepository(); tempDirs.push(cwd); @@ -393,6 +412,8 @@ describe("CheckpointReactor", () => { options?.providerSessionCwd ?? cwd, options?.providerName ?? ProviderDriverKind.make("codex"), extraProviderSessions, + options?.conversationRollback, + options?.capabilitiesFail === true, ); const orchestrationLayer = OrchestrationEngineLive.pipe( Layer.provide(OrchestrationProjectionSnapshotQueryLive), @@ -3111,6 +3132,184 @@ describe("CheckpointReactor", () => { ); }); + it("restores the files of a thread whose provider is no longer registered", async () => { + const harness = await createHarness({ hasSession: false, capabilitiesFail: true }); + const threadId = ThreadId.make("thread-1"); + const createdAt = "2026-01-01T00:00:00.000Z"; + for (const turnCount of [1, 2] as const) { + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.turn.diff.complete", + commandId: CommandId.make(`cmd-capabilities-diff-${turnCount}`), + threadId, + turnId: asTurnId(`turn-${turnCount}`), + completedAt: createdAt, + checkpointRef: checkpointRefForThreadTurn(threadId, turnCount), + status: "ready", + files: [{ path: "README.md", kind: "modified", additions: 1, deletions: 1 }], + checkpointTurnCount: turnCount, + completesTurn: true, + createdAt, + }), + ); + } + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.checkpoint.revert", + commandId: CommandId.make("cmd-capabilities-revert"), + threadId, + turnCount: 1, + createdAt, + }), + ); + // A removed provider has no runtime left that could write, so the revert + // goes on without asking it for anything. + await waitForThread(harness.readModel, (entry) => + entry.activities.some((activity) => activity.kind === "checkpoint.reverted"), + ); + expect(harness.provider.rollbackConversation).not.toHaveBeenCalled(); + expect( + fs.readFileSync(path.join(harness.cwd, "README.md"), "utf8").replaceAll("\r\n", "\n"), + ).toBe("v2\n"); + }); + + it.each([ + { case: "the agent can't be stopped", stopFails: true }, + { case: "the files can't be restored after it forgot", stopFails: false }, + ])("tells the user what happened when $case", async ({ stopFails }) => { + const harness = await createHarness({ + hasSession: true, + conversationRollback: "new-session", + }); + const threadId = ThreadId.make("thread-1"); + const createdAt = "2026-01-01T00:00:00.000Z"; + if (stopFails) { + harness.provider.rollbackConversation.mockImplementation(() => + Effect.fail( + new ProviderAdapterRequestError({ + provider: "antigravity", + method: "rollbackThread", + detail: "the agent did not stop", + }), + ), + ); + } + for (const turnCount of [1, 2] as const) { + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.turn.diff.complete", + commandId: CommandId.make(`cmd-stop-case-diff-${turnCount}`), + threadId, + turnId: asTurnId(`turn-${turnCount}`), + completedAt: createdAt, + checkpointRef: checkpointRefForThreadTurn(threadId, turnCount), + status: "ready", + files: [{ path: "README.md", kind: "modified", additions: 1, deletions: 1 }], + checkpointTurnCount: turnCount, + completesTurn: true, + createdAt, + }), + ); + } + // The checkpoint to restore is gone: the restore fails. + if (!stopFails) { + runGit(harness.cwd, ["update-ref", "-d", checkpointRefForThreadTurn(threadId, 1)]); + } + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.checkpoint.revert", + commandId: CommandId.make("cmd-stop-case-revert"), + threadId, + turnCount: 1, + createdAt, + }), + ); + const thread = await waitForThread(harness.readModel, (entry) => + entry.activities.some((activity) => activity.kind === "checkpoint.revert.failed"), + ); + const failure = thread.activities.find( + (activity) => activity.kind === "checkpoint.revert.failed", + ); + const detail = (failure?.payload as { readonly detail?: string } | undefined)?.detail ?? ""; + if (stopFails) { + expect(detail).toContain("couldn't be stopped, so no file was restored"); + } else { + expect(detail).toContain("no longer remembers the turns after this point"); + } + // Either way the files are as the agent left them. + expect( + fs.readFileSync(path.join(harness.cwd, "README.md"), "utf8").replaceAll("\r\n", "\n"), + ).toBe("v3\n"); + }); + + it.each([ + { running: true, forgotten: true }, + { running: false, forgotten: true }, + { running: false, forgotten: false }, + ])( + "stops an agent that starts over before restoring any file, and says so if it can't forget (%o)", + async ({ running, forgotten }) => { + const harness = await createHarness({ + hasSession: running, + conversationRollback: "new-session", + }); + const threadId = ThreadId.make("thread-1"); + const createdAt = "2026-01-01T00:00:00.000Z"; + // What the checkout held when the agent was told to stop. + let readmeWhenStopped: string | undefined; + harness.provider.rollbackConversation.mockImplementation(() => + Effect.sync(() => { + readmeWhenStopped = fs + .readFileSync(path.join(harness.cwd, "README.md"), "utf8") + .replaceAll("\r\n", "\n"); + return { conversationRolledBack: forgotten }; + }), + ); + + for (const turnCount of [1, 2] as const) { + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.turn.diff.complete", + commandId: CommandId.make(`cmd-new-session-diff-${turnCount}`), + threadId, + turnId: asTurnId(`turn-${turnCount}`), + completedAt: createdAt, + checkpointRef: checkpointRefForThreadTurn(threadId, turnCount), + status: "ready", + files: [{ path: "README.md", kind: "modified", additions: 1, deletions: 1 }], + checkpointTurnCount: turnCount, + completesTurn: true, + createdAt, + }), + ); + } + + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.checkpoint.revert", + commandId: CommandId.make("cmd-new-session-revert"), + threadId, + turnCount: 1, + createdAt, + }), + ); + + await waitForEvent(harness.engine, (event) => event.type === "thread.reverted"); + expect(harness.provider.rollbackConversation).toHaveBeenCalledTimes(1); + // Stopped while the reverted turn's file was still there, then restored. + expect(readmeWhenStopped).toBe("v3\n"); + expect( + fs.readFileSync(path.join(harness.cwd, "README.md"), "utf8").replaceAll("\r\n", "\n"), + ).toBe("v2\n"); + const thread = await waitForThread(harness.readModel, (entry) => + entry.activities.some((activity) => activity.kind === "checkpoint.reverted"), + ); + const kinds = thread.activities.map((activity) => activity.kind); + expect(kinds.includes("checkpoint.revert.rollback-unsupported")).toBe(!forgotten); + expect(kinds.includes("checkpoint.revert.rollback-skipped")).toBe(false); + }, + ); + it("appends an error activity when revert targets a turn missing from the read model", async () => { const harness = await createHarness({ hasSession: false }); const createdAt = "2026-01-01T00:00:00.000Z"; diff --git a/apps/server/src/orchestration/Layers/CheckpointReactor.ts b/apps/server/src/orchestration/Layers/CheckpointReactor.ts index 4e5b71cdf..75a36a1b7 100644 --- a/apps/server/src/orchestration/Layers/CheckpointReactor.ts +++ b/apps/server/src/orchestration/Layers/CheckpointReactor.ts @@ -1222,10 +1222,67 @@ const make = Effect.gen(function* () { } const context = contextResult.context; - const revertOutcome = yield* checkpointRevert.applyRevert(context); + const rolledBackTurns = Math.max(0, context.currentTurnCount - event.payload.turnCount); + const targetUserMessageId = targetUserMessageIdForCheckpointRewind({ + thread: context.thread, + targetTurnCount: event.payload.turnCount, + }); + // An agent that forgets by starting over (Antigravity) is stopped, and + // its conversation forgotten, before any file is restored: a command it + // still ran could otherwise write over a restored file. Nothing is + // started for an agent that isn't running. + // The lookup fails only when the thread's provider instance is no longer + // registered (removed or turned off). Removing an instance ends its + // runtimes, so nothing of it can still write: the files are restored as + // for an agent that isn't running. + const capabilities = + rolledBackTurns > 0 + ? yield* Effect.result( + providerService.getCapabilities( + context.thread.session?.providerInstanceId ?? + context.thread.modelSelection.instanceId, + ), + ) + : undefined; + const startsOver = + capabilities?._tag === "Success" && + capabilities.success.conversationRollback === "new-session"; + // Undefined: not such an agent. A failure means it couldn't be found or + // stopped: something it runs could still write, so no file is restored. + const stopped = startsOver + ? yield* Effect.result( + providerService.rollbackConversation({ + threadId: event.payload.threadId, + numTurns: rolledBackTurns, + ...(targetUserMessageId !== undefined ? { targetUserMessageId } : {}), + }), + ) + : undefined; + if (stopped !== undefined && stopped._tag === "Failure") { + yield* Effect.logWarning("checkpoint revert could not stop the agent", { + threadId: event.payload.threadId, + cause: String(stopped.failure), + }); + yield* failRevert( + "The agent couldn't be stopped, so no file was restored: something it runs could still write to them. Stop it and try again.", + ); + return; + } + const startedOver = + stopped?._tag === "Success" ? stopped.success.conversationRolledBack : undefined; + + const restored = yield* Effect.result(checkpointRevert.applyRevert(context)); + const revertOutcome = restored._tag === "Success" ? restored.success : null; if (revertOutcome === null) { + const filesDetail = + restored._tag === "Failure" + ? restored.failure.message + : `Filesystem checkpoint is unavailable for turn ${event.payload.turnCount}.`; + // Both facts: the agent already forgot, the files stayed as they were. yield* failRevert( - `Filesystem checkpoint is unavailable for turn ${event.payload.turnCount}.`, + startedOver === true + ? `${filesDetail} The agent's conversation was already reset: it no longer remembers the turns after this point.` + : filesDetail, ); return; } @@ -1241,18 +1298,16 @@ const make = Effect.gen(function* () { createdAt: now, }).pipe(Effect.catch(() => Effect.void)); - const rolledBackTurns = Math.max(0, context.currentTurnCount - event.payload.turnCount); if (rolledBackTurns > 0) { - if (context.hasProviderSession) { - const targetUserMessageId = targetUserMessageIdForCheckpointRewind({ - thread: context.thread, - targetTurnCount: event.payload.turnCount, - }); - const rollback = yield* providerService.rollbackConversation({ - threadId: event.payload.threadId, - numTurns: rolledBackTurns, - ...(targetUserMessageId !== undefined ? { targetUserMessageId } : {}), - }); + if (startsOver || context.hasProviderSession) { + const rollback = + startedOver !== undefined + ? { conversationRolledBack: startedOver } + : yield* providerService.rollbackConversation({ + threadId: event.payload.threadId, + numTurns: rolledBackTurns, + ...(targetUserMessageId !== undefined ? { targetUserMessageId } : {}), + }); if (!rollback.conversationRolledBack) { yield* orchestrationEngine .dispatch({ diff --git a/apps/server/src/orchestration/Layers/ContinueAtResetSweeper.test.ts b/apps/server/src/orchestration/Layers/ContinueAtResetSweeper.test.ts index 567644c0f..514d244fa 100644 --- a/apps/server/src/orchestration/Layers/ContinueAtResetSweeper.test.ts +++ b/apps/server/src/orchestration/Layers/ContinueAtResetSweeper.test.ts @@ -80,6 +80,55 @@ function claude(input: { } as unknown as ServerProvider; } +/** + * Antigravity as a reading taken `readAgoMs` ago shows it: limits that each + * cover one family of models, Gemini's weekly and the Claude & GPT pool's. + */ +function antigravity(input: { + readonly geminiUsedPercent: number; + readonly sharedUsedPercent: number; + /** When the Claude & GPT pool resets; by default with Gemini's week. */ + readonly sharedResetMs?: number; + readonly readAgoMs: number; +}) { + const family = ( + scopeLabel: string, + scopeModels: Array, + usedPercent: number, + resetsAt = WEEKLY_RESET_MS, + ) => ({ + scopeLabel, + scopeModels, + usedPercent, + remainingPercent: 100 - usedPercent, + resetsAt, + windowDurationMins: 7 * 24 * 60, + checkedAt: isoAt(NOW_MS - input.readAgoMs), + }); + return { + instanceId: INSTANCE_ID, + driver: ProviderDriverKind.make("antigravity"), + enabled: true, + installed: true, + status: "ready", + auth: { status: "authenticated" }, + models: [], + accountUsage: { + source: "grok-billing", + checkedAt: isoAt(NOW_MS - input.readAgoMs), + limits: [ + { + limitId: "antigravity", + scoped: [ + family("Gemini", ["Gemini"], input.geminiUsedPercent), + family("Claude & GPT", ["Claude", "GPT"], input.sharedUsedPercent, input.sharedResetMs), + ], + }, + ], + }, + } as unknown as ServerProvider; +} + describe("ContinueAtResetSweeper", () => { let runtime: ManagedRuntime.ManagedRuntime | null = null; @@ -227,4 +276,35 @@ describe("ContinueAtResetSweeper", () => { expect(await sweep()).toBe(0); expect(dispatched).toEqual([]); }); + + it("continues a thread on one family of models while another family stays spent", async () => { + // The thread waits on Gemini's week; Claude & GPT's pool is spent until another time. + const sharedResetMs = NOW_MS + 2 * HOUR_MS; + const { dispatched, sweep, read } = await createHarness( + antigravity({ + geminiUsedPercent: 100, + sharedUsedPercent: 100, + sharedResetMs, + readAgoMs: HOUR_MS, + }), + ); + expect(await sweep()).toBe(0); + // Gemini reset early; the other family staying spent doesn't stop a Gemini thread. + read( + antigravity({ geminiUsedPercent: 4, sharedUsedPercent: 100, sharedResetMs, readAgoMs: 0 }), + ); + expect(await sweep()).toBe(1); + expect(dispatched).toMatchObject([{ type: "thread.continue-at-reset.fire", resetEarly: true }]); + }); + + it("waits when the reading can't tell which family stopped the thread", async () => { + // Both families were spent until the reset the thread waits for. + const { dispatched, sweep, read } = await createHarness( + antigravity({ geminiUsedPercent: 100, sharedUsedPercent: 100, readAgoMs: HOUR_MS }), + ); + expect(await sweep()).toBe(0); + read(antigravity({ geminiUsedPercent: 4, sharedUsedPercent: 100, readAgoMs: 0 })); + expect(await sweep()).toBe(0); + expect(dispatched).toEqual([]); + }); }); diff --git a/apps/server/src/orchestration/Layers/ContinueAtResetSweeper.ts b/apps/server/src/orchestration/Layers/ContinueAtResetSweeper.ts index a95b55674..4a983dc53 100644 --- a/apps/server/src/orchestration/Layers/ContinueAtResetSweeper.ts +++ b/apps/server/src/orchestration/Layers/ContinueAtResetSweeper.ts @@ -4,6 +4,7 @@ import { CommandId, MessageId, type ServerProvider, type ThreadId } from "@threa import { continueAtResetTimeMs, listProviderUsageWindows, + type ProviderUsageWindowReading, readProviderUsageBlock, } from "@threadlines/shared/usageLimits"; import * as Clock from "effect/Clock"; @@ -119,9 +120,17 @@ const makeContinueAtResetSweeper = (options?: ContinueAtResetSweeperLiveOptions) return false; } if (seen === undefined) return false; - // Another spent limit would only stop the thread again. + // Another spent limit would only stop the thread again, unless it + // covers another family of models than every limit that stopped it + // (Antigravity's Claude & GPT pool beside a Gemini thread's). + const stoppedFamilies = [...seen.readAtMsByWindow.keys()].map( + (key) => windows.find((window) => window.key === key)?.family, + ); + const otherFamily = (window: ProviderUsageWindowReading) => + window.family !== undefined && + stoppedFamilies.every((family) => family !== undefined && family !== window.family); if ( - windows.some((window) => window.spent) || + windows.some((window) => window.spent && !otherFamily(window)) || readProviderUsageBlock(provider, nowMs).state === "blocked" ) { return false; diff --git a/apps/server/src/orchestration/Layers/ProviderActivityProjection.test.ts b/apps/server/src/orchestration/Layers/ProviderActivityProjection.test.ts index e74f5a3ff..4ab2f2fd4 100644 --- a/apps/server/src/orchestration/Layers/ProviderActivityProjection.test.ts +++ b/apps/server/src/orchestration/Layers/ProviderActivityProjection.test.ts @@ -425,6 +425,28 @@ describe("ProviderActivityProjection", () => { ); }); + it("keeps the start of a long command line", () => { + const command = `node build.mjs ${"--flag ".repeat(MAX_THREAD_ACTIVITY_PAYLOAD_TEXT_LENGTH)}`; + const activities = projectRuntimeEventToActivities({ + type: "item.completed", + eventId: EventId.make("evt-long-command"), + provider: ProviderDriverKind.make("codex"), + threadId: ThreadId.make("thread-1"), + turnId: TurnId.make("turn-1"), + createdAt: "2026-06-01T12:00:00.000Z", + payload: { + itemType: "command_execution", + title: "Ran command", + data: { item: { command, status: "completed" } }, + }, + } satisfies ProviderRuntimeEvent); + + const item = (activities[0]?.payload as { data?: { item?: { command?: string } } })?.data?.item; + expect(item?.command?.startsWith("node build.mjs --flag")).toBe(true); + expect(item?.command?.endsWith("...")).toBe(true); + expect(item?.command?.length).toBeLessThanOrEqual(MAX_THREAD_ACTIVITY_PAYLOAD_TEXT_LENGTH); + }); + it("preserves completed tool lifecycle status for flat provider payloads", () => { const activities = projectRuntimeEventToActivities({ type: "item.completed", diff --git a/apps/server/src/orchestration/Layers/ProviderActivityProjection.ts b/apps/server/src/orchestration/Layers/ProviderActivityProjection.ts index 945784f65..eb385c3f0 100644 --- a/apps/server/src/orchestration/Layers/ProviderActivityProjection.ts +++ b/apps/server/src/orchestration/Layers/ProviderActivityProjection.ts @@ -96,9 +96,27 @@ function truncateBlock(value: string, limit = 1_200): string { if (value.length <= limit) { return value; } - return `...${value.slice(value.length - limit + 3)}`; + // A low surrogate at the cut would leave half a character. + return `...${value.slice(value.length - limit + 3).replace(/^[\uDC00-\uDFFF]/u, "")}`; } +/** Keeps the start of a long command line: the program and its target are there. */ +function truncateCommandLine(value: string, limit: number): string { + if (value.length <= limit) { + return value; + } + return `${value.slice(0, limit - 3).replace(/[\uD800-\uDBFF]$/u, "")}...`; +} + +/** Keys that hold a command line, in the spellings agents use. */ +const COMMAND_LINE_PAYLOAD_KEYS = new Set([ + "command", + "commandLine", + "CommandLine", + "command_line", + "cmd", +]); + const OUTPUT_LIKE_PAYLOAD_KEYS = new Set([ "aggregatedOutput", "content", @@ -171,9 +189,10 @@ function compactActivityPayloadData( limits: PayloadTextCompactionLimits = DEFAULT_PAYLOAD_TEXT_LIMITS, ): unknown { if (typeof value === "string") { - return shouldCompactPayloadString(key, value, limits) - ? truncateBlock(value, limits.text) - : value; + if (!shouldCompactPayloadString(key, value, limits)) return value; + return key !== undefined && COMMAND_LINE_PAYLOAD_KEYS.has(key) + ? truncateCommandLine(value, limits.text) + : truncateBlock(value, limits.text); } if (value === null || typeof value !== "object") { diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts index 76b88c720..656f0aea3 100644 --- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts +++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts @@ -456,6 +456,9 @@ describe("ProviderCommandReactor", () => { if (index >= 0) runtimeSessions.splice(index, 1); }), ); + const noteHistoryDelivered = vi.fn( + () => Effect.void, + ); const renameBranch = vi.fn((input: unknown) => Effect.succeed({ branch: @@ -578,6 +581,7 @@ describe("ProviderCommandReactor", () => { adoptNativeSession: () => Effect.void, forgetNativeSession: () => Effect.void, dropResumeCursor, + noteHistoryDelivered, getCapabilities: (_provider) => Effect.succeed({ sessionModelSwitch: input?.sessionModelSwitch ?? "in-session", @@ -832,6 +836,7 @@ describe("ProviderCommandReactor", () => { respondToUserInput, stopSession, dropResumeCursor, + noteHistoryDelivered, renameBranch, refreshStatus, refreshLocalStatus, @@ -1719,6 +1724,167 @@ describe("ProviderCommandReactor", () => { ); }); + it("pays the history only once the prompt carrying it went out, and names the runtime that sent it", async () => { + const harness = await createHarness(); + const now = "2026-01-01T00:00:00.000Z"; + const turnStart = (id: string, text: string) => + Effect.runPromise( + harness.engine.dispatch({ + type: "thread.turn.start", + commandId: CommandId.make(`cmd-dispatch-turn-${id}`), + threadId: ThreadId.make("thread-1"), + message: { + messageId: asMessageId(`dispatch-message-${id}`), + role: "user", + text, + attachments: [], + }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "approval-required", + createdAt: now, + }), + ); + await turnStart("1", "first question"); + await waitFor(() => harness.sendTurn.mock.calls.length === 1); + const startFresh = harness.startSession.getMockImplementation(); + if (!startFresh) throw new Error("expected the harness start implementation"); + harness.startSession.mockImplementationOnce((key, input) => + startFresh(key, input).pipe(Effect.map((session) => ({ ...session, resumeFailed: true }))), + ); + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.runtime-mode.set", + commandId: CommandId.make("cmd-dispatch-runtime-mode"), + threadId: ThreadId.make("thread-1"), + runtimeMode: "full-access", + createdAt: now, + }), + ); + await waitFor(() => harness.startSession.mock.calls.length === 2); + + // Accepted, but the agent never got the prompt (its configuration failed). + harness.sendTurn.mockImplementationOnce(() => + Effect.succeed({ + threadId: ThreadId.make("thread-1"), + turnId: asTurnId("turn-2"), + undelivered: true as const, + }), + ); + await turnStart("2", "second question"); + await waitFor(() => harness.sendTurn.mock.calls.length === 2); + await Effect.runPromise(Effect.sleep("50 millis")); + expect(harness.noteHistoryDelivered).not.toHaveBeenCalled(); + + // The next send carries the history again, and pays it once it went out. + await turnStart("3", "third question"); + await waitFor(() => harness.sendTurn.mock.calls.length === 3); + const sent = harness.sendTurn.mock.calls[2]?.[0] as { readonly input?: string } | undefined; + expect(sent?.input).toContain("prior context"); + await waitFor(() => harness.noteHistoryDelivered.mock.calls.length === 1); + const live = harness.runtimeSessions.find((session) => session.threadId === "thread-1"); + expect(harness.noteHistoryDelivered.mock.calls[0]?.[0]).toEqual({ + threadId: ThreadId.make("thread-1"), + sessionCreatedAt: live?.createdAt, + }); + }); + + it("owes the history after a send that reopened its runtime without the conversation", async () => { + const harness = await createHarness(); + const turnStart = (id: string, text: string) => + Effect.runPromise( + harness.engine.dispatch({ + type: "thread.turn.start", + commandId: CommandId.make(`cmd-recovered-turn-${id}`), + threadId: ThreadId.make("thread-1"), + message: { + messageId: asMessageId(`recovered-message-${id}`), + role: "user", + text, + attachments: [], + }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "approval-required", + createdAt: "2026-01-01T00:00:00.000Z", + }), + ); + // The service had to reopen the runtime, and it couldn't resume. + harness.sendTurn.mockImplementationOnce(() => + Effect.succeed({ + threadId: ThreadId.make("thread-1"), + turnId: asTurnId("turn-recovered"), + historyOwed: true as const, + }), + ); + await turnStart("1", "first question"); + await waitFor(() => harness.sendTurn.mock.calls.length === 1); + // That message stays sent; the next one carries the history. + await turnStart("2", "second question"); + await waitFor(() => harness.sendTurn.mock.calls.length === 2); + const sent = harness.sendTurn.mock.calls[1]?.[0] as { readonly input?: string } | undefined; + expect(sent?.input).toContain("prior context"); + expect(sent?.input?.endsWith("second question")).toBe(true); + }); + + it("keeps the history owed while a send goes as the agent's own command, without it", async () => { + const harness = await createHarness(); + const now = "2026-01-01T00:00:00.000Z"; + const turnStart = (id: string, text: string) => + Effect.runPromise( + harness.engine.dispatch({ + type: "thread.turn.start", + commandId: CommandId.make(`cmd-deferred-turn-${id}`), + threadId: ThreadId.make("thread-1"), + message: { + messageId: asMessageId(`deferred-message-${id}`), + role: "user", + text, + attachments: [], + }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "approval-required", + createdAt: now, + }), + ); + await turnStart("1", "first question"); + await waitFor(() => harness.sendTurn.mock.calls.length === 1); + // The session can't reopen its conversation: the history is owed. + const startFresh = harness.startSession.getMockImplementation(); + if (!startFresh) throw new Error("expected the harness start implementation"); + harness.startSession.mockImplementationOnce((key, input) => + startFresh(key, input).pipe(Effect.map((session) => ({ ...session, resumeFailed: true }))), + ); + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.runtime-mode.set", + commandId: CommandId.make("cmd-deferred-runtime-mode"), + threadId: ThreadId.make("thread-1"), + runtimeMode: "full-access", + createdAt: now, + }), + ); + await waitFor(() => harness.startSession.mock.calls.length === 2); + + // The agent ran it as its own command and sent none of the context. + harness.sendTurn.mockImplementationOnce(() => + Effect.succeed({ + threadId: ThreadId.make("thread-1"), + turnId: asTurnId("turn-2"), + contextDeferred: true as const, + }), + ); + await turnStart("2", "/compact"); + await waitFor(() => harness.sendTurn.mock.calls.length === 2); + await Effect.runPromise(Effect.sleep("50 millis")); + expect(harness.noteHistoryDelivered).not.toHaveBeenCalled(); + + // The next ordinary message carries it, and only then is it delivered. + await turnStart("3", "second question"); + await waitFor(() => harness.sendTurn.mock.calls.length === 3); + const sent = harness.sendTurn.mock.calls[2]?.[0] as { readonly input?: string } | undefined; + expect(sent?.input).toContain("prior context"); + await waitFor(() => harness.noteHistoryDelivered.mock.calls.length === 1); + }); + it.each([ ["", false], [", also when its session couldn't reopen a conversation", true], @@ -2674,6 +2840,101 @@ describe("ProviderCommandReactor", () => { }); }); + it("gives a room's switched agent its history once, not again in the room's note", async () => { + const harness = await createHarness(); + const now = "2026-01-01T00:00:00.000Z"; + const threadId = ThreadId.make("thread-1"); + const astraId = ThreadParticipantId.make("7a0b1c2d-3e4f-4a5b-8c6d-7e8f9a0b1c2d"); + const dispatch = (command: Parameters[0]) => + Effect.runPromise(harness.engine.dispatch(command)); + await dispatch({ + type: "thread.participant.add", + commandId: CommandId.make("cmd-room-switch-add"), + threadId, + participant: { + id: astraId, + handle: "astra", + modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-6-astra" }, + }, + createdAt: now, + }); + await dispatch({ + type: "thread.turn.start", + commandId: CommandId.make("cmd-room-switch-turn-1"), + threadId, + message: { + messageId: asMessageId("room-switch-user-1"), + role: "user", + text: "fix the reconnect bug", + attachments: [], + }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "full-access", + createdAt: now, + }); + await waitFor(() => harness.sendTurn.mock.calls.length === 1); + await dispatch({ + type: "thread.message.assistant.delta", + commandId: CommandId.make("cmd-room-switch-reply"), + threadId, + messageId: asMessageId("room-switch-assistant-1"), + delta: "Fixed: the cursor now moves on ack.", + createdAt: now, + }); + await dispatch({ + type: "thread.message.assistant.complete", + commandId: CommandId.make("cmd-room-switch-reply-done"), + threadId, + messageId: asMessageId("room-switch-assistant-1"), + completesTurn: true, + createdAt: now, + }); + await dispatch({ + type: "thread.session.set", + commandId: CommandId.make("cmd-room-switch-settled"), + threadId, + session: { + threadId, + status: "ready", + providerName: "codex", + runtimeMode: "full-access", + activeTurnId: null, + lastError: null, + updatedAt: now, + }, + createdAt: now, + }); + + // The thread's own agent moves to another provider. + await dispatch({ + type: "thread.turn.start", + commandId: CommandId.make("cmd-room-switch-turn-2"), + threadId, + message: { + messageId: asMessageId("room-switch-user-2"), + role: "user", + text: "now add a test", + attachments: [], + }, + modelSelection: { + instanceId: ProviderInstanceId.make("claudeAgent"), + model: "claude-opus-4-6", + }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "full-access", + createdAt: now, + }); + await waitFor(() => harness.sendTurn.mock.calls.length === 2); + const handoff = harness.startSession.mock.calls[1]?.[1] as + | ProviderSessionStartInput + | undefined; + expect(handoff?.contextSeed).toBeDefined(); + // The seed carries the agent's own earlier turns; the prompt doesn't repeat them. + const sent = harness.sendTurn.mock.calls[1]?.[0] as { readonly input?: string } | undefined; + expect(sent?.input).not.toContain("Fixed: the cursor now moves on ack."); + expect(sent?.input?.endsWith("now add a test")).toBe(true); + }); + it("runs a room agent in its own session and tells it what it missed", async () => { const harness = await createHarness(); const now = "2026-01-01T00:00:00.000Z"; @@ -7461,6 +7722,8 @@ describe("ProviderCommandReactor", () => { readonly stopSourceSessionFirst?: boolean; /** Where the source's question and the fork's instruction were sent from. */ readonly sentFrom?: { readonly source: MessageSentFrom; readonly fork: MessageSentFrom }; + /** False: the fork's summary may still be owed when this returns. */ + readonly awaitSeedOutcome?: boolean; }, ) { const now = "2026-01-01T00:00:00.000Z"; @@ -7590,6 +7853,15 @@ describe("ProviderCommandReactor", () => { }), ); await waitFor(() => harness.sendTurn.mock.calls.length === 2); + if (options?.awaitSeedOutcome !== false) { + await waitFor( + async () => + (await harness.readModel()).threads + .find((thread) => String(thread.id) === "thread-fork") + ?.activities.some((activity) => activity.kind === ThreadForkSeedOutcomeActivityKind) === + true, + ); + } const forkStartInputs = harness.startSession.mock.calls .map((call) => call[1] as ProviderSessionStartInput) @@ -7686,6 +7958,57 @@ describe("ProviderCommandReactor", () => { ).toMatchObject({ seedMode: "context-seed" }); }); + it("owes a fork's summarized source when its first message went as the agent's own command", async () => { + const harness = await createHarness(); + // The fork's first send (the second overall) goes as the agent's command. + let sends = 0; + const sendAsUsual = harness.sendTurn.getMockImplementation(); + if (!sendAsUsual) throw new Error("expected the harness send"); + harness.sendTurn.mockImplementation((input) => { + sends += 1; + return sends === 2 + ? Effect.succeed({ + threadId: ThreadId.make("thread-fork"), + turnId: asTurnId("turn-fork-command"), + contextDeferred: true as const, + }) + : sendAsUsual(input); + }); + const { seedOutcome } = await dispatchNativeForkScenario(harness, { + awaitSeedOutcome: false, + }); + expect(seedOutcome).toBeUndefined(); + + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.turn.start", + commandId: CommandId.make("cmd-fork-after-command"), + threadId: ThreadId.make("thread-fork"), + message: { + messageId: asMessageId("user-message-fork-after-command"), + role: "user", + text: "Now go on.", + attachments: [], + }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "approval-required", + createdAt: "2026-01-01T00:00:02.000Z", + }), + ); + await waitFor(() => harness.sendTurn.mock.calls.length === 3); + const sent = harness.sendTurn.mock.calls[2]?.[0] as { readonly input?: string } | undefined; + expect(sent?.input).toContain("Carried fork context."); + expect(sent?.input?.endsWith("Now go on.")).toBe(true); + // Delivered now: a later turn carries it no more. + await waitFor( + async () => + (await harness.readModel()).threads + .find((thread) => String(thread.id) === "thread-fork") + ?.activities.some((activity) => activity.kind === ThreadForkSeedOutcomeActivityKind) === + true, + ); + }); + it("keeps forks on the context-seed path when the driver lacks native fork support", async () => { const harness = await createHarness(); diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts index 9ec25d344..4ae3b1b16 100644 --- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts +++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts @@ -749,6 +749,12 @@ const make = Effect.gen(function* () { * never on the thread (docs/design/fleet.md, Part 3f, (i)). */ readonly movedAgent?: true; + /** + * Owed because a start handed the runtime the history (a switch from + * another agent): the runtime carries it (`carriedBy`), so a room's + * catch-up never pays it again. + */ + readonly handoff?: true; /** * The runtime started seeded with the conversation, by its start time * (ProviderSession.createdAt): a send on that runtime adds no seed of @@ -1948,23 +1954,22 @@ const make = Effect.gen(function* () { if (shedsOutsideWork) yield* shedOutsideWork(thread, participantId, createdAt, handoffSession); if (contextSeed !== undefined) { - owedHistorySeeds.delete(sessionKey); - // A moved thread's debt is paid once a turn reaches the provider on - // this seeded session, not when it starts: some adapters keep the - // seed in memory until their first send. - if ( - participantId === null && + // The debt is paid once a turn reaches the provider on this seeded + // session, not when it starts: some adapters keep the seed in memory + // until their first send, and a send that goes as the agent's own + // command (contextDeferred) leaves it with them. Until then the + // binding owes it too, so a restart seeds the next start. + owedHistorySeeds.set(sessionKey, { + driverKind: desiredDriverKind, + cwd: effectiveCwd ?? undefined, + claimed: false, + ...(participantId === null && thread.historySeedOwed === true && contextSeed.entries.length > 0 - ) { - owedHistorySeeds.set(sessionKey, { - driverKind: desiredDriverKind, - cwd: effectiveCwd ?? undefined, - claimed: false, - moved: true, - carriedBy: handoffSession.createdAt, - }); - } + ? { moved: true as const } + : { handoff: true as const }), + carriedBy: handoffSession.createdAt, + }); } // Another agent than the one a move carried a session for. yield* noteCarriedStart("handoff"); @@ -2547,6 +2552,16 @@ const make = Effect.gen(function* () { isThreadForkContextPayload(forkContextActivity.payload) ? forkContextActivity.payload : undefined; + // The fork's summarized source, when no prompt carrying it went out yet + // (its first message went as the agent's own command, or never out): a + // later turn carries it. Its seed outcome is recorded once one did. + const owedForkContextText = + !isForkInitialTurn && + forkContextActivity !== undefined && + isThreadForkContextPayload(forkContextActivity.payload) && + !thread.activities.some((activity) => activity.kind === ThreadForkSeedOutcomeActivityKind) + ? withContextSeedPreamble(forkContextActivity.payload.contextText, undefined) + : undefined; const sourceThread = forkContext ? yield* resolveThread(forkContext.sourceThreadId) : undefined; // Same-driver forks on the fork's initial turn can carry full provider @@ -2730,7 +2745,13 @@ const make = Effect.gen(function* () { firstHereInMovedRoom && owedCandidate !== undefined && (owedCandidate.moved === true || owedCandidate.movedAgent === true); - const roomPaysHistory = owedCandidate !== undefined && isRoomThread(thread) && !movedSummary; + // A handoff's seed is in the runtime already: the room's note stays as + // it would be, or the first prompt carries those turns twice. + const roomPaysHistory = + owedCandidate !== undefined && + owedCandidate.handoff !== true && + isRoomThread(thread) && + !movedSummary; // A carried session holds what it saw where it was: up to the last // message it was given there (each agent's own, not the room's last), // so its first turn here is caught up on everything after; with nothing @@ -2773,7 +2794,9 @@ const make = Effect.gen(function* () { }); // A natively forked session already holds the full source history; the // context-seed preamble and re-sent source attachments would duplicate it. - const forkContextText = !nativeForkApplied ? input.providerContext : undefined; + const forkContextText = !nativeForkApplied + ? (input.providerContext ?? owedForkContextText) + : undefined; const builtSeed = owedCandidate === undefined || roomPaysHistory || owedCandidate.carriedBy !== undefined ? undefined @@ -2904,7 +2927,10 @@ const make = Effect.gen(function* () { } : undefined; - if (forkContext !== undefined) { + // A native fork holds the source as it starts; a summarized one has it + // once a prompt carrying the summary went out (`contextDelivered`). + let forkSeedOutcome: Effect.Effect = Effect.void; + if (forkContext !== undefined || owedForkContextText !== undefined) { const seedOutcomePayload: ThreadForkSeedOutcomePayload = { seedMode: nativeForkApplied ? "provider-native" : "context-seed", ...(forkFrom !== undefined @@ -2917,7 +2943,7 @@ const make = Effect.gen(function* () { } : {}), }; - yield* orchestrationEngine + forkSeedOutcome = orchestrationEngine .dispatch({ type: "thread.activity.append", commandId: serverCommandId("thread-fork-seed-outcome"), @@ -2935,7 +2961,14 @@ const make = Effect.gen(function* () { }, createdAt: input.createdAt, }) - .pipe(Effect.catch(() => Effect.void)); + .pipe( + Effect.asVoid, + Effect.catch(() => Effect.void), + ); + if (nativeForkApplied) { + yield* forkSeedOutcome; + forkSeedOutcome = Effect.void; + } } const modelForTurn = input.modelSelection ?? @@ -2987,6 +3020,28 @@ const make = Effect.gen(function* () { if (owedSeed.moved === true) { yield* markHistorySeedDelivered(input.threadId, input.messageId); } + // The binding stops owing it too, if it still describes the + // runtime that sent it (ProviderService.noteHistoryDelivered). + if (activeSession !== undefined) { + yield* providerService.noteHistoryDelivered({ + threadId: sessionKey, + sessionCreatedAt: activeSession.createdAt, + }); + } + }), + // What else this prompt carried that is owed until it goes out. + contextDelivered: forkSeedOutcome, + // The send reopened the runtime without its conversation + // (`historyOwed` on its result): the next message carries the history. + historyOwedAfterSend: + activeSession === undefined + ? Effect.void + : Effect.sync(() => { + owedHistorySeeds.set(sessionKey, { + driverKind: activeSession.provider, + cwd: activeSession.cwd ?? thread.worktreePath ?? undefined, + claimed: false, + }); }), // A send that failed before the provider took it delivered nothing. historyDebtReturned: @@ -3704,6 +3759,8 @@ const make = Effect.gen(function* () { historyDebtClaimed, historyDebtPaid, historyDebtReturned, + contextDelivered, + historyOwedAfterSend, notesDelivered, } = sendTurnRequest.value; @@ -3742,6 +3799,8 @@ const make = Effect.gen(function* () { // Whether the provider took the turn: a failure before that left the // message's text with no agent; one after (bookkeeping) did not. let providerTookTurn = false; + // None of the context in front of the message went (see below). + let contextDeferred = false; yield* providerService .sendTurn({ ...turnRequest, @@ -3764,8 +3823,24 @@ const make = Effect.gen(function* () { providerTookTurn = true; }), ), - Effect.tap(() => historyDebtPaid), + // The history and a fork's summary count as delivered only once + // the prompt carrying them went out to the agent. A send that went + // as the agent's own command (`contextDeferred`), or whose prompt + // was never written (`undelivered`: its setup failed first), + // carried none of the context in front of it, so every debt it was + // to pay stays, the binding's `historyOwed` mark included. + Effect.tap((turn) => + Effect.suspend(() => { + contextDeferred = turn.contextDeferred === true || turn.undelivered === true; + return contextDeferred + ? historyDebtReturned + : Effect.andThen(historyDebtPaid, contextDelivered); + }), + ), Effect.onError(() => historyDebtReturned), + // Recovery opened a conversation without the history: this message + // stays sent, and the next one carries the history. + Effect.tap((turn) => (turn.historyOwed === true ? historyOwedAfterSend : Effect.void)), Effect.tap((turn) => Effect.sync(() => providerTakenTurns.set(event.payload.threadId, turn.turnId)), ), @@ -3776,11 +3851,11 @@ const make = Effect.gen(function* () { }), ), Effect.tap(() => - roomContext !== undefined + roomContext !== undefined && !contextDeferred ? recordRoomContext(event.payload.threadId, roomContext, event.payload.createdAt) : Effect.void, ), - Effect.tap(() => notesDelivered), + Effect.tap(() => (contextDeferred ? Effect.void : notesDelivered)), // Replies and reports queued while the turn was starting go in now, // behind its own message (and its notes), in this thread's worker. Effect.tap(() => diff --git a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts index 150266202..e684fe328 100644 --- a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts +++ b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts @@ -165,6 +165,7 @@ function createProviderServiceHarness() { dropFails.on ? Effect.die(new Error("the session would not stop")) : Effect.sync(() => void droppedCursors.push(threadId)), + noteHistoryDelivered: () => Effect.void, getCapabilities: () => Effect.succeed({ sessionModelSwitch: "in-session" }), getInstanceInfo: (instanceId) => { const driverKind = ProviderDriverKind.make(String(instanceId)); diff --git a/apps/server/src/persistence/Layers/ProviderSessionRuntime.ts b/apps/server/src/persistence/Layers/ProviderSessionRuntime.ts index 491cb2082..651f233b4 100644 --- a/apps/server/src/persistence/Layers/ProviderSessionRuntime.ts +++ b/apps/server/src/persistence/Layers/ProviderSessionRuntime.ts @@ -131,6 +131,29 @@ const makeProviderSessionRuntimeRepository = Effect.gen(function* () { `, }); + const patchIfSession: ProviderSessionRuntimeRepositoryShape["patchIfSession"] = (input) => + sql<{ readonly threadId: string }>` + UPDATE provider_session_runtime + SET + runtime_payload_json = json_patch( + COALESCE(runtime_payload_json, '{}'), + ${JSON.stringify(input.runtimePayload)} + ), + resume_cursor_json = CASE + WHEN ${input.clearResumeCursor === true ? 1 : 0} = 1 THEN NULL + ELSE resume_cursor_json + END, + last_seen_at = ${input.lastSeenAt} + WHERE thread_id = ${input.threadId} + AND json_extract(runtime_payload_json, '$.sessionCreatedAt') = ${input.sessionCreatedAt} + RETURNING thread_id AS "threadId" + `.pipe( + Effect.map((rows) => rows.length > 0), + Effect.mapError( + toPersistenceSqlError("ProviderSessionRuntimeRepository.patchIfSession:query"), + ), + ); + const upsert: ProviderSessionRuntimeRepositoryShape["upsert"] = (runtime) => upsertRuntimeRow(runtime).pipe( Effect.mapError( @@ -196,6 +219,7 @@ const makeProviderSessionRuntimeRepository = Effect.gen(function* () { return { upsert, + patchIfSession, getByThreadId, list, deleteByThreadId, diff --git a/apps/server/src/persistence/Services/ProviderSessionRuntime.ts b/apps/server/src/persistence/Services/ProviderSessionRuntime.ts index 733723cba..f10dc273d 100644 --- a/apps/server/src/persistence/Services/ProviderSessionRuntime.ts +++ b/apps/server/src/persistence/Services/ProviderSessionRuntime.ts @@ -43,6 +43,18 @@ export const GetProviderSessionRuntimeInput = Schema.Struct({ threadId: ThreadId export type GetProviderSessionRuntimeInput = typeof GetProviderSessionRuntimeInput.Type; export const DeleteProviderSessionRuntimeInput = Schema.Struct({ threadId: ThreadId }); + +/** See ProviderSessionRuntimeRepositoryShape.patchIfSession. */ +export interface PatchProviderSessionRuntimeIfSessionInput { + readonly threadId: ThreadId; + /** The runtime the row must still name (its `sessionCreatedAt` payload field). */ + readonly sessionCreatedAt: string; + /** Flat fields merged into the payload; a null removes the field. */ + readonly runtimePayload: Readonly>; + /** Clears the resume cursor too. */ + readonly clearResumeCursor?: boolean; + readonly lastSeenAt: string; +} export type DeleteProviderSessionRuntimeInput = typeof DeleteProviderSessionRuntimeInput.Type; /** @@ -75,6 +87,15 @@ export interface ProviderSessionRuntimeRepositoryShape { ProviderSessionRuntimeRepositoryError >; + /** + * Merges flat fields into a row's payload, in one statement, only while + * the row still names runtime `sessionCreatedAt`: a write that names an + * older runtime never lands on its replacement. True when it was written. + */ + readonly patchIfSession: ( + input: PatchProviderSessionRuntimeIfSessionInput, + ) => Effect.Effect; + /** * Delete provider runtime state by canonical thread id. */ diff --git a/apps/server/src/provider/Drivers/AntigravityDriver.ts b/apps/server/src/provider/Drivers/AntigravityDriver.ts index afb566eb4..e8ae829f5 100644 --- a/apps/server/src/provider/Drivers/AntigravityDriver.ts +++ b/apps/server/src/provider/Drivers/AntigravityDriver.ts @@ -24,6 +24,10 @@ import { } from "../acp/AntigravityAcpSupport.ts"; import { type AcpProviderDriverEnv, makeAcpProviderDriver } from "../acp/AcpProviderDriver.ts"; import { antigravityReleaseFor } from "../antigravity/AntigravityRelease.ts"; +import { + type AntigravityReleaseSource, + makeAntigravityReleaseSource, +} from "../antigravity/AntigravityReleaseSource.ts"; import { makeAntigravityAuthFlows } from "../antigravity/AntigravityAuth.ts"; import { antigravityInstancePaths, @@ -43,6 +47,7 @@ import { type AntigravityRuntime, makeAntigravityRuntime, } from "../antigravity/AntigravityRuntime.ts"; +import { makeAntigravityUsageReader } from "../antigravity/AntigravityUsage.ts"; import { ProviderDriverError } from "../Errors.ts"; import type { ProviderDriver } from "../ProviderDriver.ts"; import { AntigravitySettings } from "@threadlines/contracts"; @@ -50,6 +55,15 @@ import * as Schema from "effect/Schema"; export type AntigravityDriverEnv = AcpProviderDriverEnv; +/** Linux's C library: Alpine and other musl systems get Google's musl build. */ +function hostLibc(): "glibc" | "musl" { + if (process.platform !== "linux") return "glibc"; + const report = process.report?.getReport() as + | { readonly header?: { readonly glibcVersionRuntime?: unknown } } + | undefined; + return typeof report?.header?.glibcVersionRuntime === "string" ? "glibc" : "musl"; +} + const decodeAntigravitySettings = Schema.decodeSync(AntigravitySettings); const decodeAntigravitySettingsOption = Schema.decodeUnknownOption(AntigravitySettings); /** @@ -57,6 +71,20 @@ const decodeAntigravitySettingsOption = Schema.decodeUnknownOption(AntigravitySe * its locks then serialize their installs, prunes, and leases. */ const runtimesByRoot = new Map(); +/** Likewise one release source per state folder, so instances share its hourly check. */ +const releaseSourcesByStateDir = new Map(); + +const releaseSourceFor = ( + stateDir: string, + builtIn: NonNullable>, +): AntigravityReleaseSource => { + let source = releaseSourcesByStateDir.get(stateDir); + if (!source) { + source = makeAntigravityReleaseSource({ builtIn, assetKey: builtIn.assetKey }); + releaseSourcesByStateDir.set(stateDir, source); + } + return source; +}; export const AntigravityDriver: ProviderDriver = { driverKind: ANTIGRAVITY_DRIVER_KIND, @@ -70,7 +98,7 @@ export const AntigravityDriver: ProviderDriver validateAntigravityRuntime(runtimePaths, platformRelease), + validate: validateAntigravityRuntime, }); runtimesByRoot.set(runtimeRoot, runtime); } + const releases = platformRelease + ? releaseSourceFor(serverConfig.stateDir, platformRelease) + : undefined; // Leftovers of processes whose server is gone; best effort, off the // start path. yield* Effect.forkDetach( @@ -110,21 +140,30 @@ export const AntigravityDriver: ProviderDriver + usage.reset.pipe(Effect.andThen(authFlows.run(flow)), Effect.ensuring(usage.reset)), // The sign-in settings and every variable (ADC paths included) // match what this build was created from. builtFrom: (entry) => { diff --git a/apps/server/src/provider/Layers/CodexAdapter.test.ts b/apps/server/src/provider/Layers/CodexAdapter.test.ts index 87de46210..78fb114ad 100644 --- a/apps/server/src/provider/Layers/CodexAdapter.test.ts +++ b/apps/server/src/provider/Layers/CodexAdapter.test.ts @@ -596,6 +596,7 @@ const providerSessionDirectoryTestLayer = Layer.succeed(ProviderSessionDirectory listThreadIds: () => Effect.succeed([]), listBindings: () => Effect.succeed([]), deleteBinding: () => Effect.void, + patchIfSession: () => Effect.succeed(false), }); const validationRuntimeFactory = makeRuntimeFactory(); diff --git a/apps/server/src/provider/Layers/ProviderRegistry.test.ts b/apps/server/src/provider/Layers/ProviderRegistry.test.ts index 3d42eb1d6..03a13861d 100644 --- a/apps/server/src/provider/Layers/ProviderRegistry.test.ts +++ b/apps/server/src/provider/Layers/ProviderRegistry.test.ts @@ -1552,6 +1552,47 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T ); }); + it("never carries one account's usage to another with no email to compare", () => { + const usage: ServerProviderAccountUsage = { + source: "grok-billing", + checkedAt: "2026-06-10T15:00:00.000Z", + limits: [ + { + limitId: "antigravity", + scoped: [{ scopeLabel: "Gemini", usedPercent: 40, remainingPercent: 60 }], + }, + ], + }; + const signedIn = (accountId: string) => + ({ + instanceId: ProviderInstanceId.make("antigravity"), + driver: ProviderDriverKind.make("antigravity"), + status: "ready", + enabled: true, + installed: true, + auth: { status: "authenticated", type: "oauth-personal", accountId }, + checkedAt: "2026-06-10T15:05:00.000Z", + version: "1.5.14", + models: [], + slashCommands: [], + skills: [], + }) as const satisfies ServerProvider; + const previous = { + ...signedIn("account-a"), + checkedAt: "2026-06-10T15:00:00.000Z", + accountUsage: usage, + }; + + assert.strictEqual( + mergeProviderSnapshot(previous, signedIn("account-b")).accountUsage, + undefined, + ); + assert.deepStrictEqual( + mergeProviderSnapshot(previous, signedIn("account-a")).accountUsage, + usage, + ); + }); + it("merges sparse token history across same-account usage refreshes", () => { const providerBase = { instanceId: ProviderInstanceId.make("codex"), diff --git a/apps/server/src/provider/Layers/ProviderRegistry.ts b/apps/server/src/provider/Layers/ProviderRegistry.ts index fc650f439..cc4350ec2 100644 --- a/apps/server/src/provider/Layers/ProviderRegistry.ts +++ b/apps/server/src/provider/Layers/ProviderRegistry.ts @@ -168,6 +168,14 @@ const haveMatchingChatAuthIdentity = ( ) { return false; } + // Another account with no email to compare (Antigravity): its own id tells. + if ( + previousProvider.auth.accountId && + nextProvider.auth.accountId && + previousProvider.auth.accountId !== nextProvider.auth.accountId + ) { + return false; + } return true; }; diff --git a/apps/server/src/provider/Layers/ProviderService.test.ts b/apps/server/src/provider/Layers/ProviderService.test.ts index e21105bfe..2547dc10a 100644 --- a/apps/server/src/provider/Layers/ProviderService.test.ts +++ b/apps/server/src/provider/Layers/ProviderService.test.ts @@ -115,7 +115,14 @@ type LegacyProviderRuntimeEvent = { readonly [key: string]: unknown; }; -function makeFakeCodexAdapter(provider: ProviderDriverKind = CODEX_DRIVER) { +function makeFakeCodexAdapter( + provider: ProviderDriverKind = CODEX_DRIVER, + options?: { + /** Each start gets a start time of its own, as real runtimes do. */ + readonly distinctStarts?: boolean; + }, +) { + let starts = 0; const sessions = new Map(); const goals = new Map(); const runtimeEventPubSub = Effect.runSync(PubSub.unbounded()); @@ -123,7 +130,11 @@ function makeFakeCodexAdapter(provider: ProviderDriverKind = CODEX_DRIVER) { const startSession = vi.fn( (input: ProviderSessionStartInput): Effect.Effect => Effect.sync(() => { - const now = "2026-01-01T00:00:00.000Z"; + starts += 1; + const now = + options?.distinctStarts === true + ? new Date(Date.UTC(2026, 0, 1, 0, 0, starts)).toISOString() + : "2026-01-01T00:00:00.000Z"; const session: ProviderSession = { provider, ...(input.providerInstanceId !== undefined @@ -3436,3 +3447,421 @@ fence.layer("ProviderServiceLive moving threads", (it) => { }), ); }); + +/** One agent that forgets by starting over (Antigravity's `new-session`). */ +function makeStartingOverLayer() { + const ANTIGRAVITY = ProviderDriverKind.make("antigravity"); + const agent = makeFakeCodexAdapter(ANTIGRAVITY, { distinctStarts: true }); + // A runtime still stopping holds the revert until this is released. + const hooks: { + stopping: Effect.Effect | undefined; + /** Runs once, right after the next binding read: another writer landing then. */ + afterRead: Effect.Effect | undefined; + } = { stopping: undefined, afterRead: undefined }; + const adapter = { + ...agent.adapter, + capabilities: { ...agent.adapter.capabilities, conversationRollback: "new-session" as const }, + whenStopped: () => Effect.suspend(() => hooks.stopping ?? Effect.void), + }; + const runtimeRepositoryLayer = ProviderSessionRuntimeRepositoryLive.pipe( + Layer.provide(SqlitePersistenceMemory), + ); + const directoryLayer = Layer.effect( + ProviderSessionDirectory, + Effect.gen(function* () { + const live = yield* ProviderSessionDirectory; + return { + ...live, + getBinding: (threadId: ThreadId) => + live.getBinding(threadId).pipe( + Effect.tap(() => + Effect.suspend(() => { + const interleave = hooks.afterRead; + hooks.afterRead = undefined; + return interleave ?? Effect.void; + }), + ), + ), + }; + }), + ).pipe(Layer.provide(ProviderSessionDirectoryLive.pipe(Layer.provide(runtimeRepositoryLayer)))); + const layer = it.layer( + Layer.mergeAll( + makeProviderServiceWithScrubber().pipe( + Layer.provide(ThreadSessionAdmissionPermissive), + Layer.provide( + Layer.succeed( + ProviderAdapterRegistry, + makeAdapterRegistryMock({ [ANTIGRAVITY]: adapter }), + ), + ), + Layer.provide(directoryLayer), + Layer.provide(defaultServerSettingsLayer), + Layer.provideMerge(AnalyticsService.layerTest), + Layer.provide(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)), + ), + directoryLayer, + runtimeRepositoryLayer, + NodeServices.layer, + ), + ); + return { agent, ANTIGRAVITY, hooks, layer }; +} + +const startingOver = makeStartingOverLayer(); + +startingOver.layer("ProviderServiceLive forgetting a conversation", (it) => { + const instanceId = ProviderInstanceId.make("antigravity"); + const start = (key: ThreadId, resumeCursor?: unknown) => + Effect.gen(function* () { + const provider = yield* ProviderService; + return yield* provider.startSession(key, { + provider: startingOver.ANTIGRAVITY, + providerInstanceId: instanceId, + threadId: key, + cwd: "/tmp/project", + ...(resumeCursor !== undefined ? { resumeCursor } : {}), + runtimeMode: "full-access", + }); + }); + const lastStartCursor = () => + ( + startingOver.agent.startSession.mock.calls.at(-1)?.[0] as + | { readonly resumeCursor?: unknown } + | undefined + )?.resumeCursor; + + it.effect( + "forgets an idle agent's conversation without starting it, and seeds every start until a send carries the history", + () => + Effect.gen(function* () { + const provider = yield* ProviderService; + const directory = yield* ProviderSessionDirectory; + const key = asThreadId("thread-starting-over"); + const first = yield* start(key); + yield* startingOver.agent.stopSession(first.threadId); + startingOver.agent.startSession.mockClear(); + + const rollback = yield* provider.rollbackConversation({ threadId: key, numTurns: 1 }); + assert.isTrue(rollback.conversationRolledBack); + // Nothing was started (or asked) to forget it. + assert.equal(startingOver.agent.startSession.mock.calls.length, 0); + assert.equal(startingOver.agent.rollbackThread.mock.calls.length, 0); + const binding = Option.getOrUndefined(yield* directory.getBinding(key)); + assert.equal(binding?.resumeCursor ?? null, null); + + // A caller that still holds the old cursor can't reopen it. + const reopened = yield* start(key, first.resumeCursor); + assert.isUndefined(lastStartCursor()); + assert.isTrue(reopened.resumeFailed); + // A restart before a send carried the history: still owed. + yield* startingOver.agent.stopSession(key); + const again = yield* start(key); + assert.isUndefined(lastStartCursor()); + assert.isTrue(again.resumeFailed); + + // A late word from the runtime before clears nothing. + yield* provider.noteHistoryDelivered({ + threadId: key, + sessionCreatedAt: reopened.createdAt, + }); + yield* startingOver.agent.stopSession(key); + const stillOwed = yield* start(key); + assert.isTrue(stillOwed.resumeFailed); + + yield* provider.noteHistoryDelivered({ + threadId: key, + sessionCreatedAt: stillOwed.createdAt, + }); + yield* startingOver.agent.stopSession(key); + const whole = yield* start(key); + assert.deepEqual(lastStartCursor(), stillOwed.resumeCursor); + assert.isUndefined(whole.resumeFailed); + }), + ); + + it.effect("owes a handed-over history until a send carries it, across a restart", () => + Effect.gen(function* () { + const provider = yield* ProviderService; + const key = asThreadId("thread-handed-over"); + const handedOver = yield* provider.startSession(key, { + provider: startingOver.ANTIGRAVITY, + providerInstanceId: instanceId, + threadId: key, + cwd: "/tmp/project", + runtimeMode: "full-access", + contextSeed: { version: 1, fromProvider: CODEX_DRIVER, entries: [] }, + }); + // The adapter carries the seed itself: this start owes none. + assert.isUndefined(handedOver.resumeFailed); + // A restart before a send carried it: the next start is seeded. + yield* startingOver.agent.stopSession(key); + const restarted = yield* start(key, handedOver.resumeCursor); + assert.isUndefined(lastStartCursor()); + assert.isTrue(restarted.resumeFailed); + }), + ); + + it.effect( + "owes the history of a conversation the adapter couldn't reopen, across a restart", + () => + Effect.gen(function* () { + const provider = yield* ProviderService; + const key = asThreadId("thread-resume-failed"); + const first = yield* start(key); + yield* startingOver.agent.stopSession(key); + // The adapter falls back to a new conversation, as Codex does. + const startAsUsual = startingOver.agent.startSession.getMockImplementation(); + if (!startAsUsual) throw new Error("expected the fake start"); + startingOver.agent.startSession.mockImplementationOnce((input) => + startAsUsual(input).pipe(Effect.map((session) => ({ ...session, resumeFailed: true }))), + ); + const fallback = yield* start(key, first.resumeCursor); + assert.isTrue(fallback.resumeFailed); + // A restart before a send carried the history: still owed. + yield* startingOver.agent.stopSession(key); + const restarted = yield* start(key, fallback.resumeCursor); + assert.isUndefined(lastStartCursor()); + assert.isTrue(restarted.resumeFailed); + yield* provider.noteHistoryDelivered({ + threadId: key, + sessionCreatedAt: restarted.createdAt, + }); + }), + ); + + it.effect("ends a runtime whose rollback can't stop it, and fails when it can't be ended", () => + Effect.gen(function* () { + const provider = yield* ProviderService; + const key = asThreadId("thread-starting-over-stuck"); + yield* start(key); + const failing = new ProviderAdapterRequestError({ + provider: "antigravity", + method: "rollbackThread", + detail: "the agent did not stop", + }); + startingOver.agent.rollbackThread.mockImplementationOnce(() => Effect.fail(failing)); + startingOver.agent.stopSession.mockClear(); + const ended = yield* provider.rollbackConversation({ threadId: key, numTurns: 1 }); + assert.isTrue(ended.conversationRolledBack); + assert.equal(startingOver.agent.stopSession.mock.calls.length, 1); + + const stuck = asThreadId("thread-starting-over-unstoppable"); + yield* start(stuck); + startingOver.agent.rollbackThread.mockImplementationOnce(() => Effect.fail(failing)); + startingOver.agent.stopSession.mockImplementationOnce(() => Effect.fail(failing)); + const refused = yield* Effect.result( + provider.rollbackConversation({ threadId: stuck, numTurns: 1 }), + ); + assert.equal(refused._tag, "Failure"); + }), + ); + + it.effect("waits for a stopping agent's process to go before the revert goes on", () => + Effect.gen(function* () { + const provider = yield* ProviderService; + const directory = yield* ProviderSessionDirectory; + const key = asThreadId("thread-starting-over-stopping"); + const first = yield* start(key); + // Stopping: hasSession no longer reports it, its process is not gone. + yield* startingOver.agent.stopSession(key); + const gone = yield* Deferred.make(); + startingOver.hooks.stopping = Deferred.await(gone); + const revert = yield* provider + .rollbackConversation({ threadId: key, numTurns: 1 }) + .pipe(Effect.forkChild); + yield* advanceTestClock(1_000); + assert.isUndefined(revert.pollUnsafe()); + const held = Option.getOrUndefined(yield* directory.getBinding(key)); + assert.deepEqual(held?.resumeCursor, first.resumeCursor); + + yield* Deferred.succeed(gone, undefined); + const done = yield* Fiber.join(revert); + startingOver.hooks.stopping = undefined; + assert.isTrue(done.conversationRolledBack); + }), + ); + + it.effect("ends a runtime that won't finish stopping, and fails the revert if it stays", () => + Effect.gen(function* () { + const provider = yield* ProviderService; + const key = asThreadId("thread-starting-over-stuck-stopping"); + yield* start(key); + yield* startingOver.agent.stopSession(key); + startingOver.agent.stopSession.mockClear(); + startingOver.hooks.stopping = Effect.never; + const revert = yield* provider + .rollbackConversation({ threadId: key, numTurns: 1 }) + .pipe(Effect.result, Effect.forkChild); + yield* advanceTestClock(20_000); + // The wait ran out: the runtime is ended, then waited on once more. + assert.equal(startingOver.agent.stopSession.mock.calls.length, 1); + yield* advanceTestClock(20_000); + const outcome = yield* Fiber.join(revert); + startingOver.hooks.stopping = undefined; + assert.equal(outcome._tag, "Failure"); + }), + ); + + it.effect("fails the revert in bounded time when ending the runtime stalls too", () => + Effect.gen(function* () { + const provider = yield* ProviderService; + const key = asThreadId("thread-starting-over-stuck-stop-call"); + yield* start(key); + yield* startingOver.agent.stopSession(key); + startingOver.hooks.stopping = Effect.never; + // The stop it falls back on never returns (a stalled stop holds its lock). + startingOver.agent.stopSession.mockImplementationOnce(() => Effect.never); + const revert = yield* provider + .rollbackConversation({ threadId: key, numTurns: 1 }) + .pipe(Effect.result, Effect.forkChild); + yield* advanceTestClock(60_000); + const outcome = yield* Fiber.join(revert); + startingOver.hooks.stopping = undefined; + assert.equal(outcome._tag, "Failure"); + }), + ); + + it.effect("never lets an older runtime's acknowledgement or forget land on its replacement", () => + Effect.gen(function* () { + const provider = yield* ProviderService; + const directory = yield* ProviderSessionDirectory; + const key = asThreadId("thread-replaced-meanwhile"); + const older = yield* start(key); + // Runtime A owes the history. + yield* directory.upsert({ + threadId: key, + provider: startingOver.ANTIGRAVITY, + providerInstanceId: instanceId, + runtimePayload: { historyOwed: true }, + }); + // Runtime B replaces it between A's read and A's write. + const replace = directory.upsert({ + threadId: key, + provider: startingOver.ANTIGRAVITY, + providerInstanceId: instanceId, + resumeCursor: { opaque: "runtime-b" }, + runtimePayload: { historyOwed: true, sessionCreatedAt: "2026-06-01T00:00:00.000Z" }, + }); + const replaced = () => + Effect.map( + directory.getBinding(key), + (binding) => + (Option.getOrUndefined(binding)?.runtimePayload ?? {}) as Record, + ); + startingOver.hooks.afterRead = replace.pipe(Effect.orDie); + yield* provider.noteHistoryDelivered({ threadId: key, sessionCreatedAt: older.createdAt }); + // A write that read nothing first: B lands after it instead. + if (startingOver.hooks.afterRead !== undefined) { + startingOver.hooks.afterRead = undefined; + yield* replace; + } + assert.equal((yield* replaced()).historyOwed, true); + + // The same for a lost-session exit that names A. + startingOver.hooks.afterRead = replace.pipe(Effect.orDie); + startingOver.agent.emit({ + type: "session.exited", + eventId: asEventId("evt-lost-older-runtime"), + provider: startingOver.ANTIGRAVITY, + providerInstanceId: instanceId, + threadId: key, + createdAt: "2026-01-01T00:00:00.000Z", + payload: { exitKind: "graceful", conversationLost: { sessionCreatedAt: older.createdAt } }, + }); + yield* advanceTestClock(20); + if (startingOver.hooks.afterRead !== undefined) { + startingOver.hooks.afterRead = undefined; + yield* replace; + } + const binding = Option.getOrUndefined(yield* directory.getBinding(key)); + assert.deepEqual(binding?.resumeCursor, { opaque: "runtime-b" }); + }), + ); + + it.effect("owes the history when a send had to reopen a runtime that couldn't resume", () => + Effect.gen(function* () { + const provider = yield* ProviderService; + const directory = yield* ProviderSessionDirectory; + const key = asThreadId("thread-recovered-fresh"); + yield* start(key); + // The runtime went after the turn was prepared. + yield* startingOver.agent.stopSession(key); + const startAsUsual = startingOver.agent.startSession.getMockImplementation(); + if (!startAsUsual) throw new Error("expected the fake start"); + startingOver.agent.startSession.mockImplementationOnce((input) => + startAsUsual(input).pipe(Effect.map((session) => ({ ...session, resumeFailed: true }))), + ); + const turn = yield* provider.sendTurn({ threadId: key, input: "go on", attachments: [] }); + assert.isTrue(turn.historyOwed); + const binding = Option.getOrUndefined(yield* directory.getBinding(key)); + assert.equal( + (binding?.runtimePayload as Record | null | undefined)?.historyOwed, + true, + ); + }), + ); + + it.effect("stops a running agent's work through its rollback before forgetting", () => + Effect.gen(function* () { + const provider = yield* ProviderService; + const key = asThreadId("thread-starting-over-live"); + yield* start(key); + startingOver.agent.rollbackThread.mockClear(); + const rollback = yield* provider.rollbackConversation({ threadId: key, numTurns: 2 }); + assert.isTrue(rollback.conversationRolledBack); + assert.deepEqual(startingOver.agent.rollbackThread.mock.calls[0]?.slice(0, 2), [key, 2]); + }), + ); + + it.effect("forgets a conversation the agent reports it can't go on with", () => + Effect.gen(function* () { + const directory = yield* ProviderSessionDirectory; + const key = asThreadId("thread-conversation-lost"); + const first = yield* start(key); + // The service subscribes to the agent's events once it is up. + yield* advanceTestClock(10); + startingOver.agent.emit({ + type: "session.exited", + eventId: asEventId("evt-conversation-lost"), + provider: startingOver.ANTIGRAVITY, + providerInstanceId: instanceId, + threadId: key, + createdAt: "2026-01-01T00:00:00.000Z", + // A late exit of an older runtime leaves this one's conversation alone. + payload: { + exitKind: "graceful", + conversationLost: { sessionCreatedAt: "2025-01-01T00:00:00.000Z" }, + }, + }); + yield* advanceTestClock(20); + const kept = Option.getOrUndefined(yield* directory.getBinding(key)); + assert.deepEqual(kept?.resumeCursor, first.resumeCursor); + // The runtime's cursor moves on with its turns; it is still the same session. + yield* directory.upsert({ + threadId: key, + provider: startingOver.ANTIGRAVITY, + providerInstanceId: instanceId, + resumeCursor: { moved: "on", after: first.resumeCursor ?? null }, + }); + startingOver.agent.emit({ + type: "session.exited", + eventId: asEventId("evt-conversation-lost-own"), + provider: startingOver.ANTIGRAVITY, + providerInstanceId: instanceId, + threadId: key, + createdAt: "2026-01-01T00:00:00.000Z", + payload: { exitKind: "graceful", conversationLost: { sessionCreatedAt: first.createdAt } }, + }); + for (let attempt = 0; attempt < 100; attempt += 1) { + const binding = Option.getOrUndefined(yield* directory.getBinding(key)); + if ((binding?.resumeCursor ?? null) === null) break; + yield* advanceTestClock(5); + } + yield* startingOver.agent.stopSession(key); + const reopened = yield* start(key, first.resumeCursor); + assert.isUndefined(lastStartCursor()); + assert.isTrue(reopened.resumeFailed); + }), + ); +}); diff --git a/apps/server/src/provider/Layers/ProviderService.ts b/apps/server/src/provider/Layers/ProviderService.ts index d675a7403..e5d48c980 100644 --- a/apps/server/src/provider/Layers/ProviderService.ts +++ b/apps/server/src/provider/Layers/ProviderService.ts @@ -66,7 +66,11 @@ import { providerTurnMetricAttributes, withMetrics, } from "../../observability/Metrics.ts"; -import { type ProviderAdapterError, ProviderValidationError } from "../Errors.ts"; +import { + type ProviderAdapterError, + ProviderAdapterRequestError, + ProviderValidationError, +} from "../Errors.ts"; import type { ProviderAdapterShape } from "../Services/ProviderAdapter.ts"; import { ThreadSessionAdmission } from "../Services/ThreadSessionAdmission.ts"; import { ProjectInstructions } from "../Services/ProjectInstructions.ts"; @@ -91,6 +95,8 @@ const COMMAND_OUTPUT_TAIL_CHARS = 4_096; const EARLY_SESSION_SWEEP_INTERVAL = Duration.seconds(30); /** How long quiesceThread waits for a start or recovery of the thread already under way. */ const QUIESCE_START_WAIT = Duration.seconds(90); +/** How long a revert waits for a stopping agent's process to go, before ending it, and after. */ +const REVERT_STOP_WAIT = Duration.seconds(20); import { AnalyticsService } from "../../telemetry/Services/AnalyticsService.ts"; import { analyticsAgentProperties, @@ -218,6 +224,8 @@ function toRuntimePayloadFromSession( readonly lastRuntimeEvent?: string; readonly lastRuntimeEventAt?: string; readonly earlyUnused?: boolean; + /** See readPersistedHistoryOwed. */ + readonly historyOwed?: boolean; /** A start: what it asked of the room endpoint, recorded over any older start's. */ readonly startedWith?: { readonly guideTools: boolean }; }, @@ -227,6 +235,9 @@ function toRuntimePayloadFromSession( model: session.model ?? null, activeTurnId: session.activeTurnId ?? null, lastError: session.lastError ?? null, + // Which runtime the binding describes: history acknowledgements and + // forgets name it (noteHistoryDelivered, forgetConversation). + sessionCreatedAt: session.createdAt, // Kept so a recovered runtime gets the room tools it was started with. ...(session.roomTools !== undefined ? { roomTools: session.roomTools } : {}), // A start replaces both (null clears an older start's room tools in the @@ -241,9 +252,29 @@ function toRuntimePayloadFromSession( ? { lastRuntimeEventAt: extra.lastRuntimeEventAt } : {}), ...(extra?.earlyUnused !== undefined ? { earlyUnused: extra.earlyUnused } : {}), + ...(extra?.historyOwed !== undefined ? { historyOwed: extra.historyOwed } : {}), }; } +/** + * The agent's conversation lacks the thread's history: Threadlines forgot it + * (a revert on an agent that can't rewind, a conversation the agent can't go + * on with), or a start handed the history over and no send has carried it + * yet. Every start then opens a new conversation and reports `resumeFailed`, + * so the thread seeds its next message; a send that carried the history + * clears it (`noteHistoryDelivered`). Kept in the binding, so a restart in + * between can't reopen the conversation as it was. + */ +function readPersistedHistoryOwed(runtimePayload: ProviderRuntimeBinding["runtimePayload"]) { + return ( + runtimePayload !== null && + typeof runtimePayload === "object" && + !Array.isArray(runtimePayload) && + "historyOwed" in runtimePayload && + runtimePayload.historyOwed === true + ); +} + /** * A fresh session started early whose conversation nothing has used: its * resume cursor points at a conversation the provider may never have @@ -672,6 +703,7 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( readonly lastRuntimeEvent?: string; readonly lastRuntimeEventAt?: string; readonly earlyUnused?: boolean; + readonly historyOwed?: boolean; readonly startedWith?: { readonly guideTools: boolean }; }, ) => @@ -699,6 +731,16 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( event: ProviderRuntimeEvent, ): Effect.Effect => Effect.sync(() => correlateRuntimeEventWithInstance(source, event)).pipe( + // An agent that can't go on with its conversation: forgotten before + // anyone hears the session ended, so no start can reopen it. + Effect.tap((canonicalEvent) => + canonicalEvent.type === "session.exited" && + canonicalEvent.payload.conversationLost !== undefined + ? forgetConversation(canonicalEvent.threadId, { + onlySession: canonicalEvent.payload.conversationLost.sessionCreatedAt, + }) + : Effect.void, + ), Effect.flatMap((canonicalEvent) => increment(providerRuntimeEventsTotal, { provider: canonicalEvent.provider, @@ -803,10 +845,13 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( } const adapter = yield* registry.getByInstance(bindingInstanceId); // A cursor nothing used points at a conversation that may not exist. + // Nor one whose conversation was forgotten: the thread's next start + // opens a new one and seeds it. const hasResumeCursor = input.binding.resumeCursor !== null && input.binding.resumeCursor !== undefined && - !readPersistedEarlyUnused(input.binding.runtimePayload); + !readPersistedEarlyUnused(input.binding.runtimePayload) && + !readPersistedHistoryOwed(input.binding.runtimePayload); const hasActiveSession = yield* adapter.hasSession(input.binding.threadId); if (hasActiveSession) { const activeSessions = yield* adapter.listSessions(); @@ -823,7 +868,7 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( strategy: "adopt-existing", hasResumeCursor: existing.resumeCursor !== undefined, }); - return { adapter, session: existing } as const; + return { adapter, session: existing, historyOwed: false } as const; } } @@ -874,9 +919,13 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( instanceId: bindingInstanceId, timing: { kind: "resume", startMs }, }); + // As after any start: a conversation it couldn't reopen owes the + // thread's history, kept in the binding until a send carries it. + const historyOwed = resumed.resumeFailed === true; yield* upsertSessionBinding( { ...resumed, providerInstanceId: bindingInstanceId }, input.binding.threadId, + historyOwed ? { historyOwed: true } : undefined, ); yield* analytics.record("provider.session.recovered", { provider: resumed.provider, @@ -884,7 +933,7 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( hasResumeCursor: resumed.resumeCursor !== undefined, startMs, }); - return { adapter, session: resumed } as const; + return { adapter, session: resumed, historyOwed } as const; }), ).pipe( withMetrics({ @@ -943,6 +992,8 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( instanceId, threadId: input.threadId, isActive: true, + // Reopened without its conversation: the thread owes it its history. + historyOwed: recovered.historyOwed, } as const; }); @@ -1061,8 +1112,17 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( ))); const persistedCursorUsable = persistedSharesHistory && !readPersistedEarlyUnused(persistedBinding?.runtimePayload); - const effectiveResumeCursor = - input.resumeCursor ?? (persistedCursorUsable ? persistedBinding?.resumeCursor : undefined); + // A forgotten conversation is never reopened, whoever passes its cursor. + const historyOwed = + persistedSharesHistory && readPersistedHistoryOwed(persistedBinding?.runtimePayload); + const effectiveResumeCursor = historyOwed + ? undefined + : (input.resumeCursor ?? + (persistedCursorUsable ? persistedBinding?.resumeCursor : undefined)); + // Started with no history of its own: the thread seeds its next message + // (a start handed a seed carries it already). + const owesHistorySeed = + historyOwed && input.contextSeed === undefined && input.forkFrom === undefined; const effectiveCwd = input.cwd ?? (persistedSharesHistory ? readPersistedCwd(persistedBinding?.runtimePayload) : undefined); @@ -1086,9 +1146,12 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( const adapter = yield* registry.getByInstance(resolvedInstanceId); const startBeganAtMs = yield* Clock.currentTimeMillis; const startBeganNanos = yield* Clock.monotonicTimeNanos; + // The cursor the adapter gets is the one decided above, never the + // caller's as given: a forgotten conversation's must not get through. + const { resumeCursor: _requestedCursor, ...startInput } = input; const session = yield* adapter.startSession( yield* withProjectInstructions({ - ...input, + ...startInput, providerInstanceId: resolvedInstanceId, ...(effectiveCwd !== undefined ? { cwd: effectiveCwd } : {}), ...(effectiveResumeCursor !== undefined ? { resumeCursor: effectiveResumeCursor } : {}), @@ -1132,6 +1195,7 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( session.resumeFailed !== true ? { resumed: true } : {}), + ...(owesHistorySeed ? { resumeFailed: true } : {}), }; yield* stopStaleSessionsForThread({ @@ -1147,6 +1211,12 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( yield* upsertSessionBinding(sessionWithInstance, threadId, { modelSelection: input.modelSelection, earlyUnused: early && fresh, + // Owed until a send carries it: the forgotten conversation's, the + // seed this start handed over (an adapter may hold it until a send), + // or the history of a conversation the adapter couldn't reopen. + ...(historyOwed || input.contextSeed !== undefined || session.resumeFailed === true + ? { historyOwed: true } + : {}), startedWith: { guideTools: input.guideTools === true }, }); yield* analytics.record("provider.session.started", { @@ -1753,7 +1823,12 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( }), ), ); - return turn; + // The message went to a conversation recovery opened without the + // thread's history: the caller owes it to the next message. This one + // stays sent; it was prepared for the runtime that had the history. + return "historyOwed" in routed && routed.historyOwed + ? { ...turn, historyOwed: true as const } + : turn; }).pipe( withMetrics({ counter: providerTurnsTotal, @@ -2831,6 +2906,8 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( return yield* Effect.gen(function* () { // Using an early session makes it the thread's. yield* adoptEarlySession(input.threadId); + const forgotten = yield* forgetByStartingOver(input.threadId, input.numTurns); + if (forgotten !== undefined) return { conversationRolledBack: forgotten }; const routed = yield* resolveRoutableSession({ threadId: input.threadId, operation: "ProviderService.rollbackConversation", @@ -2880,6 +2957,122 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( ); }); + /** + * Forgets a saved conversation in the thread's binding (see + * readPersistedHistoryOwed): its cursor goes, the history is owed, and no + * runtime is named any more, so no older session's acknowledgement clears + * the debt. With `onlySession`, only while the binding still holds that + * session (a lost session's late exit leaves its replacement alone). + * False when the binding couldn't be read or written; the agent then + * remembers. + */ + const forgetConversation = (threadId: ThreadId, options?: { readonly onlySession?: string }) => + Effect.gen(function* () { + // A forget that names its runtime checks and writes in one step: a + // replacement started meanwhile keeps its conversation. + if (options?.onlySession !== undefined) { + yield* directory.patchIfSession({ + threadId, + sessionCreatedAt: options.onlySession, + runtimePayload: { historyOwed: true, sessionCreatedAt: null }, + clearResumeCursor: true, + }); + return true; + } + const binding = Option.getOrUndefined(yield* directory.getBinding(threadId)); + if (binding === undefined) return true; + yield* directory.upsert({ + threadId, + provider: binding.provider, + ...(binding.providerInstanceId !== undefined + ? { providerInstanceId: binding.providerInstanceId } + : {}), + resumeCursor: null, + runtimePayload: { historyOwed: true, sessionCreatedAt: null }, + }); + return true; + }).pipe( + Effect.catchCause((cause) => + Effect.logWarning("provider service could not forget a conversation", { + threadId, + cause: Cause.pretty(cause), + }).pipe(Effect.as(false)), + ), + ); + + /** + * A revert for an agent that forgets by starting over (`new-session`): a + * live runtime stops what it runs and ends (its `rollbackThread`), then the + * binding forgets the conversation. Nothing is started for it. Undefined + * for every other agent, which `rollbackConversation` handles as before. + */ + const forgetByStartingOver = (threadId: ThreadId, numTurns: number) => + Effect.gen(function* () { + // A binding that can't be read fails the revert: whether something of + // the agent still runs can't be known. + const binding = Option.getOrUndefined(yield* directory.getBinding(threadId)); + // No saved conversation: nothing can bring the reverted turns back. + if (binding === undefined) return true; + if (binding.providerInstanceId === undefined) return undefined; + const adapter = yield* registry + .getByInstance(binding.providerInstanceId) + .pipe(Effect.orElseSucceed(() => undefined)); + if (adapter?.capabilities.conversationRollback !== "new-session") return undefined; + if (yield* adapter.hasSession(threadId)) { + // A rollback that can't stop the work ends the runtime instead; one + // that can't be ended either fails the revert. + yield* adapter.rollbackThread(threadId, numTurns).pipe( + Effect.catchCause((cause) => + Effect.logWarning("provider service ends a runtime its rollback couldn't stop", { + threadId, + cause: Cause.pretty(cause), + }).pipe(Effect.andThen(adapter.stopSession(threadId))), + ), + ); + } + // A runtime that is stopping (hasSession no longer reports it) can + // still write through a command it started: the files wait until its + // process is gone (whenStopped). A wait past the limit ends the runtime; + // one that still won't go fails the revert. + const whenStopped = adapter.whenStopped; + if (whenStopped !== undefined) { + const gone = yield* whenStopped(threadId).pipe(Effect.timeoutOption(REVERT_STOP_WAIT)); + if (Option.isNone(gone)) { + yield* Effect.logWarning("provider service ends a runtime still stopping at a revert", { + threadId, + }); + // Bounded too: a stop already stalled may hold the lock this one waits for. + yield* adapter + .stopSession(threadId) + .pipe(Effect.ignore, Effect.timeoutOption(REVERT_STOP_WAIT)); + const ended = yield* whenStopped(threadId).pipe(Effect.timeoutOption(REVERT_STOP_WAIT)); + if (Option.isNone(ended)) { + return yield* new ProviderAdapterRequestError({ + provider: adapter.provider, + method: "rollbackThread", + detail: "The agent's process did not stop.", + }); + } + } + } + const forgotten = yield* forgetConversation(threadId); + yield* analytics.record("provider.conversation.rolled_back", { + provider: adapter.provider, + turns: numTurns, + }); + return forgotten; + }); + + const noteHistoryDelivered: ProviderServiceShape["noteHistoryDelivered"] = ({ + threadId, + sessionCreatedAt, + }) => + // Checked and written in one step: another runtime than the one that + // sent it (a replacement started meanwhile) still owes it. + directory + .patchIfSession({ threadId, sessionCreatedAt, runtimePayload: { historyOwed: false } }) + .pipe(Effect.asVoid, Effect.ignoreCause({ log: true })); + /** * Every provider session key of a thread: its own agent first, then any * room agents. A subagent lives inside exactly one of those runtimes, and @@ -3378,6 +3571,7 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( adoptNativeSession, forgetNativeSession, dropResumeCursor, + noteHistoryDelivered, getCapabilities, getInstanceInfo, rollbackConversation, diff --git a/apps/server/src/provider/Layers/ProviderSessionDirectory.test.ts b/apps/server/src/provider/Layers/ProviderSessionDirectory.test.ts index 6846dddbd..512392f8d 100644 --- a/apps/server/src/provider/Layers/ProviderSessionDirectory.test.ts +++ b/apps/server/src/provider/Layers/ProviderSessionDirectory.test.ts @@ -4,7 +4,7 @@ import os from "node:os"; import path from "node:path"; import * as NodeServices from "@effect/platform-node/NodeServices"; -import { ProviderDriverKind, ThreadId } from "@threadlines/contracts"; +import { ProviderDriverKind, ProviderInstanceId, ThreadId } from "@threadlines/contracts"; import { it, assert } from "@effect/vitest"; import { assertSome } from "@effect/vitest/utils"; import * as Effect from "effect/Effect"; @@ -33,6 +33,54 @@ function makeDirectoryLayer(persistenceLayer: Layer.Layer { + it("writes a guarded patch only while the binding still names that runtime", () => + Effect.gen(function* () { + const directory = yield* ProviderSessionDirectory; + const threadId = ThreadId.make("thread-guarded"); + yield* directory.upsert({ + threadId, + provider: ProviderDriverKind.make("codex"), + providerInstanceId: ProviderInstanceId.make("codex"), + resumeCursor: { opaque: "runtime-b" }, + runtimePayload: { sessionCreatedAt: "runtime-b", historyOwed: true, cwd: "/work" }, + }); + const payload = () => + Effect.map(directory.getBinding(threadId), (binding) => Option.getOrUndefined(binding)); + + // An older runtime's write: nothing lands. + assert.isFalse( + yield* directory.patchIfSession({ + threadId, + sessionCreatedAt: "runtime-a", + runtimePayload: { historyOwed: false, sessionCreatedAt: null }, + clearResumeCursor: true, + }), + ); + assert.deepEqual((yield* payload())?.runtimePayload, { + sessionCreatedAt: "runtime-b", + historyOwed: true, + cwd: "/work", + }); + assert.deepEqual((yield* payload())?.resumeCursor, { opaque: "runtime-b" }); + + // Its own runtime's: merged in, the rest kept, the cursor cleared. + assert.isTrue( + yield* directory.patchIfSession({ + threadId, + sessionCreatedAt: "runtime-b", + runtimePayload: { historyOwed: false }, + clearResumeCursor: true, + }), + ); + const after = yield* payload(); + assert.deepEqual(after?.runtimePayload, { + sessionCreatedAt: "runtime-b", + historyOwed: false, + cwd: "/work", + }); + assert.equal(after?.resumeCursor ?? null, null); + })); + it("upserts and reads thread bindings", () => Effect.gen(function* () { const directory = yield* ProviderSessionDirectory; diff --git a/apps/server/src/provider/Layers/ProviderSessionDirectory.ts b/apps/server/src/provider/Layers/ProviderSessionDirectory.ts index 5880a404c..aab67170a 100644 --- a/apps/server/src/provider/Layers/ProviderSessionDirectory.ts +++ b/apps/server/src/provider/Layers/ProviderSessionDirectory.ts @@ -153,6 +153,14 @@ const makeProviderSessionDirectory = Effect.gen(function* () { .pipe(Effect.mapError(toPersistenceError("ProviderSessionDirectory.upsert:upsert"))); }); + const patchIfSession: ProviderSessionDirectoryShape["patchIfSession"] = (input) => + Effect.gen(function* () { + const lastSeenAt = DateTime.formatIso(yield* DateTime.now); + return yield* repository + .patchIfSession({ ...input, lastSeenAt }) + .pipe(Effect.mapError(toPersistenceError("ProviderSessionDirectory.patchIfSession"))); + }); + const getProvider: ProviderSessionDirectoryShape["getProvider"] = (threadId) => getBinding(threadId).pipe( Effect.flatMap((binding) => @@ -199,6 +207,7 @@ const makeProviderSessionDirectory = Effect.gen(function* () { listThreadIds, listBindings, deleteBinding, + patchIfSession, } satisfies ProviderSessionDirectoryShape; }); diff --git a/apps/server/src/provider/Layers/ProviderSessionReaper.test.ts b/apps/server/src/provider/Layers/ProviderSessionReaper.test.ts index a12374df9..321ed5672 100644 --- a/apps/server/src/provider/Layers/ProviderSessionReaper.test.ts +++ b/apps/server/src/provider/Layers/ProviderSessionReaper.test.ts @@ -254,6 +254,7 @@ describe("ProviderSessionReaper", () => { adoptNativeSession: () => Effect.void, forgetNativeSession: () => Effect.void, dropResumeCursor: () => Effect.void, + noteHistoryDelivered: () => Effect.void, getCapabilities: () => Effect.succeed({ sessionModelSwitch: "in-session" }), getInstanceInfo: (instanceId) => { const driverKind = ProviderDriverKind.make(String(instanceId)); diff --git a/apps/server/src/provider/Services/ProviderAdapter.ts b/apps/server/src/provider/Services/ProviderAdapter.ts index d98f2bfbe..3d8971b4a 100644 --- a/apps/server/src/provider/Services/ProviderAdapter.ts +++ b/apps/server/src/provider/Services/ProviderAdapter.ts @@ -159,8 +159,13 @@ export interface ProviderAdapterCapabilities { * remembers the reverted turns, and a revert says so. Default `native`. A * rollback's own `conversationRolledBack` overrides it, for an agent that * can rewind only to the turns it knows the positions of (Grok). + * `new-session` (Antigravity): `rollbackThread` stops the running work and + * ends the session, and ProviderService forgets the saved conversation in + * the thread's binding, so the next turn opens a new one seeded with the + * turns kept. A revert stops it before restoring files, and reaches it with + * no runtime live without starting one. */ - readonly conversationRollback?: "native" | "none"; + readonly conversationRollback?: "native" | "none" | "new-session"; /** * Whether a session may be started before its first message, while the user @@ -366,6 +371,17 @@ export interface ProviderAdapterShape { */ readonly hasSession: (threadId: ThreadId) => Effect.Effect; + /** + * Resolves once no runtime of this session key can still act: at once when + * none exists, otherwise once the runtime's process (with every child + * process it started) is gone. `hasSession` turns false as soon as a stop + * begins, so a caller that must not touch files the agent may still hold + * open (a revert) waits on this after asking for the stop; a live runtime + * is waited on until something stops it. Never fails. Absent: a stopped + * session is gone when `stopSession` returns. + */ + readonly whenStopped?: (threadId: ThreadId) => Effect.Effect; + /** * Read a provider thread snapshot. */ diff --git a/apps/server/src/provider/Services/ProviderService.ts b/apps/server/src/provider/Services/ProviderService.ts index 5f092bbf8..7338fb346 100644 --- a/apps/server/src/provider/Services/ProviderService.ts +++ b/apps/server/src/provider/Services/ProviderService.ts @@ -386,6 +386,20 @@ export interface ProviderServiceShape { */ readonly dropResumeCursor: (threadId: ThreadId) => Effect.Effect; + /** + * The thread's history went out to the agent of this session key, in a + * prompt the session that started at `sessionCreatedAt` + * (ProviderSession.createdAt) wrote to the agent (a send whose result + * says neither `contextDeferred` nor `undelivered`). Its + * binding stops owing the history (`historyOwed`), so later starts resume + * the conversation, but only while the binding still holds that session: a + * late word from an older session clears nothing. + */ + readonly noteHistoryDelivered: (input: { + readonly threadId: ThreadId; + readonly sessionCreatedAt: string; + }) => Effect.Effect; + /** * Read capabilities for the adapter bound to a configured provider instance. */ @@ -400,7 +414,13 @@ export interface ProviderServiceShape { /** * Roll back provider conversation state by a number of turns. * `conversationRolledBack` is false when the provider cannot forget turns - * (see `ProviderAdapterCapabilities.conversationRollback`). + * (see `ProviderAdapterCapabilities.conversationRollback`). An agent that + * forgets by starting over (`new-session`) has its running work stopped + * (its process ended if a cancel can't) and its saved conversation + * forgotten in the thread's binding; nothing is started for it. It fails + * when the agent couldn't be found or stopped, so nothing of it can be + * known to have stopped writing; it answers false when it stopped but the + * binding couldn't be written. */ readonly rollbackConversation: (input: { readonly threadId: ThreadId; diff --git a/apps/server/src/provider/Services/ProviderSessionDirectory.ts b/apps/server/src/provider/Services/ProviderSessionDirectory.ts index 473b4351a..c2d06d343 100644 --- a/apps/server/src/provider/Services/ProviderSessionDirectory.ts +++ b/apps/server/src/provider/Services/ProviderSessionDirectory.ts @@ -66,6 +66,19 @@ export interface ProviderSessionDirectoryShape { readonly deleteBinding: ( threadId: ThreadId, ) => Effect.Effect; + + /** + * Merges flat payload fields into a binding (and clears its cursor), in + * one step, only while it still names runtime `sessionCreatedAt` (the + * `sessionCreatedAt` ProviderService writes on every start). False when it + * names another runtime, or there is none: nothing was written. + */ + readonly patchIfSession: (input: { + readonly threadId: ThreadId; + readonly sessionCreatedAt: string; + readonly runtimePayload: Readonly>; + readonly clearResumeCursor?: boolean; + }) => Effect.Effect; } export class ProviderSessionDirectory extends Context.Service< diff --git a/apps/server/src/provider/acp/AcpAdapter.test.ts b/apps/server/src/provider/acp/AcpAdapter.test.ts index 946035953..4dfb61eb8 100644 --- a/apps/server/src/provider/acp/AcpAdapter.test.ts +++ b/apps/server/src/provider/acp/AcpAdapter.test.ts @@ -473,6 +473,34 @@ it.live.skipIf(isWindows)( ); cursorAdapterTestLayer("CursorAdapterLive", (it) => { + it.effect("opens a fresh session when the agent can't reopen the saved one, and says so", () => + Effect.gen(function* () { + const adapter = yield* CursorAdapter; + const settings = yield* ServerSettingsService; + const wrapperPath = yield* Effect.promise(() => + makeMockAgentWrapper({ T3_ACP_FAIL_LOAD_SESSION: "1" }), + ); + yield* settings.updateSettings({ providers: { cursor: { binaryPath: wrapperPath } } }); + + const session = yield* adapter.startSession({ + threadId: ThreadId.make("cursor-resume-refused"), + provider: ProviderDriverKind.make("cursor"), + cwd: process.cwd(), + runtimeMode: "full-access", + modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "default" }, + resumeCursor: { schemaVersion: 1, sessionId: "saved-before-an-update" }, + }); + + // The thread's history then goes with its next message + // (ProviderCommandReactor's owed history seed). + assert.isTrue(session.resumeFailed); + assert.notEqual( + (session.resumeCursor as { readonly sessionId?: unknown } | undefined)?.sessionId, + "saved-before-an-update", + ); + }), + ); + it.effect("starts a session and maps mock ACP prompt flow to runtime events", () => Effect.gen(function* () { const adapter = yield* CursorAdapter; diff --git a/apps/server/src/provider/acp/AcpAdapter.ts b/apps/server/src/provider/acp/AcpAdapter.ts index 625dc6ded..9ba0279dd 100644 --- a/apps/server/src/provider/acp/AcpAdapter.ts +++ b/apps/server/src/provider/acp/AcpAdapter.ts @@ -24,6 +24,8 @@ import { type RuntimeMode, type ThreadId, TurnId, + type UsageTokenTotals, + type ServerProviderSlashCommand, } from "@threadlines/contracts"; import { withFailureCategory } from "../providerFailureCategory.ts"; import { makeAgentProcessLedger } from "../agentProcessLedger.ts"; @@ -39,6 +41,7 @@ import { import { renderThreadContextSeed, withContextSeedPreamble } from "@threadlines/shared/contextSeed"; import { countTextReplacementStats } from "@threadlines/shared/textReplacementStats"; import { randomUUIDv4 } from "@threadlines/shared/uuid"; +import { sameSlashCommands, slashCommandAtStart } from "@threadlines/shared/slashCommands"; import * as Cause from "effect/Cause"; import * as Clock from "effect/Clock"; import * as DateTime from "effect/DateTime"; @@ -51,6 +54,7 @@ import * as FileSystem from "effect/FileSystem"; import * as Option from "effect/Option"; import * as Path from "effect/Path"; import * as PubSub from "effect/PubSub"; +import * as Queue from "effect/Queue"; import * as Schema from "effect/Schema"; import * as Scope from "effect/Scope"; import * as Semaphore from "effect/Semaphore"; @@ -109,34 +113,61 @@ import { import { makeAcpNativeLoggers } from "./AcpNativeLogging.ts"; import type { AcpExtensionContext, + AcpPromptOutcomeWatch, + AcpPromptFailure, + AcpPromptPlanMode, AcpProviderDescriptor, AcpProviderSettings, + AcpSubagents, AcpTurnOutcome, } from "./AcpProviderDescriptor.ts"; +import { type AcpAttachmentBudget, acpAttachmentContent } from "./AcpPromptAttachments.ts"; +import { type AcpSubagentRoster, makeAcpSubagentRoster } from "./AcpSubagentRoster.ts"; import { applyAcpModelSelection, defaultResolveAcpModelId, makeAcpProviderRuntime, } from "./AcpProviderRuntime.ts"; import { + type AcpPermissionRequest, + type AcpToolCallReport, type AcpPlanUpdate, type AcpSessionMode, type AcpSessionModeState, type AcpToolCallState, acpTurnUsageTotals, + describePermissionRequest, + mergeToolCallState, + toolCallSubstance, parsePermissionRequest, } from "./AcpRuntimeModel.ts"; +import { THREADLINES_ACP_CLIENT_INFO } from "./acpClientInfo.ts"; +import { + type AcpPromptOutcomeRead, + type AcpTurnCommand, + type AcpTurnEnd, + type AcpTurnEvent, + type AcpTurnMachineState, + type AcpTurnTimer, + initialTurnMachineState, + stepTurnMachine, + workPending, +} from "./AcpTurnMachine.ts"; import { type AcpSessionRuntimeShape } from "./AcpSessionRuntime.ts"; const encodeUnknownJsonStringExit = Schema.encodeUnknownExit(Schema.fromJsonString(Schema.Unknown)); const ACP_RESUME_VERSION = 1 as const; +/** A session's command list reaches the clients at most this often. */ +const ACP_SESSION_COMMANDS_INTERVAL_MS = 5_000; /** * How long a cancelled prompt may take to return. Past it the turn settles * as cancelled here and the process is recycled; the next turn resumes the * conversation in a fresh one. */ const ACP_CANCEL_DEADLINE = Duration.seconds(15); +/** How long a revert lets the agent stop its work before its session ends. */ +const ACP_REVERT_WIND_DOWN = Duration.seconds(3); /** * An agent's own turn (see `agentTurns`) that has gone this long without * output is closed here, in case its end notice never comes. Long: a command @@ -144,6 +175,34 @@ const ACP_CANCEL_DEADLINE = Duration.seconds(15); */ const ACP_AGENT_TURN_QUIET_LIMIT = Duration.minutes(15); const ACP_AGENT_TURN_QUIET_CHECK = Duration.seconds(30); +/** + * A held turn ends this long after the agent's last word once nothing holds + * it: another wake can follow straight after a reply. + */ +const ACP_HELD_TURN_SETTLE = Duration.seconds(2); +/** A reply the agent started by itself whose closing `usage_update` never comes ends after this. */ +const ACP_HELD_REPLY_QUIET_LIMIT = Duration.minutes(2); +/** How long reading a prompt's real outcome (`turnMachine.outcome`) may take. */ +const ACP_OUTCOME_CHECK_TIMEOUT = Duration.seconds(10); +/** + * How long noting where the agent's records stand may hold a prompt back + * (`turnMachine.outcome.watch`): past it the prompt goes with no baseline, + * and its outcome is its own answer. The one sender waits on it. + */ +const ACP_OUTCOME_WATCH_TIMEOUT = Duration.seconds(2); +/** + * How long after a cancel its notice is still expected (and dropped). An + * agent that never sends one must not cost a real reply in those words later. + */ +const ACP_NOTICE_EXPIRY = Duration.seconds(30); +/** How often a stop that waits on subagents reads their records again. */ +const ACP_STOP_CHECK_INTERVAL = Duration.seconds(1); +/** + * How long stopping a machine session waits for its event reader to get + * through what is already queued (answers, their usage, the turn's end). + * The reader never waits on I/O, so this is only a guard against a bug. + */ +const ACP_STOP_DRAIN_LIMIT = Duration.seconds(5); /** * The most turns a resume cursor remembers the agent's prompt positions for * (see `conversationHistory`); a revert further back trims Threadlines' turn @@ -175,6 +234,19 @@ export interface AcpAdapterOptions { * ledger), for agents that keep no usage of their own on disk. Never fails. */ readonly recordTurnUsage?: (entry: UsageLedgerEntry) => Effect.Effect; + /** + * For `agentCommands` descriptors: a session's own command list changed + * (`undefined`: the session ended). The driver puts it on the provider + * status (`ServerProvider.sessionCommands`). Never fails. + */ + readonly onSessionCommands?: ( + sessionKey: ThreadId, + commands: ReadonlyArray | undefined, + ) => Effect.Effect; + /** The skills the provider status lists, by name: a typed `/name` runs one. */ + readonly skillNames?: Effect.Effect>; + /** Tests only: holds the turn machine's driver up at its seams (`AcpTurnMachineSeam`). */ + readonly turnMachineSeams?: (seam: AcpTurnMachineSeam) => Effect.Effect; } interface PendingApproval { @@ -188,6 +260,8 @@ interface PendingUserInput { interface AcpSessionContext { readonly threadId: ThreadId; + /** Done once a stop has closed the session's process scope (`whenStopped`). */ + readonly closed: Deferred.Deferred; session: ProviderSession; /** A room's side runtime: read-only, every request declined, its mode never changed. */ readonly lockdown: "side-answer" | "side-review" | undefined; @@ -211,6 +285,10 @@ interface AcpSessionContext { lastContextUsageKey: string | undefined; /** The agent's session id, as its usage is recorded under. */ readonly acpSessionId: string; + /** What the agent's `initialize` answer says it reads in a prompt. */ + readonly promptCapabilities: EffectAcpSchema.PromptCapabilities | null | undefined; + /** The subagents this session's tool calls launched (`subagents`), as the thread shows them. */ + readonly subagentRoster: AcpSubagentRoster | undefined; /** * The session's running cost at the last turn boundary, when it is known * exactly: zero for a session opened here, or a report between turns. A turn @@ -228,8 +306,6 @@ interface AcpSessionContext { activeReasoning: { readonly itemId: string; readonly turnId: TurnId; text: string } | undefined; /** The session cwd and its real path: agents report real paths (macOS `/private/tmp`). */ readonly cwdRoots: ReadonlyArray; - /** The turn a `session/cancel` was sent for, so the agent's cancel notice is dropped. */ - cancelledTurnId: TurnId | undefined; /** The plan the agent wrote this turn (prompt-command plan mode). */ planMarkdown: string | undefined; /** Earlier conversation for an agent that starts without it, sent with the first turn. */ @@ -287,9 +363,134 @@ interface AcpSessionContext { | undefined; /** The newest position the agent has listed, so a later prompt is placed after it. */ newestPosition: number | undefined; + /** The turn machine and what its commands need (`descriptor.turnMachine`). */ + readonly machine: AcpMachineSession | undefined; stopped: boolean; } +type AcpTurnCompletedPayload = Extract["payload"]; + +/** A failed turn's completion, from how the agent's own words say it failed. */ +function failedTurnPayload( + failure: AcpPromptFailure, + stopReason: string | null, +): AcpTurnCompletedPayload { + return { + state: "failed", + stopReason, + errorMessage: failure.errorMessage, + ...withFailureCategory(failure.failureCategory), + ...(failure.usageLimit !== undefined ? { usageLimit: failure.usageLimit } : {}), + }; +} + +type AcpMachineEvent = AcpTurnEvent; +type AcpMachineCommand = AcpTurnCommand; + +/** What a send or a steer hears back from the turn machine. */ +type AcpMachineReply = + | { readonly accepted: TurnId } + | { readonly rejected: "no-active-turn" | "turn-finishing" }; + +/** A prompt a send or a steer asked for, until the machine sends it. */ +interface AcpMachinePrompt { + readonly parts: ReadonlyArray; + /** A send's: the mode and model its turn applies before the prompt goes out. */ + readonly configure: Effect.Effect | undefined; + readonly model: string | undefined; + readonly resolvedModel: string | undefined; + /** The context preamble this prompt carries; back to the session if it never goes out. */ + readonly preamble: string | undefined; + /** A send's: hears whether its prompt was written to the agent (`reportDelivery`). */ + readonly delivered: Deferred.Deferred | undefined; +} + +/** A prompt the machine sent, with what its answer is read against. */ +interface AcpMachinePromptSent extends AcpMachinePrompt { + readonly turnId: TurnId; + /** Its place in the turn: 1 for the turn's first, then each steer's. */ + readonly index: number; + /** Set by the prompt's fiber before it reports the prompt sent, or answered. */ + watch: AcpPromptOutcomeWatch | undefined; + exit: Exit.Exit | undefined; +} + +/** + * A session on the turn machine: the machine's state, which only the event + * reader steps, and the data its commands carry out (the prompts sends and + * steers asked for, the turns' models, the armed timers). + */ +interface AcpMachineSession { + state: AcpTurnMachineState; + /** Sends and steers waiting on the machine, by id. */ + readonly callers: Map< + string, + { + readonly prompt: AcpMachinePrompt; + readonly messageId?: string; + readonly planMode: AcpPromptPlanMode | undefined; + readonly reply: Deferred.Deferred; + } + >; + readonly prompts: Map; + readonly turns: Map< + string, + { + readonly model: string | undefined; + readonly resolvedModel: string | undefined; + readonly planMode: AcpPromptPlanMode | undefined; + } + >; + readonly timers: Map>; + /** When the agent last did anything: quiet timers count from here. */ + lastActivityMs: number; + /** + * The prompts the machine sent, in its order: one sender takes them, so + * each (its turn's mode and model setup first) reaches the agent after + * every prompt the machine sent before it. + */ + readonly outbox: Queue.Queue; +} + +/** + * Where a test can hold the turn machine's driver up to force an ordering + * (`AcpAdapterOptions.turnMachineSeams`). Each runs where it says and may + * wait; nothing in production sets one. + */ +export type AcpTurnMachineSeam = + /** On the event reader: a step's state is committed, its commands not yet run. */ + | { + readonly point: "stepCommitted"; + readonly event: AcpTurnEvent["type"]; + readonly commands: ReadonlyArray["type"]>; + /** Prompt records the driver still holds as the step begins. */ + readonly promptsHeld: number; + } + /** On the prompt sender: before a prompt's mode and model setup returns. */ + | { readonly point: "promptSetup"; readonly prompt: number } + /** On the wire reader: a prompt's answer is read, not yet queued for the event reader. */ + | { readonly point: "answerRead"; readonly prompt: number } + /** Off the reader: during a prompt's outcome check. */ + | { readonly point: "outcomeRead"; readonly prompt: number } + /** Stopping a session: everything is settled, its process scope not yet closed. */ + | { readonly point: "processTeardown" } + /** Off the reader: the child records are read, the reading not yet posted. */ + | { readonly point: "childrenRead"; readonly generation: number }; + +/** A turn's end payload as the machine reads it. */ +function turnPayloadState(payload: AcpTurnCompletedPayload): "completed" | "failed" | "cancelled" { + return payload.state === "completed" || payload.state === "failed" ? payload.state : "cancelled"; +} + +/** No tokens: a usage line that carries only a cost. */ +const EMPTY_USAGE_TOTALS: UsageTokenTotals = { + uncachedInputTokens: 0, + cachedInputTokens: 0, + cacheCreationTokens: 0, + outputTokens: 0, + reasoningTokens: 0, +}; + /** Plan-gate replies are one short sentence; more text than this is content. */ const PLAN_GATE_SCAN_MAX_CHARS = 500; @@ -608,6 +809,14 @@ export function makeAcpAdapter( } >(); const adapterScope = yield* Scope.Scope; + /** + * Sessions the agent can no longer continue, as this adapter marked them + * (`markSessionLost`). ProviderService forgets each in the thread's + * binding when the session's exit says so (`conversationLost`); until it + * has, a start asked to resume one opens a new conversation here anyway, + * so a message sent right after the exit can't reopen it. + */ + const lostSessions = new Set(); const threadLocksRef = yield* SynchronizedRef.make(new Map()); const runtimeEventPubSub = yield* PubSub.unbounded(); @@ -616,7 +825,14 @@ export function makeAcpAdapter( const makeEventStamp = () => Effect.all({ eventId: nextEventId, createdAt: nowIso }); const offerRuntimeEvent = (event: ProviderRuntimeEvent) => - PubSub.publish(runtimeEventPubSub, event).pipe(Effect.asVoid); + PubSub.publish(runtimeEventPubSub, event).pipe( + // The subagent view follows the session's turns and usage updates. + Effect.andThen( + Effect.suspend( + () => sessions.get(event.threadId)?.subagentRoster?.observe(event) ?? Effect.void, + ), + ), + ); /** The prompt that carried the brief is gone: the conversation holds what it held before. */ const requeueProjectBrief = (ctx: AcpSessionContext) => { @@ -831,7 +1047,6 @@ export function makeAcpAdapter( ctx.lastPlanFingerprint = undefined; ctx.activeTurnText = ""; ctx.lastProviderStatus = undefined; - ctx.cancelledTurnId = undefined; ctx.planMarkdown = undefined; ctx.promptOutcome = undefined; ctx.costTurnOpen = true; @@ -849,7 +1064,7 @@ export function makeAcpAdapter( ctx: AcpSessionContext, turnId: TurnId, model: string | undefined, - usage: EffectAcpSchema.Usage | null | undefined, + totals: UsageTokenTotals | null, ) => Effect.gen(function* () { const costUsd = @@ -862,7 +1077,6 @@ export function makeAcpAdapter( // Settled: a report from here on (one landing while this line is // written included) is the next turn's starting point. ctx.costTurnOpen = false; - const totals = acpTurnUsageTotals(usage); const record = options?.recordTurnUsage; if (!record || (totals === null && costUsd === null)) return; yield* record({ @@ -1013,6 +1227,58 @@ export function makeAcpAdapter( } }); + /** + * A permission request as the descriptor describes its tool call + * (`normalizeToolCall`): an MCP call the agent runs through a command + * shows the server, tool and arguments it runs, under the same kind. + */ + /** + * What an open approval is for once a later update about its call arrived + * (`latest`, the call as the session now shows it), or `undefined` when + * that hasn't changed. The request keeps its kind, as on first asking. + */ + const reaskedPermissionRequest = ( + params: EffectAcpSchema.RequestPermissionRequest, + current: AcpPermissionRequest, + latest: AcpToolCallState, + ): AcpPermissionRequest | undefined => { + const merged = + current.toolCall === undefined ? latest : mergeToolCallState(current.toolCall, latest); + // The session's own classification of the call is the newest word on it. + const toolCall: AcpToolCallState = + latest.itemType !== undefined ? { ...merged, itemType: latest.itemType } : merged; + const described = describePermissionRequest(params, toolCall); + const detail = toolCall.itemType !== undefined ? toolCall.detail : described.detail; + const next: AcpPermissionRequest = { + kind: current.kind, + ...(detail !== undefined ? { detail } : {}), + toolCall, + }; + // Tied to what it would authorize, not only to how it reads. + const same = + next.detail === current.detail && + next.toolCall?.title === current.toolCall?.title && + toolCallSubstance(next.toolCall) === toolCallSubstance(current.toolCall); + return same ? undefined : next; + }; + + const normalizedPermissionRequest = ( + request: AcpPermissionRequest, + report: EffectAcpSchema.RequestPermissionRequest["toolCall"], + ): AcpPermissionRequest => { + const normalize = descriptor.normalizeToolCall; + if (normalize === undefined || request.toolCall === undefined) return request; + const toolCall = normalize(request.toolCall, report as AcpToolCallReport); + // The request keeps its kind, so it is asked and answered as before; a + // call the descriptor retyped shows its own detail (what really runs). + const detail = toolCall.itemType !== undefined ? toolCall.detail : request.detail; + return { + kind: request.kind, + ...(detail !== undefined ? { detail } : {}), + toolCall, + }; + }; + /** * The turn an update belongs to: for a tool call that started in an * earlier turn (a background shell), that turn; else the active one; @@ -1022,6 +1288,21 @@ export function makeAcpAdapter( Effect.gen(function* () { if (ctx.agentTurn !== undefined) ctx.agentTurnLastActivityMs = Date.now(); const earlier = toolCallId === undefined ? undefined : ctx.toolCallTurns.get(toolCallId); + // On the turn machine, output is an event: it opens a reply, or the + // agent's own turn when none runs. A late update for an earlier + // turn's tool opens nothing. + const machine = ctx.machine; + if (machine !== undefined) { + if (earlier === undefined || machine.state.turn !== undefined) { + yield* applyTurnEvent(ctx, { + type: "agentOutput", + newTurnId: crypto.randomUUID(), + }); + } else { + yield* noteActivity(machine); + } + return earlier ?? ctx.activeTurnId; + } if (earlier !== undefined) return earlier; if (ctx.activeTurnId !== undefined) return ctx.activeTurnId; if (!descriptor.agentTurns) return undefined; @@ -1047,27 +1328,148 @@ export function makeAcpAdapter( return Effect.succeed(ctx); }; - const stopSessionInternal = (ctx: AcpSessionContext) => + /** + * What each session last advertised, for `agentCommands` descriptors: + * every name (a typed `/name` is its command, hidden ones included) and + * the list the composer shows, reported through `onSessionCommands` no + * more than once per `ACP_SESSION_COMMANDS_INTERVAL` and never unchanged. + */ + const sessionCommandState = new WeakMap< + AcpSessionContext, + { + names: ReadonlySet; + reported: ReadonlyArray | undefined; + reportedAtMs: number; + pending: ReadonlyArray | undefined; + } + >(); + + const noteSessionCommands = ( + ctx: AcpSessionContext, + commands: ReadonlyArray, + ) => + Effect.gen(function* () { + const hidden = descriptor.agentCommands?.hidden; + const shown = commands.filter((command) => !hidden?.has(command.name)); + const report = options?.onSessionCommands; + let state = sessionCommandState.get(ctx); + if (state === undefined) { + state = { names: new Set(), reported: undefined, reportedAtMs: 0, pending: undefined }; + sessionCommandState.set(ctx, state); + // The list goes with the session. + if (report !== undefined) { + yield* Scope.addFinalizer(ctx.scope, report(ctx.threadId, undefined)); + } + } + state.names = new Set(commands.map((command) => command.name)); + if (report === undefined) return; + const current = state.pending ?? state.reported; + if (current !== undefined && sameSlashCommands(current, shown)) return; + const waitMs = state.reportedAtMs + ACP_SESSION_COMMANDS_INTERVAL_MS - Date.now(); + if (waitMs <= 0 && state.pending === undefined) { + state.reported = shown; + state.reportedAtMs = Date.now(); + yield* report(ctx.threadId, shown); + return; + } + // Too soon after the last report: the newest list goes when the + // interval is up, and lists in between are never sent. + const scheduled = state.pending !== undefined; + state.pending = shown; + if (scheduled) return; + const flushing = state; + yield* Effect.sleep(Math.max(0, waitMs)).pipe( + Effect.andThen( + Effect.suspend(() => { + const next = flushing.pending; + flushing.pending = undefined; + if (next === undefined) return Effect.void; + if (flushing.reported !== undefined && sameSlashCommands(flushing.reported, next)) { + return Effect.void; + } + flushing.reported = next; + flushing.reportedAtMs = Date.now(); + return report(ctx.threadId, next); + }), + ), + Effect.forkIn(ctx.scope), + ); + }); + + /** + * Whether a typed `/name` runs one of the agent's own commands: one this + * session advertised, or a skill the status lists. + */ + const isAgentCommand = (ctx: AcpSessionContext, name: string) => + Effect.gen(function* () { + if (sessionCommandState.get(ctx)?.names.has(name) === true) return true; + const skills = options?.skillNames; + return skills === undefined ? false : (yield* skills).has(name); + }); + + const stopSessionInternal = ( + ctx: AcpSessionContext, + exitKind: "graceful" | "error" = "graceful", + exit?: { readonly conversationLost?: { readonly sessionCreatedAt: string } }, + ) => Effect.gen(function* () { if (ctx.stopped) return; ctx.stopped = true; yield* settlePendingApprovalsAsCancelled(ctx.pendingApprovals); yield* settlePendingUserInputsAsEmptyAnswers(ctx.pendingUserInputs); + // The agent's process takes its subagents with it. + if (ctx.subagentRoster !== undefined) yield* ctx.subagentRoster.end; if (ctx.promptFiber) { yield* Fiber.interrupt(ctx.promptFiber); } + // On the turn machine the stop is an event: the reader gets to it + // after everything already queued (an answer and its usage, a turn's + // end), and only then is it stopped. + const machine = ctx.machine; + const drained = + machine === undefined || ctx.notificationFiber === undefined + ? false + : yield* Effect.gen(function* () { + const done = yield* Deferred.make(); + yield* ctx.acp.inOrder( + applyTurnEvent(ctx, { type: "sessionStopping" }).pipe( + Effect.andThen(Deferred.succeed(done, undefined)), + Effect.asVoid, + ), + ); + return Option.isSome( + yield* Deferred.await(done).pipe(Effect.timeoutOption(ACP_STOP_DRAIN_LIMIT)), + ); + }); if (ctx.notificationFiber) { yield* Fiber.interrupt(ctx.notificationFiber); } + if (machine !== undefined) { + // A reader that never got there: the stop is stepped here instead. + if (!drained) yield* applyTurnEvent(ctx, { type: "sessionStopping" }); + for (const [id, caller] of machine.callers) { + machine.callers.delete(id); + yield* Deferred.succeed(caller.reply, { rejected: "no-active-turn" }); + if (caller.prompt.delivered !== undefined) { + yield* Deferred.succeed(caller.prompt.delivered, false); + } + } + // Nothing more goes out: a prompt not yet written never will be. + for (const sent of machine.prompts.values()) { + if (sent.delivered !== undefined) yield* Deferred.succeed(sent.delivered, false); + } + } + yield* seam({ point: "processTeardown" }); yield* Effect.ignore(Scope.close(ctx.scope, Exit.void)); sessions.delete(ctx.threadId); + yield* Deferred.succeed(ctx.closed, undefined); yield* offerRuntimeEvent({ type: "session.exited", ...(yield* makeEventStamp()), provider: PROVIDER, threadId: ctx.threadId, - payload: { exitKind: "graceful" }, + payload: { exitKind, ...exit }, }); }); @@ -1124,6 +1526,7 @@ export function makeAcpAdapter( const mappedModeId = descriptor.agentModeFor?.({ runtimeMode: input.runtimeMode, interactionMode: input.interactionMode, + availableModeIds: modeState?.availableModes.map((mode) => mode.id) ?? [], }); const requestedModeId = mappedModeId !== undefined && @@ -1199,6 +1602,14 @@ export function makeAcpAdapter( } const pendingApprovals = new Map(); + /** + * The approvals waiting on the user, by the tool call they ask + * about: an update that changes what one is for asks it again. + */ + const openApprovals = new Map< + string, + { readonly reask: (latest: AcpToolCallState) => Effect.Effect } + >(); const pendingUserInputs = new Map(); const sessionScope = yield* Scope.make("sequential"); let sessionScopeTransferred = false; @@ -1208,7 +1619,13 @@ export function makeAcpAdapter( let ctx!: AcpSessionContext; const resumed = parseAcpResumeCursor(input.resumeCursor); - const resumeSessionId = resumed?.sessionId; + // A session the agent can no longer continue is not reopened: the + // thread starts a new one with its history, as after a failed resume. + const lostSession = + resumed !== undefined && lostSessions.has(resumed.sessionId) + ? resumed.sessionId + : undefined; + const resumeSessionId = lostSession === undefined ? resumed?.sessionId : undefined; // A native fork opens on the agent's copy of the source conversation, // up to the boundary. One it can't make exactly (a boundary it can't // place, or one before the first prompt) fails here, and the caller @@ -1387,10 +1804,13 @@ export function makeAcpAdapter( : resumeSessionId ? { resumeSessionId } : {}), - clientInfo: { name: "threadlines", version: "0.0.0" }, + clientInfo: THREADLINES_ACP_CLIENT_INFO, mcpServers, runtimeMode: input.runtimeMode, - ...(descriptor.agentTurns ? { liveOutsidePrompt: true } : {}), + ...(descriptor.agentTurns || descriptor.turnMachine ? { liveOutsidePrompt: true } : {}), + ...(descriptor.turnMachine ? { trackSilentToolCalls: true } : {}), + // An open approval must hear of an update that changes only what it would authorize. + reportRevisedToolCalls: true, ...acpNativeLoggers, }).pipe( Effect.provideService(Scope.Scope, sessionScope), @@ -1430,7 +1850,21 @@ export function makeAcpAdapter( } else if (ahead?.after !== undefined && context.openPrompt === ahead.after) { yield* showAs(ahead.turnId); } else { - yield* acp.inOrder(Effect.suspend(() => showAs(context.activeTurnId))); + yield* acp.inOrder( + Effect.gen(function* () { + // On the turn machine a request is an event: with no + // turn running (a wake asks for a permission) it opens + // one of the agent's own, and no quiet limit runs while + // it waits on the user. + if (context.machine !== undefined) { + yield* applyTurnEvent(context, { + type: "requestOpened", + newTurnId: crypto.randomUUID(), + }); + } + yield* showAs(context.activeTurnId); + }), + ); } return shown; }); @@ -1470,7 +1904,12 @@ export function makeAcpAdapter( }), ); const resolved = yield* Deferred.await(answers).pipe( - Effect.ensuring(Effect.sync(() => pendingUserInputs.delete(requestId))), + Effect.ensuring( + Effect.suspend(() => { + pendingUserInputs.delete(requestId); + return closeMachineRequest(ctx); + }), + ), ); const turnId = yield* Deferred.await(shown); yield* offerRuntimeEvent({ @@ -1623,10 +2062,23 @@ export function makeAcpAdapter( }); return selected(question.optionIdForAnswers(answers)); } - const permissionRequest = parsePermissionRequest(params); + // A request may restate only part of the call: it is read on + // top of what the session's updates already said about it. + const known = yield* acp.getToolCall(params.toolCall.toolCallId); + const permissionRequest = normalizedPermissionRequest( + parsePermissionRequest(params, known), + params.toolCall, + ); const planFileWrite = permissionRequest.toolCall !== undefined && - descriptor.planMode?.isPlanFile(permissionRequest.toolCall) === true; + descriptor.planMode?.isPlanFile( + permissionRequest.toolCall, + // Only this session's own plan: a request from another + // session (a subagent's) never writes it unasked. + ctx !== undefined && String(params.sessionId) === ctx.acpSessionId + ? ctx.acpSessionId + : undefined, + ) === true; if (planFileWrite && permissionRequest.toolCall) { const planMarkdown = descriptor.planMode?.planMarkdown( permissionRequest.toolCall, @@ -1646,10 +2098,14 @@ export function makeAcpAdapter( const once = acpPermissionOptionId("accept", offered); if (once !== undefined) return selected(once); } - const requestId = ApprovalRequestId.make(crypto.randomUUID()); - const runtimeRequestId = RuntimeRequestId.make(requestId); const decision = yield* Deferred.make(); - pendingApprovals.set(requestId, { decision, kind: permissionRequest.kind }); + // The card the user can answer now: asked again under a new + // id when what it is for changes, so the old one can't be. + const card = { + requestId: ApprovalRequestId.make(crypto.randomUUID()), + permissionRequest, + }; + pendingApprovals.set(card.requestId, { decision, kind: permissionRequest.kind }); const warningFor = (kind: EffectAcpSchema.PermissionOption["kind"]) => { const option = offered.find((candidate) => candidate.kind === kind); return option ? descriptor.permissionOptionWarning?.(option) : undefined; @@ -1666,7 +2122,7 @@ export function makeAcpAdapter( } : undefined; const availableDecisions = acpAvailableDecisions(offered); - const shown = yield* showRequest((turnId) => + const openCard = (turnId: TurnId | undefined) => Effect.gen(function* () { yield* offerRuntimeEvent( makeAcpRequestOpenedEvent({ @@ -1674,10 +2130,10 @@ export function makeAcpAdapter( provider: PROVIDER, threadId: input.threadId, turnId, - requestId: runtimeRequestId, - permissionRequest, + requestId: RuntimeRequestId.make(card.requestId), + permissionRequest: card.permissionRequest, detail: - permissionRequest.detail ?? + card.permissionRequest.detail ?? encodeJsonStringForDiagnostics(params)?.slice(0, 2000) ?? "[unserializable params]", args: params, @@ -1688,12 +2144,51 @@ export function makeAcpAdapter( rawPayload: params, }), ); - }), - ); + }); + const shown = yield* showRequest(openCard); + const toolCallId = params.toolCall.toolCallId; + const openApproval = { + reask: (latest: AcpToolCallState) => + Effect.gen(function* () { + const next = reaskedPermissionRequest(params, card.permissionRequest, latest); + if (next === undefined) return; + if (!(yield* Deferred.isDone(shown))) { + // Not on screen yet: it shows as it now is. + card.permissionRequest = next; + return; + } + const turnId = yield* Deferred.await(shown); + const withdrawn = card.requestId; + pendingApprovals.delete(withdrawn); + yield* offerRuntimeEvent( + makeAcpRequestResolvedEvent({ + stamp: yield* makeEventStamp(), + provider: PROVIDER, + threadId: input.threadId, + turnId, + requestId: RuntimeRequestId.make(withdrawn), + permissionRequest: card.permissionRequest, + }), + ); + card.requestId = ApprovalRequestId.make(crypto.randomUUID()); + card.permissionRequest = next; + pendingApprovals.set(card.requestId, { decision, kind: next.kind }); + yield* openCard(turnId); + }), + }; + openApprovals.set(toolCallId, openApproval); // Gone however the wait ends (an interrupted handler included), // or the quiet watch would hold the agent's turn open forever. const resolved = yield* Deferred.await(decision).pipe( - Effect.ensuring(Effect.sync(() => pendingApprovals.delete(requestId))), + Effect.ensuring( + Effect.suspend(() => { + pendingApprovals.delete(card.requestId); + if (openApprovals.get(toolCallId) === openApproval) { + openApprovals.delete(toolCallId); + } + return closeMachineRequest(ctx); + }), + ), ); const turnId = yield* Deferred.await(shown); yield* offerRuntimeEvent( @@ -1702,8 +2197,8 @@ export function makeAcpAdapter( provider: PROVIDER, threadId: input.threadId, turnId, - requestId: runtimeRequestId, - permissionRequest, + requestId: RuntimeRequestId.make(card.requestId), + permissionRequest: card.permissionRequest, decision: resolved, }), ); @@ -1733,11 +2228,16 @@ export function makeAcpAdapter( modelSelection: boundModelSelection, }); + const resumeFailure = + started.resumeFailure ?? + (lostSession !== undefined + ? `${descriptor.presentation.displayName} can no longer continue its earlier conversation.` + : undefined); // A resumed conversation keeps the turn history its cursor carried. const keepsHistory = resumed !== undefined && started.sessionId === resumed.sessionId && - started.resumeFailure === undefined; + resumeFailure === undefined; const history = keepsHistory ? resumed.history.map((entry) => ({ ...entry })) : []; const resumedNewestPosition = keepsHistory ? resumed.newestPosition : forkNewest; // The brief is sent again whenever it changed. Only the thread's @@ -1773,7 +2273,7 @@ export function makeAcpAdapter( projectBriefHash, ), ...(roomToolsRequested ? { roomTools: roomToolsAttached } : {}), - ...(started.resumeFailure !== undefined ? { resumeFailed: true } : {}), + ...(resumeFailure !== undefined ? { resumeFailed: true } : {}), createdAt: now, updatedAt: now, }; @@ -1796,10 +2296,29 @@ export function makeAcpAdapter( lastProviderStatus: undefined, lastContextUsageKey: undefined, acpSessionId: started.sessionId, + promptCapabilities: started.initializeResult.agentCapabilities?.promptCapabilities, + subagentRoster: + descriptor.subagents === undefined + ? undefined + : makeAcpSubagentRoster({ + subagents: descriptor.subagents, + sessionId: started.sessionId, + emit: (event, turnId) => + Effect.gen(function* () { + yield* offerRuntimeEvent({ + ...event, + ...(yield* makeEventStamp()), + provider: PROVIDER, + threadId: input.threadId, + ...(turnId ? { turnId } : {}), + } as ProviderRuntimeEvent); + }), + fork: (effect) => effect.pipe(Effect.forkIn(sessionScope), Effect.asVoid), + }), // A session reopened from elsewhere has spent an unknown amount. costBaselineUsd: (resumeSessionId !== undefined || forkSession !== undefined) && - started.resumeFailure === undefined + resumeFailure === undefined ? undefined : 0, latestCostUsd: undefined, @@ -1807,7 +2326,6 @@ export function makeAcpAdapter( costReportedThisTurn: false, activeReasoning: undefined, cwdRoots: realCwd === cwd ? [cwd] : [cwd, realCwd], - cancelledTurnId: undefined, planMarkdown: undefined, // A switch from another agent starts without the history: the // thread hands it over. (A failed resume is seeded by the reactor.) @@ -1827,7 +2345,20 @@ export function makeAcpAdapter( promptOutcome: undefined, openPrompt: undefined, newestPosition: resumedNewestPosition, + machine: + descriptor.turnMachine === undefined + ? undefined + : { + state: initialTurnMachineState(), + callers: new Map(), + prompts: new Map(), + turns: new Map(), + timers: new Map(), + lastActivityMs: yield* Clock.currentTimeMillis, + outbox: yield* Queue.unbounded(), + }, stopped: false, + closed: yield* Deferred.make(), }; const notificationFiber = yield* Stream.runDrain( @@ -1844,6 +2375,17 @@ export function makeAcpAdapter( case "InOrder": yield* event.run; return; + case "PromptSent": + // Written to the agent (`promptInOrder`): what it carries is delivered. + yield* applyTurnEvent(ctx, { type: "promptDispatched", prompt: event.key }); + return; + case "PromptAnswered": { + // In its place among the updates (`promptInOrder`). + const sent = ctx.machine?.prompts.get(event.key); + if (sent !== undefined) sent.exit = event.answer; + yield* answerMachinePrompt(ctx, event.key); + return; + } case "SessionStatus": if (event.message === ctx.lastProviderStatus) { return; @@ -1863,6 +2405,9 @@ export function makeAcpAdapter( } return; case "ContextUsage": { + // The update that closes each model call: a reply the + // agent started by itself ends with it. + yield* applyTurnEvent(ctx, { type: "replyEnded" }); // Drives the composer's context meter, same event Codex // and Claude send. Not gated on a prompt: the fill after a // resumed session's replay is still the right reading. @@ -1886,6 +2431,15 @@ export function makeAcpAdapter( }); return; } + case "AvailableCommandsUpdated": { + // The composer's `/` list for this session; a side + // runtime answers no messages of its own, so it lists none. + if (descriptor.agentCommands === undefined || ctx.lockdown !== undefined) { + return; + } + yield* noteSessionCommands(ctx, event.commands); + return; + } case "SessionCost": ctx.latestCostUsd = event.totalUsd; // A report between turns marks the boundary exactly. @@ -1894,6 +2448,66 @@ export function makeAcpAdapter( return; case "ModeChanged": return; + case "ToolCallRevised": { + // Changed only in what it would do: an approval open for it is asked again. + const openApproval = openApprovals.get(event.toolCall.toolCallId); + if (openApproval !== undefined) yield* openApproval.reask(event.toolCall); + return; + } + case "ToolCallTracked": + // Work whose updates show nothing new still counts (a + // timer's "Running schedule" stays as it started). + if (ctx.machine !== undefined) { + yield* noteActivity(ctx.machine); + yield* trackMachineWork(ctx, event.toolCall); + } + // A launch approved earlier completes with nothing new to show. + if (ctx.subagentRoster !== undefined) { + yield* ctx.subagentRoster.noteToolCall( + event.toolCall, + ctx.toolCallTurns.get(event.toolCall.toolCallId) ?? ctx.activeTurnId, + ); + } + return; + case "CancellationNotice": { + // The notice a cancel owed is dropped; any other is output. + const commands = + ctx.machine === undefined + ? [] + : yield* applyTurnEvent(ctx, { + type: "cancellationNotice", + newTurnId: crypto.randomUUID(), + }); + if (commands.some((command) => command.type === "dropNotice")) return; + if (ctx.machine === undefined) yield* turnForOutput(ctx); + yield* closeReasoning(ctx); + const segment = yield* acp.openAssistantSegmentNow; + const turnId = ctx.activeTurnId; + if (segment.opened) { + yield* offerRuntimeEvent( + makeAcpAssistantItemEvent({ + stamp: yield* makeEventStamp(), + provider: PROVIDER, + threadId: ctx.threadId, + turnId, + itemId: segment.itemId, + lifecycle: "item.started", + }), + ); + } + yield* offerRuntimeEvent( + makeAcpContentDeltaEvent({ + stamp: yield* makeEventStamp(), + provider: PROVIDER, + threadId: ctx.threadId, + turnId, + itemId: segment.itemId, + text: event.text, + rawPayload: event.rawPayload, + }), + ); + return; + } case "ReasoningDelta": yield* logNative(ctx.threadId, "session/update", event.rawPayload); yield* turnForOutput(ctx); @@ -1935,7 +2549,7 @@ export function makeAcpAdapter( yield* closeReasoning(ctx); yield* logNative(ctx.threadId, "session/update", event.rawPayload); // The plan card stands for the agent's plan-file writes. - if (descriptor.planMode?.isPlanFile(event.toolCall)) { + if (descriptor.planMode?.isPlanFile(event.toolCall, ctx.acpSessionId)) { const planMarkdown = descriptor.planMode.planMarkdown(event.toolCall); if (planMarkdown !== undefined) ctx.planMarkdown = planMarkdown; return; @@ -1945,6 +2559,14 @@ export function makeAcpAdapter( : []; const toolCallId = event.toolCall.toolCallId; const turnId = yield* turnForOutput(ctx, toolCallId); + if (ctx.machine !== undefined) yield* trackMachineWork(ctx, event.toolCall); + if (ctx.subagentRoster !== undefined) { + yield* ctx.subagentRoster.noteToolCall(event.toolCall, turnId); + } + // An approval still open for this call is asked again if + // what it is for has changed. + const openApproval = openApprovals.get(toolCallId); + if (openApproval !== undefined) yield* openApproval.reask(event.toolCall); if ( event.toolCall.status === "completed" || event.toolCall.status === "failed" @@ -1969,14 +2591,6 @@ export function makeAcpAdapter( return; } case "ContentDelta": - if ( - descriptor.cancellationNotice !== undefined && - ctx.cancelledTurnId !== undefined && - ctx.cancelledTurnId === ctx.activeTurnId && - event.text.trim() === descriptor.cancellationNotice - ) { - return; - } yield* turnForOutput(ctx); yield* closeReasoning(ctx); if (ctx.activeTurnText.length < PLAN_GATE_SCAN_MAX_CHARS) { @@ -2004,7 +2618,23 @@ export function makeAcpAdapter( ).pipe(Effect.forkIn(sessionScope)); ctx.notificationFiber = notificationFiber; + if (ctx.machine !== undefined) { + yield* runPromptSender(ctx, ctx.machine).pipe(Effect.forkIn(sessionScope)); + } sessions.set(input.threadId, ctx); + // A turn the machine holds open waits on no request the exit would + // fail: the machine hears of the exit itself. + if (ctx.machine !== undefined && acp.process !== undefined) { + const session = ctx; + yield* acp.process.exited.pipe( + Effect.andThen( + Effect.suspend(() => + session.stopped ? Effect.void : postTurnEvent(session, { type: "processExited" }), + ), + ), + Effect.forkIn(sessionScope), + ); + } sessionScopeTransferred = true; recordHistory(ctx); @@ -2032,7 +2662,7 @@ export function makeAcpAdapter( threadId: input.threadId, payload: { providerThreadId: started.sessionId }, }); - if (started.resumeFailure !== undefined) { + if (resumeFailure !== undefined) { yield* offerRuntimeEvent({ type: "runtime.warning", ...(yield* makeEventStamp()), @@ -2040,7 +2670,7 @@ export function makeAcpAdapter( threadId: input.threadId, payload: { message: `${descriptor.presentation.displayName} could not reopen its earlier conversation, so it starts a new one with this thread's history.`, - detail: started.resumeFailure, + detail: resumeFailure, warningKind: "resume-failed", }, }); @@ -2056,11 +2686,13 @@ export function makeAcpAdapter( ); /** - * A message as ACP content: its text, then each attachment (an image's - * bytes, or a note naming a file the agent reads from disk: ACP prompt - * input has no document type, see buildFileAttachmentNote). + * A message as ACP content: its text, then each attachment. By default an + * image's bytes, or a note naming a file the agent reads from disk (see + * buildFileAttachmentNote); an agent that reads more natively says how + * (`attachmentDelivery`, see AcpPromptAttachments). */ const promptContent = ( + ctx: AcpSessionContext, text: string | undefined, attachments: Parameters[0]["attachments"], method: string, @@ -2068,6 +2700,7 @@ export function makeAcpAdapter( Effect.gen(function* () { const parts: Array = []; if (text !== undefined) parts.push({ type: "text", text }); + const budget: AcpAttachmentBudget = { inlineBytes: 0 }; for (const attachment of attachments ?? []) { const attachmentPath = resolveAttachmentPath({ attachmentsDir: serverConfig.attachmentsDir, @@ -2080,6 +2713,27 @@ export function makeAcpAdapter( detail: `Invalid attachment id '${attachment.id}'.`, }); } + const delivery = descriptor.attachmentDelivery?.(attachment, ctx.promptCapabilities); + if (delivery !== undefined) { + const blocks = yield* acpAttachmentContent({ + attachment, + path: attachmentPath, + delivery, + budget, + }).pipe( + Effect.mapError( + (cause) => + new ProviderAdapterRequestError({ + provider: PROVIDER, + method, + detail: cause.message, + cause, + }), + ), + ); + parts.push(...blocks); + continue; + } if (attachment.type === "file") { parts.push({ type: "text", text: buildFileAttachmentNote(attachment, attachmentPath) }); continue; @@ -2104,51 +2758,869 @@ export function makeAcpAdapter( return parts; }); - // The turn id is returned as soon as `session/prompt` is dispatched — - // orchestration marks the turn accepted from that result, so it must - // land before the streamed items and the completion, exactly as the - // native drivers behave. The prompt itself runs in the session scope. - const sendTurn: AcpAdapterShape["sendTurn"] = (input) => - Effect.flatMap(requireSession(input.threadId), (ctx) => - // One turn start at a time per session: two sends racing here would - // both see no prompt in flight and run their prompts interleaved. - ctx.turnStartLock.withPermit(startTurn(ctx, input)), + /** + * A prompt's answer as its turn ends with it. Multi-provider harnesses + * advertise their whole catalog and reject a plan-gated model as a + * one-line "reply": that is the failure it is, so the chat can offer the + * upgrade page. A refusal that produced no text would render as a + * silently empty turn: it says so instead (`refused` is fx's dialect). + */ + const answeredTurnPayload = ( + stopReason: EffectAcpSchema.StopReason | null | undefined, + activeTurnText: string, + providerStatus: string | undefined, + ): AcpTurnCompletedPayload => { + const turnText = activeTurnText.trim(); + if (stopReason !== "cancelled" && isProviderPlanGateReply(turnText)) { + return { state: "failed", stopReason: "plan_gated", errorMessage: turnText }; + } + if ((stopReason === "refusal" || stopReason === "refused") && turnText.length === 0) { + return { + state: "failed", + stopReason: stopReason ?? null, + ...withFailureCategory(reportedFailureCategory("refusal", providerStatus)), + // A rate-limit retry that ran out also surfaces as a bare refusal; + // the provider's own status tells them apart. + errorMessage: providerStatus + ? `${descriptor.presentation.displayName} returned no output. Provider status: ${providerStatus}` + : `${descriptor.presentation.displayName} reported the model refused this request and returned no output.`, + }; + } + return { + state: stopReason === "cancelled" ? "cancelled" : "completed", + stopReason: stopReason ?? null, + }; + }; + + /** A prompt that failed, in the agent's own words where it gave them. */ + const promptFailurePayload = ( + ctx: AcpSessionContext, + failure: unknown, + ): AcpTurnCompletedPayload => { + const reportedOutcome = ctx.promptOutcome?.state === "failed" ? ctx.promptOutcome : undefined; + const reportedFailure = reportedOutcome?.errorMessage; + const failureCategory = + reportedFailureCategory(reportedOutcome?.failureCategory, ctx.lastProviderStatus) ?? + (isAuthRequiredFailure(failure) ? ("auth" as const) : undefined); + const detail = reportedFailure + ? reportedFailure + : failure instanceof Error + ? mapAcpToAdapterError( + PROVIDER, + ctx.threadId, + "session/prompt", + failure as EffectAcpErrors.AcpError, + ).message + : String(failure); + return { + state: "failed", + stopReason: isProviderPlanGateMessage(detail) ? "plan_gated" : null, + errorMessage: ctx.lastProviderStatus + ? `${detail} Provider status: ${ctx.lastProviderStatus}` + : detail, + ...withFailureCategory(failureCategory), + }; + }; + + /** A prompt's reported tokens, read the agent's way (`turnUsageTotals`). */ + const usageTotalsOf = descriptor.turnUsageTotals ?? acpTurnUsageTotals; + + // ── The turn machine (`descriptor.turnMachine`) ───────────────────── + // + // An agent on the turn machine has one owner for its turn's state: the + // pure reducer in AcpTurnMachine.ts, stepped on the session's event + // reader in order with the agent's updates. Every other source (a send, + // a steer, Stop, a prompt's answer, a timer, the process exiting) posts + // an event there; the commands it returns run here, in order. + + const machineOptions = descriptor.turnMachine; + + /** How the machine's quiet timers last; the cancel deadline is `ACP_CANCEL_DEADLINE`. */ + const quietLimit = (timer: Exclude) => + timer === "settle" + ? ACP_HELD_TURN_SETTLE + : timer === "replyQuiet" + ? (machineOptions?.replyQuietLimit ?? ACP_HELD_REPLY_QUIET_LIMIT) + : (machineOptions?.silentLimit ?? ACP_AGENT_TURN_QUIET_LIMIT); + + /** Events that are the agent doing something: each restarts the quiet timers. */ + const isAgentActivity = (event: AcpMachineEvent) => + event.type !== "send" && + event.type !== "childrenAtWork" && + event.type !== "steer" && + event.type !== "stopRequested" && + event.type !== "timerFired" && + event.type !== "processExited" && + event.type !== "sessionStopping" && + event.type !== "outcomeRead" && + event.type !== "promptDispatched"; + + /** The driver's seams, for tests (`AcpAdapterOptions.turnMachineSeams`). */ + const seam = (point: AcpTurnMachineSeam) => + options?.turnMachineSeams === undefined ? Effect.void : options.turnMachineSeams(point); + + /** The agent did something: quiet timers count from now. */ + const noteActivity = (machine: AcpMachineSession) => + Effect.map(Clock.currentTimeMillis, (now) => { + machine.lastActivityMs = now; + }); + + /** + * Steps the machine with one event, on the event reader, and runs its + * commands. One step is one unit: nothing interrupts it between the + * commit and its last command (a session stop is an event the reader + * gets to after it). + */ + const applyTurnEvent = ( + ctx: AcpSessionContext, + event: AcpMachineEvent, + ): Effect.Effect> => + Effect.uninterruptible( + Effect.gen(function* () { + const machine = ctx.machine; + if (machine === undefined) return []; + if (isAgentActivity(event)) yield* noteActivity(machine); + const step = stepTurnMachine(machine.state, event); + machine.state = step.state; + yield* seam({ + point: "stepCommitted", + event: event.type, + commands: step.commands.map((command) => command.type), + promptsHeld: machine.prompts.size, + }); + for (const command of step.commands) yield* runTurnCommand(ctx, machine, command); + return step.commands; + }), ); - const startTurn = (ctx: AcpSessionContext, input: Parameters[0]) => + /** + * A prompt's answer, stepped: the step reads its usage and starts its + * outcome check (which keeps what it needs), and nothing reads its + * record after, so it goes. Its parts can be large (inline attachments). + * A late answer to a prompt a steer replaced goes the same way. + */ + const answerMachinePrompt = (ctx: AcpSessionContext, prompt: number) => + applyTurnEvent(ctx, { type: "promptAnswered", prompt }).pipe( + Effect.ensuring(Effect.sync(() => void ctx.machine?.prompts.delete(prompt))), + Effect.asVoid, + ); + + /** A request the agent made was answered (or given up on): quiet limits may run again. */ + const closeMachineRequest = (ctx: AcpSessionContext | undefined) => + ctx?.machine === undefined ? Effect.void : postTurnEvent(ctx, { type: "requestClosed" }); + + /** Posts an event to the machine from outside the reader, in order with the updates. */ + const postTurnEvent = (ctx: AcpSessionContext, event: AcpMachineEvent) => + ctx.acp.inOrder(applyTurnEvent(ctx, event).pipe(Effect.asVoid)); + + /** The machine's events for a tool call that goes on after its prompt. */ + const trackMachineWork = (ctx: AcpSessionContext, toolCall: AcpToolCallState) => Effect.gen(function* () { - if (ctx.promptFiber) { - // ACP serializes prompts per session; a turn sent while one is in - // flight starts after it, never interleaved with it. - yield* Fiber.await(ctx.promptFiber); + const work = machineOptions?.workAfterPrompt(toolCall); + const id = toolCall.toolCallId; + // Taken for work before, and now shown to be something else (an MCP + // call the agent ran through a command): it holds nothing. + if (work === undefined) { + const machine = ctx.machine; + if (machine?.state.running.some(([running]) => running === id) === true) { + yield* applyTurnEvent(ctx, { type: "workDropped", id }); + } + return; } - // The reader catches up first, so a turn the agent began before this - // message is open (and ended below) rather than taking its output. - yield* ctx.acp.flushEvents(); + const ended = toolCall.status === "completed" || toolCall.status === "failed"; + if (work.kind === "subagents") { + if (toolCall.status === "completed") { + yield* applyTurnEvent(ctx, { type: "subagentsLaunched", id, count: work.count }); + } + return; + } + yield* applyTurnEvent( + ctx, + ended ? { type: "workEnded", id } : { type: "workStarted", id, kind: work.kind }, + ); + }); + + /** + * Arms one of the machine's timers. A quiet timer fires once its limit + * has passed since the later of its arming and the agent's last + * activity: activity while it waits moves the end, not the whole wait. + */ + const armTurnTimer = ( + ctx: AcpSessionContext, + machine: AcpMachineSession, + timer: AcpTurnTimer, + generation: number, + ): Effect.Effect => + Effect.gen(function* () { + const armedAt = yield* Clock.currentTimeMillis; + const quiet = + timer !== "cancelDeadline" && timer !== "noticeExpiry" && timer !== "stopCheck"; + const limit = + timer === "cancelDeadline" + ? ACP_CANCEL_DEADLINE + : timer === "noticeExpiry" + ? ACP_NOTICE_EXPIRY + : timer === "stopCheck" + ? ACP_STOP_CHECK_INTERVAL + : quietLimit(timer); + const limitMs = Duration.toMillis(limit); + const wait = (ms: number): Effect.Effect => + Effect.sleep(Duration.millis(ms)).pipe( + Effect.andThen( + ctx.acp.inOrder( + Effect.gen(function* () { + const armed = machine.state.timers.find(([name]) => name === timer); + if (armed?.[1] !== generation) return; + const since = quiet ? Math.max(armedAt, machine.lastActivityMs) : armedAt; + const left = since + limitMs - (yield* Clock.currentTimeMillis); + if (left > 0) { + const fiber = yield* wait(left).pipe(Effect.forkIn(ctx.scope)); + machine.timers.set(timer, fiber); + return; + } + yield* applyTurnEvent(ctx, { type: "timerFired", timer, generation }); + }), + ), + ), + ); + machine.timers.set(timer, yield* wait(limitMs).pipe(Effect.forkIn(ctx.scope))); + }); + + /** + * The session's one prompt sender: takes the machine's prompts in the + * order it sent them, and sends each (its turn's mode and model setup + * first) only after the one before it is on the wire, so a steer never + * reaches the agent ahead of the prompt it steers. A prompt's answer + * reaches the machine as the reader reads it (`PromptAnswered`); one that + * never went out answers with why. + */ + const runPromptSender = (ctx: AcpSessionContext, machine: AcpMachineSession) => + Effect.forever( + Queue.take(machine.outbox).pipe( + Effect.flatMap((prompt) => sendMachinePrompt(ctx, machine, prompt)), + ), + ); + + /** Sends one prompt for the sender: returns once it is on the wire (or failed to go). */ + const sendMachinePrompt = ( + ctx: AcpSessionContext, + machine: AcpMachineSession, + prompt: number, + ) => + Effect.gen(function* () { + const sent = machine.prompts.get(prompt); + if (sent === undefined) return; + const exit = yield* Effect.exit( + Effect.gen(function* () { + if (sent.configure !== undefined) yield* sent.configure; + yield* seam({ point: "promptSetup", prompt }); + // Where the agent's records stand as this prompt goes out. + sent.watch = + machineOptions?.outcome === undefined + ? undefined + : yield* machineOptions.outcome.watch(ctx.acpSessionId, sent.model).pipe( + // A stalled file system must not hold every prompt behind this one. + Effect.timeoutOption(ACP_OUTCOME_WATCH_TIMEOUT), + Effect.map(Option.getOrUndefined), + Effect.catchCause((cause) => + Effect.logWarning("acp.prompt-outcome.watch-failed", { + provider: PROVIDER, + cause: Cause.pretty(cause), + }).pipe(Effect.as(undefined)), + ), + ); + const promptMeta = descriptor.promptMeta?.(sent.turnId); + yield* ctx.acp.promptInOrder( + prompt, + { + prompt: [...sent.parts], + ...(promptMeta ? { _meta: { ...promptMeta } } : {}), + }, + seam({ point: "answerRead", prompt }), + ); + }), + ); + // A stopping session ends the turn itself. + if (Exit.isSuccess(exit) || Cause.hasInterruptsOnly(exit.cause)) return; + yield* ctx.acp.inOrder( + Effect.suspend(() => { + sent.exit = Exit.failCause(exit.cause); + return answerMachinePrompt(ctx, prompt); + }).pipe(Effect.asVoid), + ); + }); + + /** + * How a machine prompt's answer reads: the payload its turn ends with, + * after the agent's own records had their say (`outcome`). `seen` is what + * the reader had when the answer arrived. + */ + const readMachineOutcome = ( + ctx: AcpSessionContext, + sent: AcpMachinePromptSent, + seen: { + readonly turnText: string; + readonly providerStatus: string | undefined; + }, + ): Effect.Effect> => + Effect.gen(function* () { + const exit = sent.exit; + const check = (answer: Parameters[0]) => + sent.watch === undefined + ? Effect.succeed(undefined) + : sent.watch.check(answer).pipe( + // A check that hangs (a network read) must not hold the turn. + Effect.timeoutOption(ACP_OUTCOME_CHECK_TIMEOUT), + Effect.map(Option.getOrUndefined), + Effect.catchCause((cause) => + Effect.logWarning("acp.prompt-outcome.check-failed", { + provider: PROVIDER, + cause: Cause.pretty(cause), + }).pipe(Effect.as(undefined)), + ), + ); + if (exit !== undefined && Exit.isSuccess(exit)) { + const result = exit.value; + ctx.turns.push({ id: sent.turnId, items: [{ prompt: sent.parts, result }] }); + ctx.session = { + ...ctx.session, + updatedAt: yield* nowIso, + ...(sent.resolvedModel !== undefined ? { model: sent.resolvedModel } : {}), + }; + const hidden = + result.stopReason === "cancelled" ? undefined : yield* check({ response: result }); + const payload = hidden + ? failedTurnPayload(hidden, result.stopReason ?? null) + : answeredTurnPayload(result.stopReason, seen.turnText, seen.providerStatus); + return { + state: turnPayloadState(payload), + answer: payload, + sessionLost: hidden?.sessionLost === true, + }; + } + // The agent may never have taken the prompt: the brief goes again. + if (ctx.projectBriefCarrier?.turnId === sent.turnId) requeueProjectBrief(ctx); + const failure = exit === undefined ? undefined : Cause.squash(exit.cause); + yield* notifyAuthRequired(failure); + const reported = yield* check({ error: failure }); + const payload = reported + ? failedTurnPayload(reported, null) + : promptFailurePayload(ctx, failure); + return { state: "failed", answer: payload, sessionLost: reported?.sessionLost === true }; + }); + + /** Carries out one of the machine's commands. Runs on the event reader: nothing here waits long. */ + const runTurnCommand = ( + ctx: AcpSessionContext, + machine: AcpMachineSession, + command: AcpMachineCommand, + ): Effect.Effect => + Effect.gen(function* () { + switch (command.type) { + case "startTurn": { + const turnId = TurnId.make(command.turnId); + const caller = + command.sendId === undefined ? undefined : machine.callers.get(command.sendId); + ctx.activeTurnId = turnId; + resetTurnState(ctx); + ctx.history.push( + caller?.messageId !== undefined + ? { turnId, messageId: caller.messageId } + : caller !== undefined + ? { turnId } + : { turnId, agentTurn: true }, + ); + recordHistory(ctx); + ctx.session = { ...ctx.session, activeTurnId: turnId, updatedAt: yield* nowIso }; + machine.turns.set(command.turnId, { + model: caller?.prompt.model ?? ctx.session.model, + resolvedModel: caller?.prompt.resolvedModel ?? resolveModelId(ctx.session.model), + planMode: caller?.planMode, + }); + yield* offerRuntimeEvent({ + type: "turn.started", + ...(yield* makeEventStamp()), + provider: PROVIDER, + threadId: ctx.threadId, + turnId, + payload: caller !== undefined ? { model: caller.prompt.resolvedModel } : {}, + ...(caller === undefined + ? { raw: { source: "acp.jsonrpc" as const, method: "session/update", payload: {} } } + : {}), + }); + return; + } + case "sendPrompt": { + const callerId = + "sendId" in command.source ? command.source.sendId : command.source.steerId; + const caller = machine.callers.get(callerId); + const turn = machine.turns.get(command.turnId); + if (caller === undefined) return; + const turnPrompts = machine.state.turn?.prompts ?? []; + const sent: AcpMachinePromptSent = { + ...caller.prompt, + turnId: TurnId.make(command.turnId), + // Its place in the turn: a steer's prompt has a usage line of its own. + index: turnPrompts.indexOf(command.prompt) + 1, + model: caller.prompt.model ?? turn?.model, + resolvedModel: caller.prompt.resolvedModel ?? turn?.resolvedModel, + watch: undefined, + exit: undefined, + }; + machine.prompts.set(command.prompt, sent); + yield* Queue.offer(machine.outbox, command.prompt); + return; + } + case "reportDelivery": { + const sent = machine.prompts.get(command.prompt); + if (sent === undefined) return; + if (!command.delivered) { + // Never written: the context it carried waits for the next message. + if (sent.preamble !== undefined && ctx.pendingContextPreamble === undefined) { + ctx.pendingContextPreamble = sent.preamble; + } + if (ctx.projectBriefCarrier?.turnId === sent.turnId) requeueProjectBrief(ctx); + } + if (sent.delivered !== undefined) { + yield* Deferred.succeed(sent.delivered, command.delivered); + } + return; + } + case "acceptSend": + case "acceptSteer": + case "rejectSend": + case "rejectSteer": { + const callerId = "sendId" in command ? command.sendId : command.steerId; + const caller = machine.callers.get(callerId); + machine.callers.delete(callerId); + if (caller === undefined) return; + yield* Deferred.succeed( + caller.reply, + command.type === "acceptSend" || command.type === "acceptSteer" + ? { accepted: TurnId.make(command.turnId) } + : { rejected: command.type === "rejectSteer" ? command.reason : "no-active-turn" }, + ); + return; + } + case "readOutcome": { + const sent = machine.prompts.get(command.prompt); + if (sent === undefined) return; + const seen = { turnText: ctx.activeTurnText, providerStatus: ctx.lastProviderStatus }; + yield* seam({ point: "outcomeRead", prompt: command.prompt }).pipe( + Effect.andThen(readMachineOutcome(ctx, sent, seen)), + Effect.flatMap((outcome) => + postTurnEvent(ctx, { type: "outcomeRead", prompt: command.prompt, outcome }), + ), + Effect.forkIn(ctx.scope), + ); + return; + } + case "readChildren": { + // The agent's own records, off the reader and bounded. A launch + // counts only for the child its own call id started, so records + // from before a resume, or of another launch, prove nothing; one + // the records don't tie to a single child is left out, and the + // protocol count stands for it. + const states = descriptor.subagents?.states; + if (states === undefined) return; + const { generation, launches } = command; + yield* states({ + sessionId: ctx.acpSessionId, + launchCallIds: launches.map(([id]) => id), + }).pipe( + Effect.timeoutOption(ACP_OUTCOME_CHECK_TIMEOUT), + Effect.map(Option.getOrUndefined), + Effect.tap(() => seam({ point: "childrenRead", generation })), + Effect.flatMap((reading) => { + if (reading === undefined) return Effect.void; + const covered = launches.flatMap(([id, count]) => { + const child = reading.byLaunch.get(id); + return child === undefined || count !== 1 + ? [] + : [[id, child.state === "working" ? 1 : 0] as const]; + }); + return postTurnEvent(ctx, { + type: "childrenAtWork", + generation, + launches: covered, + }); + }), + Effect.forkIn(ctx.scope), + ); + return; + } + case "recordUsage": { + const sent = machine.prompts.get(command.prompt); + if (sent === undefined) return; + const exit = sent.exit; + const totals = + exit !== undefined && Exit.isSuccess(exit) ? usageTotalsOf(exit.value.usage) : null; + yield* recordMachinePromptUsage(ctx, sent, totals); + return; + } + case "sendCancel": + yield* ctx.acp.cancel.pipe(Effect.ignore, Effect.forkIn(ctx.scope)); + return; + case "endTurn": + yield* endMachineTurn(ctx, machine, command.turnId, command.end); + return; + case "armTimer": { + const previous = machine.timers.get(command.timer); + if (previous !== undefined) yield* Fiber.interrupt(previous); + yield* armTurnTimer(ctx, machine, command.timer, command.generation); + return; + } + case "disarmTimer": { + const fiber = machine.timers.get(command.timer); + machine.timers.delete(command.timer); + if (fiber !== undefined) yield* Fiber.interrupt(fiber); + return; + } + case "recycleAgent": + // Stopped first, so nothing the agent does lands after the turn's end. + yield* offerRuntimeEvent({ + type: "runtime.warning", + ...(yield* makeEventStamp()), + provider: PROVIDER, + threadId: ctx.threadId, + ...(ctx.activeTurnId !== undefined ? { turnId: ctx.activeTurnId } : {}), + payload: { + message: `${descriptor.presentation.displayName} did not stop in time, so it was restarted. The next message picks the conversation up again.`, + warningKind: "cancel-timeout", + }, + }); + yield* stopFromMachine(ctx, "graceful"); + return; + case "stopSession": + // A lost conversation: ProviderService forgets it in the thread's + // binding, if the binding still names this one. + yield* stopFromMachine( + ctx, + command.reason === "exited" ? "error" : "graceful", + command.reason === "sessionLost" + ? { conversationLost: { sessionCreatedAt: ctx.session.createdAt } } + : undefined, + ); + return; + case "markSessionLost": + // Before the session ends: a start racing ProviderService's forget opens anew. + lostSessions.add(ctx.acpSessionId); + return; + case "dropNotice": + return; + } + }); + + /** Stops the session from a machine command, off the reader (stopping interrupts it). */ + const stopFromMachine = ( + ctx: AcpSessionContext, + exitKind: "graceful" | "error", + exit?: { readonly conversationLost?: { readonly sessionCreatedAt: string } }, + ) => + withThreadLock( + ctx.threadId, + Effect.suspend(() => + sessions.get(ctx.threadId) === ctx + ? stopSessionInternal(ctx, exitKind, exit) + : Effect.void, + ), + ).pipe(Effect.forkIn(adapterScope), Effect.asVoid); + + /** + * Writes one answered prompt's tokens, and the session's reported cost + * since the last line, so neither waits for the turn's end (a hold, a stop + * or a restart would lose it). A steered prompt has an id of its own. + */ + const recordMachinePromptUsage = ( + ctx: AcpSessionContext, + sent: AcpMachinePromptSent, + totals: UsageTokenTotals | null, + ) => + Effect.gen(function* () { + const costUsd = takeReportedCost(ctx); + const record = options?.recordTurnUsage; + if (!record || (totals === null && costUsd === null)) return; + yield* record({ + atMs: yield* Clock.currentTimeMillis, + sessionId: ctx.acpSessionId, + turnId: sent.index <= 1 ? sent.turnId : `${sent.turnId}:${sent.index}`, + model: sent.resolvedModel ?? ctx.session.model ?? "default", + totals: totals ?? EMPTY_USAGE_TOTALS, + costUsd, + }).pipe(Effect.forkIn(adapterScope)); + }); + + /** + * The session's running cost spent since the last line written, when it + * is known exactly; the baseline moves to where it now stands. + */ + const takeReportedCost = (ctx: AcpSessionContext): number | null => { + if (!ctx.costReportedThisTurn) return null; + const costUsd = + ctx.costBaselineUsd !== undefined && ctx.latestCostUsd !== undefined + ? Math.max(0, ctx.latestCostUsd - ctx.costBaselineUsd) + : null; + ctx.costBaselineUsd = ctx.latestCostUsd; + ctx.costReportedThisTurn = false; + return costUsd; + }; + + /** The turn's one terminal event, after its reply and thought close in place. */ + const endMachineTurn = ( + ctx: AcpSessionContext, + machine: AcpMachineSession, + turnId: string, + end: AcpTurnEnd, + ) => + Effect.gen(function* () { + const id = TurnId.make(turnId); + const data = machine.turns.get(turnId); + machine.turns.delete(turnId); + const closedItem = yield* ctx.acp.closeAssistantSegmentNow; + if (closedItem !== undefined) { + yield* offerRuntimeEvent( + makeAcpAssistantItemEvent({ + stamp: yield* makeEventStamp(), + provider: PROVIDER, + threadId: ctx.threadId, + turnId: id, + itemId: closedItem, + lifecycle: "item.completed", + }), + ); + } + yield* closeReasoning(ctx); + const planMarkdown = data?.planMode ? ctx.planMarkdown?.trim() : undefined; + if (planMarkdown && end.kind === "answered" && end.outcome.state === "completed") { + yield* offerRuntimeEvent({ + type: "turn.proposed.completed", + ...(yield* makeEventStamp()), + provider: PROVIDER, + threadId: ctx.threadId, + turnId: id, + payload: { planMarkdown }, + }); + } + if (ctx.activeTurnId === id) { + ctx.activeTurnId = undefined; + ctx.session = { ...ctx.session, activeTurnId: undefined, updatedAt: yield* nowIso }; + } + const stamp = yield* makeEventStamp(); + if (end.kind === "aborted") { + yield* offerRuntimeEvent({ + type: "turn.aborted", + ...stamp, + provider: PROVIDER, + threadId: ctx.threadId, + turnId: id, + payload: { reason: "The session stopped." }, + }); + } else { + yield* offerRuntimeEvent({ + type: "turn.completed", + ...stamp, + provider: PROVIDER, + threadId: ctx.threadId, + turnId: id, + payload: + end.kind === "answered" + ? end.outcome.answer + : end.kind === "agentDone" + ? { state: "completed", stopReason: null } + : end.kind === "stopped" + ? { state: "cancelled", stopReason: "cancelled" } + : { + state: "failed", + stopReason: null, + errorMessage: `${descriptor.presentation.displayName} stopped before its work finished.`, + }, + }); + } + // Cost reported after the turn's last prompt answered (its own replies). + const costUsd = takeReportedCost(ctx); + ctx.costTurnOpen = false; + const record = options?.recordTurnUsage; + if (record && costUsd !== null && costUsd > 0) { + yield* record({ + atMs: yield* Clock.currentTimeMillis, + sessionId: ctx.acpSessionId, + turnId: `${turnId}:after`, + model: data?.resolvedModel ?? ctx.session.model ?? "default", + totals: EMPTY_USAGE_TOTALS, + costUsd, + }).pipe(Effect.forkIn(adapterScope)); + } + }); + + /** A message for a machine agent: prepared here, started by the machine when its turn comes. */ + const sendTurnByMachine = ( + ctx: AcpSessionContext, + machine: AcpMachineSession, + input: Parameters[0], + ) => + Effect.gen(function* () { + const turnId = TurnId.make(crypto.randomUUID()); + const prepared = yield* prepareTurnPrompt(ctx, input); + carryPromptPreface(ctx, turnId, prepared); + const reply = yield* Deferred.make(); + const delivered = yield* Deferred.make(); + const sendId = `send:${turnId}`; + /** A send that never went out leaves the context it took for the next. */ + const keepContext = () => { + if (prepared.contextPreamble !== undefined && ctx.pendingContextPreamble === undefined) { + ctx.pendingContextPreamble = prepared.contextPreamble; + } + if (ctx.projectBriefCarrier?.turnId === turnId) requeueProjectBrief(ctx); + }; + machine.callers.set(sendId, { + prompt: { + parts: prepared.promptParts, + configure: prepared.configure, + model: prepared.model, + resolvedModel: prepared.resolvedModel, + preamble: prepared.contextPreamble, + delivered, + }, + ...(input.messageId !== undefined ? { messageId: input.messageId } : {}), + planMode: prepared.planMode, + reply, + }); if (ctx.stopped) { + machine.callers.delete(sendId); + keepContext(); return yield* new ProviderAdapterSessionNotFoundError({ provider: PROVIDER, threadId: input.threadId, }); } - // A message sent while the agent runs a turn of its own ends that - // turn here; the agent takes the message after it, as Claude does. - if (ctx.agentTurn !== undefined) { - yield* closeAgentTurn(ctx, { state: "completed" }); + yield* postTurnEvent(ctx, { type: "send", sendId, turnId }); + const answer = yield* Deferred.await(reply); + if ("rejected" in answer) { + keepContext(); + return yield* new ProviderAdapterSessionNotFoundError({ + provider: PROVIDER, + threadId: input.threadId, + }); } - const turnId = TurnId.make(crypto.randomUUID()); + // Returns once the prompt was written, or its setup failed first: + // only a written prompt delivered the message and the context in + // front of it (`undelivered`). A stop settles this too. + const written = yield* Deferred.await(delivered); + return { + threadId: input.threadId, + turnId, + resumeCursor: ctx.session.resumeCursor, + // A typed agent command left the thread's history and brief owed. + ...(prepared.contextDeferred ? { contextDeferred: true as const } : {}), + ...(written ? {} : { undelivered: true as const }), + }; + }); + + /** A message sent mid-turn to a machine agent: another prompt of the running turn. */ + const steerTurnByMachine: NonNullable = (input) => + Effect.gen(function* () { + const ctx = yield* requireSession(input.threadId); + const machine = ctx.machine; + if (machine === undefined) { + return yield* steerRejectedError( + PROVIDER, + descriptor.presentation.displayName, + "no-active-turn", + ); + } + const text = input.input?.trim() ?? ""; + const parts = yield* promptContent( + ctx, + text.length > 0 ? text : undefined, + input.attachments, + "turn/steer", + ); + const reply = yield* Deferred.make(); + const steerId = `steer:${crypto.randomUUID()}`; + machine.callers.set(steerId, { + prompt: { + parts, + configure: undefined, + model: undefined, + resolvedModel: undefined, + preamble: undefined, + delivered: undefined, + }, + planMode: undefined, + reply, + }); + if (ctx.stopped) { + machine.callers.delete(steerId); + return yield* steerRejectedError( + PROVIDER, + descriptor.presentation.displayName, + "no-active-turn", + ); + } + yield* postTurnEvent(ctx, { + type: "steer", + steerId, + expectedTurnId: input.expectedTurnId, + }); + const answer = yield* Deferred.await(reply); + if ("rejected" in answer) { + return yield* steerRejectedError( + PROVIDER, + descriptor.presentation.displayName, + answer.rejected, + ); + } + return { + threadId: input.threadId, + turnId: answer.accepted, + resumeCursor: ctx.session.resumeCursor, + }; + }); + + /** + * A message's prompt as the agent gets it: the thread's history and the + * project's brief in front when owed, plan mode's prefix, the attachments. + */ + const prepareTurnPrompt = ( + ctx: AcpSessionContext, + input: Parameters[0], + ) => + Effect.gen(function* () { const turnModelSelection = input.modelSelection?.instanceId === boundInstanceId ? input.modelSelection : undefined; const model = turnModelSelection?.model ?? ctx.session.model; const resolvedModel = resolveModelId(model); + // The agent runs a command (or a skill) only when the message starts + // with it. A message is one only when the person's own typed text, + // trimmed (never the context in front of it, never plain text or an + // agent's words), starts with `/` and a name the session advertised + // or a skill the status lists. It then goes alone, as typed: no plan prefix, and + // the context the server put in front of it, the earlier conversation + // and the project brief wait for the next message (`contextDeferred` + // tells the server its debts stay). + const typed = input.typed; + const typedCommand = + descriptor.agentCommands !== undefined && typed !== undefined + ? slashCommandAtStart(typed.text.trim()) + : undefined; + const sendsAgentCommand = + typedCommand !== undefined && (yield* isAgentCommand(ctx, typedCommand)); + const userText = + sendsAgentCommand && typed ? typed.text.trim() : (input.input?.trim() ?? ""); + const contextDeferred = + sendsAgentCommand && + (typed?.context !== undefined || ctx.pendingContextPreamble !== undefined); // Prompt-command plan mode (Antigravity's `/plan`) is a text prefix. const lockedDown = ctx.lockdown !== undefined; const planMode = - input.interactionMode === "plan" && !lockedDown ? descriptor.planMode : undefined; - const contextPreamble = ctx.pendingContextPreamble; - const projectBrief = ctx.projectBrief; - const userText = input.input?.trim() ?? ""; + input.interactionMode === "plan" && !lockedDown && !sendsAgentCommand + ? descriptor.planMode + : undefined; + const contextPreamble = sendsAgentCommand ? undefined : ctx.pendingContextPreamble; + const projectBrief: ProjectBriefPreface = sendsAgentCommand + ? { text: undefined, hash: ctx.projectBrief.hash } + : ctx.projectBrief; const contextText = contextPreamble !== undefined ? withContextSeedPreamble(contextPreamble, userText) @@ -2161,6 +3633,7 @@ export function makeAcpAdapter( : projectBrief.text : contextText; const promptParts = yield* promptContent( + ctx, seededText.length > 0 || planMode ? planMode ? `${planMode.promptPrefix}${seededText}` @@ -2169,7 +3642,6 @@ export function makeAcpAdapter( input.attachments, "session/prompt", ); - if (promptParts.length === 0) { return yield* new ProviderAdapterValidationError({ provider: PROVIDER, @@ -2177,29 +3649,100 @@ export function makeAcpAdapter( issue: "Turn requires non-empty text or attachments.", }); } - - yield* applyRequestedSessionConfiguration({ - runtime: ctx.acp, - threadId: input.threadId, - runtimeMode: ctx.session.runtimeMode, - interactionMode: input.interactionMode, - lockedDown, - modelSelection: - model === undefined ? undefined : { model, options: turnModelSelection?.options }, + // The mode and model the message asks for, set before its prompt goes out. + const configure = Effect.gen(function* () { + yield* applyRequestedSessionConfiguration({ + runtime: ctx.acp, + threadId: input.threadId, + runtimeMode: ctx.session.runtimeMode, + interactionMode: input.interactionMode, + lockedDown, + modelSelection: + model === undefined ? undefined : { model, options: turnModelSelection?.options }, + }); + const turnModeId = lockedDown + ? undefined + : descriptor.sessionModeForTurn?.(input.interactionMode); + const sessionId = parseAcpResumeCursor(ctx.session.resumeCursor)?.sessionId; + if (turnModeId !== undefined && sessionId !== undefined) { + yield* ctx.acp + .request("session/set_mode", { sessionId, modeId: turnModeId }) + .pipe( + Effect.mapError((cause) => + mapAcpToAdapterError(PROVIDER, input.threadId, "session/set_mode", cause), + ), + ); + } }); - const turnModeId = lockedDown - ? undefined - : descriptor.sessionModeForTurn?.(input.interactionMode); - const sessionId = parseAcpResumeCursor(ctx.session.resumeCursor)?.sessionId; - if (turnModeId !== undefined && sessionId !== undefined) { - yield* ctx.acp - .request("session/set_mode", { sessionId, modeId: turnModeId }) - .pipe( - Effect.mapError((cause) => - mapAcpToAdapterError(PROVIDER, input.threadId, "session/set_mode", cause), - ), - ); + return { + model, + resolvedModel, + planMode, + contextPreamble, + projectBrief, + promptParts, + configure, + contextDeferred, + }; + }); + + /** The turn carries the history and brief its prompt led with: they are not owed again. */ + const carryPromptPreface = ( + ctx: AcpSessionContext, + turnId: TurnId, + prepared: Effect.Success>, + ) => { + if (prepared.contextPreamble !== undefined) ctx.pendingContextPreamble = undefined; + const projectBrief = prepared.projectBrief; + if (projectBrief.text !== undefined) { + ctx.projectBriefCarrier = { + turnId, + preface: projectBrief, + hashBefore: ctx.projectBriefHash, + }; + ctx.projectBrief = { text: undefined, hash: projectBrief.hash }; + ctx.projectBriefHash = projectBrief.hash; + } + }; + + // The turn id is returned as soon as `session/prompt` is dispatched — + // orchestration marks the turn accepted from that result, so it must + // land before the streamed items and the completion, exactly as the + // native drivers behave. The prompt itself runs in the session scope. + const sendTurn: AcpAdapterShape["sendTurn"] = (input) => + Effect.flatMap(requireSession(input.threadId), (ctx) => + ctx.machine !== undefined + ? sendTurnByMachine(ctx, ctx.machine, input) + : // One turn start at a time per session: two sends racing here would + // both see no prompt in flight and run their prompts interleaved. + ctx.turnStartLock.withPermit(startTurn(ctx, input)), + ); + + const startTurn = (ctx: AcpSessionContext, input: Parameters[0]) => + Effect.gen(function* () { + if (ctx.promptFiber) { + // ACP serializes prompts per session; a turn sent while one is in + // flight starts after it, never interleaved with it. + yield* Fiber.await(ctx.promptFiber); + } + // The reader catches up first, so a turn the agent began before this + // message is open (and ended below) rather than taking its output. + yield* ctx.acp.flushEvents(); + if (ctx.stopped) { + return yield* new ProviderAdapterSessionNotFoundError({ + provider: PROVIDER, + threadId: input.threadId, + }); + } + // A message sent while the agent runs a turn of its own ends that + // turn here; the agent takes the message after it, as Claude does. + if (ctx.agentTurn !== undefined) { + yield* closeAgentTurn(ctx, { state: "completed" }); } + const turnId = TurnId.make(crypto.randomUUID()); + const prepared = yield* prepareTurnPrompt(ctx, input); + const { planMode, resolvedModel, promptParts } = prepared; + yield* prepared.configure; ctx.activeTurnId = turnId; const prompt = { turnId, @@ -2208,16 +3751,7 @@ export function makeAcpAdapter( }; ctx.openPrompt = prompt; resetTurnState(ctx); - ctx.pendingContextPreamble = undefined; - if (projectBrief.text !== undefined) { - ctx.projectBriefCarrier = { - turnId, - preface: projectBrief, - hashBefore: ctx.projectBriefHash, - }; - ctx.projectBrief = { text: undefined, hash: projectBrief.hash }; - ctx.projectBriefHash = projectBrief.hash; - } + carryPromptPreface(ctx, turnId, prepared); ctx.session = { ...ctx.session, activeTurnId: turnId, updatedAt: yield* nowIso }; ctx.history.push({ turnId, @@ -2280,46 +3814,19 @@ export function makeAcpAdapter( updatedAt: yield* nowIso, ...(resolvedModel !== undefined ? { model: resolvedModel } : {}), }; - // Multi-provider harnesses advertise their whole catalog and - // reject a plan-gated model as a one-line "reply" — surface that - // as the failure it is so the chat can offer the upgrade page. - const turnText = ctx.activeTurnText.trim(); - const planGateMessage = - result.stopReason !== "cancelled" && isProviderPlanGateReply(turnText) - ? turnText - : undefined; - // A refusal that produced no text would render as a silently - // empty turn; say so instead. (`refused` is fx's dialect.) - const silentRefusal = - (result.stopReason === "refusal" || result.stopReason === "refused") && - turnText.length === 0; yield* offerRuntimeEvent({ type: "turn.completed", ...(yield* makeEventStamp()), provider: PROVIDER, threadId: input.threadId, turnId, - payload: planGateMessage - ? { state: "failed", stopReason: "plan_gated", errorMessage: planGateMessage } - : silentRefusal - ? { - state: "failed", - stopReason: result.stopReason ?? null, - ...withFailureCategory( - reportedFailureCategory("refusal", ctx.lastProviderStatus), - ), - // A rate-limit retry that ran out also surfaces as a - // bare refusal; the provider's own status tells them apart. - errorMessage: ctx.lastProviderStatus - ? `${descriptor.presentation.displayName} returned no output. Provider status: ${ctx.lastProviderStatus}` - : `${descriptor.presentation.displayName} reported the model refused this request and returned no output.`, - } - : { - state: result.stopReason === "cancelled" ? "cancelled" : "completed", - stopReason: result.stopReason ?? null, - }, + payload: answeredTurnPayload( + result.stopReason, + ctx.activeTurnText, + ctx.lastProviderStatus, + ), }); - yield* settleTurnUsage(ctx, turnId, resolvedModel, result.usage); + yield* settleTurnUsage(ctx, turnId, resolvedModel, usageTotalsOf(result.usage)); return; } if (Cause.hasInterruptsOnly(exit.cause)) { @@ -2329,39 +3836,16 @@ export function makeAcpAdapter( if (ctx.projectBriefCarrier?.turnId === turnId) requeueProjectBrief(ctx); const failure = Cause.squash(exit.cause); yield* notifyAuthRequired(failure); - const reportedOutcome = - ctx.promptOutcome?.state === "failed" ? ctx.promptOutcome : undefined; - const reportedFailure = reportedOutcome?.errorMessage; - const failureCategory = - reportedFailureCategory(reportedOutcome?.failureCategory, ctx.lastProviderStatus) ?? - (isAuthRequiredFailure(failure) ? ("auth" as const) : undefined); - const detail = reportedFailure - ? reportedFailure - : failure instanceof Error - ? mapAcpToAdapterError( - PROVIDER, - input.threadId, - "session/prompt", - failure as EffectAcpErrors.AcpError, - ).message - : String(failure); yield* offerRuntimeEvent({ type: "turn.completed", ...(yield* makeEventStamp()), provider: PROVIDER, threadId: input.threadId, turnId, - payload: { - state: "failed", - stopReason: isProviderPlanGateMessage(detail) ? "plan_gated" : null, - errorMessage: ctx.lastProviderStatus - ? `${detail} Provider status: ${ctx.lastProviderStatus}` - : detail, - ...withFailureCategory(failureCategory), - }, + payload: promptFailurePayload(ctx, failure), }); // No result, so no tokens; a running cost the agent reported still counts. - yield* settleTurnUsage(ctx, turnId, resolvedModel, undefined); + yield* settleTurnUsage(ctx, turnId, resolvedModel, null); }).pipe( Effect.ensuring( Effect.gen(function* () { @@ -2376,7 +3860,13 @@ export function makeAcpAdapter( ); ctx.promptFiber = yield* Effect.forkIn(runPrompt, ctx.scope); - return { threadId: input.threadId, turnId, resumeCursor: ctx.session.resumeCursor }; + return { + threadId: input.threadId, + turnId, + resumeCursor: ctx.session.resumeCursor, + // A typed agent command left the thread's history and brief owed. + ...(prepared.contextDeferred ? { contextDeferred: true as const } : {}), + }; }); /** @@ -2417,9 +3907,13 @@ export function makeAcpAdapter( const ctx = yield* requireSession(threadId); const turnId = ctx.activeTurnId; const promptFiber = ctx.promptFiber; - if (turnId !== undefined) ctx.cancelledTurnId = turnId; yield* settlePendingApprovalsAsCancelled(ctx.pendingApprovals); yield* settlePendingUserInputsAsEmptyAnswers(ctx.pendingUserInputs); + // The turn machine sends the cancel, arms the deadline and ends the turn. + if (ctx.machine !== undefined) { + yield* postTurnEvent(ctx, { type: "stopRequested" }); + return; + } yield* Effect.ignore( ctx.acp.cancel.pipe( Effect.mapError((error) => @@ -2447,7 +3941,10 @@ export function makeAcpAdapter( } }); - /** A message sent mid-turn, added to the running turn (`descriptor.steer`). */ + /** + * A message sent mid-turn, added to the running turn: by the agent's own + * steer (`descriptor.steer`), or as another prompt (`turnMachine`). + */ const steerTurn: AcpAdapterShape["steerTurn"] = descriptor.steer ? (input) => Effect.gen(function* () { @@ -2470,6 +3967,7 @@ export function makeAcpAdapter( } const text = input.input?.trim() ?? ""; const content = yield* promptContent( + ctx, text.length > 0 ? text : undefined, input.attachments, "turn/steer", @@ -2485,7 +3983,9 @@ export function makeAcpAdapter( ); return { threadId: input.threadId, turnId, resumeCursor: ctx.session.resumeCursor }; }) - : undefined; + : descriptor.turnMachine?.steer === true + ? steerTurnByMachine + : undefined; const respondToRequest: AcpAdapterShape["respondToRequest"] = (threadId, requestId, decision) => Effect.gen(function* () { @@ -2527,7 +4027,8 @@ export function makeAcpAdapter( * to the first reverted message's prompt, so it forgets the reverted * turns. Without a known position for that prompt (a turn before this * cursor's history, or a prompt the agent couldn't place) the agent - * keeps them, and the result says so. + * keeps them, and the result says so. With `rollbackByNewSession` the + * session ends instead (`forgetByNewSession`). */ const rollbackThread: AcpAdapterShape["rollbackThread"] = (threadId, numTurns, options) => Effect.gen(function* () { @@ -2541,6 +4042,15 @@ export function makeAcpAdapter( } ctx.turns.splice(Math.max(0, ctx.turns.length - numTurns)); const conversationHistory = descriptor.conversationHistory; + if (conversationHistory === undefined && descriptor.rollbackByNewSession === true) { + yield* withThreadLock( + threadId, + Effect.suspend(() => + sessions.get(threadId) === ctx ? forgetByNewSession(ctx) : Effect.void, + ), + ); + return { threadId, turns: ctx.turns, conversationRolledBack: true }; + } // The last turn's prompt position may still be on its way. if (ctx.activeTurnId === undefined && ctx.promptFiber !== undefined) { yield* Fiber.await(ctx.promptFiber).pipe( @@ -2589,8 +4099,37 @@ export function makeAcpAdapter( return { threadId, turns: ctx.turns, conversationRolledBack: rewound }; }); + /** + * For an agent that can't rewind (`rollbackByNewSession`): the session + * ends. ProviderService then forgets its conversation in the thread's + * binding, so the next message starts a new one seeded with the turns + * kept. Work still going is stopped first as Stop does (a cancel ends the + * agent's commands and subagents, Antigravity 1.5.10), and the agent gets + * a moment to wind it down before its process ends. + */ + const forgetByNewSession = (ctx: AcpSessionContext) => + Effect.gen(function* () { + // On the turn machine, Stop is its own path: it cancels the running + // turn and the work it left, and ends the turn once. + const machine = ctx.machine; + const working = () => + ctx.activeTurnId !== undefined || + (machine !== undefined && + (workPending(machine.state) || machine.state.stopping !== undefined)); + if (working()) { + yield* interruptTurn(ctx.threadId).pipe(Effect.ignore); + yield* Effect.gen(function* () { + while (working()) yield* Effect.sleep("50 millis"); + }).pipe(Effect.timeoutOption(ACP_REVERT_WIND_DOWN)); + } + yield* stopSessionInternal(ctx); + }); + const stopSession: AcpAdapterShape["stopSession"] = (threadId) => - withThreadLock(threadId, Effect.flatMap(requireSession(threadId), stopSessionInternal)); + withThreadLock( + threadId, + Effect.flatMap(requireSession(threadId), (ctx) => stopSessionInternal(ctx)), + ); /** * A turn in flight counts as running, waiting on the user's answer or @@ -2606,6 +4145,13 @@ export function makeAcpAdapter( ), ); + /** `ProviderAdapterShape.whenStopped`: the stopping session stays in `sessions` until its scope closed. */ + const whenStopped = (threadId: ThreadId): Effect.Effect => + Effect.suspend(() => { + const ctx = sessions.get(threadId); + return ctx === undefined ? Effect.void : Deferred.await(ctx.closed); + }); + const hasSession: AcpAdapterShape["hasSession"] = (threadId) => Effect.sync(() => { const c = sessions.get(threadId); @@ -2615,11 +4161,53 @@ export function makeAcpAdapter( // A snapshot per run: stopping a session removes it from the map. const stopAll: AcpAdapterShape["stopAll"] = () => Effect.suspend(() => - Effect.forEach(Array.from(sessions.values()), stopSessionInternal, { discard: true }), + Effect.forEach(Array.from(sessions.values()), (ctx) => stopSessionInternal(ctx), { + discard: true, + }), ); + /** + * A launched subagent's steps, read from the agent's own records + * (`subagents`), by its launching call's id. The newest page by default, + * like other agents' transcripts. + */ + const readSubagentTranscript = (subagents: AcpSubagents) => + ((threadId, input) => + Effect.gen(function* () { + const ctx = yield* requireSession(threadId); + const read = yield* subagents.transcript({ + sessionId: ctx.acpSessionId, + launchCallId: input.agentId, + }); + if (read === undefined) { + return yield* new ProviderAdapterRequestError({ + provider: PROVIDER, + method: "readSubagentTranscript", + detail: subagents.unrecordedMessage, + }); + } + const total = read.entries.length; + const limit = input.limit !== undefined && input.limit > 0 ? input.limit : total; + const offset = input.fromEnd + ? Math.max(0, total - limit) + : Math.min(input.offset ?? 0, total); + const role = read.launch.role.trim(); + return { + entries: read.entries.slice(offset, offset + limit), + truncated: read.truncated || offset > 0 || offset + limit < total, + offset, + totalEntries: total, + agent: { + id: read.childId, + ...(role ? { agentType: role, description: role } : {}), + spawnDepth: 1, + directInput: "unsupported" as const, + }, + }; + })) satisfies NonNullable; + yield* Effect.addFinalizer(() => - Effect.forEach(sessions.values(), stopSessionInternal, { discard: true }).pipe( + Effect.forEach(sessions.values(), (ctx) => stopSessionInternal(ctx), { discard: true }).pipe( Effect.tap(() => PubSub.shutdown(runtimeEventPubSub)), Effect.tap(() => managedNativeEventLogger?.close() ?? Effect.void), ), @@ -2629,8 +4217,10 @@ export function makeAcpAdapter( provider: PROVIDER, capabilities: { sessionModelSwitch: "in-session", - conversationRollback: "none", - ...(descriptor.steer ? { activeTurnSteering: "supported" as const } : {}), + conversationRollback: descriptor.rollbackByNewSession ? "new-session" : "none", + ...(descriptor.steer || descriptor.turnMachine?.steer === true + ? { activeTurnSteering: "supported" as const } + : {}), ...(descriptor.conversationHistory ? { nativeThreadFork: "supported" as const } : {}), }, startSession, @@ -2644,10 +4234,14 @@ export function makeAcpAdapter( stopSession, listSessions, hasSession, + whenStopped, stopAll, noteBeforeStop: processes.beforeStop, confirmThreadStopped: processes.confirm, listProcesses: processes.owners, + ...(descriptor.subagents + ? { readSubagentTranscript: readSubagentTranscript(descriptor.subagents) } + : {}), streamEvents: Stream.fromPubSub(runtimeEventPubSub), } satisfies AcpAdapterShape; }); diff --git a/apps/server/src/provider/acp/AcpCoreRuntimeEvents.ts b/apps/server/src/provider/acp/AcpCoreRuntimeEvents.ts index f42ad0775..6edbc0169 100644 --- a/apps/server/src/provider/acp/AcpCoreRuntimeEvents.ts +++ b/apps/server/src/provider/acp/AcpCoreRuntimeEvents.ts @@ -143,7 +143,8 @@ export function makeAcpRequestResolvedEvent(input: { readonly turnId: TurnId | undefined; readonly requestId: RuntimeRequestId; readonly permissionRequest: AcpPermissionRequest; - readonly decision: ProviderApprovalDecision; + /** Absent for a card withdrawn unanswered (asked again in other words). */ + readonly decision?: ProviderApprovalDecision; }): ProviderRuntimeEvent { return { type: "request.resolved", @@ -154,7 +155,7 @@ export function makeAcpRequestResolvedEvent(input: { requestId: input.requestId, payload: { requestType: canonicalRequestTypeFromAcpKind(input.permissionRequest.kind), - decision: input.decision, + ...(input.decision !== undefined ? { decision: input.decision } : {}), }, }; } @@ -204,7 +205,7 @@ export function makeAcpToolCallEvent(input: { turnId: input.turnId, itemId: RuntimeItemId.make(input.toolCall.toolCallId), payload: { - itemType: canonicalItemTypeFromAcpToolKind(input.toolCall.kind), + itemType: input.toolCall.itemType ?? canonicalItemTypeFromAcpToolKind(input.toolCall.kind), ...(runtimeStatus ? { status: runtimeStatus } : {}), ...(input.toolCall.title ? { title: input.toolCall.title } : {}), ...(input.toolCall.detail ? { detail: input.toolCall.detail } : {}), diff --git a/apps/server/src/provider/acp/AcpPromptAttachments.test.ts b/apps/server/src/provider/acp/AcpPromptAttachments.test.ts new file mode 100644 index 000000000..0d0423974 --- /dev/null +++ b/apps/server/src/provider/acp/AcpPromptAttachments.test.ts @@ -0,0 +1,143 @@ +// @effect-diagnostics nodeBuiltinImport:off +import * as os from "node:os"; +import * as path from "node:path"; +import { mkdtemp, rm, symlink, writeFile } from "node:fs/promises"; + +import type { ChatAttachment } from "@threadlines/contracts"; +import { it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import { describe, expect } from "vite-plus/test"; + +import { antigravityAttachmentDelivery } from "../antigravity/AntigravityAttachments.ts"; +import { acpAttachmentContent } from "./AcpPromptAttachments.ts"; + +const image = (sizeBytes: number): ChatAttachment => ({ + type: "image", + id: "img-1", + name: "shot.png", + mimeType: "image/png", + sizeBytes, +}); + +const withDir = (use: (dir: string) => Effect.Effect) => + Effect.acquireUseRelease( + Effect.promise(() => mkdtemp(path.join(os.tmpdir(), "acp-attachments-"))), + use, + (dir) => Effect.promise(() => rm(dir, { recursive: true, force: true })), + ); + +describe("acpAttachmentContent", () => { + it.live("refuses a staged file replaced by a link", () => + withDir((dir) => + Effect.gen(function* () { + const target = path.join(dir, "secret.png"); + const staged = path.join(dir, "img-1.png"); + yield* Effect.promise(async () => { + await writeFile(target, "secret"); + await symlink(target, staged); + }); + const error = yield* Effect.flip( + acpAttachmentContent({ + attachment: image(6), + path: staged, + delivery: "inline", + budget: { inlineBytes: 0 }, + }), + ); + expect(error._tag).toBe("AcpAttachmentReadError"); + // A PDF link to it is refused too. + const linked = yield* Effect.flip( + acpAttachmentContent({ + attachment: { ...image(6), type: "file", kind: "pdf", mimeType: "application/pdf" }, + path: staged, + delivery: "link", + budget: { inlineBytes: 0 }, + }), + ); + expect(linked._tag).toBe("AcpAttachmentReadError"); + }), + ), + ); + + it.live("goes by the bytes it reads, not the size the record claims", () => + withDir((dir) => + Effect.gen(function* () { + const staged = path.join(dir, "img-1.png"); + // The record says 4 bytes; the file has grown past an image's limit. + yield* Effect.promise(() => writeFile(staged, Buffer.alloc(10 * 1024 * 1024 + 1))); + const grown = yield* acpAttachmentContent({ + attachment: image(4), + path: staged, + delivery: "inline", + budget: { inlineBytes: 0 }, + }); + expect(grown.map((block) => block.type)).toEqual(["text"]); + + // The message's allowance is charged with the real bytes. + yield* Effect.promise(() => writeFile(staged, Buffer.alloc(3_000))); + const budget = { inlineBytes: 50 * 1024 * 1024 - 2_000 }; + const over = yield* acpAttachmentContent({ + attachment: image(4), + path: staged, + delivery: "inline", + budget, + }); + expect(over.map((block) => block.type)).toEqual(["text"]); + const roomy = { inlineBytes: 0 }; + const sent = yield* acpAttachmentContent({ + attachment: image(4), + path: staged, + delivery: "inline", + budget: roomy, + }); + expect(sent.map((block) => block.type)).toEqual(["image"]); + expect(roomy.inlineBytes).toBe(3_000); + + // Embedded text counts toward the same allowance. + const notes = path.join(dir, "notes.txt"); + yield* Effect.promise(() => writeFile(notes, "x".repeat(3_000))); + const text: ChatAttachment = { + type: "file", + kind: "text", + id: "txt-1", + name: "notes.txt", + mimeType: "text/plain", + sizeBytes: 3_000, + }; + const full = yield* acpAttachmentContent({ + attachment: text, + path: notes, + delivery: "text", + budget: { inlineBytes: 50 * 1024 * 1024 - 2_000 }, + }); + expect(full.map((block) => block.type)).toEqual(["text"]); + const counted = { inlineBytes: 0 }; + yield* acpAttachmentContent({ + attachment: text, + path: notes, + delivery: "text", + budget: counted, + }); + expect(counted.inlineBytes).toBe(3_000); + }), + ), + ); +}); + +describe("antigravityAttachmentDelivery", () => { + it("links a PDF even when the agent takes no embedded text", () => { + const pdf: ChatAttachment = { + type: "file", + kind: "pdf", + id: "pdf-1", + name: "spec.pdf", + mimeType: "application/pdf", + sizeBytes: 9, + }; + const text: ChatAttachment = { ...pdf, kind: "text", mimeType: "text/plain" }; + expect(antigravityAttachmentDelivery(pdf, {})).toBe("link"); + expect(antigravityAttachmentDelivery(pdf, { embeddedContext: false })).toBe("link"); + // Embedded text still needs the capability. + expect(antigravityAttachmentDelivery(text, { embeddedContext: false })).toBe("note"); + }); +}); diff --git a/apps/server/src/provider/acp/AcpPromptAttachments.ts b/apps/server/src/provider/acp/AcpPromptAttachments.ts new file mode 100644 index 000000000..dc339ae2a --- /dev/null +++ b/apps/server/src/provider/acp/AcpPromptAttachments.ts @@ -0,0 +1,197 @@ +// @effect-diagnostics nodeBuiltinImport:off -- node:url links a staged file; node:fs reads it without following a link. +/** + * How an attachment reaches an ACP agent as prompt content. By default an + * image goes inline and any other file goes as a note naming its staged path + * (`buildFileAttachmentNote`), which works for every agent. An agent that + * reads more natively says so per attachment (`AcpProviderDescriptor. + * attachmentDelivery`), and the ways here are plain ACP content blocks: + * + * - `inline`: an image or audio block with the bytes. + * - `link`: a `resource_link` to the staged file (ACP's baseline block). + * - `text`: an embedded text `resource`, decoded as UTF-8, or UTF-16 when the + * file starts with its byte order mark. + * + * Anything that doesn't fit its way (too big, not text after all) falls back + * to the note, so a file always reaches the agent one way or another. + * + * @module provider/acp/AcpPromptAttachments + */ +import { type ChatAttachment, PROVIDER_SEND_TURN_MAX_IMAGE_BYTES } from "@threadlines/contracts"; +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; +import type * as EffectAcpSchema from "effect-acp/schema"; +import * as NodeFS from "node:fs"; +import * as NodeFSP from "node:fs/promises"; +import { pathToFileURL } from "node:url"; + +import { + buildFileAttachmentNote, + INLINE_TEXT_ATTACHMENT_MAX_BYTES, +} from "../fileAttachmentPrompt.ts"; + +/** How one attachment travels (see the module comment). */ +export type AcpAttachmentDelivery = "inline" | "link" | "text" | "note"; + +/** The most audio one file may send inline. */ +const INLINE_AUDIO_MAX_BYTES = 20 * 1024 * 1024; +/** The most bytes one message sends inline, images and audio together. */ +const INLINE_MESSAGE_MAX_BYTES = 50 * 1024 * 1024; + +/** A MIME type without its parameters (`text/plain; charset=utf-8` is `text/plain`). */ +export function bareMimeType(mimeType: string): string { + return mimeType.split(";", 1)[0]?.trim().toLowerCase() ?? ""; +} + +/** What one message has sent inline so far. */ +export interface AcpAttachmentBudget { + inlineBytes: number; +} + +/** + * Text as the file holds it: UTF-16 with its byte order mark, else UTF-8. + * `undefined` for bytes that aren't valid text in that encoding, or hold a NUL. + */ +export function decodeAttachmentText(bytes: Uint8Array): string | undefined { + const encoding = + bytes[0] === 0xff && bytes[1] === 0xfe + ? "utf-16le" + : bytes[0] === 0xfe && bytes[1] === 0xff + ? "utf-16be" + : "utf-8"; + try { + const text = new TextDecoder(encoding, { fatal: true }).decode(bytes); + return text.includes("\0") ? undefined : text; + } catch { + return undefined; + } +} + +const note = (attachment: ChatAttachment, path: string): EffectAcpSchema.ContentBlock => ({ + type: "text", + text: buildFileAttachmentNote(attachment, path), +}); + +/** A staged attachment that couldn't be read, or isn't a regular file. */ +export class AcpAttachmentReadError extends Schema.TaggedError()( + "AcpAttachmentReadError", + { message: Schema.String, cause: Schema.optional(Schema.Defect()) }, +) {} + +const isAttachmentReadError = Schema.is(AcpAttachmentReadError); + +const notAFile = (name: string) => + new AcpAttachmentReadError({ message: `Attachment '${name}' is not a regular file.` }); + +/** The limit one attachment sent this way may reach, before the message's own. */ +function deliveryLimit(delivery: "inline" | "text", mimeType: string): number { + if (delivery === "text") return INLINE_TEXT_ATTACHMENT_MAX_BYTES; + return mimeType.startsWith("audio/") + ? INLINE_AUDIO_MAX_BYTES + : PROVIDER_SEND_TURN_MAX_IMAGE_BYTES; +} + +/** + * The staged file's bytes, read through one handle: never through a link, + * only a regular file, and no more than `maxBytes` whatever its record or + * its size says (it may have grown). `too-big` past the cap. Fails when the + * staged file isn't a regular file or can't be read. + */ +const readStaged = (path: string, name: string, maxBytes: number) => + Effect.tryPromise({ + try: async (): Promise => { + const handle = await NodeFSP.open( + path, + NodeFS.constants.O_RDONLY | + (NodeFS.constants.O_NOFOLLOW ?? 0) | + (NodeFS.constants.O_NONBLOCK ?? 0), + ); + try { + const stat = await handle.stat(); + if (!stat.isFile()) throw notAFile(name); + if (stat.size > maxBytes) return "too-big"; + // One byte past the cap tells a file that grew since its size was read. + const buffer = Buffer.alloc(maxBytes + 1); + let total = 0; + while (total < buffer.length) { + const { bytesRead } = await handle.read(buffer, total, buffer.length - total, total); + if (bytesRead === 0) break; + total += bytesRead; + } + return total > maxBytes ? "too-big" : buffer.subarray(0, total); + } finally { + await handle.close(); + } + }, + catch: (cause) => + isAttachmentReadError(cause) + ? cause + : new AcpAttachmentReadError({ message: `Could not read attachment '${name}'.`, cause }), + }); + +/** Whether the staged file is a regular file, not a link, for a link to it. */ +const isStagedFile = (path: string) => + Effect.promise(() => + NodeFSP.lstat(path).then( + (info) => info.isFile(), + () => false, + ), + ); + +/** + * The content blocks for one attachment, sent the way `delivery` says, or + * as its note when it doesn't fit that way. Bytes sent inline are charged to + * the message's budget as read, not as recorded. Fails only when the staged + * file can't be read, or isn't a regular file. + */ +export const acpAttachmentContent = (input: { + readonly attachment: ChatAttachment; + readonly path: string; + readonly delivery: AcpAttachmentDelivery; + readonly budget: AcpAttachmentBudget; +}) => + Effect.gen(function* () { + const { attachment, path, delivery, budget } = input; + const mimeType = bareMimeType(attachment.mimeType); + if (delivery === "note") return [note(attachment, path)]; + if (delivery === "link") { + if (!(yield* isStagedFile(path))) { + return yield* notAFile(attachment.name); + } + return [ + { + type: "resource_link", + uri: pathToFileURL(path).href, + name: attachment.name, + mimeType, + size: attachment.sizeBytes, + }, + ] satisfies ReadonlyArray; + } + // Embedded text counts toward the message's allowance like inline bytes. + const cap = Math.min( + deliveryLimit(delivery, mimeType), + INLINE_MESSAGE_MAX_BYTES - budget.inlineBytes, + ); + // A record already past the cap is never read. + if (cap <= 0 || attachment.sizeBytes > cap) return [note(attachment, path)]; + const bytes = yield* readStaged(path, attachment.name, cap); + if (bytes === "too-big") return [note(attachment, path)]; + if (delivery === "text") { + const text = decodeAttachmentText(bytes); + if (text === undefined) return [note(attachment, path)]; + budget.inlineBytes += bytes.byteLength; + return [ + { + type: "resource", + resource: { uri: pathToFileURL(path).href, mimeType, text }, + }, + ] satisfies ReadonlyArray; + } + budget.inlineBytes += bytes.byteLength; + const data = Buffer.from(bytes).toString("base64"); + return [ + mimeType.startsWith("audio/") + ? { type: "audio", data, mimeType } + : { type: "image", data, mimeType: mimeType || attachment.mimeType }, + ] satisfies ReadonlyArray; + }); diff --git a/apps/server/src/provider/acp/AcpProvider.ts b/apps/server/src/provider/acp/AcpProvider.ts index d102e0861..cf1c5e7b1 100644 --- a/apps/server/src/provider/acp/AcpProvider.ts +++ b/apps/server/src/provider/acp/AcpProvider.ts @@ -9,12 +9,14 @@ * * @module provider/acp/AcpProvider */ +import { THREADLINES_ACP_CLIENT_INFO } from "./acpClientInfo.ts"; import type { ModelCapabilities, ServerProvider, ServerProviderAuth, ServerProviderDetection, ServerProviderModel, + ServerProviderSkill, } from "@threadlines/contracts"; import * as Cause from "effect/Cause"; import * as Clock from "effect/Clock"; @@ -270,7 +272,7 @@ const withAcpProbeRuntime = ( environment, childProcessSpawner: spawner, cwd: process.cwd(), - clientInfo: { name: "threadlines-provider-probe", version: "0.0.0" }, + clientInfo: { ...THREADLINES_ACP_CLIENT_INFO, name: "threadlines-provider-probe" }, }); return yield* useRuntime(runtime); }).pipe(Effect.scoped); @@ -483,6 +485,7 @@ export function buildAcpProviderSnapshot(i readonly probe: AcpProviderProbeOutcome; readonly discoveredModels?: ReadonlyArray; readonly discoveryWarning?: string; + readonly skills?: ReadonlyArray; }): ServerProviderDraft { const message = [input.probe.message, input.discoveryWarning] .map((part) => part?.trim()) @@ -501,6 +504,7 @@ export function buildAcpProviderSnapshot(i EMPTY_ACP_MODEL_CAPABILITIES, ), ...(discovered.length > 0 ? { modelCatalogSource: "live" as const } : {}), + ...(input.skills ? { skills: input.skills } : {}), probe: { installed: input.probe.installed, version: input.probe.version, @@ -584,6 +588,11 @@ export const checkAcpProviderStatus = ( discoveredModels = yield* descriptor.enrichDiscoveredModels(discoveredModels, environment); } + const skills = + descriptor.listSkills && probe.installed + ? yield* descriptor.listSkills(settings, environment) + : undefined; + return buildAcpProviderSnapshot({ descriptor, checkedAt, @@ -591,6 +600,7 @@ export const checkAcpProviderStatus = ( probe, discoveredModels, ...(discoveryWarning ? { discoveryWarning } : {}), + ...(skills ? { skills } : {}), }); }).pipe(Effect.withSpan("checkAcpProviderStatus")); diff --git a/apps/server/src/provider/acp/AcpProviderDescriptor.ts b/apps/server/src/provider/acp/AcpProviderDescriptor.ts index a32d9ea7a..c12546f27 100644 --- a/apps/server/src/provider/acp/AcpProviderDescriptor.ts +++ b/apps/server/src/provider/acp/AcpProviderDescriptor.ts @@ -10,22 +10,28 @@ * @module provider/acp/AcpProviderDescriptor */ import type { + ChatAttachment, ModelCapabilities, ProviderDriverKind, ProviderFailureCategory, ProviderInteractionMode, ProviderOptionSelection, ProviderRuntimeEvent, + ProviderSubagentTranscriptEntry, ProviderUserInputAnswers, RuntimeMode, + RuntimeUsageLimit, ServerProvider, ServerProviderDetection, ServerProviderModel, + ServerProviderSkill, ThreadId, TurnId, + UsageTokenTotals, UserInputQuestion, } from "@threadlines/contracts"; import type { HttpClient } from "effect/http"; +import type * as Duration from "effect/Duration"; import type * as Effect from "effect/Effect"; import type * as FileSystem from "effect/FileSystem"; import type * as Path from "effect/Path"; @@ -41,7 +47,8 @@ import type { } from "../providerMaintenance.ts"; import type { UsageLedgerProvider } from "../../usage/usageLedger.ts"; import type { ProviderProbeResult, ServerProviderPresentation } from "../providerSnapshot.ts"; -import type { AcpPlanUpdate, AcpToolCallState } from "./AcpRuntimeModel.ts"; +import type { AcpAttachmentDelivery } from "./AcpPromptAttachments.ts"; +import type { AcpPlanUpdate, AcpToolCallReport, AcpToolCallState } from "./AcpRuntimeModel.ts"; import type { AcpSessionRuntimeShape, AcpSpawnInput } from "./AcpSessionRuntime.ts"; /** Settings fields every ACP provider config must carry. */ @@ -85,15 +92,32 @@ export interface AcpPromptPlanMode { /** Prepended to the turn's text in plan mode, e.g. `/plan `. */ readonly promptPrefix: string; /** - * Whether this tool call writes the agent's own plan file. Such writes are - * approved without asking (they never touch the workspace) and are not - * shown as tool calls: the plan card stands for them. + * Whether this tool call writes the plan file of the session `sessionId` + * (the session asking; `undefined` when that isn't this one, and then + * nothing is). Such writes are approved without asking (they never touch + * the workspace) and are not shown as tool calls: the plan card stands for + * them. */ - readonly isPlanFile: (toolCall: AcpToolCallState) => boolean; + readonly isPlanFile: (toolCall: AcpToolCallState, sessionId: string | undefined) => boolean; /** The plan's markdown, when this plan-file write carries it. */ readonly planMarkdown: (toolCall: AcpToolCallState) => string | undefined; } +/** How an agent's own slash commands reach the composer; see `agentCommands`. */ +export interface AcpAgentCommands { + /** + * Commands Threadlines does itself, left out of the list: plan mode is + * Threadlines' `/plan`, a sign-in belongs in Settings. A user who types + * one still sends it. + */ + readonly hidden: ReadonlySet; + /** + * The agent runs a skill when a message starts with `/`, so the + * skills `listSkills` finds join the `/` list too (`ServerProvider.slashSkills`). + */ + readonly slashSkills: boolean; +} + export interface AcpConfigUpdate { readonly configId: string; readonly value: string | boolean; @@ -141,6 +165,148 @@ export interface AcpTurnOutcome { readonly failureCategory?: ProviderFailureCategory; } +/** + * Why a prompt the agent answered as finished, or refused with an error, + * really failed (Antigravity ends a turn normally on an upstream error). + */ +export interface AcpPromptFailure { + /** The words the chat shows. */ + readonly errorMessage: string; + readonly failureCategory?: ProviderFailureCategory; + /** A plan's usage limit stopped the turn: when it resets, for the usage-limit notice. */ + readonly usageLimit?: RuntimeUsageLimit; + /** + * The agent can no longer continue this session (Antigravity's saved + * thinking lost its signature). The session is stopped after the turn, and + * the next message starts a new one seeded with the thread's history. + */ + readonly sessionLost?: boolean; +} + +/** + * Reads how a prompt really ended (`AcpTurnMachineOptions.outcome`). `watch` + * runs as each prompt goes out (it may note where the agent's own records + * stand) and returns the check run when that prompt answers or fails. + */ +export interface AcpPromptOutcome { + /** `model`: the picker slug the turn runs on, when known. */ + readonly watch: ( + sessionId: string, + model: string | undefined, + ) => Effect.Effect; +} + +export interface AcpPromptOutcomeWatch { + readonly check: ( + answer: + | { readonly response: EffectAcpSchema.PromptResponse } + /** What `session/prompt` failed with, usually an `AcpRequestError`. */ + | { readonly error: unknown }, + ) => Effect.Effect; +} + +/** + * What a tool call the agent goes on with after its prompt answers is: a + * command it awaits, a timer it set, or subagents it launched (a batch + * counts each). `undefined` for one that ends with the prompt. + */ +export type AcpWorkAfterPrompt = + | { readonly kind: "command" | "timer" } + | { readonly kind: "subagents"; readonly count: number }; + +/** + * An agent whose turns run on the turn machine (`AcpTurnMachine`, + * Antigravity 1.5.10+): it answers its prompt while work it started goes on + * and replies by itself when that work ends, so the turn stays open, working + * and stoppable, until the work and the replies it wakes are done. Only for + * an agent that sends `usage_update` after each model call: that update is + * how a reply it started by itself is known to end. With `subagents`, the + * hold on launched subagents follows the agent's records of them. + */ +export interface AcpTurnMachineOptions { + readonly workAfterPrompt: (toolCall: AcpToolCallState) => AcpWorkAfterPrompt | undefined; + /** + * A message sent mid-turn goes as another `session/prompt`, which steers + * the turn. Off, it waits for the turn to end, as for any agent. + */ + readonly steer: boolean; + /** + * How long the turn waits without a word from the agent while only + * commands and subagents hold it; past it, the turn ends. A timer the + * agent set holds it with no limit (a timer is silent until it fires). + */ + readonly silentLimit: Duration.Duration; + /** + * How long a reply the agent started by itself (or a wake a finished + * command owes) may go without output before it counts as ended when its + * closing `usage_update` never comes (default 2 minutes). + */ + readonly replyQuietLimit?: Duration.Duration; + /** How a prompt really ended, where the agent's answer can hide a failure. */ + readonly outcome?: AcpPromptOutcome; +} + +/** A subagent a tool call launched, as the launch named it. */ +export interface AcpSubagentLaunch { + readonly role: string; + readonly prompt: string; +} + +/** What became of a launched subagent, by the agent's own records. */ +export interface AcpSubagentState { + /** `reported`: it sent the agent its report; `killed`: the agent stopped it. */ + readonly state: "working" | "reported" | "killed"; + /** Its report, when it has sent one. */ + readonly report?: string; +} + +/** + * Subagents an agent launches with a tool call that returns at once and + * reports no end for (Antigravity's `invoke_subagent`): only the agent's own + * records say which child a call started, whether it is done, and what it + * did. With it, each launch shows as a subagent (`AcpSubagentRoster`), and + * on the turn machine a launch holds the turn while its child is at work. + */ +export interface AcpSubagents { + /** The subagents this tool call launches; `undefined` for any other call. */ + readonly launches: (toolCall: AcpToolCallState) => ReadonlyArray | undefined; + /** + * The state of each launching call's child, by call id. A call the records + * don't tie to its child is left out; `complete` is false when some record + * didn't read, so a child left out may only be unreadable. `undefined` + * when the records can't be read at all. + */ + readonly states: (input: { + readonly sessionId: string; + readonly launchCallIds: ReadonlyArray; + }) => Effect.Effect< + | { + readonly byLaunch: ReadonlyMap; + readonly complete: boolean; + } + | undefined + >; + /** + * The child a launching call started and its steps, or `undefined` when + * the records don't say which child it started. + */ + readonly transcript: (input: { + readonly sessionId: string; + readonly launchCallId: string; + }) => Effect.Effect< + | { + readonly childId: string; + readonly launch: AcpSubagentLaunch; + readonly entries: ReadonlyArray; + /** Only the transcript's end was read. */ + readonly truncated: boolean; + } + | undefined + >; + /** What the subagent view says when `transcript` finds nothing. */ + readonly unrecordedMessage: string; +} + /** Runtime hooks handed to a vendor's extension registration. */ export interface AcpExtensionContext { readonly threadId: ThreadId; @@ -370,16 +536,27 @@ export interface AcpProviderDescriptor { readonly text: string; readonly content: ReadonlyArray; }) => Effect.Effect; + /** Turns run on the turn machine (`AcpTurnMachineOptions`); `steer` and `agentTurns` don't apply. */ + readonly turnMachine?: AcpTurnMachineOptions; + /** Subagents launched by a tool call, read from the agent's own records. */ + readonly subagents?: AcpSubagents; /** * Where the Usage page counts this agent's turns when it keeps no usage on * disk. Only for an agent whose turn `usage` is known to be the turn's own: * ACP doesn't say whether it is that or a running total, and agents differ * (Copilot's is a running total), so community agents have none. Unset for * an agent whose own files the usage scan reads (Grok), and for one that - * reports no turn usage (Cursor, and Antigravity, whose `usage_update` - * carries a bare total). + * reports no turn usage (Cursor). */ readonly usageLedger?: { readonly provider: UsageLedgerProvider }; + /** + * The agent's own reading of a prompt's `usage`, where the generic one + * (`acpTurnUsageTotals`, which takes input to include cached reads, as fx's + * does) would miscount it. Antigravity leaves cached reads out of input. + */ + readonly turnUsageTotals?: ( + usage: EffectAcpSchema.Usage | null | undefined, + ) => UsageTokenTotals | null; /** * The context fill an agent reports on its own updates rather than with * ACP's `usage_update` (Grok's `_meta.totalTokens`), and its window size. @@ -400,6 +577,22 @@ export interface AcpProviderDescriptor { * a revert trims only Threadlines' turn list, and the agent remembers. */ readonly conversationHistory?: AcpConversationHistory; + /** + * For an agent with no `conversationHistory`: a revert stops what the + * session runs and ends it (`conversationRollback: "new-session"`), and + * ProviderService forgets the saved conversation, so the next message + * opens a new one seeded with the turns kept (Antigravity). Without it the + * agent remembers them, and the revert says so. + */ + readonly rollbackByNewSession?: boolean; + /** + * The agent's slash commands (ACP `available_commands_update`) reach the + * composer's `/` list for the session's thread, as live state on the + * provider status (`AcpAdapterOptions.onSessionCommands`), and a typed + * `/name` the session lists goes as the agent's own command. Absent: the + * list is ignored, as for agents whose lists were never checked here. + */ + readonly agentCommands?: AcpAgentCommands; /** * The `session/set_mode` mode for a turn's interaction mode, for an agent * that switches modes without listing them (Grok: `plan`, `default`). @@ -421,7 +614,18 @@ export interface AcpProviderDescriptor { readonly agentModeFor?: (input: { readonly runtimeMode: RuntimeMode; readonly interactionMode: ProviderInteractionMode | undefined; + /** The modes the session offers; empty when it lists none. */ + readonly availableModeIds: ReadonlyArray; }) => string | undefined; + /** + * Checks the agent's `initialize` answer before a session opens, e.g. that + * it is a version Threadlines can run. A failure stops the start and its + * message is what the user sees. + */ + readonly verifyAgent?: ( + settings: Settings, + response: EffectAcpSchema.InitializeResponse, + ) => Effect.Effect; /** * `"native"` for agents Threadlines has never been tested with (the ACP * registry's), which it drives through their own controls instead of @@ -456,6 +660,37 @@ export interface AcpProviderDescriptor { readonly permissionOptionWarning?: ( option: EffectAcpSchema.PermissionOption, ) => string | undefined; + /** + * Rewrites each session update before the core reads it: the runtime + * events (and so what is stored and shown) carry only what this returns. + * The opt-in protocol log still records the wire as it came. Antigravity + * bounds its tool text and leaves out inline images here. + */ + readonly normalizeSessionUpdate?: ( + notification: EffectAcpSchema.SessionNotification, + ) => EffectAcpSchema.SessionNotification; + /** + * Rewrites each tool call after its updates are merged, for a call the + * agent describes as something it isn't (Antigravity runs MCP tools it + * left out of its context through a command, `call_mcp_tool`). Given the + * report that just arrived, so it can tell what that report positively + * says from what earlier ones did. Also applied to a permission request's + * call, where it may change what the request shows but never its kind. + */ + readonly normalizeToolCall?: ( + toolCall: AcpToolCallState, + report: AcpToolCallReport, + ) => AcpToolCallState; + /** + * How each attachment reaches this agent (`AcpPromptAttachments`), given + * what its `initialize` answer says it reads. Absent, or `undefined` for an + * attachment: an image goes inline and any other file as a note naming its + * staged path, as for every ACP agent. + */ + readonly attachmentDelivery?: ( + attachment: ChatAttachment, + promptCapabilities: EffectAcpSchema.PromptCapabilities | null | undefined, + ) => AcpAttachmentDelivery | undefined; /** Text the agent appends when a prompt is cancelled; dropped from the reply. */ readonly cancellationNotice?: string; readonly planMode?: AcpPromptPlanMode; @@ -533,6 +768,15 @@ export interface AcpProviderDescriptor { | Path.Path | HttpClient.HttpClient >; + /** + * The skills the agent loads, read from disk for the provider snapshot + * (ACP has no call that lists them before a session). Asked for on each + * status check of an installed agent; must never fail. + */ + readonly listSkills?: ( + settings: Settings, + environment: NodeJS.ProcessEnv, + ) => Effect.Effect>; /** * How long one ACP model-discovery session may take. Defaults to 15s; * agents that boot a VM first (fx inside WSL) need more. diff --git a/apps/server/src/provider/acp/AcpProviderDriver.test.ts b/apps/server/src/provider/acp/AcpProviderDriver.test.ts index 6dda907f6..67523f74d 100644 --- a/apps/server/src/provider/acp/AcpProviderDriver.test.ts +++ b/apps/server/src/provider/acp/AcpProviderDriver.test.ts @@ -7,13 +7,57 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import * as Effect from "effect/Effect"; import { HttpClient } from "effect/http"; import { ChildProcessSpawner } from "effect/process"; +import type { ServerProvider } from "@threadlines/contracts"; import { describe, expect, it } from "vite-plus/test"; import { checkAcpProviderStatus, makeAcpCatalogCache } from "./AcpProvider.ts"; -import { makeAcpProviderMaintenanceResolver, resolveAcpBinaryPath } from "./AcpProviderDriver.ts"; +import { + groupSessionCommands, + withSessionCommands, + makeAcpProviderMaintenanceResolver, + resolveAcpBinaryPath, +} from "./AcpProviderDriver.ts"; import { CURSOR_ACP_DESCRIPTOR } from "./CursorAcpSupport.ts"; import { FX_ACP_DESCRIPTOR } from "./FxAcpSupport.ts"; +describe("groupSessionCommands", () => { + it("sends each distinct list once, with the sessions that listed it", () => { + const usual = [{ name: "goal" }, { name: "compact" }]; + expect( + groupSessionCommands( + new Map([ + ["thread-a", usual], + ["thread-b", [{ name: "goal" }]], + ["thread-c", [...usual]], + ]), + ), + ).toEqual([ + { sessions: ["thread-a", "thread-c"], commands: usual }, + { sessions: ["thread-b"], commands: [{ name: "goal" }] }, + ]); + }); +}); + +describe("withSessionCommands", () => { + const status = { instanceId: "antigravity", models: [] } as unknown as ServerProvider; + const listed = new Map([["thread-a", [{ name: "goal" }]]]); + + it("drops a list the snapshot carried from before the session ended", () => { + const stale = withSessionCommands(status, listed); + expect(stale.sessionCommands).toBeDefined(); + expect(withSessionCommands(stale, new Map()).sessionCommands).toBeUndefined(); + }); + + it("keeps the same snapshot when nothing changed, so nothing is published", () => { + const current = withSessionCommands(status, listed); + expect(withSessionCommands(current, new Map(listed))).toBe(current); + expect(withSessionCommands(status, new Map())).toBe(status); + expect(withSessionCommands(current, new Map([["thread-a", [{ name: "compact" }]]]))).not.toBe( + current, + ); + }); +}); + describe("makeAcpCatalogCache", () => { const model = (slug: string) => ({ slug, diff --git a/apps/server/src/provider/acp/AcpProviderDriver.ts b/apps/server/src/provider/acp/AcpProviderDriver.ts index 3c594ea99..09954c2f3 100644 --- a/apps/server/src/provider/acp/AcpProviderDriver.ts +++ b/apps/server/src/provider/acp/AcpProviderDriver.ts @@ -8,7 +8,12 @@ * * @module provider/acp/AcpProviderDriver */ -import type { ServerProvider } from "@threadlines/contracts"; +import type { + ServerProvider, + ServerProviderSessionCommands, + ServerProviderSlashCommand, +} from "@threadlines/contracts"; +import { sameSlashCommands } from "@threadlines/shared/slashCommands"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; @@ -22,6 +27,7 @@ import { appendUsageLedgerEntry, type UsageLedgerEntry } from "../../usage/usage import { ProviderDriverError } from "../Errors.ts"; import { ProviderEventLoggers } from "../Layers/ProviderEventLoggers.ts"; import { makeManagedServerProvider } from "../makeManagedServerProvider.ts"; +import type { ServerProviderShape } from "../Services/ServerProvider.ts"; import { defaultProviderContinuationIdentity, type ProviderDriver, @@ -51,6 +57,49 @@ import { makeAcpTextGeneration } from "./AcpTextGeneration.ts"; const SNAPSHOT_REFRESH_INTERVAL = Duration.minutes(5); +/** + * A snapshot with the sessions' lists as they are now: the same snapshot + * when they didn't change (nothing is published then), and none of a list + * the snapshot carried from before. + */ +export function withSessionCommands( + snapshot: ServerProvider, + bySession: ReadonlyMap>, +): ServerProvider { + const { sessionCommands: previous, ...rest } = snapshot; + if (bySession.size === 0) return previous === undefined ? snapshot : rest; + const next = groupSessionCommands(bySession); + const unchanged = + previous !== undefined && + previous.length === next.length && + previous.every((group, index) => { + const other = next[index]; + return ( + other !== undefined && + group.sessions.length === other.sessions.length && + group.sessions.every((session, at) => session === other.sessions[at]) && + sameSlashCommands(group.commands, other.commands) + ); + }); + return unchanged ? snapshot : { ...rest, sessionCommands: next }; +} + +/** Sessions' lists for the status: each distinct list once, with the sessions that listed it. */ +export function groupSessionCommands( + bySession: ReadonlyMap>, +): ReadonlyArray { + const groups: Array<{ + sessions: Array; + commands: ReadonlyArray; + }> = []; + for (const [session, commands] of bySession) { + const group = groups.find((entry) => sameSlashCommands(entry.commands, commands)); + if (group) group.sessions.push(session); + else groups.push({ sessions: [session], commands }); + } + return groups; +} + export type AcpProviderDriverEnv = | ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem @@ -171,15 +220,24 @@ export function makeAcpProviderDriver( continuationKey: descriptor.continuationKey(config, processEnv), } : defaultProviderContinuationIdentity({ driverKind: DRIVER_KIND, instanceId }); - const stampIdentity = (snapshot: ServerProviderDraft): ServerProvider => ({ + // What each running session listed (`agentCommands` descriptors), + // by session key: live state on the status, never stored, so every + // snapshot (a scheduled check included) carries the current lists. + const sessionCommands = new Map>(); + const stampInstance = (snapshot: ServerProviderDraft): ServerProvider => ({ ...snapshot, instanceId, driver: DRIVER_KIND, ...(displayName ? { displayName } : {}), ...(accentColor ? { accentColor } : {}), continuation: { groupKey: continuationIdentity.continuationKey }, + ...(descriptor.agentCommands?.slashSkills === true ? { slashSkills: true } : {}), ...descriptor.snapshotExtras?.(), }); + // Every snapshot carries the lists as they are now, never ones it was + // built from (an enrichment that read the status before a session ended). + const stampIdentity = (snapshot: ServerProviderDraft): ServerProvider => + withSessionCommands(stampInstance(snapshot), sessionCommands); // A bare binary name is resolved once against the server's PATH plus // the known CLI install folders, so a CLI installed after the process // started (or one living outside cmd.exe's view) still spawns. @@ -219,11 +277,45 @@ export function makeAcpProviderDriver( ), ) : undefined; + // Set once the snapshot exists; sessions only start after that. + let liveSnapshot: ServerProviderShape | undefined; + const agentCommandHooks = + descriptor.agentCommands === undefined + ? {} + : { + onSessionCommands: ( + sessionKey: string, + commands: ReadonlyArray | undefined, + ) => + Effect.suspend(() => { + if (commands === undefined) sessionCommands.delete(sessionKey); + else sessionCommands.set(sessionKey, commands); + // An unchanged status is not published again. + return ( + liveSnapshot?.patchSnapshot((current) => + withSessionCommands(current, sessionCommands), + ) ?? Effect.void + ); + }).pipe(Effect.ignoreCause({ log: true })), + skillNames: Effect.suspend( + () => liveSnapshot?.getSnapshot ?? Effect.succeed(undefined), + ).pipe( + Effect.map( + (current): ReadonlySet => + new Set( + (current?.skills ?? []) + .filter((skill) => skill.enabled) + .map((skill) => skill.name), + ), + ), + ), + }; const adapter = yield* makeAcpAdapter(descriptor, effectiveConfig, { environment: processEnv, ...(eventLoggers.native ? { nativeEventLogger: eventLoggers.native } : {}), instanceId, ...(recordTurnUsage ? { recordTurnUsage } : {}), + ...agentCommandHooks, }); const textGeneration = yield* makeAcpTextGeneration( descriptor, @@ -285,6 +377,8 @@ export function makeAcpProviderDriver( ), ); + liveSnapshot = snapshot; + return { instanceId, driverKind: DRIVER_KIND, diff --git a/apps/server/src/provider/acp/AcpProviderRuntime.ts b/apps/server/src/provider/acp/AcpProviderRuntime.ts index 1d0d350a8..567edcb27 100644 --- a/apps/server/src/provider/acp/AcpProviderRuntime.ts +++ b/apps/server/src/provider/acp/AcpProviderRuntime.ts @@ -15,6 +15,7 @@ import * as Layer from "effect/Layer"; import type * as Scope from "effect/Scope"; import { ChildProcessSpawner } from "effect/process"; import type * as EffectAcpErrors from "effect-acp/errors"; +import type * as EffectAcpSchema from "effect-acp/schema"; import type { AcpConfigUpdate, @@ -37,6 +38,7 @@ export interface AcpProviderRuntimeInput e AcpSessionRuntimeOptions, | "authMethodId" | "authenticateTimeoutMs" + | "cancellationNotice" | "cancelMeta" | "clientCapabilities" | "contextUsage" @@ -44,6 +46,7 @@ export interface AcpProviderRuntimeInput e | "sessionControls" | "spawn" | "stderrFailure" + | "verifyInitialize" > { readonly childProcessSpawner: ChildProcessSpawner.ChildProcessSpawner["Service"]; readonly settings: Settings; @@ -123,6 +126,21 @@ export const makeAcpProviderRuntime = ( ...(descriptor.initializeMeta ? { initializeMeta: descriptor.initializeMeta } : {}), ...(descriptor.cancelMeta ? { cancelMeta: descriptor.cancelMeta } : {}), ...(descriptor.contextUsage ? { contextUsage: descriptor.contextUsage } : {}), + ...(descriptor.normalizeSessionUpdate + ? { normalizeSessionUpdate: descriptor.normalizeSessionUpdate } + : {}), + ...(descriptor.normalizeToolCall + ? { normalizeToolCall: descriptor.normalizeToolCall } + : {}), + ...(descriptor.cancellationNotice !== undefined + ? { cancellationNotice: descriptor.cancellationNotice } + : {}), + ...(descriptor.verifyAgent + ? { + verifyInitialize: (response: EffectAcpSchema.InitializeResponse) => + descriptor.verifyAgent!(settings, response), + } + : {}), }).pipe( Layer.provide(Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, childProcessSpawner)), ), diff --git a/apps/server/src/provider/acp/AcpRuntimeModel.test.ts b/apps/server/src/provider/acp/AcpRuntimeModel.test.ts index 67b7ecad6..cad6d8753 100644 --- a/apps/server/src/provider/acp/AcpRuntimeModel.test.ts +++ b/apps/server/src/provider/acp/AcpRuntimeModel.test.ts @@ -69,6 +69,30 @@ describe("AcpRuntimeModel", () => { ]); }); + it("reads the agent's command list as typed names, each once", () => { + const { events } = parseSessionUpdateEvent({ + sessionId: "session-1", + update: { + sessionUpdate: "available_commands_update", + availableCommands: [ + { name: "goal", description: " Work toward a goal ", input: { hint: "objective" } }, + { name: "/compact", description: "" }, + { name: "goal", description: "A second goal" }, + { name: "two words", description: "Not typeable" }, + ], + }, + }); + expect(events).toEqual([ + { + _tag: "AvailableCommandsUpdated", + commands: [ + { name: "goal", description: "Work toward a goal", input: { hint: "objective" } }, + { name: "compact" }, + ], + }, + ]); + }); + it("reads context window fill from usage_update", () => { const parsed = parseSessionUpdateEvent({ sessionId: "session-1", diff --git a/apps/server/src/provider/acp/AcpRuntimeModel.ts b/apps/server/src/provider/acp/AcpRuntimeModel.ts index f616858ad..f491b3b2b 100644 --- a/apps/server/src/provider/acp/AcpRuntimeModel.ts +++ b/apps/server/src/provider/acp/AcpRuntimeModel.ts @@ -1,6 +1,11 @@ import type * as EffectAcpSchema from "effect-acp/schema"; +import { cleanSlashCommands } from "@threadlines/shared/slashCommands"; import { deriveToolActivityPresentation } from "@threadlines/shared/toolActivity"; -import type { ToolLifecycleItemType, UsageTokenTotals } from "@threadlines/contracts"; +import type { + ServerProviderSlashCommand, + ToolLifecycleItemType, + UsageTokenTotals, +} from "@threadlines/contracts"; function isRecord(value: unknown): value is Record { return typeof value === "object" && value !== null && !Array.isArray(value); @@ -29,9 +34,29 @@ export interface AcpToolCallState { readonly status?: "pending" | "inProgress" | "completed" | "failed"; readonly command?: string; readonly detail?: string; + /** + * The timeline row type, when the agent's `kind` doesn't say it (an MCP + * call an agent runs as a command). Set by a descriptor's + * `normalizeToolCall`; absent, the row type follows `kind`. + */ + readonly itemType?: ToolLifecycleItemType; readonly data: Record; } +/** + * One report of a tool call as the agent sent it: a `tool_call` or + * `tool_call_update`, or a permission request's call. Read by a descriptor's + * `normalizeToolCall`, which needs what this report says, not only the + * merged state. + */ +export interface AcpToolCallReport { + readonly title?: string | null | undefined; + readonly kind?: string | null | undefined; + readonly rawInput?: unknown; + readonly content?: ReadonlyArray<{ readonly type: string }> | null | undefined; + readonly locations?: ReadonlyArray | null | undefined; +} + export interface AcpPlanUpdate { readonly explanation?: string | null; readonly plan: ReadonlyArray<{ @@ -96,6 +121,11 @@ export type AcpParsedSessionEvent = /** The session's running cost in USD so far, from ACP `usage_update`. */ readonly _tag: "SessionCost"; readonly totalUsd: number; + } + | { + /** The commands the agent runs on `/`, from ACP `available_commands_update`. */ + readonly _tag: "AvailableCommandsUpdated"; + readonly commands: ReadonlyArray; }; type AcpSessionSetupResponse = @@ -402,7 +432,12 @@ function canonicalItemTypeFromAcpToolKind(kind: string | undefined): ToolLifecyc } } -function makeToolCallState( +/** + * A tool call's state from one report of it, named and described the way + * the core shows every call. Also how a descriptor's `normalizeToolCall` + * rebuilds a call it stops retyping, so no earlier label stays on it. + */ +export function makeToolCallState( input: { readonly toolCallId: string; readonly title?: string | null | undefined; @@ -561,10 +596,17 @@ function diffContentPaths( ); } +/** + * A permission request as the approval shows it. ACP lets the request carry + * only part of the call (its id, say), so it is read on top of what the + * session already knows of the call (`known`, its updates merged): a command + * an earlier update named is never left out of the approval. + */ export function parsePermissionRequest( params: EffectAcpSchema.RequestPermissionRequest, + known?: AcpToolCallState, ): AcpPermissionRequest { - const toolCall = makeToolCallState( + const fromRequest = makeToolCallState( { toolCallId: params.toolCall.toolCallId, title: params.toolCall.title, @@ -577,9 +619,54 @@ export function parsePermissionRequest( }, { fallbackStatus: "pending" }, ); - const kind = normalizeToolKind(params.toolCall.kind) ?? "unknown"; + const toolCall = + known !== undefined && fromRequest !== undefined + ? mergeToolCallState(known, fromRequest) + : (fromRequest ?? known); + return describePermissionRequest(params, toolCall); +} + +/** + * What a tool call would do, as text that changes whenever that does: its + * kind and row type, its command, the paths it names, its input, and an + * edit's old and new text. An approval is tied to this, not to how the call + * reads: an edit whose replacement text changed is a different edit even + * when its title and path are the same. + */ +export function toolCallSubstance(toolCall: AcpToolCallState | undefined): string { + if (toolCall === undefined) return ""; + const { content, locations, rawInput } = toolCall.data; + const changes = Array.isArray(content) + ? content.flatMap((entry) => + isRecord(entry) && entry.type === "diff" + ? [{ path: entry.path, oldText: entry.oldText ?? null, newText: entry.newText }] + : [], + ) + : []; + const paths = Array.isArray(locations) + ? locations.flatMap((entry) => (isRecord(entry) ? [entry.path] : [])) + : []; + return JSON.stringify([ + toolCall.kind ?? null, + toolCall.itemType ?? null, + toolCall.command ?? null, + paths, + changes, + rawInput ?? null, + ]); +} + +/** The kind and words of an approval for this call, as far as it is known. */ +export function describePermissionRequest( + params: EffectAcpSchema.RequestPermissionRequest, + toolCall: AcpToolCallState | undefined, +): AcpPermissionRequest { + const kind = normalizeToolKind(params.toolCall.kind) ?? toolCall?.kind ?? "unknown"; // An edit is named by the files it changes, not its generic title. - const editedPaths = diffContentPaths(params.toolCall.content); + const content = toolCall?.data.content; + const editedPaths = Array.isArray(content) + ? diffContentPaths(content as ReadonlyArray) + : []; const detail = toolCall?.command ?? (editedPaths.length > 0 ? editedPaths.join(", ") : undefined) ?? @@ -714,6 +801,13 @@ export function parseSessionUpdateEvent(params: EffectAcpSchema.SessionNotificat } break; } + case "available_commands_update": { + events.push({ + _tag: "AvailableCommandsUpdated", + commands: cleanSlashCommands(upd.availableCommands), + }); + break; + } default: break; } diff --git a/apps/server/src/provider/acp/AcpSessionRuntime.ts b/apps/server/src/provider/acp/AcpSessionRuntime.ts index 0e5d8218e..08d5b44e3 100644 --- a/apps/server/src/provider/acp/AcpSessionRuntime.ts +++ b/apps/server/src/provider/acp/AcpSessionRuntime.ts @@ -6,13 +6,14 @@ import * as Exit from "effect/Exit"; import * as Layer from "effect/Layer"; import * as Queue from "effect/Queue"; import * as Ref from "effect/Ref"; +import * as Schema from "effect/Schema"; import * as Scope from "effect/Scope"; import * as Context from "effect/Context"; import * as Stream from "effect/Stream"; import { ChildProcessSpawner } from "effect/process"; import * as EffectAcpClient from "effect-acp/client"; import * as EffectAcpErrors from "effect-acp/errors"; -import type * as EffectAcpSchema from "effect-acp/schema"; +import * as EffectAcpSchema from "effect-acp/schema"; import type * as EffectAcpProtocol from "effect-acp/protocol"; import { hideWindowsConsole, makeCommandWithShell } from "@threadlines/shared/childProcess"; @@ -27,10 +28,12 @@ import { LEGACY_MODE_OPTION_ID, legacyControlConfigOptions, mergeToolCallState, + toolCallSubstance, parseSessionModeState, parseSessionUpdateEvent, type AcpParsedSessionEvent, type AcpSessionModeState, + type AcpToolCallReport, type AcpToolCallState, } from "./AcpRuntimeModel.ts"; @@ -98,8 +101,16 @@ export interface AcpSessionRuntimeOptions { readonly cancelMeta?: Readonly>; readonly clientInfo: { readonly name: string; + readonly title?: string; readonly version: string; }; + /** + * Checks the agent's `initialize` answer before anything else is sent. + * A failure ends the start with its message (an agent too old to run). + */ + readonly verifyInitialize?: ( + response: EffectAcpSchema.InitializeResponse, + ) => Effect.Effect; /** * ACP auth method to invoke after `initialize`. Omit for agents that * authenticate outside the protocol (e.g. fx, which advertises no auth @@ -142,6 +153,33 @@ export interface AcpSessionRuntimeOptions { * that starts turns of its own), not replayed history to drop. */ readonly liveOutsidePrompt?: boolean; + /** Rewrites each session update before anything reads it (see `AcpProviderDescriptor.normalizeSessionUpdate`). */ + readonly normalizeSessionUpdate?: ( + notification: EffectAcpSchema.SessionNotification, + ) => EffectAcpSchema.SessionNotification; + /** Rewrites each merged tool call (see `AcpProviderDescriptor.normalizeToolCall`). */ + readonly normalizeToolCall?: ( + toolCall: AcpToolCallState, + report: AcpToolCallReport, + ) => AcpToolCallState; + /** + * Also hand the reader tool call updates that show nothing new (a status + * change with no new detail) as `ToolCallTracked`, for a client that keeps + * count of running work (`AcpProviderDescriptor.turnMachine`). + */ + readonly trackSilentToolCalls?: boolean; + /** + * Also hand the reader a tool call update that shows nothing new but + * changes what the call would do (`toolCallSubstance`) as + * `ToolCallRevised`, for a client with approvals open. + */ + readonly reportRevisedToolCalls?: boolean; + /** + * Text the agent appends when a prompt is cancelled. A reply chunk that is + * just this text comes as `CancellationNotice`, before it starts a + * message: the client decides whether it is the notice a cancel owed. + */ + readonly cancellationNotice?: string; /** Context fill carried on the agent's own updates (see `AcpProviderDescriptor.contextUsage`). */ readonly contextUsage?: { readonly usedTokens: (notification: EffectAcpSchema.SessionNotification) => number | undefined; @@ -205,6 +243,12 @@ export interface AcpSessionRuntimeShape { readonly handleForeignSessionUpdate: ( handler: (notification: EffectAcpSchema.SessionNotification) => Effect.Effect, ) => Effect.Effect; + /** + * What the session knows of a tool call still open (its updates merged), + * so a permission request that restates only part of the call is read + * with the rest. + */ + readonly getToolCall: (toolCallId: string) => Effect.Effect; readonly start: () => Effect.Effect; readonly getEvents: () => Stream.Stream; /** @@ -233,6 +277,19 @@ export interface AcpSessionRuntimeShape { * text after it starts a new message. Prompts end theirs themselves. */ readonly closeAssistantSegment: Effect.Effect; + /** + * Ends the reply being streamed at once, for a reader that closes a turn + * in place: the item id it closed, for the reader to complete itself. + */ + readonly closeAssistantSegmentNow: Effect.Effect; + /** + * The reply being streamed, opened at once if none is, for a reader that + * shows text it held back: its item id, and whether the reader must start it. + */ + readonly openAssistantSegmentNow: Effect.Effect<{ + readonly itemId: string; + readonly opened: boolean; + }>; /** * What the agent answered to `initialize`, as soon as it has: still there * when the session is then refused (an agent that wants a sign-in first @@ -244,6 +301,23 @@ export interface AcpSessionRuntimeShape { readonly prompt: ( payload: Omit, ) => Effect.Effect; + /** + * Sends a prompt whose answer the reader sees in its place among the + * agent's updates: `PromptAnswered` with `key` is queued as the response + * is read, ahead of every update the agent sent after it, with the reply + * it closed already queued before it. `PromptSent` with `key` comes first, + * once the prompt is written to the agent; a prompt that fails before + * that gets neither. Returns once the prompt is on its way, so prompts + * sent one after another reach the agent in that order. + * A session sends its prompts this way or with `prompt`, not both. + * `beforeQueued` runs on the wire reader just before the answer is + * queued (tests hold the reader there). + */ + readonly promptInOrder: ( + key: number, + payload: Omit, + beforeQueued?: Effect.Effect, + ) => Effect.Effect; readonly cancel: Effect.Effect; readonly setMode: ( modeId: string, @@ -271,6 +345,42 @@ export interface AcpSessionEventStreamBarrier { readonly holdUntil?: Deferred.Deferred; } +/** A tool call's state that changed nothing shown (see `trackSilentToolCalls`). */ +export interface AcpSessionToolCallTracked { + readonly _tag: "ToolCallTracked"; + readonly toolCall: AcpToolCallState; +} + +/** + * A tool call whose update changed what it would do (`toolCallSubstance`) + * but nothing its row shows. Not shown; read by the approval logic, which + * must not keep an approval answerable for a call that changed under it. + */ +export interface AcpSessionToolCallRevised { + readonly _tag: "ToolCallRevised"; + readonly toolCall: AcpToolCallState; +} + +/** The agent's cancellation notice, not yet shown (see `cancellationNotice`). */ +export interface AcpSessionCancellationNotice { + readonly _tag: "CancellationNotice"; + readonly text: string; + readonly rawPayload: unknown; +} + +/** A prompt sent with `promptInOrder` was written to the agent. Always before its `PromptAnswered`. */ +export interface AcpSessionPromptSent { + readonly _tag: "PromptSent"; + readonly key: number; +} + +/** A prompt sent with `promptInOrder` answered (or failed), placed where the answer was read. */ +export interface AcpSessionPromptAnswered { + readonly _tag: "PromptAnswered"; + readonly key: number; + readonly answer: Exit.Exit; +} + /** Work for the reader to run where it was queued (see `inOrder`). */ export interface AcpSessionInOrderWork { readonly _tag: "InOrder"; @@ -280,7 +390,12 @@ export interface AcpSessionInOrderWork { export type AcpSessionRuntimeEvent = | AcpParsedSessionEvent | AcpSessionEventStreamBarrier - | AcpSessionInOrderWork; + | AcpSessionInOrderWork + | AcpSessionToolCallTracked + | AcpSessionToolCallRevised + | AcpSessionCancellationNotice + | AcpSessionPromptSent + | AcpSessionPromptAnswered; /** Upper bound on waiting for the reader; a dead consumer must not wedge a turn. */ const EVENT_FLUSH_TIMEOUT = "5 seconds"; @@ -487,8 +602,9 @@ const makeAcpSessionRuntime = ( // `session/load` replays the conversation as ordinary updates; only // updates produced by a prompt we sent are live content, or, for an agent - // that starts turns of its own, anything after the session opened. - const promptInFlightRef = yield* Ref.make(false); + // that starts turns of its own, anything after the session opened. A count: + // an agent steered by a second prompt has two open at once. + const promptsInFlightRef = yield* Ref.make(0); /** Turns the agent started or ended itself so far (`markAgentTurnBoundary`). */ const agentTurnBoundariesRef = yield* Ref.make(0); const liveOutsidePromptRef = yield* Ref.make(false); @@ -501,8 +617,9 @@ const makeAcpSessionRuntime = ( // A resumed session restarts segment numbering at 0 in this process, so // its items would collide with the ones persisted by the previous run. const itemIdScope = options.resumeSessionId ? `:r${Date.now().toString(36)}` : ""; - yield* acp.handleSessionUpdate((notification) => + yield* acp.handleSessionUpdate((received) => Effect.gen(function* () { + const notification = options.normalizeSessionUpdate?.(received) ?? received; const ownSessionId = yield* Ref.get(ownSessionIdRef); if (ownSessionId !== undefined && String(notification.sessionId) !== ownSessionId) { const handler = yield* Ref.get(foreignUpdateHandlerRef); @@ -524,11 +641,20 @@ const makeAcpSessionRuntime = ( modeStateRef, toolCallsRef, assistantSegmentRef, - promptInFlightRef, + promptsInFlightRef, liveOutsidePromptRef, itemIdScope, params: notification, + // A descriptor classifies a tool call by what the agent sent, not + // by the bounded copy (bounding can drop a field that matters). + receivedUpdate: received.update, ...(nativeControls ? { configOptionsRef } : {}), + ...(options.normalizeToolCall ? { normalizeToolCall: options.normalizeToolCall } : {}), + ...(options.trackSilentToolCalls ? { trackSilentToolCalls: true } : {}), + ...(options.reportRevisedToolCalls ? { reportRevisedToolCalls: true } : {}), + ...(options.cancellationNotice !== undefined + ? { cancellationNotice: options.cancellationNotice } + : {}), }); }), ); @@ -740,6 +866,7 @@ const makeAcpSessionRuntime = ( ); yield* Ref.set(initializeResultRef, initializeResult); + if (options.verifyInitialize) yield* options.verifyInitialize(initializeResult); if (shouldAuthenticate(options.authMethodId, initializeResult.authMethods)) { const authenticatePayload = { @@ -929,6 +1056,8 @@ const makeAcpSessionRuntime = ( handleExtRequest: acp.handleExtRequest, handleExtNotification: acp.handleExtNotification, handleForeignSessionUpdate: (handler) => Ref.set(foreignUpdateHandlerRef, handler), + getToolCall: (toolCallId) => + Ref.get(toolCallsRef).pipe(Effect.map((calls) => calls.get(toolCallId))), start: () => start, getEvents: () => Stream.fromQueue(eventQueue), flushEvents: (holdUntil) => @@ -953,6 +1082,37 @@ const makeAcpSessionRuntime = ( queue: eventQueue, assistantSegmentRef, }), + closeAssistantSegmentNow: Ref.modify(assistantSegmentRef, (current) => + current.activeItemId === undefined + ? ([undefined, current] as const) + : ([current.activeItemId, { nextSegmentIndex: current.nextSegmentIndex }] as const), + ), + openAssistantSegmentNow: getStartedState.pipe( + Effect.orDie, + Effect.flatMap((started) => + Ref.modify( + assistantSegmentRef, + ( + current, + ): readonly [ + { readonly itemId: string; readonly opened: boolean }, + AcpAssistantSegmentState, + ] => { + if (current.activeItemId !== undefined) { + return [{ itemId: current.activeItemId, opened: false }, current] as const; + } + const itemId = assistantItemId( + `${started.sessionId}${itemIdScope}`, + current.nextSegmentIndex, + ); + return [ + { itemId, opened: true }, + { nextSegmentIndex: current.nextSegmentIndex + 1, activeItemId: itemId }, + ] as const; + }, + ), + ), + ), getInitializeResult: Ref.get(initializeResultRef), getModeState: Ref.get(modeStateRef), getConfigOptions: readConfigOptions, @@ -966,21 +1126,110 @@ const makeAcpSessionRuntime = ( return Effect.gen(function* () { yield* closeActiveAssistantSegment({ queue: eventQueue, assistantSegmentRef }); const boundariesBefore = yield* Ref.get(agentTurnBoundariesRef); - yield* Ref.set(promptInFlightRef, true); + yield* Ref.update(promptsInFlightRef, (count) => count + 1); const response = yield* runLoggedRequest( "session/prompt", requestPayload, acp.agent.prompt(requestPayload), - ).pipe(Effect.ensuring(Ref.set(promptInFlightRef, false))); + ).pipe(Effect.ensuring(Ref.update(promptsInFlightRef, (count) => count - 1))); // A turn the agent began before this answer already ended the - // prompt's reply; the reply streaming now is that turn's. - if ((yield* Ref.get(agentTurnBoundariesRef)) === boundariesBefore) { + // prompt's reply; the reply streaming now is that turn's. A + // steered prompt's answer leaves the reply of the one that + // carries the turn on alone. + if ( + (yield* Ref.get(agentTurnBoundariesRef)) === boundariesBefore && + (yield* Ref.get(promptsInFlightRef)) === 0 + ) { yield* closeActiveAssistantSegment({ queue: eventQueue, assistantSegmentRef }); } return response; }); }), ), + promptInOrder: (key, payload, beforeQueued) => + Effect.gen(function* () { + const started = yield* getStartedState; + const requestPayload = { + sessionId: started.sessionId, + ...payload, + } satisfies EffectAcpSchema.PromptRequest; + yield* closeActiveAssistantSegment({ queue: eventQueue, assistantSegmentRef }); + const boundariesBefore = yield* Ref.get(agentTurnBoundariesRef); + yield* Ref.update(promptsInFlightRef, (count) => count + 1); + yield* logRequest({ + method: "session/prompt", + payload: requestPayload, + status: "started", + }); + // Queued once: when the request is out, or by its answer if that + // is read first (an answer proves the prompt was written). + let sentQueued = false; + const queueSent = Effect.suspend(() => { + if (sentQueued) return Effect.void; + sentQueued = true; + return Queue.offer(eventQueue, { _tag: "PromptSent", key }).pipe(Effect.asVoid); + }); + // Runs on the reader, as the response is read: nothing the agent + // sent after it is handled before this is queued. + const onAnswer = (answer: Exit.Exit) => + Effect.gen(function* () { + yield* queueSent; + yield* Ref.update(promptsInFlightRef, (count) => count - 1); + // As `prompt`: the answer ends the prompt's reply, unless a turn + // the agent began itself, or a newer prompt, carries one on. + if ( + (yield* Ref.get(agentTurnBoundariesRef)) === boundariesBefore && + (yield* Ref.get(promptsInFlightRef)) === 0 + ) { + yield* closeActiveAssistantSegment({ queue: eventQueue, assistantSegmentRef }); + } + const decoded: Exit.Exit = + Exit.isSuccess(answer) + ? Exit.mapError( + decodePromptResponse(answer.value), + (issue) => + new EffectAcpErrors.AcpProtocolParseError({ + detail: "Invalid session/prompt response", + cause: issue, + }), + ) + : Exit.failCause(answer.cause); + const failed = Exit.isFailure(decoded) ? decoded : undefined; + const fatal = failed === undefined ? undefined : yield* Ref.get(fatalRef); + const settled = + fatal === undefined + ? decoded + : Exit.fail( + new EffectAcpErrors.AcpRequestError({ + code: -32000, + errorMessage: fatal, + data: { reason: "stderr" }, + }), + ); + if (beforeQueued !== undefined) yield* beforeQueued; + yield* Queue.offer(eventQueue, { _tag: "PromptAnswered", key, answer: settled }); + // The log only reads it: it never holds the reader up. + yield* ( + Exit.isSuccess(settled) + ? logRequest({ + method: "session/prompt", + payload: requestPayload, + status: "succeeded", + result: settled.value, + }) + : logRequest({ + method: "session/prompt", + payload: requestPayload, + status: "failed", + cause: settled.cause, + }) + ).pipe(Effect.forkIn(runtimeScope)); + }); + yield* acp.raw + .requestInOrder("session/prompt", requestPayload, onAnswer) + .pipe(Effect.tapError(() => Ref.update(promptsInFlightRef, (count) => count - 1))); + yield* queueSent; + }), cancel: getStartedState.pipe( Effect.flatMap((started) => acp.agent.cancel({ @@ -1072,23 +1321,42 @@ const handleSessionUpdate = ({ modeStateRef, toolCallsRef, assistantSegmentRef, - promptInFlightRef, + promptsInFlightRef, liveOutsidePromptRef, itemIdScope, params, + receivedUpdate, configOptionsRef, + normalizeToolCall, + trackSilentToolCalls, + reportRevisedToolCalls, + cancellationNotice, }: { readonly queue: Queue.Queue; readonly modeStateRef: Ref.Ref; readonly toolCallsRef: Ref.Ref>; readonly assistantSegmentRef: Ref.Ref; - readonly promptInFlightRef: Ref.Ref; + readonly promptsInFlightRef: Ref.Ref; readonly liveOutsidePromptRef: Ref.Ref; /** Suffix keeping item ids unique across resumes (segment numbering restarts per process). */ readonly itemIdScope: string; readonly params: EffectAcpSchema.SessionNotification; + /** The update as the agent sent it, before `normalizeSessionUpdate`. */ + readonly receivedUpdate?: EffectAcpSchema.SessionNotification["update"]; /** Given for native controls only: the agent's own option updates land here. */ readonly configOptionsRef?: Ref.Ref>; + readonly normalizeToolCall?: ( + toolCall: AcpToolCallState, + report: AcpToolCallReport, + ) => AcpToolCallState; + readonly trackSilentToolCalls?: boolean; + /** + * Also hand the reader a tool call update that shows nothing new but + * changes what the call would do (`toolCallSubstance`) as + * `ToolCallRevised`, for a client with approvals open. + */ + readonly reportRevisedToolCalls?: boolean; + readonly cancellationNotice?: string; }): Effect.Effect => Effect.gen(function* () { if (configOptionsRef && params.update.sessionUpdate === "config_option_update") { @@ -1100,7 +1368,7 @@ const handleSessionUpdate = ({ current === undefined ? current : updateModeState(current, parsed.modeId!), ); } - const live = (yield* Ref.get(promptInFlightRef)) || (yield* Ref.get(liveOutsidePromptRef)); + const live = (yield* Ref.get(promptsInFlightRef)) > 0 || (yield* Ref.get(liveOutsidePromptRef)); for (const event of parsed.events) { if (!live && isPromptContentEvent(event)) { // History replay after session/load (or stray output between @@ -1124,7 +1392,9 @@ const handleSessionUpdate = ({ }); const { previous, merged } = yield* Ref.modify(toolCallsRef, (current) => { const previous = current.get(event.toolCall.toolCallId); - const nextToolCall = mergeToolCallState(previous, event.toolCall); + const mergedToolCall = mergeToolCallState(previous, event.toolCall); + const report = (receivedUpdate ?? params.update) as AcpToolCallReport; + const nextToolCall = normalizeToolCall?.(mergedToolCall, report) ?? mergedToolCall; const next = new Map(current); if (nextToolCall.status === "completed" || nextToolCall.status === "failed") { next.delete(nextToolCall.toolCallId); @@ -1134,6 +1404,12 @@ const handleSessionUpdate = ({ return [{ previous, merged: nextToolCall }, next] as const; }); if (!shouldEmitToolCallUpdate(previous, merged)) { + if (trackSilentToolCalls) { + yield* Queue.offer(queue, { _tag: "ToolCallTracked", toolCall: merged }); + } + if (reportRevisedToolCalls && toolCallSubstance(previous) !== toolCallSubstance(merged)) { + yield* Queue.offer(queue, { _tag: "ToolCallRevised", toolCall: merged }); + } continue; } yield* Queue.offer(queue, { @@ -1144,6 +1420,14 @@ const handleSessionUpdate = ({ continue; } if (event._tag === "ContentDelta") { + if (cancellationNotice !== undefined && event.text.trim() === cancellationNotice) { + yield* Queue.offer(queue, { + _tag: "CancellationNotice", + text: event.text, + rawPayload: event.rawPayload, + }); + continue; + } if (event.text.trim().length === 0) { const assistantSegmentState = yield* Ref.get(assistantSegmentRef); if (!assistantSegmentState.activeItemId) { @@ -1185,6 +1469,11 @@ function shouldEmitToolCallUpdate( if (next.status === "completed" || next.status === "failed") { return true; } + // A descriptor that retypes a call (`normalizeToolCall`) changes what the + // row is, whatever its words; the earlier type must not stay on screen. + if (previous !== undefined && previous.itemType !== next.itemType) { + return true; + } if (!next.detail) { return false; } @@ -1232,6 +1521,8 @@ const ensureActiveAssistantSegment = ({ ), ); +const decodePromptResponse = Schema.decodeUnknownExit(EffectAcpSchema.PromptResponse); + const closeActiveAssistantSegment = ({ queue, assistantSegmentRef, diff --git a/apps/server/src/provider/acp/AcpSubagentEvents.ts b/apps/server/src/provider/acp/AcpSubagentEvents.ts new file mode 100644 index 000000000..0c557cef6 --- /dev/null +++ b/apps/server/src/provider/acp/AcpSubagentEvents.ts @@ -0,0 +1,121 @@ +/** + * The runtime events that show a subagent launched by a tool call + * (`AcpProviderDescriptor.subagents`), in the shape Grok's subagents already + * use: a `task.started` and `task.completed`, `subagent.metadata.updated` + * with the role and prompt, and a replace-all task snapshot of what still + * runs. The subagent is known by its launching call's id, which the + * transcript route asks for. + * + * @module provider/acp/AcpSubagentEvents + */ +import { RuntimeTaskId } from "@threadlines/contracts"; + +import type { AcpExtensionRuntimeEvent, AcpSubagentLaunch } from "./AcpProviderDescriptor.ts"; + +/** How a launched subagent stands in the roster. */ +export type AcpSubagentStatus = "running" | "completed" | "interrupted"; + +/** The most of a report kept on the task's summary (the full one is the result). */ +const SUMMARY_LIMIT = 2_000; + +/** One launch's subagent: a batch launch's roles and prompts read as one. */ +export function describeAcpSubagentLaunches( + launches: ReadonlyArray, +): AcpSubagentLaunch { + const [only] = launches; + if (launches.length === 1 && only !== undefined) return only; + return { + role: launches.map((launch) => launch.role).join(", "), + prompt: launches.map((launch) => `${launch.role}\n${launch.prompt}`).join("\n\n"), + }; +} + +const nonEmpty = (value: string) => { + const trimmed = value.trim(); + return trimmed.length > 0 ? trimmed : undefined; +}; + +/** A launch went through: the subagent runs in the background. */ +export function acpSubagentStartedEvents( + launchCallId: string, + launch: AcpSubagentLaunch, +): ReadonlyArray { + const role = nonEmpty(launch.role); + const prompt = nonEmpty(launch.prompt); + return [ + { + type: "task.started", + payload: { + taskId: RuntimeTaskId.make(launchCallId), + taskType: "agent", + isBackgrounded: true, + spawnDepth: 1, + pendingCountManagedBySnapshot: true, + ...(role ? { description: role, subagentType: role } : {}), + }, + }, + { + type: "subagent.metadata.updated", + payload: { + callId: launchCallId, + agentThreadId: launchCallId, + transcriptAgentId: launchCallId, + treeDepth: 1, + isBackgrounded: true, + status: "running", + ...(role ? { agentRole: role, taskName: role } : {}), + ...(prompt ? { objective: prompt } : {}), + }, + }, + ]; +} + +/** A subagent ended: it reported, or was stopped. */ +export function acpSubagentSettledEvents( + launchCallId: string, + status: Exclude, + report: string | undefined, +): ReadonlyArray { + const result = report === undefined ? undefined : nonEmpty(report); + return [ + { + type: "task.completed", + payload: { + taskId: RuntimeTaskId.make(launchCallId), + status: status === "interrupted" ? "stopped" : status, + taskType: "agent", + pendingCountManagedBySnapshot: true, + ...(result ? { summary: result.slice(0, SUMMARY_LIMIT) } : {}), + }, + }, + { + type: "subagent.metadata.updated", + payload: { + callId: launchCallId, + agentThreadId: launchCallId, + status, + ...(result ? { resultBody: result } : {}), + }, + }, + ]; +} + +/** The replace-all snapshot of the subagents still running. */ +export function acpSubagentSnapshotEvent( + running: ReadonlyArray<{ readonly launchCallId: string; readonly launch: AcpSubagentLaunch }>, +): AcpExtensionRuntimeEvent { + return { + type: "task.snapshot.updated", + payload: { + tasks: running.map(({ launchCallId, launch }) => { + const role = nonEmpty(launch.role); + return { + taskId: RuntimeTaskId.make(launchCallId), + taskType: "agent", + kind: "agent" as const, + ...(role ? { description: role } : {}), + }; + }), + }, + }; +} diff --git a/apps/server/src/provider/acp/AcpSubagentRoster.test.ts b/apps/server/src/provider/acp/AcpSubagentRoster.test.ts new file mode 100644 index 000000000..2d7cae392 --- /dev/null +++ b/apps/server/src/provider/acp/AcpSubagentRoster.test.ts @@ -0,0 +1,188 @@ +import { + EventId, + ProviderDriverKind, + type ProviderRuntimeEvent, + ThreadId, + TurnId, +} from "@threadlines/contracts"; +import { it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import { describe, expect } from "vite-plus/test"; + +import type { AcpExtensionRuntimeEvent, AcpSubagentState } from "./AcpProviderDescriptor.ts"; +import { makeAcpSubagentRoster } from "./AcpSubagentRoster.ts"; + +const TURN = TurnId.make("turn-1"); + +type Reading = + | { readonly byLaunch: ReadonlyMap; readonly complete: boolean } + | undefined; + +/** A roster whose records say whatever `records.next` holds, with every event it emits. */ +function makeRoster() { + const records: { next: Reading } = { next: undefined }; + const emitted: Array = []; + const roster = makeAcpSubagentRoster({ + subagents: { + launches: (toolCall) => [{ role: "Researcher", prompt: `Work on ${toolCall.toolCallId}` }], + states: () => Effect.succeed(records.next), + transcript: () => Effect.succeed(undefined), + unrecordedMessage: "not recorded", + }, + sessionId: "session-1", + emit: (event) => Effect.sync(() => void emitted.push(event)), + // Reads run inline, so each step's effects are visible at once. + fork: (effect) => effect, + }); + const statuses = () => + emitted.flatMap((event) => + event.type === "subagent.metadata.updated" && event.payload.status !== undefined + ? [`${event.payload.callId}:${event.payload.status}`] + : [], + ); + return { roster, records, emitted, statuses }; +} + +const launch = (id: string) => ({ toolCallId: id, status: "completed" as const, data: {} }); + +const turnCompleted = (state: "completed" | "cancelled"): ProviderRuntimeEvent => ({ + type: "turn.completed", + eventId: EventId.make(`evt-${state}`), + provider: ProviderDriverKind.make("antigravity"), + threadId: ThreadId.make("thread-1"), + createdAt: "2026-11-23T12:00:00.000Z", + turnId: TURN, + payload: { state }, +}); + +const usageUpdated: ProviderRuntimeEvent = { + type: "thread.token-usage.updated", + eventId: EventId.make("evt-usage"), + provider: ProviderDriverKind.make("antigravity"), + threadId: ThreadId.make("thread-1"), + createdAt: "2026-11-23T12:00:00.000Z", + payload: { usage: { usedTokens: 10 } }, +}; + +describe("AcpSubagentRoster", () => { + it.effect("never marks a subagent done for want of a reading", () => + Effect.gen(function* () { + const { roster, records, statuses } = makeRoster(); + yield* roster.noteToolCall(launch("call_a"), TURN); + // The records can't be read when the turn ends: nothing is settled. + records.next = undefined; + yield* roster.observe(turnCompleted("completed")); + expect(statuses()).toEqual(["call_a:running"]); + // Nor when some record didn't read and this child isn't named. + records.next = { byLaunch: new Map(), complete: false }; + yield* roster.observe(turnCompleted("completed")); + expect(statuses()).toEqual(["call_a:running"]); + // A later reading that names its report settles it, with the report. + records.next = { + byLaunch: new Map([["call_a", { state: "reported", report: "Found it." }]]), + complete: true, + }; + yield* roster.observe(usageUpdated); + expect(statuses()).toEqual(["call_a:running", "call_a:completed"]); + expect(roster.size()).toBe(0); + }), + ); + + it.effect("lets a later reading correct a subagent guessed done at its turn's end", () => + Effect.gen(function* () { + const { roster, records, statuses, emitted } = makeRoster(); + yield* roster.noteToolCall(launch("call_a"), TURN); + // A complete reading that doesn't name it: its turn was held until it reported. + records.next = { byLaunch: new Map(), complete: true }; + yield* roster.observe(turnCompleted("completed")); + expect(statuses()).toEqual(["call_a:running", "call_a:completed"]); + // The records then name it at work: it shows running again. + records.next = { byLaunch: new Map([["call_a", { state: "working" }]]), complete: true }; + yield* roster.observe(usageUpdated); + expect(statuses().at(-1)).toBe("call_a:running"); + // And its report settles it for good. + records.next = { + byLaunch: new Map([["call_a", { state: "reported", report: "Done." }]]), + complete: true, + }; + yield* roster.observe(usageUpdated); + expect(statuses().at(-1)).toBe("call_a:completed"); + expect( + emitted.findLast((event) => event.type === "subagent.metadata.updated")?.payload, + ).toMatchObject({ resultBody: "Done." }); + expect(roster.size()).toBe(0); + }), + ); + + it.effect("keeps only subagents still running or guessed, and shows a launch once", () => + Effect.gen(function* () { + const { roster, records, statuses } = makeRoster(); + for (let index = 0; index < 50; index += 1) { + yield* roster.noteToolCall(launch(`call_${index}`), TURN); + } + // A repeated update of a launch adds nothing. + yield* roster.noteToolCall(launch("call_0"), TURN); + expect(statuses().filter((status) => status === "call_0:running")).toHaveLength(1); + expect(roster.size()).toBe(50); + // Records settle ten; a complete reading guesses the rest done. + records.next = { + byLaunch: new Map( + Array.from({ length: 10 }, (_, index) => [ + `call_${index}`, + { state: index % 2 === 0 ? "reported" : "killed" } as const, + ]), + ), + complete: true, + }; + yield* roster.observe(turnCompleted("completed")); + // Settled ones are gone, and guesses are capped. + expect(roster.size()).toBe(32); + yield* roster.end; + expect(roster.size()).toBe(0); + }), + ); + + it.effect("stops every running subagent with a cancelled turn", () => + Effect.gen(function* () { + const { roster, statuses } = makeRoster(); + yield* roster.noteToolCall(launch("call_a"), TURN); + yield* roster.observe(turnCompleted("cancelled")); + expect(statuses()).toEqual(["call_a:running", "call_a:interrupted"]); + expect(roster.size()).toBe(0); + }), + ); + + it.effect( + "guesses an unrecorded launch done on a later reading if the one at its turn's end failed", + () => + Effect.gen(function* () { + const { roster, records, statuses } = makeRoster(); + yield* roster.noteToolCall(launch("call_a"), TURN); + records.next = undefined; + yield* roster.observe(turnCompleted("completed")); + expect(statuses()).toEqual(["call_a:running"]); + // The next complete reading still knows its turn ended. + records.next = { byLaunch: new Map(), complete: true }; + yield* roster.observe(usageUpdated); + expect(statuses()).toEqual(["call_a:running", "call_a:completed"]); + }), + ); + + it.effect("never shows a launch it still keeps twice, however many came after it", () => + Effect.gen(function* () { + const { roster, records, statuses } = makeRoster(); + yield* roster.noteToolCall(launch("call_0"), TURN); + for (let index = 1; index <= 600; index += 1) { + yield* roster.noteToolCall(launch(`call_${index}`), TurnId.make("turn-2")); + } + // The first launch's completion comes again, from another turn. + yield* roster.noteToolCall(launch("call_0"), TurnId.make("turn-3")); + expect(statuses().filter((status) => status === "call_0:running")).toHaveLength(1); + // It still belongs to its own turn: that turn's end settles it. + records.next = { byLaunch: new Map(), complete: true }; + yield* roster.observe(turnCompleted("completed")); + expect(statuses()).toContain("call_0:completed"); + expect(statuses()).not.toContain("call_1:completed"); + }), + ); +}); diff --git a/apps/server/src/provider/acp/AcpSubagentRoster.ts b/apps/server/src/provider/acp/AcpSubagentRoster.ts new file mode 100644 index 000000000..c1e39a372 --- /dev/null +++ b/apps/server/src/provider/acp/AcpSubagentRoster.ts @@ -0,0 +1,235 @@ +/** + * The subagents a session's tool calls launched (`AcpProviderDescriptor. + * subagents`), as the thread shows them: running until the agent's records + * say a child reported or was killed, or the session's turn or process ends. + * + * It keeps no part of a turn's hold. It learns what happened from the tool + * calls and from the runtime events the adapter emits anyway: + * - each reply message's end (`item.completed` for an assistant message) + * and each context update: read the records (a child's report wakes the + * agent, whose reply follows it); + * - `turn.completed`: read the records; a turn that completed was held + * until its subagents reported, so its launches a complete reading doesn't + * name show as done (on that reading or any later complete one), as a + * guess a later reading can still correct; + * - a cancelled turn: Antigravity 1.5.10 stops every subagent on a cancel; + * - the session's end (`end`): its process took the subagents with it. + * + * A reading that isn't available changes nothing: "couldn't read" is never + * "finished". Only running subagents and guessed ones are kept (a few dozen + * at most); one the records settled has said all it will. + * + * @module provider/acp/AcpSubagentRoster + */ +import type { ProviderRuntimeEvent, TurnId } from "@threadlines/contracts"; +import * as Effect from "effect/Effect"; + +import type { + AcpExtensionRuntimeEvent, + AcpSubagentLaunch, + AcpSubagents, +} from "./AcpProviderDescriptor.ts"; +import type { AcpToolCallState } from "./AcpRuntimeModel.ts"; +import { + acpSubagentSettledEvents, + acpSubagentSnapshotEvent, + acpSubagentStartedEvents, + describeAcpSubagentLaunches, +} from "./AcpSubagentEvents.ts"; + +/** Launch ids remembered so a repeated update never shows a launch twice. */ +const SEEN_LAUNCH_LIMIT = 512; +/** Subagents shown as done on a guess, kept so a later reading can correct them. */ +const GUESSED_LIMIT = 32; +/** Turns remembered as completed, for guessing their unrecorded launches done later. */ +const ENDED_TURN_LIMIT = 64; + +export interface AcpSubagentRoster { + /** A tool call update: a launch that went through shows as a running subagent, once. */ + readonly noteToolCall: ( + toolCall: AcpToolCallState, + turnId: TurnId | undefined, + ) => Effect.Effect; + /** An event the adapter emitted for this session (see the module comment). */ + readonly observe: (event: ProviderRuntimeEvent) => Effect.Effect; + /** The session ended: every running subagent stopped with it. */ + readonly end: Effect.Effect; + /** How many subagents it still keeps (running or guessed done). */ + readonly size: () => number; +} + +interface Entry { + readonly turnId: TurnId | undefined; + readonly launch: AcpSubagentLaunch; + /** `guessed`: shown done because its turn ended; no record said so yet. */ + status: "running" | "guessed"; +} + +export function makeAcpSubagentRoster(input: { + readonly subagents: AcpSubagents; + readonly sessionId: string; + /** Emits one of the roster's events, on the given turn. */ + readonly emit: ( + event: AcpExtensionRuntimeEvent, + turnId: TurnId | undefined, + ) => Effect.Effect; + /** Runs a records read in the session's scope, so the event that asked moves on. */ + readonly fork: (effect: Effect.Effect) => Effect.Effect; +}): AcpSubagentRoster { + const entries = new Map(); + const seen = new Set(); + /** + * Turns that completed. A launch of one that no complete reading names is + * guessed done on whichever complete reading comes first, so a reading + * that failed right at the turn's end doesn't leave it running for good. + */ + const endedTurns = new Set(); + const running = () => + [...entries].flatMap(([id, entry]) => (entry.status === "running" ? [id] : [])); + + const emitAll = (events: ReadonlyArray, turnId: TurnId | undefined) => + Effect.forEach(events, (event) => input.emit(event, turnId), { discard: true }); + + const emitSnapshot = Effect.suspend(() => + input.emit( + acpSubagentSnapshotEvent( + [...entries].flatMap(([launchCallId, entry]) => + entry.status === "running" ? [{ launchCallId, launch: entry.launch }] : [], + ), + ), + undefined, + ), + ); + + /** Ends a subagent for good: the records said so, or its session stopped it. */ + const settle = (id: string, status: "completed" | "interrupted", report?: string) => + Effect.gen(function* () { + const entry = entries.get(id); + if (entry === undefined) return; + entries.delete(id); + // A guess already showed it done; only a report adds anything. + if (entry.status === "guessed" && status === "completed" && report === undefined) return; + yield* emitAll(acpSubagentSettledEvents(id, status, report), entry.turnId); + yield* emitSnapshot; + }); + + /** Shows a running subagent as done on its turn's end, keeping it to correct later. */ + const guessDone = (id: string) => + Effect.gen(function* () { + const entry = entries.get(id); + if (entry === undefined || entry.status !== "running") return; + entry.status = "guessed"; + yield* emitAll(acpSubagentSettledEvents(id, "completed", undefined), entry.turnId); + yield* emitSnapshot; + const guessed = [...entries].filter(([, candidate]) => candidate.status === "guessed"); + for (const [oldest] of guessed.slice(0, Math.max(0, guessed.length - GUESSED_LIMIT))) { + entries.delete(oldest); + } + }); + + /** A guess the records contradict: the subagent is still at work. */ + const reopen = (id: string) => + Effect.gen(function* () { + const entry = entries.get(id); + if (entry === undefined || entry.status !== "guessed") return; + entry.status = "running"; + yield* emitAll(acpSubagentStartedEvents(id, entry.launch), entry.turnId); + yield* emitSnapshot; + }); + + /** + * Brings the kept subagents in line with the records. Launches of a turn + * that completed that a complete reading doesn't name are guessed done. + */ + const read = () => + Effect.gen(function* () { + const ids = [...entries.keys()]; + if (ids.length === 0) return; + const reading = yield* input.subagents.states({ + sessionId: input.sessionId, + launchCallIds: ids, + }); + if (reading === undefined) return; + for (const id of ids) { + const state = reading.byLaunch.get(id); + if (state === undefined) { + const turnId = entries.get(id)?.turnId; + if (reading.complete && turnId !== undefined && endedTurns.has(turnId)) { + yield* guessDone(id); + } + continue; + } + if (state.state === "working") yield* reopen(id); + else + yield* settle(id, state.state === "killed" ? "interrupted" : "completed", state.report); + } + }); + + // One read at a time; a request while one runs reads once more after it. + let reading = false; + let again = false; + const requestRead = (): Effect.Effect => + Effect.suspend(() => { + if (entries.size === 0) return Effect.void; + if (reading) { + again = true; + return Effect.void; + } + reading = true; + const loop: Effect.Effect = read().pipe( + Effect.ensuring(Effect.sync(() => (reading = false))), + Effect.andThen( + Effect.suspend(() => { + if (!again) return Effect.void; + again = false; + return requestRead(); + }), + ), + ); + return input.fork(loop); + }); + + const stopAll = Effect.suspend(() => + Effect.forEach(running(), (id) => settle(id, "interrupted"), { discard: true }), + ); + + return { + noteToolCall: (toolCall, turnId) => + Effect.gen(function* () { + const id = toolCall.toolCallId; + // A launch still kept is never shown again, however long ago it began. + if (toolCall.status !== "completed" || seen.has(id) || entries.has(id)) return; + const launches = input.subagents.launches(toolCall); + if (launches === undefined) return; + seen.add(id); + if (seen.size > SEEN_LAUNCH_LIMIT) { + const [oldest] = seen; + if (oldest !== undefined) seen.delete(oldest); + } + const launch = describeAcpSubagentLaunches(launches); + entries.set(id, { turnId, launch, status: "running" }); + yield* emitAll(acpSubagentStartedEvents(id, launch), turnId); + yield* emitSnapshot; + }), + observe: (event) => { + if ( + event.type === "thread.token-usage.updated" || + (event.type === "item.completed" && event.payload.itemType === "assistant_message") + ) { + return requestRead(); + } + if (event.type !== "turn.completed") return Effect.void; + if (event.payload.state === "cancelled") return stopAll; + if (event.payload.state === "completed" && event.turnId !== undefined) { + endedTurns.add(event.turnId); + if (endedTurns.size > ENDED_TURN_LIMIT) { + const [oldest] = endedTurns; + if (oldest !== undefined) endedTurns.delete(oldest); + } + } + return requestRead(); + }, + end: Effect.suspend(() => stopAll.pipe(Effect.andThen(Effect.sync(() => entries.clear())))), + size: () => entries.size, + }; +} diff --git a/apps/server/src/provider/acp/AcpTextGeneration.ts b/apps/server/src/provider/acp/AcpTextGeneration.ts index a8e774435..fc0b57a86 100644 --- a/apps/server/src/provider/acp/AcpTextGeneration.ts +++ b/apps/server/src/provider/acp/AcpTextGeneration.ts @@ -5,6 +5,7 @@ * * @module provider/acp/AcpTextGeneration */ +import { THREADLINES_ACP_CLIENT_INFO } from "./acpClientInfo.ts"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Option from "effect/Option"; @@ -93,7 +94,7 @@ export const makeAcpTextGeneration = Effect.fn("makeAcpTextGeneration")(function environment, childProcessSpawner: commandSpawner, cwd: runCwd, - clientInfo: { name: "threadlines-git-text", version: "0.0.0" }, + clientInfo: { ...THREADLINES_ACP_CLIENT_INFO, name: "threadlines-git-text" }, }); // Text generation needs no tools: every request is refused. yield* runtime.handleRequestPermission(() => @@ -114,11 +115,13 @@ export const makeAcpTextGeneration = Effect.fn("makeAcpTextGeneration")(function const promptResult = yield* Effect.gen(function* () { yield* runtime.start(); + const modeState = yield* runtime.getModeState; yield* Effect.ignore( runtime.setMode( descriptor.agentModeFor?.({ runtimeMode: "approval-required", interactionMode: undefined, + availableModeIds: modeState?.availableModes.map((mode) => mode.id) ?? [], }) ?? ACP_TEXT_GENERATION_MODE_ID, ), ); diff --git a/apps/server/src/provider/acp/AcpTurnMachine.test.ts b/apps/server/src/provider/acp/AcpTurnMachine.test.ts new file mode 100644 index 000000000..afd06b4fa --- /dev/null +++ b/apps/server/src/provider/acp/AcpTurnMachine.test.ts @@ -0,0 +1,975 @@ +// @effect-diagnostics nodeBuiltinImport:off -- the explorer hashes its seen states. +/** + * The turn machine's tests: an exhaustive explorer over every event + * sequence up to a depth, with steering on and off, then the named races. + * + * Every run explores to the default depths (`DEFAULT_STEER_DEPTH`, + * `DEFAULT_QUEUE_DEPTH`). `ACP_EXPLORER_FULL=1` explores to the full depths + * instead (about two and a half minutes and 2.5 GB); run it after changing + * the machine. + */ +import { createHash } from "node:crypto"; + +import { describe, expect, it } from "vite-plus/test"; + +import { + type AcpPromptOutcomeRead, + type AcpTurnCommand, + type AcpTurnEvent, + type AcpTurnMachineState, + type AcpTurnTimer, + desiredTimers, + initialTurnMachineState, + stepTurnMachine, + workPending, +} from "./AcpTurnMachine.ts"; + +type Answer = "answer"; +type State = AcpTurnMachineState; +type Event = AcpTurnEvent; +type Command = AcpTurnCommand; + +const outcome = ( + state: AcpPromptOutcomeRead["state"], + sessionLost = false, +): AcpPromptOutcomeRead => ({ state, answer: "answer", sessionLost }); + +/** What the explorer remembers beside the state: what was promised and what was kept. */ +interface Monitor { + readonly sends: number; + readonly steers: number; + readonly agentTurns: number; + /** Turns started and not ended. */ + readonly open: ReadonlyArray; + readonly closed: ReadonlyArray; + /** Sends and steers not yet accepted or turned down. */ + readonly unansweredCallers: ReadonlyArray; + /** `readOutcome` commands whose `outcomeRead` hasn't come back. */ + readonly reads: ReadonlyArray; + /** How often each call started as work (a call can start again after it was dropped). */ + readonly workStarts: number; + readonly launches: number; + /** `readChildren` commands not answered yet, any of which may answer next (the newest two). */ + readonly childReads: ReadonlyArray<{ + readonly generation: number; + readonly launches: ReadonlyArray; + }>; + /** The driver stops the session: a recycle or a stop was asked for and not yet delivered. */ + readonly stopAsked: boolean; + /** Prompts the machine sent, those written to the agent, and those whose delivery was reported. */ + readonly prompts: ReadonlyArray; + readonly written: ReadonlyArray; + readonly reported: ReadonlyArray; +} + +interface World { + readonly state: State; + readonly monitor: Monitor; +} + +const initialWorld: World = { + state: initialTurnMachineState(), + monitor: { + sends: 0, + steers: 0, + agentTurns: 0, + open: [], + closed: [], + unansweredCallers: [], + reads: [], + workStarts: 0, + launches: 0, + childReads: [], + stopAsked: false, + prompts: [], + written: [], + reported: [], + }, +}; + +/** The launches the explorer makes: one that records can cover, then a batch that they can't. */ +const LAUNCHES: ReadonlyArray = [ + ["l1", 1], + ["l2", 2], +]; + +/** + * Every event the adapter could produce next, with small bounded domains. + * `steer` off is an agent whose messages mid-turn wait (`turnMachine.steer`). + */ +function possibleEvents(world: World, steer: boolean): ReadonlyArray { + const { state, monitor } = world; + const events: Array = []; + if (monitor.sends < 2) { + events.push({ type: "send", sendId: `s${monitor.sends + 1}`, turnId: `u${monitor.sends + 1}` }); + } + if (steer && monitor.steers < 2) { + const steerId = `t${monitor.steers + 1}`; + if (state.turn !== undefined) { + events.push({ type: "steer", steerId, expectedTurnId: state.turn.id }); + } + if (monitor.steers === 0) events.push({ type: "steer", steerId, expectedTurnId: "stale" }); + } + for (const prompt of state.undispatched) events.push({ type: "promptDispatched", prompt }); + for (const prompt of state.unanswered) events.push({ type: "promptAnswered", prompt }); + for (const prompt of monitor.reads) { + events.push( + { type: "outcomeRead", prompt, outcome: outcome("completed") }, + { type: "outcomeRead", prompt, outcome: outcome("failed") }, + { type: "outcomeRead", prompt, outcome: outcome("cancelled") }, + { type: "outcomeRead", prompt, outcome: outcome("failed", true) }, + ); + } + // A command and a timer, each of which may start again after it was dropped. + if (monitor.workStarts < 3) { + for (const [id, kind] of [ + ["c1", "command"], + ["w1", "timer"], + ] as const) { + if (!state.running.some(([running]) => running === id)) { + events.push({ type: "workStarted", id, kind }); + } + } + } + const ending = new Set([...state.running.map(([id]) => id), ...(state.stopping?.commands ?? [])]); + for (const id of ending) events.push({ type: "workEnded", id }, { type: "workDropped", id }); + const launch = LAUNCHES[monitor.launches]; + if (launch !== undefined) { + events.push({ type: "subagentsLaunched", id: launch[0], count: launch[1] }); + } + // Any outstanding reading may answer next, older ones included: none at + // work, every child at work, or one that missed the newest launch. + for (const read of monitor.childReads) { + const covered = read.launches.filter(([, count]) => count === 1); + events.push( + { + type: "childrenAtWork", + generation: read.generation, + launches: covered.map(([id]) => [id, 0] as const), + }, + { + type: "childrenAtWork", + generation: read.generation, + launches: covered.map(([id, count]) => [id, count] as const), + }, + ); + if (covered.length > 0) { + events.push({ + type: "childrenAtWork", + generation: read.generation, + launches: covered.slice(0, -1).map(([id]) => [id, 0] as const), + }); + } + } + const newTurnId = `a${monitor.agentTurns + 1}`; + if (monitor.agentTurns < 2) { + events.push( + { type: "agentOutput", newTurnId }, + { type: "cancellationNotice", newTurnId }, + ...(state.requestsOpen < 2 ? [{ type: "requestOpened" as const, newTurnId }] : []), + ); + } else if (state.turn !== undefined) { + events.push({ type: "agentOutput", newTurnId }, { type: "cancellationNotice", newTurnId }); + } + events.push({ type: "replyEnded" }); + if (state.requestsOpen > 0) events.push({ type: "requestClosed" }); + events.push({ type: "stopRequested" }); + // The armed timer, and a callback of the one it replaced still queued. + for (const [timer, generation] of state.timers) { + events.push({ type: "timerFired", timer, generation }); + if (generation > 1) events.push({ type: "timerFired", timer, generation: generation - 1 }); + } + events.push({ type: "processExited" }, { type: "sessionStopping" }); + return events; +} + +function check(condition: boolean, message: string, trail: ReadonlyArray): void { + if (!condition) { + throw new Error( + `${message}\nafter: ${trail.map((event) => JSON.stringify(event)).join("\n ")}`, + ); + } +} + +const ENDS_THE_READER: ReadonlySet = new Set(["recycleAgent", "stopSession"]); + +/** Applies one event, checking every invariant on the way; returns the next world. */ +function advance(world: World, event: Event, trail: ReadonlyArray): World { + const before = world.state; + const { state, commands } = stepTurnMachine(before, event); + let monitor = world.monitor; + const types = commands.map((command) => command.type); + + // Bookkeeping of the event's own counters. + if (event.type === "send") monitor = { ...monitor, sends: monitor.sends + 1 }; + if (event.type === "steer") monitor = { ...monitor, steers: monitor.steers + 1 }; + if (event.type === "send" || event.type === "steer") { + const caller = event.type === "send" ? event.sendId : event.steerId; + monitor = { ...monitor, unansweredCallers: [...monitor.unansweredCallers, caller] }; + } + if (event.type === "workStarted") monitor = { ...monitor, workStarts: monitor.workStarts + 1 }; + if (event.type === "subagentsLaunched") monitor = { ...monitor, launches: monitor.launches + 1 }; + if (event.type === "childrenAtWork") { + monitor = { + ...monitor, + childReads: monitor.childReads.filter((read) => read.generation !== event.generation), + }; + // An older reading changes nothing. + if (event.generation !== before.childRead.generation) { + check( + JSON.stringify(state) === JSON.stringify(before), + "an older reading of the records changed the state", + trail, + ); + } + } + if (event.type === "outcomeRead") { + monitor = { ...monitor, reads: monitor.reads.filter((prompt) => prompt !== event.prompt) }; + } + if (event.type === "sessionStopping") monitor = { ...monitor, stopAsked: false }; + if (event.type === "promptDispatched" && before.undispatched.includes(event.prompt)) { + monitor = { ...monitor, written: [...monitor.written, event.prompt] }; + } + // A prompt whose setup failed (answered before it was written) is reported undelivered. + if (event.type === "promptAnswered" && before.undispatched.includes(event.prompt)) { + check( + commands.some( + (command) => + command.type === "reportDelivery" && + command.prompt === event.prompt && + !command.delivered, + ), + "a send whose setup failed was not reported undispatched", + trail, + ); + } + + // What can end the reader comes after the turn's end it goes with. + const lastEnd = types.lastIndexOf("endTurn"); + const firstStop = types.findIndex((type) => ENDS_THE_READER.has(type)); + check( + lastEnd < 0 || firstStop < 0 || lastEnd < firstStop, + "a command that ends the reader came before the turn's end", + trail, + ); + + for (const command of commands) { + switch (command.type) { + case "startTurn": + check(!monitor.open.includes(command.turnId), "a turn started twice", trail); + check(!monitor.closed.includes(command.turnId), "an ended turn started again", trail); + check(monitor.open.length === 0, "a turn started while another was open", trail); + check( + command.sendId === undefined || state.stopping === undefined, + "a turn of a send started while a stop waits", + trail, + ); + monitor = { ...monitor, open: [...monitor.open, command.turnId] }; + if (command.sendId === undefined) + monitor = { ...monitor, agentTurns: monitor.agentTurns + 1 }; + break; + case "endTurn": { + check(monitor.open.includes(command.turnId), "a turn ended that was not open", trail); + monitor = { + ...monitor, + open: monitor.open.filter((id) => id !== command.turnId), + closed: [...monitor.closed, command.turnId], + }; + // Never completed while a newer prompt of the turn is unanswered. + const turn = before.turn; + const succeeded = + command.end.kind === "agentDone" || + (command.end.kind === "answered" && command.end.outcome.state === "completed"); + if (succeeded && turn !== undefined && turn.newest !== undefined) { + check( + !turn.prompts.some( + (prompt) => prompt >= turn.newest! && state.unanswered.includes(prompt), + ), + "a turn completed while a newer prompt was unanswered", + trail, + ); + } + break; + } + case "acceptSend": + case "rejectSend": + case "acceptSteer": + case "rejectSteer": { + const caller = "sendId" in command ? command.sendId : command.steerId; + check(monitor.unansweredCallers.includes(caller), `${caller} answered twice`, trail); + monitor = { + ...monitor, + unansweredCallers: monitor.unansweredCallers.filter((id) => id !== caller), + }; + break; + } + case "readOutcome": + monitor = { ...monitor, reads: [...monitor.reads, command.prompt] }; + break; + case "reportDelivery": + check(!monitor.reported.includes(command.prompt), "a delivery reported twice", trail); + check( + command.delivered === monitor.written.includes(command.prompt), + command.delivered + ? "a prompt never written was reported dispatched" + : "a written prompt was reported undispatched", + trail, + ); + monitor = { ...monitor, reported: [...monitor.reported, command.prompt] }; + break; + case "readChildren": + check(command.launches.length > 0, "the records were read for no launch", trail); + monitor = { + ...monitor, + childReads: [ + ...monitor.childReads.slice(-1), + { generation: command.generation, launches: command.launches }, + ], + }; + break; + case "recycleAgent": + case "stopSession": + monitor = { ...monitor, stopAsked: true }; + break; + case "sendPrompt": + monitor = { ...monitor, prompts: [...monitor.prompts, command.prompt] }; + // A new turn's prompt never lands inside another turn's. + if ("sendId" in command.source && before.turn !== undefined) { + const previous = before.turn; + check( + previous.id === command.turnId || + previous.newest === undefined || + !state.unanswered.includes(previous.newest), + "a turn's prompt was sent while another turn's prompt was open", + trail, + ); + } + break; + default: + break; + } + } + + // The machine's view of the open turn matches what it announced. + check( + state.turn === undefined + ? monitor.open.length === 0 + : monitor.open.length === 1 && monitor.open[0] === state.turn.id, + "the open turn and the announced turns disagree", + trail, + ); + check( + state.subagents >= 0 && + state.wakesOwed >= 0 && + state.requestsOpen >= 0 && + state.noticesExpected >= 0, + "a count went negative", + trail, + ); + // Timers armed are exactly the ones the state needs. + check( + JSON.stringify(state.timers.map(([timer]) => timer).toSorted()) === + JSON.stringify([...desiredTimers(state)].toSorted()), + "the armed timers are not the ones the state needs", + trail, + ); + // Stop always has a deadline armed until the turn ends and the work it stopped is over. + if (!state.ended && (state.turn?.stopRequested === true || state.stopping !== undefined)) { + check( + state.timers.some(([timer]) => timer === "cancelDeadline"), + "Stop is pending with no deadline armed", + trail, + ); + } + check( + state.stopping === undefined || + state.stopping.commands.length > 0 || + state.stopping.launches.length > 0, + "a stop waits on nothing", + trail, + ); + // A queued send waits only on a turn or a stop, both of which end. + check( + state.queue.length === 0 || state.turn !== undefined || state.stopping !== undefined, + "a send is queued with nothing ahead of it", + trail, + ); + // A hold with nothing left to wait for ends by itself. + if (state.turn?.phase.tag === "waiting" && !workPending(state) && state.requestsOpen === 0) { + check( + state.timers.some(([timer]) => timer === "settle"), + "a hold with nothing left has no settle timer", + trail, + ); + } + // After Stop for a prompt not yet sent, its sending re-sends the cancel. + if (event.type === "promptDispatched" && before.turn?.stopRequested === true) { + if (before.turn.prompts.includes(event.prompt)) { + check(types.includes("sendCancel"), "a prompt went out after Stop with no cancel", trail); + } + } + // A notice owed by a cancel is expected only until its expiry fires. + if ( + event.type === "timerFired" && + event.timer === "noticeExpiry" && + before.timers.some( + ([timer, generation]) => timer === "noticeExpiry" && generation === event.generation, + ) + ) { + check(state.noticesExpected === 0, "a notice is still expected after it expired", trail); + } + if (state.noticesExpected > 0 && !state.ended) { + check( + state.timers.some(([timer]) => timer === "noticeExpiry"), + "a notice is expected with no expiry armed", + trail, + ); + } + // The session's end ends every turn and answers every caller. + if (state.ended) { + check( + state.turn === undefined && monitor.open.length === 0, + "a turn outlived the session", + trail, + ); + check(state.queue.length === 0, "a send outlived the session", trail); + check(state.stopping === undefined, "a stop outlived the session", trail); + } + if (event.type === "processExited" || event.type === "sessionStopping") { + check(state.ended && state.turn === undefined, "the session ended with a turn open", trail); + } + return { state, monitor }; +} + +/** Every caller answered, as the queue and open turns allow. */ +function callersSettled(world: World): boolean { + const waiting = new Set(world.state.queue.map((send) => send.sendId)); + return world.monitor.unansweredCallers.every((caller) => waiting.has(caller)); +} + +/** + * A fair schedule from here: the agent answers every prompt, every read + * comes back, every request is answered, its work and replies end, and + * every armed timer fires. Under it every send and steer hears back. + */ +function drain(world: World, steer: boolean): World { + let current = world; + const trail: Array = []; + for (let step = 0; step < 80; step += 1) { + const { state, monitor } = current; + if (monitor.unansweredCallers.length === 0 && state.queue.length === 0) return current; + const next: Event | undefined = + (state.undispatched[0] !== undefined + ? { type: "promptDispatched", prompt: state.undispatched[0] } + : undefined) ?? + (state.unanswered[0] !== undefined + ? { type: "promptAnswered", prompt: state.unanswered[0] } + : undefined) ?? + (monitor.reads[0] !== undefined + ? { type: "outcomeRead", prompt: monitor.reads[0], outcome: outcome("completed") } + : undefined) ?? + (state.requestsOpen > 0 ? { type: "requestClosed" } : undefined) ?? + (state.running[0] !== undefined + ? { type: "workEnded", id: state.running[0][0] } + : undefined) ?? + (state.stopping?.commands[0] !== undefined + ? { type: "workEnded", id: state.stopping.commands[0] } + : undefined) ?? + (state.replyOpen ? { type: "replyEnded" } : undefined) ?? + (state.timers[0] !== undefined + ? { type: "timerFired", timer: state.timers[0][0], generation: state.timers[0][1] } + : undefined); + if (next === undefined) break; + trail.push(next); + current = advance(current, next, trail); + } + check( + current.monitor.unansweredCallers.length === 0 && current.state.queue.length === 0, + `a send or steer never heard back under a fair schedule (steer ${steer ? "on" : "off"})`, + trail, + ); + // And every prompt sent says whether it was delivered. + check( + current.monitor.prompts.every( + (prompt) => + current.monitor.reported.includes(prompt) || current.state.undispatched.includes(prompt), + ), + "a prompt's delivery was never reported", + trail, + ); + return current; +} + +/** + * Breadth-first over every event sequence up to `depth`, skipping states + * already seen; `visit` sees each new world once. + */ +function explore(depth: number, steer: boolean, visit: (world: World) => void): number { + const seen = new Set(); + let frontier: Array<{ world: World; trail: ReadonlyArray }> = [ + { world: initialWorld, trail: [] }, + ]; + visit(initialWorld); + for (let level = 0; level < depth; level += 1) { + const next: Array<{ world: World; trail: ReadonlyArray }> = []; + for (const { world, trail } of frontier) { + for (const event of possibleEvents(world, steer)) { + const nextTrail = [...trail, event]; + const advanced = advance(world, event, nextTrail); + check(callersSettled(advanced), "a send or steer was left without an answer", nextTrail); + // A digest, not the text: millions of states fit in memory. + const key = createHash("sha1").update(JSON.stringify(advanced)).digest("base64"); + if (seen.has(key)) continue; + seen.add(key); + visit(advanced); + if (level < depth - 1) next.push({ world: advanced, trail: nextTrail }); + } + } + frontier = next; + } + return seen.size; +} + +/** Runs events from a fresh machine, returning every command in order and the last state. */ +function run(events: ReadonlyArray): { state: State; commands: Array } { + let state = initialTurnMachineState(); + const commands: Array = []; + for (const event of events) { + const step = stepTurnMachine(state, event); + state = step.state; + commands.push(...step.commands); + } + return { state, commands }; +} + +const fire = (state: State, timer: AcpTurnTimer): Event => { + const armed = state.timers.find(([name]) => name === timer); + if (armed === undefined) throw new Error(`${timer} is not armed`); + return { type: "timerFired", timer, generation: armed[1] }; +}; + +const ends = (commands: ReadonlyArray) => + commands.flatMap((command) => (command.type === "endTurn" ? [command] : [])); + +/** What must hold from every reachable world, checked as each is first reached. */ +function checkWorld(world: World, steer: boolean): void { + const state = world.state; + // Stop, from any state, ends the turn the user sees or arms the deadline; + // the deadline alone then ends everything, the turn's end before the recycle. + const stopped = stepTurnMachine(state, { type: "stopRequested" }); + if (!state.ended && (state.turn !== undefined || workPending(state))) { + const after = stopped.state; + const pending = after.turn?.stopRequested === true || after.stopping !== undefined; + if (pending) { + expect(after.timers.some(([timer]) => timer === "cancelDeadline")).toBe(true); + const deadline = stepTurnMachine(after, fire(after, "cancelDeadline")); + expect(deadline.state.turn).toBeUndefined(); + expect(deadline.state.stopping).toBeUndefined(); + const types = deadline.commands + .map((command) => command.type) + .filter((type) => type !== "armTimer" && type !== "disarmTimer"); + expect(types.at(-1)).toBe("recycleAgent"); + if (after.turn !== undefined) { + expect(ends(deadline.commands).map((end) => end.turnId)).toEqual([after.turn.id]); + } + } else if (state.turn !== undefined) { + // Ended; a queued message may have started the next turn. + expect(after.turn?.id).not.toBe(state.turn.id); + } + // Held work Stop cancelled is kept, not forgotten. + const commandsHeld = state.running.some(([, kind]) => kind === "command"); + if ( + commandsHeld && + state.turn?.phase.tag !== "prompting" && + state.turn?.phase.tag !== "settling" + ) { + expect(after.stopping).toBeDefined(); + } + } + // The session stopping or the agent exiting ends the open turn exactly once. + for (const type of ["sessionStopping", "processExited"] as const) { + if (type === "processExited" && state.ended) continue; + const step = stepTurnMachine(state, { type }); + const ended = ends(step.commands).map((end) => end.turnId); + expect(ended).toEqual(state.turn === undefined ? [] : [state.turn.id]); + expect(step.state.turn).toBeUndefined(); + expect(step.commands.some((command) => command.type === "startTurn")).toBe(false); + } + // A hold ends through timers alone once the agent's work is done. + if (state.turn?.phase.tag === "waiting" && state.requestsOpen === 0) { + const heldId = state.turn.id; + let current = state; + for (let round = 0; round < 8 && current.turn?.id === heldId; round += 1) { + const armed = current.timers.find( + ([timer]) => timer !== "cancelDeadline" && timer !== "stopCheck", + ); + if (armed === undefined) break; + current = stepTurnMachine(current, fire(current, armed[0])).state; + } + const timerRunning = current.running.some(([, kind]) => kind === "timer"); + // A queued message may have started the next turn: the held one is over. + if (!timerRunning) expect(current.turn?.id).not.toBe(heldId); + } + // Every send and steer hears back under a fair schedule. + if (world.monitor.unansweredCallers.length > 0) drain(world, steer); +} + +const FULL_DEPTH = process.env.ACP_EXPLORER_FULL === "1"; +/** + * The default run: the deepest that stays under about 30 seconds and 1 GB + * (8 and 8: about 720,000 states with steering and 290,000 without, 22 + * seconds and 0.55 GB on an M-series Mac). + */ +const DEFAULT_STEER_DEPTH = 8; +const DEFAULT_STEER_STATES = 700_000; +const DEFAULT_QUEUE_DEPTH = 8; +const DEFAULT_QUEUE_STATES = 280_000; + +describe.each( + FULL_DEPTH + ? [ + { steer: true, depth: 9, atLeast: 2_000_000 }, + { steer: false, depth: 10, atLeast: 2_000_000 }, + ] + : [ + { steer: true, depth: DEFAULT_STEER_DEPTH, atLeast: DEFAULT_STEER_STATES }, + { steer: false, depth: DEFAULT_QUEUE_DEPTH, atLeast: DEFAULT_QUEUE_STATES }, + ], +)("AcpTurnMachine, every reachable state (steering $steer)", ({ steer, depth, atLeast }) => { + // The alphabet is bounded to two sends, two steers (none with steering + // off), a command and a timer that can each start again after a drop + // (three starts in all), a launch the records can cover and a batch they + // can't, every outstanding reading of the records answering in any order + // (none at work, all at work, or one that missed a launch), up to two + // open requests, a stale timer callback beside each armed one, and two + // turns of the agent's own. The full depths, 9 with steering (about 2.6 + // million states) and 10 without (about 2.8 million), take over two + // minutes; every named race below is shorter. + let checked = 0; + const states = explore(depth, steer, (world) => { + checkWorld(world, steer); + checked += 1; + }); + + it("explores a state space large enough to mean something", () => { + expect(states).toBeGreaterThan(atLeast); + expect(checked).toBe(states + 1); + }); +}); + +describe("AcpTurnMachine, the reviewed races", () => { + it("Stop as the prompt turns into a hold ends the turn, never holds it (finding 1)", () => { + const { state, commands } = run([ + { type: "send", sendId: "s1", turnId: "u1" }, + { type: "promptDispatched", prompt: 1 }, + { type: "workStarted", id: "w1", kind: "timer" }, + { type: "stopRequested" }, + { type: "promptAnswered", prompt: 1 }, + { type: "outcomeRead", prompt: 1, outcome: outcome("completed") }, + ]); + expect(ends(commands)).toHaveLength(1); + expect(state.turn).toBeUndefined(); + // The deadline was armed once, at Stop, and stayed armed until the turn ended. + const deadline = commands.filter( + (command) => + (command.type === "armTimer" || command.type === "disarmTimer") && + command.timer === "cancelDeadline", + ); + expect(deadline.map((command) => command.type)).toEqual(["armTimer", "disarmTimer"]); + expect(commands.findIndex((command) => command.type === "disarmTimer")).toBeGreaterThan( + commands.findIndex((command) => command.type === "endTurn"), + ); + }); + + it("Stop before the prompt went out cancels again when it does, and the deadline backs it (finding 2)", () => { + const stopped = run([{ type: "send", sendId: "s1", turnId: "u1" }, { type: "stopRequested" }]); + expect(stopped.commands.filter((command) => command.type === "sendCancel")).toHaveLength(1); + const dispatched = stepTurnMachine(stopped.state, { type: "promptDispatched", prompt: 1 }); + expect(dispatched.commands).toContainEqual({ type: "sendCancel" }); + // The prompt hangs: the deadline recycles the agent and ends the turn. + const deadline = stepTurnMachine(dispatched.state, fire(dispatched.state, "cancelDeadline")); + expect(deadline.commands).toContainEqual({ type: "recycleAgent" }); + expect(ends(deadline.commands)).toEqual([ + { type: "endTurn", turnId: "u1", end: { kind: "stopped" } }, + ]); + }); + + it("a report that lands while the answer is read counts, and nothing holds the turn (finding 3)", () => { + const { state, commands } = run([ + { type: "send", sendId: "s1", turnId: "u1" }, + { type: "promptDispatched", prompt: 1 }, + { type: "subagentsLaunched", id: "l1", count: 1 }, + { type: "promptAnswered", prompt: 1 }, + { type: "agentOutput", newTurnId: "a1" }, + { type: "replyEnded" }, + { type: "outcomeRead", prompt: 1, outcome: outcome("completed") }, + ]); + expect(state.subagents).toBe(0); + expect(ends(commands).map((end) => end.turnId)).toEqual(["u1"]); + }); + + it("a batched launch counts each subagent, and each finished command owes its own wake (finding 5)", () => { + const launched = run([ + { type: "send", sendId: "s1", turnId: "u1" }, + { type: "subagentsLaunched", id: "l1", count: 2 }, + { type: "workStarted", id: "c1", kind: "command" }, + { type: "workStarted", id: "c2", kind: "command" }, + { type: "promptAnswered", prompt: 1 }, + { type: "outcomeRead", prompt: 1, outcome: outcome("completed") }, + { type: "workEnded", id: "c1" }, + { type: "workEnded", id: "c2" }, + ]); + expect(launched.state.wakesOwed).toBe(2); + let state = launched.state; + // Two wakes, then two reports: the turn holds through all four replies. + for (let reply = 0; reply < 4; reply += 1) { + expect(state.turn?.phase.tag).toBe("waiting"); + state = stepTurnMachine(state, { type: "agentOutput", newTurnId: "a1" }).state; + state = stepTurnMachine(state, { type: "replyEnded" }).state; + } + expect(state.subagents).toBe(0); + expect(state.wakesOwed).toBe(0); + const settled = stepTurnMachine(state, fire(state, "settle")); + expect(ends(settled.commands).map((end) => end.turnId)).toEqual(["u1"]); + }); + + /** A turn holding two subagents, its answer read. */ + const holdingTwo: ReadonlyArray = [ + { type: "send", sendId: "s1", turnId: "u1" }, + { type: "subagentsLaunched", id: "l1", count: 2 }, + { type: "promptAnswered", prompt: 1 }, + { type: "outcomeRead", prompt: 1, outcome: outcome("completed") }, + ]; + + /** The records' answer to the newest reading. */ + const records = (state: State, launches: ReadonlyArray): Event => ({ + type: "childrenAtWork", + generation: state.childRead.generation, + launches, + }); + + it("several reports in one reply end the hold once the records say so (child records)", () => { + const { state, commands } = run([ + ...holdingTwo, + { type: "agentOutput", newTurnId: "a1" }, + { type: "replyEnded" }, + ]); + // One reply: the protocol count alone would still hold one subagent. + expect(state.subagents).toBe(1); + expect(commands).toContainEqual({ + type: "readChildren", + generation: state.childRead.generation, + launches: [["l1", 2]], + }); + const read = stepTurnMachine(state, records(state, [["l1", 0]])); + expect(read.state.timers.map(([timer]) => timer)).toEqual(["settle"]); + }); + + it("a killed child stops holding the turn (child records)", () => { + // The records list one child reported, one killed: none running. + const held = run(holdingTwo).state; + const { state } = run([...holdingTwo, records(held, [["l1", 0]])]); + expect(state.timers.map(([timer]) => timer)).toEqual(["settle"]); + }); + + it("with no records, or a reading that misses a launch, the protocol count stands (child records)", () => { + const held = run(holdingTwo).state; + const missed = run([...holdingTwo, records(held, [])]); + expect(missed.state.children).toBeUndefined(); + expect(missed.state.timers.map(([timer]) => timer)).toEqual(["silent"]); + // Each report frees one subagent. + let state = missed.state; + for (let report = 0; report < 2; report += 1) { + state = stepTurnMachine(state, { type: "agentOutput", newTurnId: "a1" }).state; + state = stepTurnMachine(state, { type: "replyEnded" }).state; + } + expect(state.timers.map(([timer]) => timer)).toEqual(["settle"]); + }); + + it("records of an earlier launch don't cover a new one (finding 4)", () => { + // After a resume the records cover the whole conversation; the machine + // knows only this session's launch, whose record isn't written yet. + const held = run([ + { type: "send", sendId: "s1", turnId: "u1" }, + { type: "subagentsLaunched", id: "l-new", count: 1 }, + { type: "promptAnswered", prompt: 1 }, + { type: "outcomeRead", prompt: 1, outcome: outcome("completed") }, + ]).state; + // An old child, reported long ago, is no launch of this machine's. + const read = stepTurnMachine(held, records(held, [["l-old", 0]])); + expect(read.state.children).toBeUndefined(); + expect(read.state.turn?.phase.tag).toBe("waiting"); + expect(read.state.timers.map(([timer]) => timer)).toEqual(["silent"]); + }); + + it("an older reading of the records that lands last is dropped (finding 4)", () => { + const { state } = run([ + ...holdingTwo, + { type: "agentOutput", newTurnId: "a1" }, + { type: "replyEnded" }, + ]); + const newest = state.childRead.generation; + expect(newest).toBeGreaterThan(1); + // The newer reading says one is still at work; the older, slower one says none. + const current = stepTurnMachine(state, records(state, [["l1", 1]])).state; + const stale = stepTurnMachine(current, { + type: "childrenAtWork", + generation: newest - 1, + launches: [["l1", 0]], + }); + expect(stale.state).toEqual(current); + expect(stale.state.turn?.phase.tag).toBe("waiting"); + }); + + it("Stop on held work ends the turn at once and keeps the work until it ends (finding 3)", () => { + const held = run([ + { type: "send", sendId: "s1", turnId: "u1" }, + { type: "workStarted", id: "c1", kind: "command" }, + { type: "promptAnswered", prompt: 1 }, + { type: "outcomeRead", prompt: 1, outcome: outcome("completed") }, + ]).state; + const stopped = stepTurnMachine(held, { type: "stopRequested" }); + expect(ends(stopped.commands)).toEqual([ + { type: "endTurn", turnId: "u1", end: { kind: "stopped" } }, + ]); + expect(stopped.state.stopping).toEqual({ commands: ["c1"], launches: [] }); + expect(stopped.state.timers.map(([timer]) => timer)).toContain("cancelDeadline"); + // A message sent meanwhile waits for the stop. + const sent = stepTurnMachine(stopped.state, { type: "send", sendId: "s2", turnId: "u2" }); + expect(sent.commands.map((command) => command.type)).not.toContain("startTurn"); + // The agent shows the command ended: the stop is over and the message goes. + const ended = stepTurnMachine(sent.state, { type: "workEnded", id: "c1" }); + expect(ended.state.stopping).toBeUndefined(); + expect(ended.state.wakesOwed).toBe(0); + expect(ended.commands).toContainEqual({ type: "startTurn", turnId: "u2", sendId: "s2" }); + expect(ended.commands).toContainEqual({ type: "disarmTimer", timer: "cancelDeadline" }); + }); + + it("a cancel the agent ignores recycles it at the deadline, the turn's end first (findings 1 and 3)", () => { + const stopping = run([ + { type: "send", sendId: "s1", turnId: "u1" }, + { type: "workStarted", id: "c1", kind: "command" }, + { type: "promptAnswered", prompt: 1 }, + { type: "outcomeRead", prompt: 1, outcome: outcome("completed") }, + { type: "stopRequested" }, + { type: "send", sendId: "s2", turnId: "u2" }, + ]).state; + const deadline = stepTurnMachine(stopping, fire(stopping, "cancelDeadline")); + expect(deadline.commands.map((command) => command.type)).toEqual( + expect.arrayContaining(["rejectSend", "recycleAgent"]), + ); + expect(deadline.commands.findLast((command) => command.type !== "disarmTimer")).toEqual({ + type: "recycleAgent", + }); + expect(deadline.state.ended).toBe(true); + // Stop during a prompt: the turn's end goes out before the recycle. + const prompting = run([ + { type: "send", sendId: "s1", turnId: "u1" }, + { type: "stopRequested" }, + ]); + const types = stepTurnMachine( + prompting.state, + fire(prompting.state, "cancelDeadline"), + ).commands.map((command) => command.type); + expect(types.indexOf("endTurn")).toBeLessThan(types.indexOf("recycleAgent")); + }); + + it("a stop waiting on a subagent ends once the records show it stopped", () => { + const held = run([ + { type: "send", sendId: "s1", turnId: "u1" }, + { type: "subagentsLaunched", id: "l1", count: 1 }, + { type: "promptAnswered", prompt: 1 }, + { type: "outcomeRead", prompt: 1, outcome: outcome("completed") }, + ]).state; + const stopped = stepTurnMachine(held, { type: "stopRequested" }); + expect(stopped.state.stopping).toEqual({ commands: [], launches: [["l1", 1]] }); + expect(stopped.commands.map((command) => command.type)).toContain("readChildren"); + // Still at work at first; the next check finds it killed. + const working = stepTurnMachine(stopped.state, records(stopped.state, [["l1", 1]])).state; + expect(working.stopping).toBeDefined(); + const check = stepTurnMachine(working, fire(working, "stopCheck")); + const killed = stepTurnMachine(check.state, records(check.state, [["l1", 0]])); + expect(killed.state.stopping).toBeUndefined(); + expect(killed.state.timers.map(([timer]) => timer)).toEqual(["noticeExpiry"]); + }); + + it("a call taken for a command and then shown to be an MCP call holds nothing", () => { + const { state } = run([ + { type: "send", sendId: "s1", turnId: "u1" }, + { type: "workStarted", id: "c1", kind: "command" }, + { type: "workDropped", id: "c1" }, + { type: "promptAnswered", prompt: 1 }, + { type: "outcomeRead", prompt: 1, outcome: outcome("completed") }, + ]); + expect(state.turn).toBeUndefined(); + }); + + it("a cancel's notice that never comes is no longer expected after a while", () => { + const { state } = run([ + { type: "send", sendId: "s1", turnId: "u1" }, + { type: "stopRequested" }, + { type: "promptAnswered", prompt: 1 }, + { type: "outcomeRead", prompt: 1, outcome: outcome("cancelled") }, + ]); + expect(state.noticesExpected).toBe(1); + const expired = stepTurnMachine(state, fire(state, "noticeExpiry")).state; + expect(expired.noticesExpected).toBe(0); + // A later reply in those words is output, opening a turn. + const late = stepTurnMachine(expired, { type: "cancellationNotice", newTurnId: "a1" }); + expect(late.commands.map((command) => command.type)).toContain("startTurn"); + }); + + it("a revert's Stop with no turn cancels the work still running", () => { + // A command still running after its turn ended (a message ended the hold). + const { state } = run([{ type: "workStarted", id: "c1", kind: "command" }]); + expect(state.turn).toBeUndefined(); + const stopped = stepTurnMachine(state, { type: "stopRequested" }); + expect(stopped.commands).toContainEqual({ type: "sendCancel" }); + expect(stopped.state.running).toEqual([]); + expect(stopped.state.stopping).toEqual({ commands: ["c1"], launches: [] }); + }); + + it("stopping the session during a hold ends the held turn (finding 6)", () => { + const held = run([ + { type: "send", sendId: "s1", turnId: "u1" }, + { type: "workStarted", id: "c1", kind: "command" }, + { type: "promptAnswered", prompt: 1 }, + { type: "outcomeRead", prompt: 1, outcome: outcome("completed") }, + ]); + expect(held.state.turn?.phase.tag).toBe("waiting"); + const stopping = stepTurnMachine(held.state, { type: "sessionStopping" }); + expect(ends(stopping.commands)).toEqual([ + { type: "endTurn", turnId: "u1", end: { kind: "aborted" } }, + ]); + }); + + it("a cancellation notice after a quick follow-up is dropped, not shown (finding 8)", () => { + const { state, commands } = run([ + { type: "send", sendId: "s1", turnId: "u1" }, + { type: "promptDispatched", prompt: 1 }, + { type: "stopRequested" }, + { type: "promptAnswered", prompt: 1 }, + { type: "outcomeRead", prompt: 1, outcome: outcome("cancelled") }, + { type: "send", sendId: "s2", turnId: "u2" }, + { type: "promptDispatched", prompt: 2 }, + { type: "promptAnswered", prompt: 2 }, + { type: "outcomeRead", prompt: 2, outcome: outcome("completed") }, + { type: "cancellationNotice", newTurnId: "a1" }, + ]); + expect(commands.slice(-3)).toContainEqual({ type: "dropNotice" }); + expect(commands.filter((command) => command.type === "startTurn")).toHaveLength(2); + expect(state.turn).toBeUndefined(); + }); + + it("a steer while the answer is read takes the turn on; the stale outcome is ignored", () => { + const { state, commands } = run([ + { type: "send", sendId: "s1", turnId: "u1" }, + { type: "promptAnswered", prompt: 1 }, + { type: "steer", steerId: "t1", expectedTurnId: "u1" }, + { type: "outcomeRead", prompt: 1, outcome: outcome("completed") }, + ]); + expect(ends(commands)).toEqual([]); + expect(state.turn?.newest).toBe(2); + expect(state.turn?.phase.tag).toBe("prompting"); + }); +}); diff --git a/apps/server/src/provider/acp/AcpTurnMachine.ts b/apps/server/src/provider/acp/AcpTurnMachine.ts new file mode 100644 index 000000000..ea145bf98 --- /dev/null +++ b/apps/server/src/provider/acp/AcpTurnMachine.ts @@ -0,0 +1,763 @@ +/** + * AcpTurnMachine — the life of a turn for an agent whose turns outlive their + * prompt (`AcpProviderDescriptor.turnMachine`: Antigravity), as one pure + * reducer. + * + * Such an agent answers its prompt while work it started goes on (a command + * it awaits, a timer, a subagent) and replies by itself when that work ends; + * a message sent mid-turn goes as another prompt that steers the turn; Stop + * must end the turn whatever it is doing. Every source of change (a send, a + * steer, a prompt's answer, the agent's output, Stop, a timer, the process + * exiting, the session stopping) is an event, and `step` alone decides what + * the turn is and what the adapter does next. It reads no clock and does no + * I/O: the adapter runs it in one place, in order with the agent's updates + * (on the session's event reader), and carries out the commands. + * + * Timers are a function of the state (`desiredTimers`), re-derived after + * every step, so a state that needs a deadline always has one armed. Quiet + * timers ("after so long without a word from the agent") count from the + * agent's last activity in the adapter; the machine only arms, disarms and + * hears them fire. + * + * Stop ends the turn the user sees at once, but not the work: commands and + * subagents still running when Stop came are kept (`stopping`) with the + * cancel deadline armed, until the agent shows they ended or the deadline + * recycles it. A message sent meanwhile waits for that. + * + * @module provider/acp/AcpTurnMachine + */ + +/** Work the agent goes on with after its prompt answers. A timer holds the turn with no limit. */ +export type AcpWorkKind = "command" | "timer"; + +export type AcpTurnTimer = + /** Stop was asked for: past it the agent is recycled and the turn ends cancelled. */ + | "cancelDeadline" + /** A held turn with nothing left to wait for ends after a short quiet. */ + | "settle" + /** + * A reply the agent started by itself whose closing update never comes, + * or a wake a finished command owes that never comes, ends after a quiet. + */ + | "replyQuiet" + /** A turn held only by commands and subagents ends after a long silence. */ + | "silent" + /** A cancel's notice that hasn't come by now never will: it is no longer dropped. */ + | "noticeExpiry" + /** A stop waits on subagents: their records are read again. */ + | "stopCheck"; + +export const ACP_TURN_TIMERS: ReadonlyArray = [ + "cancelDeadline", + "settle", + "replyQuiet", + "silent", + "noticeExpiry", + "stopCheck", +]; + +/** How a prompt's answer reads, once the adapter has checked it. `answer` is the adapter's own. */ +export interface AcpPromptOutcomeRead { + readonly state: "completed" | "failed" | "cancelled"; + readonly answer: Answer; + /** The agent can't continue the session: it stops, and the next message starts fresh. */ + readonly sessionLost: boolean; +} + +/** Why a turn ended. */ +export type AcpTurnEnd = + /** Its last prompt's answer, as read (completed, failed or cancelled). */ + | { readonly kind: "answered"; readonly outcome: AcpPromptOutcomeRead } + /** A turn the agent started by itself, done. */ + | { readonly kind: "agentDone" } + /** Stopped: with no prompt left to answer, or when the cancel deadline passed. */ + | { readonly kind: "stopped" } + /** The agent process exited. */ + | { readonly kind: "exited" } + /** The session stopped under it. */ + | { readonly kind: "aborted" }; + +export interface AcpMachineTurn { + readonly id: string; + /** Every prompt the turn sent, oldest first. */ + readonly prompts: ReadonlyArray; + /** The prompt that carries the turn; none for a turn the agent started that took no steer. */ + readonly newest: number | undefined; + readonly phase: + | { readonly tag: "prompting" } + | { readonly tag: "settling" } + | { readonly tag: "waiting"; readonly end: AcpTurnEnd }; + readonly stopRequested: boolean; +} + +export interface AcpTurnMachineState { + /** The session is over (stopped, exited, recycled): nothing more starts. */ + readonly ended: boolean; + readonly turn: AcpMachineTurn | undefined; + readonly nextPrompt: number; + /** Prompts sent and not answered yet, of any turn. */ + readonly unanswered: ReadonlyArray; + /** Prompts not yet written to the agent (their setup may still fail). */ + readonly undispatched: ReadonlyArray; + /** Sends waiting for the running turn to end, oldest first. */ + readonly queue: ReadonlyArray<{ readonly sendId: string; readonly turnId: string }>; + /** Work running past its prompt, by tool call id. */ + readonly running: ReadonlyArray; + /** Subagent launches already counted, by tool call id (a launch counts once). */ + readonly launches: ReadonlyArray; + /** The launches that hold the turn, with how many subagents each started. */ + readonly held: ReadonlyArray; + /** Subagents launched and not yet heard back from (protocol counting). */ + readonly subagents: number; + /** + * How many of each held launch's subagents are still at work by the + * agent's own records, once a reading covered every held launch: then the + * hold follows the records, not the protocol count. A launch since then + * counts in full. + */ + readonly children: ReadonlyArray | undefined; + /** The newest `readChildren` asked for, and the launches it asked about; older readings are dropped. */ + readonly childRead: { readonly generation: number; readonly launches: ReadonlyArray }; + /** + * Work a Stop cancelled that the agent hasn't shown ended: commands by + * tool call id, subagent launches with their count. The cancel deadline + * runs meanwhile, and no new turn starts. + */ + readonly stopping: + | { + readonly commands: ReadonlyArray; + readonly launches: ReadonlyArray; + } + | undefined; + /** A reply the agent started by itself has output and no closing update yet. */ + readonly replyOpen: boolean; + /** Commands and timers that ended outside a prompt: each wakes the agent to reply once. */ + readonly wakesOwed: number; + /** Approvals and questions waiting on the user: no quiet limit runs meanwhile. */ + readonly requestsOpen: number; + /** Cancels whose notice the agent hasn't sent yet: that many notices are dropped. */ + readonly noticesExpected: number; + readonly timers: ReadonlyArray; + readonly timerGeneration: number; +} + +export type AcpTurnEvent = + /** The user sent a message: a turn of its own, after the running one. */ + | { readonly type: "send"; readonly sendId: string; readonly turnId: string } + /** The user sent a message into the running turn. */ + | { readonly type: "steer"; readonly steerId: string; readonly expectedTurnId: string } + /** A prompt was written to the agent. */ + | { readonly type: "promptDispatched"; readonly prompt: number } + /** + * A prompt answered or failed. Placed after every update it produced. One + * not written yet failed before it went out (its mode or model setup). + */ + | { readonly type: "promptAnswered"; readonly prompt: number } + /** The adapter read how a prompt really ended (`readOutcome`). */ + | { + readonly type: "outcomeRead"; + readonly prompt: number; + readonly outcome: AcpPromptOutcomeRead; + } + | { readonly type: "workStarted"; readonly id: string; readonly kind: AcpWorkKind } + | { readonly type: "workEnded"; readonly id: string } + /** A tool call taken for work turns out to be something else (an MCP call): it holds nothing. */ + | { readonly type: "workDropped"; readonly id: string } + | { readonly type: "subagentsLaunched"; readonly id: string; readonly count: number } + /** + * The agent's own records, for the `readChildren` of `generation`: how + * many subagents of each launch they show still at work. A launch the + * records don't cover (its record not written yet) is left out. + */ + | { + readonly type: "childrenAtWork"; + readonly generation: number; + readonly launches: ReadonlyArray; + } + /** The agent sent something. `newTurnId` names the turn it opens if none runs. */ + | { readonly type: "agentOutput"; readonly newTurnId: string } + /** The `usage_update` that closes each model call. */ + | { readonly type: "replyEnded" } + /** The agent asked the user something (an approval, a question). */ + | { readonly type: "requestOpened"; readonly newTurnId: string } + | { readonly type: "requestClosed" } + /** The agent's cancellation notice arrived. */ + | { readonly type: "cancellationNotice"; readonly newTurnId: string } + | { readonly type: "stopRequested" } + | { readonly type: "timerFired"; readonly timer: AcpTurnTimer; readonly generation: number } + | { readonly type: "processExited" } + | { readonly type: "sessionStopping" }; + +export type AcpTurnCommand = + /** Open the turn: a user's (`sendId`) or the agent's own. */ + | { readonly type: "startTurn"; readonly turnId: string; readonly sendId?: string } + | { + readonly type: "sendPrompt"; + readonly prompt: number; + readonly turnId: string; + readonly source: { readonly sendId: string } | { readonly steerId: string }; + } + | { readonly type: "acceptSend"; readonly sendId: string; readonly turnId: string } + /** + * Whether a prompt was written to the agent, said once per prompt: true + * as it goes out, false when it failed first or the session ended before + * it did. Only a written prompt delivered what it carried. + */ + | { readonly type: "reportDelivery"; readonly prompt: number; readonly delivered: boolean } + | { readonly type: "rejectSend"; readonly sendId: string } + | { readonly type: "acceptSteer"; readonly steerId: string; readonly turnId: string } + | { + readonly type: "rejectSteer"; + readonly steerId: string; + readonly reason: "no-active-turn" | "turn-finishing"; + } + /** Read how the prompt really ended, then report `outcomeRead`. */ + | { readonly type: "readOutcome"; readonly prompt: number } + /** Read which of these launches' children are still at work, then report `childrenAtWork` with `generation`. */ + | { + readonly type: "readChildren"; + readonly generation: number; + readonly launches: ReadonlyArray; + } + | { readonly type: "recordUsage"; readonly prompt: number } + | { readonly type: "sendCancel" } + /** The turn's one terminal event. */ + | { readonly type: "endTurn"; readonly turnId: string; readonly end: AcpTurnEnd } + | { readonly type: "armTimer"; readonly timer: AcpTurnTimer; readonly generation: number } + | { readonly type: "disarmTimer"; readonly timer: AcpTurnTimer } + /** The cancel deadline passed: stop the agent process. Comes after the turn's end. */ + | { readonly type: "recycleAgent" } + | { readonly type: "stopSession"; readonly reason: "exited" | "sessionLost" } + | { readonly type: "markSessionLost" } + /** The notice just seen is the one a cancel owed: show nothing. */ + | { readonly type: "dropNotice" }; + +export interface AcpTurnStep { + readonly state: AcpTurnMachineState; + readonly commands: ReadonlyArray>; +} + +export function initialTurnMachineState(): AcpTurnMachineState { + return { + ended: false, + turn: undefined, + nextPrompt: 1, + unanswered: [], + undispatched: [], + queue: [], + running: [], + launches: [], + held: [], + subagents: 0, + children: undefined, + childRead: { generation: 0, launches: [] }, + stopping: undefined, + replyOpen: false, + wakesOwed: 0, + requestsOpen: 0, + noticesExpected: 0, + timers: [], + timerGeneration: 0, + }; +} + +/** How many of a held launch's subagents the records show at work; its count when they don't say. */ +function launchOut(state: AcpTurnMachineState, [id, count]: readonly [string, number]) { + return state.children?.find(([launch]) => launch === id)?.[1] ?? count; +} + +/** + * Subagents still out: by the agent's own records when a reading covered + * every held launch (any launched since counting in full), else the + * protocol count. + */ +export function subagentsOut(state: AcpTurnMachineState): number { + if (state.children === undefined) return state.subagents; + return state.held.reduce((sum, launch) => sum + launchOut(state, launch), 0); +} + +/** Something the agent still owes the turn: work, a subagent, a wake, an open reply. */ +export function workPending(state: AcpTurnMachineState): boolean { + return ( + state.running.length > 0 || subagentsOut(state) > 0 || state.replyOpen || state.wakesOwed > 0 + ); +} + +/** The timers a state needs armed. */ +export function desiredTimers(state: AcpTurnMachineState): ReadonlyArray { + if (state.ended) return []; + const timers: Array = []; + if (state.noticesExpected > 0) timers.push("noticeExpiry"); + const turn = state.turn; + if (turn?.stopRequested === true || state.stopping !== undefined) timers.push("cancelDeadline"); + if (state.stopping !== undefined && state.stopping.launches.length > 0) timers.push("stopCheck"); + if (turn === undefined) return timers; + const quietAllowed = state.requestsOpen === 0 && !turn.stopRequested; + // A reply under way, or one a finished command owes, that never ends. + if (quietAllowed && turn.phase.tag !== "prompting" && (state.replyOpen || state.wakesOwed > 0)) { + timers.push("replyQuiet"); + } + if (quietAllowed && turn.phase.tag === "waiting") { + if (!workPending(state)) timers.push("settle"); + else if ( + !state.replyOpen && + state.wakesOwed === 0 && + !state.running.some(([, kind]) => kind === "timer") + ) { + timers.push("silent"); + } + } + return timers; +} + +type Mutable = { -readonly [K in keyof T]: T[K] }; + +/** Applies one event: the next state and what the adapter does, in order. */ +export function stepTurnMachine( + previous: AcpTurnMachineState, + event: AcpTurnEvent, +): AcpTurnStep { + const state: Mutable> = { ...previous }; + const commands: Array> = []; + + const clearWork = () => { + state.running = []; + state.held = []; + state.subagents = 0; + // Back to counting by protocol until the records are read again. + state.children = undefined; + state.replyOpen = false; + state.wakesOwed = 0; + }; + + /** + * Stop on work the agent still runs: the cancel is sent, and the commands + * and subagents it must end are kept until the agent shows they did (a + * timer gives no word when a cancel ends it, so none is waited on). + */ + const stopWork = () => { + const commands = state.running.flatMap(([id, kind]) => (kind === "command" ? [id] : [])); + const launches = + subagentsOut(state) > 0 + ? state.held.filter( + (launch) => state.children === undefined || launchOut(state, launch) > 0, + ) + : []; + clearWork(); + if (commands.length === 0 && launches.length === 0) return; + const previous = state.stopping; + state.stopping = { + commands: [...new Set([...(previous?.commands ?? []), ...commands])], + launches: [ + ...(previous?.launches ?? []), + ...launches.filter(([id]) => previous?.launches.some(([old]) => old === id) !== true), + ], + }; + readChildren(); + }; + + /** The stopped work is all over: what waited on it goes on. */ + const settleStopping = () => { + const stopping = state.stopping; + if (stopping === undefined || stopping.commands.length > 0 || stopping.launches.length > 0) { + return; + } + state.stopping = undefined; + startQueued(); + }; + + const startPromptTurn = (send: { readonly sendId: string; readonly turnId: string }) => { + const prompt = state.nextPrompt; + state.nextPrompt += 1; + state.turn = { + id: send.turnId, + prompts: [prompt], + newest: prompt, + phase: { tag: "prompting" }, + stopRequested: false, + }; + state.unanswered = [...state.unanswered, prompt]; + state.undispatched = [...state.undispatched, prompt]; + state.replyOpen = false; + state.wakesOwed = 0; + commands.push( + { type: "startTurn", turnId: send.turnId, sendId: send.sendId }, + { type: "sendPrompt", prompt, turnId: send.turnId, source: { sendId: send.sendId } }, + { type: "acceptSend", sendId: send.sendId, turnId: send.turnId }, + ); + }; + + /** + * The next queued send starts once no turn runs. A turn ends only once + * its newest prompt has answered (or the session ends), so the new prompt + * never lands inside another turn's; an older prompt a steer replaced is + * the agent's to answer and holds nothing up. + */ + const startQueued = () => { + if (state.ended || state.turn !== undefined || state.stopping !== undefined) return; + const [next, ...rest] = state.queue; + if (next === undefined) return; + state.queue = rest; + startPromptTurn(next); + }; + + const rejectQueue = () => { + for (const send of state.queue) commands.push({ type: "rejectSend", sendId: send.sendId }); + state.queue = []; + }; + + const endTurn = (end: AcpTurnEnd) => { + const turn = state.turn; + if (turn === undefined) return; + commands.push({ type: "endTurn", turnId: turn.id, end }); + state.turn = undefined; + state.replyOpen = false; + state.wakesOwed = 0; + startQueued(); + }; + + /** Called before the turn's end, so the end starts no queued send. */ + const endSession = () => { + state.ended = true; + clearWork(); + state.stopping = undefined; + rejectQueue(); + // A prompt not written by now never delivered anything. + for (const prompt of state.undispatched) { + commands.push({ type: "reportDelivery", prompt, delivered: false }); + } + state.undispatched = []; + }; + + /** Output outside a prompt opens a reply; with no turn, a turn of the agent's own. */ + const agentSpoke = (newTurnId: string) => { + if (state.ended) return; + const turn = state.turn; + if (turn === undefined) { + state.turn = { + id: newTurnId, + prompts: [], + newest: undefined, + phase: { tag: "waiting", end: { kind: "agentDone" } }, + stopRequested: false, + }; + state.replyOpen = true; + commands.push({ type: "startTurn", turnId: newTurnId }); + return; + } + if (turn.phase.tag !== "prompting") state.replyOpen = true; + }; + + /** + * A reply the agent started by itself is over: it answered a wake, else a + * subagent's report. With subagents out, the records are read again: they + * say exactly which are done (several reports in one reply, a kill). + */ + const endReply = () => { + state.replyOpen = false; + if (state.wakesOwed > 0) state.wakesOwed -= 1; + else if (state.subagents > 0) state.subagents -= 1; + readChildren(); + }; + + /** + * Asks the records which children of the held launches (and of launches + * a stop waits on) are still at work, when any are counted out. + */ + const readChildren = () => { + if (state.ended) return; + const held = subagentsOut(state) > 0 ? state.held : []; + const stopped = state.stopping?.launches ?? []; + const launches = [...held, ...stopped.filter(([id]) => !held.some(([own]) => own === id))]; + if (launches.length === 0) return; + const generation = state.childRead.generation + 1; + state.childRead = { generation, launches: launches.map(([id]) => id) }; + commands.push({ type: "readChildren", generation, launches }); + }; + + /** A held turn whose work is all done and quiet, or that went silent, ends. */ + const endWaiting = () => { + const turn = state.turn; + if (turn?.phase.tag === "waiting") endTurn(turn.phase.end); + }; + + switch (event.type) { + case "send": { + if (state.ended) { + commands.push({ type: "rejectSend", sendId: event.sendId }); + break; + } + state.queue = [...state.queue, { sendId: event.sendId, turnId: event.turnId }]; + // A message sent while a turn waits on the agent's work, or runs as + // the agent's own, ends that turn; the agent takes the message after it. + if (state.turn?.phase.tag === "waiting") endWaiting(); + else startQueued(); + break; + } + case "steer": { + const turn = state.turn; + if (state.ended || turn === undefined || turn.id !== event.expectedTurnId) { + commands.push({ type: "rejectSteer", steerId: event.steerId, reason: "no-active-turn" }); + break; + } + if (turn.stopRequested) { + commands.push({ type: "rejectSteer", steerId: event.steerId, reason: "turn-finishing" }); + break; + } + const prompt = state.nextPrompt; + state.nextPrompt += 1; + state.turn = { + ...turn, + prompts: [...turn.prompts, prompt], + newest: prompt, + phase: { tag: "prompting" }, + }; + state.unanswered = [...state.unanswered, prompt]; + state.undispatched = [...state.undispatched, prompt]; + // What the agent did by itself is over: this prompt carries the turn on. + state.replyOpen = false; + state.wakesOwed = 0; + commands.push( + { type: "sendPrompt", prompt, turnId: turn.id, source: { steerId: event.steerId } }, + { type: "acceptSteer", steerId: event.steerId, turnId: turn.id }, + ); + break; + } + case "promptDispatched": { + if (!state.undispatched.includes(event.prompt)) break; + state.undispatched = state.undispatched.filter((prompt) => prompt !== event.prompt); + commands.push({ type: "reportDelivery", prompt: event.prompt, delivered: true }); + // A cancel sent before this prompt went out may have reached the agent first. + const turn = state.turn; + if (turn?.stopRequested === true && turn.prompts.includes(event.prompt)) { + commands.push({ type: "sendCancel" }); + } + break; + } + case "promptAnswered": { + if (!state.unanswered.includes(event.prompt)) break; + state.unanswered = state.unanswered.filter((prompt) => prompt !== event.prompt); + if (state.undispatched.includes(event.prompt)) { + // Its setup failed: the prompt never went out. + state.undispatched = state.undispatched.filter((prompt) => prompt !== event.prompt); + commands.push({ type: "reportDelivery", prompt: event.prompt, delivered: false }); + } + commands.push({ type: "recordUsage", prompt: event.prompt }); + const turn = state.turn; + if (turn !== undefined && !state.ended) { + if (turn.newest === event.prompt && turn.phase.tag === "prompting") { + state.turn = { ...turn, phase: { tag: "settling" } }; + commands.push({ type: "readOutcome", prompt: event.prompt }); + readChildren(); + } + } + break; + } + case "outcomeRead": { + const turn = state.turn; + if ( + turn === undefined || + state.ended || + turn.newest !== event.prompt || + turn.phase.tag !== "settling" + ) { + break; + } + const end: AcpTurnEnd = { kind: "answered", outcome: event.outcome }; + if (event.outcome.sessionLost) { + endSession(); + endTurn(end); + commands.push({ type: "markSessionLost" }, { type: "stopSession", reason: "sessionLost" }); + break; + } + if (turn.stopRequested) { + stopWork(); + endTurn(end); + break; + } + if (event.outcome.state === "completed" && workPending(state)) { + state.turn = { ...turn, phase: { tag: "waiting", end } }; + break; + } + if (event.outcome.state !== "completed") clearWork(); + endTurn(end); + break; + } + case "workStarted": { + state.running = [ + ...state.running.filter(([id]) => id !== event.id), + [event.id, event.kind] as const, + ]; + break; + } + case "workEnded": { + const stopping = state.stopping; + if (stopping?.commands.includes(event.id) === true) { + // A command the cancel ended: its end wakes nothing. + state.stopping = { + ...stopping, + commands: stopping.commands.filter((id) => id !== event.id), + }; + settleStopping(); + break; + } + if (!state.running.some(([id]) => id === event.id)) break; + state.running = state.running.filter(([id]) => id !== event.id); + // Outside a prompt, its wake (not a subagent's report) is the reply that follows. + if (state.turn?.phase.tag !== "prompting") state.wakesOwed += 1; + break; + } + case "workDropped": { + state.running = state.running.filter(([id]) => id !== event.id); + const stopping = state.stopping; + if (stopping?.commands.includes(event.id) === true) { + state.stopping = { + ...stopping, + commands: stopping.commands.filter((id) => id !== event.id), + }; + settleStopping(); + } + break; + } + case "subagentsLaunched": { + if (state.launches.includes(event.id) || event.count <= 0) break; + state.launches = [...state.launches, event.id]; + state.held = [...state.held, [event.id, event.count] as const]; + state.subagents += event.count; + break; + } + case "childrenAtWork": { + // Only the newest reading counts: an older one may say less than it knows. + if (state.ended || event.generation !== state.childRead.generation) break; + const covered = new Map(event.launches); + const asked = state.held.filter(([id]) => state.childRead.launches.includes(id)); + // A reading that misses a held launch (its record not written yet) + // proves nothing about it: the count stands as it was. + if (asked.length > 0 && asked.every(([id]) => covered.has(id))) { + state.children = asked.map( + ([id, count]) => [id, Math.min(count, Math.max(0, covered.get(id) ?? count))] as const, + ); + } + const stopping = state.stopping; + if (stopping !== undefined) { + state.stopping = { + ...stopping, + launches: stopping.launches.filter(([id]) => covered.get(id) !== 0), + }; + settleStopping(); + } + break; + } + case "agentOutput": { + agentSpoke(event.newTurnId); + break; + } + case "replyEnded": { + if (state.replyOpen) endReply(); + break; + } + case "requestOpened": { + agentSpoke(event.newTurnId); + if (!state.ended) state.requestsOpen += 1; + break; + } + case "requestClosed": { + state.requestsOpen = Math.max(0, state.requestsOpen - 1); + break; + } + case "cancellationNotice": { + if (state.noticesExpected > 0) { + state.noticesExpected -= 1; + commands.push({ type: "dropNotice" }); + } else { + agentSpoke(event.newTurnId); + } + break; + } + case "stopRequested": { + const turn = state.turn; + // No turn, but work the agent still runs (a revert stops it): cancel it. + if (!state.ended && turn === undefined && workPending(state)) { + commands.push({ type: "sendCancel" }); + state.noticesExpected += 1; + stopWork(); + break; + } + if (state.ended || turn === undefined || turn.stopRequested) break; + commands.push({ type: "sendCancel" }); + // Each cancel may be followed by the agent's notice; that one is dropped. + state.noticesExpected += 1; + if (turn.phase.tag === "waiting") { + // Nothing to answer: the turn ends now, and the work it waited on + // stays stopping until the agent shows it ended. + stopWork(); + endTurn({ kind: "stopped" }); + break; + } + state.turn = { ...turn, stopRequested: true }; + break; + } + case "timerFired": { + const armed = state.timers.find(([timer]) => timer === event.timer); + if (armed === undefined || armed[1] !== event.generation) break; + state.timers = state.timers.filter(([timer]) => timer !== event.timer); + switch (event.timer) { + case "cancelDeadline": + if (state.turn?.stopRequested === true || state.stopping !== undefined) { + // The turn's end goes out before the recycle that ends the reader. + endSession(); + endTurn({ kind: "stopped" }); + commands.push({ type: "recycleAgent" }); + } + break; + case "stopCheck": + readChildren(); + break; + case "replyQuiet": + if (state.replyOpen) endReply(); + // A wake that never came. + else if (state.wakesOwed > 0) state.wakesOwed -= 1; + break; + case "settle": + if (!workPending(state)) endWaiting(); + break; + case "silent": + clearWork(); + endWaiting(); + break; + case "noticeExpiry": + state.noticesExpected = 0; + break; + } + break; + } + case "processExited": { + if (state.ended) break; + endSession(); + endTurn({ kind: "exited" }); + commands.push({ type: "stopSession", reason: "exited" }); + break; + } + case "sessionStopping": { + endSession(); + endTurn({ kind: "aborted" }); + break; + } + } + + // Timers follow the state: arm what it needs, disarm what it no longer does. + const wanted = desiredTimers(state); + const timers: Array = []; + for (const [timer, generation] of state.timers) { + if (wanted.includes(timer)) timers.push([timer, generation]); + else commands.push({ type: "disarmTimer", timer }); + } + for (const timer of wanted) { + if (timers.some(([armed]) => armed === timer)) continue; + state.timerGeneration += 1; + timers.push([timer, state.timerGeneration]); + commands.push({ type: "armTimer", timer, generation: state.timerGeneration }); + } + state.timers = timers; + return { state, commands }; +} diff --git a/apps/server/src/provider/acp/AntigravityAcpSupport.test.ts b/apps/server/src/provider/acp/AntigravityAcpSupport.test.ts index f8a206078..81e979654 100644 --- a/apps/server/src/provider/acp/AntigravityAcpSupport.test.ts +++ b/apps/server/src/provider/acp/AntigravityAcpSupport.test.ts @@ -1,16 +1,21 @@ -import { LEGACY_RUNTIME_MODES, RUNTIME_MODES } from "@threadlines/contracts"; -import { effectiveRuntimeMode } from "@threadlines/shared/runtimeMode"; +import { RUNTIME_MODES } from "@threadlines/contracts"; import { describe, expect, it } from "vite-plus/test"; import type * as EffectAcpSchema from "effect-acp/schema"; import { antigravityAgentMode, + antigravityAgentProblem, + antigravityModelsFromCatalog, antigravityModelsFromChoices, + isAntigravityPlanFileEdit, + isLegacyAntigravityServerPath, + nextAntigravityCatalog, parseAntigravitySignInUrl, resolveAntigravityModelId, } from "./AntigravityAcpSupport.ts"; -// The model list a free-tier account got from agy-acp-server 1.3.0. +// The model list a free-tier account got from agy-acp-server 1.3.0, which +// named the reasoning level in the model. const RECORDED_CHOICES = [ ["gemini-3.8-flash-high", "Gemini 3.8 Flash (High)"], ["gemini-3.8-flash-medium", "Gemini 3.8 Flash (Medium)"], @@ -64,14 +69,114 @@ describe("Antigravity models", () => { }); describe("antigravityAgentMode", () => { - it("runs a level Antigravity lacks at the level the composer shows", () => { + const CLI_MODES = ["default", "accept-edits", "plan", "auto"]; + + it("maps each access level onto the CLI's modes, never to one it refuses", () => { + expect( + RUNTIME_MODES.map((mode) => [mode, antigravityAgentMode(mode, "default", CLI_MODES)]), + ).toEqual([ + ["approval-required", "default"], + ["auto-accept-edits", "accept-edits"], + ["auto", "auto"], + // Full access has no CLI mode: Threadlines answers each request. + ["full-access", "default"], + ]); + expect(antigravityAgentMode("full-access", "plan", CLI_MODES)).toBe("default"); + }); + + it("runs Auto as Auto-accept edits where the session offers no Auto", () => { + const withoutAuto = CLI_MODES.filter((mode) => mode !== "auto"); + expect(antigravityAgentMode("auto", "default", withoutAuto)).toBe("accept-edits"); for (const mode of RUNTIME_MODES) { - const shown = effectiveRuntimeMode(mode, LEGACY_RUNTIME_MODES)!; - expect(antigravityAgentMode(mode, "default"), mode).toBe( - antigravityAgentMode(shown, "default"), - ); + expect(withoutAuto, mode).toContain(antigravityAgentMode(mode, "default", withoutAuto)); } - expect(antigravityAgentMode("auto", "default")).toBe("auto_edit"); + }); +}); + +describe("antigravityAgentProblem", () => { + const problem = (version: string | undefined) => + antigravityAgentProblem({ + agentInfo: version === undefined ? null : { name: "Antigravity ACP Server", version }, + }); + + it("refuses an agent older than the minimum, or one that won't say its version", () => { + expect(problem("1.5.14")).toBeUndefined(); + expect(problem("1.6.0")).toBeUndefined(); + expect(problem("1.5.13")).toContain("needs 1.5.14 or newer"); + expect(problem("1.5.2")).toContain("is 1.5.2"); + // Build tags and prereleases don't lift a version over the minimum. + expect(problem("1.5.9+local")).toContain("needs 1.5.14 or newer"); + expect(problem("1.5.14-rc.1")).toContain("needs 1.5.14 or newer"); + expect(problem("1.5.14+build.7")).toBeUndefined(); + expect(problem(undefined)).toContain("doesn't say its version"); + }); + + it("knows a path to Google's old server, which the CLI replaced", () => { + expect(isLegacyAntigravityServerPath("/opt/agy/agy_acp_server.par")).toBe(true); + expect(isLegacyAntigravityServerPath("C:\\agy\\agy_acp_server.exe")).toBe(true); + expect(isLegacyAntigravityServerPath("/usr/local/bin/agy")).toBe(false); + }); +}); + +describe("Antigravity reasoning levels", () => { + const thought = (current: string, values: ReadonlyArray) => + ({ + id: "thought_level", + name: "Thinking", + category: "thought_level", + type: "select", + currentValue: current, + options: values.map((value) => ({ value, name: value[0]!.toUpperCase() + value.slice(1) })), + }) satisfies EffectAcpSchema.SessionConfigOption; + const model = (current: string) => + ({ + id: "model", + name: "Model", + category: "model", + type: "select", + currentValue: current, + options: [ + { value: "gemini-4-argon", name: "Gemini 4 Argon" }, + { value: "claude-sonnet-4-6", name: "Claude Sonnet 4.6" }, + { value: "gpt-6-1", name: "GPT-6.1" }, + ], + }) satisfies EffectAcpSchema.SessionConfigOption; + + it("remembers each model's own levels as sessions report them", () => { + const first = nextAntigravityCatalog(undefined, [ + model("gemini-4-argon"), + thought("high", ["low", "medium", "high"]), + ]); + // Claude has no reasoning option of its own in this session. + const second = nextAntigravityCatalog(first as never, [model("claude-sonnet-4-6")]); + const models = antigravityModelsFromCatalog(second!); + const levels = (slug: string) => { + const descriptor = models.find((entry) => entry.slug === slug)?.capabilities + ?.optionDescriptors?.[0]; + return descriptor?.type === "select" + ? [descriptor.id, descriptor.options.map((option) => option.id)] + : undefined; + }; + // Models keep the agent's own ids, so they are sent back unchanged. + expect(models.map((entry) => entry.slug)).toEqual([ + "gemini-4-argon", + "claude-sonnet-4-6", + "gpt-6-1", + ]); + expect(levels("gemini-4-argon")).toEqual(["thought_level", ["low", "medium", "high"]]); + expect(levels("claude-sonnet-4-6")).toBeUndefined(); + // Not seen yet: the current model's levels stand in (here, none). + expect(levels("gpt-6-1")).toBeUndefined(); + }); + + it("falls back to folding names when the agent names the level in the model", () => { + const next = nextAntigravityCatalog(undefined, configOptions); + expect(next?.thoughtLevels).toBeUndefined(); + expect(antigravityModelsFromCatalog(next!).map((entry) => entry.slug)).toEqual([ + "gemini-3.8-flash", + "gemini-3.7-flash", + "gemini-3.1-pro", + ]); }); }); @@ -100,3 +205,23 @@ describe("parseAntigravitySignInUrl", () => { ); }); }); + +describe("isAntigravityPlanFileEdit", () => { + const brain = "/profile/antigravity-acp/brain"; + const edit = (path: string) => ({ + toolCallId: "call_plan", + kind: "edit", + data: { + content: [{ type: "diff", path, oldText: "", newText: "# Plan" }], + locations: [{ path }], + }, + }); + + it("takes only the asking session's own plan, never a path with dot steps", () => { + expect(isAntigravityPlanFileEdit(edit(`${brain}/s1/plan.md`), brain, "s1")).toBe(true); + // Through a link inside the session's folder these open another file. + expect(isAntigravityPlanFileEdit(edit(`${brain}/s1/link/../plan.md`), brain, "s1")).toBe(false); + expect(isAntigravityPlanFileEdit(edit(`${brain}/s1/./plan.md`), brain, "s1")).toBe(false); + expect(isAntigravityPlanFileEdit(edit(`${brain}/s2/plan.md`), brain, "s1")).toBe(false); + }); +}); diff --git a/apps/server/src/provider/acp/AntigravityAcpSupport.ts b/apps/server/src/provider/acp/AntigravityAcpSupport.ts index 863f7f4ee..7b3e319fd 100644 --- a/apps/server/src/provider/acp/AntigravityAcpSupport.ts +++ b/apps/server/src/provider/acp/AntigravityAcpSupport.ts @@ -3,18 +3,28 @@ * ACP driver, built per provider instance (each instance has its own * profile and shares the managed runtime). * - * Antigravity runs as Google's own ACP server (`agy_acp_server`), which - * Threadlines downloads and verifies itself (`antigravity/AntigravityRuntime`). - * What differs from other ACP agents, from a recorded 1.3.0 session: + * Antigravity runs as Google's Antigravity CLI in ACP mode (`agy acp`), + * which Threadlines downloads and verifies itself + * (`antigravity/AntigravityRuntime`), or a custom `agy` the user names. + * Either must be at least `ANTIGRAVITY_MIN_VERSION`. What differs from other + * ACP agents: * - * - Sign-in prints a Google URL on stderr and listens on a 127.0.0.1 port - * for the redirect; outside a sign-in flow that line means "sign in again". - * - Modes `default` / `auto_edit` / `yolo` map onto the runtime modes. + * - Sign-in happens outside ACP (`antigravity/AntigravityAuth`); a session + * without one is refused, and the status says so. + * - Modes `default` / `accept-edits` / `auto` (where the session offers it) + * map onto the runtime modes; full access runs in `default` and + * Threadlines answers each request. * - Questions arrive as permission requests (`interaction_*` ids). - * - Model names carry the effort ("Gemini 3.8 Flash (High)"); Threadlines - * lists each family once with a Reasoning option. + * - The reasoning level is its own `thought_level` option, listed for the + * selected model only, so each model's levels are remembered as they are + * seen. Older agents folded it into the model name ("Gemini 3.8 Flash + * (High)"); that is still read as a fallback. * - `/plan ` writes a plan file into the profile and stops for review: * that is plan mode. + * - The session lists its own `/` commands and skills, which the composer + * offers; a message starting with one goes as typed. + * - It can't rewind its conversation, so a revert starts a new session + * seeded with the turns kept. * - Edits carry exact ACP `diff` content, and the agent writes the files * itself, so no client file system is offered. * @@ -23,8 +33,8 @@ import { spawn as spawnChild } from "node:child_process"; import { existsSync } from "node:fs"; import * as fs from "node:fs/promises"; -import { tmpdir } from "node:os"; -import { dirname, join, resolve as resolvePath, sep } from "node:path"; +import { homedir, tmpdir } from "node:os"; +import { isAbsolute, join, normalize, resolve as resolvePath } from "node:path"; import { createInterface } from "node:readline"; import { @@ -40,6 +50,7 @@ import { createModelCapabilities, getProviderOptionSelectionValue, } from "@threadlines/shared/model"; +import { compareSemverVersions } from "@threadlines/shared/semver"; import * as Effect from "effect/Effect"; import * as Schema from "effect/Schema"; import { withUsualCommandLookup } from "@threadlines/shared/windowsCommandLookup"; @@ -47,20 +58,34 @@ import * as EffectAcpErrors from "effect-acp/errors"; import type * as EffectAcpSchema from "effect-acp/schema"; import { - ANTIGRAVITY_RELEASE, + ANTIGRAVITY_MIN_VERSION, antigravityLaunchArgs, type AntigravityPlatformRelease, } from "../antigravity/AntigravityRelease.ts"; +import type { AntigravityReleaseSource } from "../antigravity/AntigravityReleaseSource.ts"; +import { antigravityAttachmentDelivery } from "../antigravity/AntigravityAttachments.ts"; +import { antigravitySubagents } from "../antigravity/AntigravitySubagents.ts"; +import { + normalizeAntigravitySessionUpdate, + normalizeAntigravityToolCall, +} from "../antigravity/AntigravityToolCalls.ts"; +import { antigravityTurnBehavior } from "../antigravity/AntigravityTurns.ts"; import { acquireAntigravityTempDir, recordAntigravityAgent, antigravityEnvironment, + type AntigravityCatalogCache, type AntigravityInstancePaths, type AntigravityModelChoice, + type AntigravityThoughtLevels, prepareAntigravityProfile, + readAntigravityAgentRefusal, readAntigravityCatalog, + writeAntigravityAgentRefusal, writeAntigravityCatalog, } from "../antigravity/AntigravityProfile.ts"; +import { makeAntigravitySkillsLister } from "../antigravity/AntigravitySkills.ts"; +import { antigravityUserHome } from "../antigravity/AntigravityUserConfig.ts"; import { holdLaunchGate, type LaunchGate } from "../managedRuntime/LaunchGate.ts"; import { antigravityCredentialEnvironment, @@ -71,18 +96,26 @@ import { readAntigravitySignInCheck, resolveAntigravityAdc, } from "../antigravity/AntigravitySignInMethod.ts"; -import type { AntigravityRuntime } from "../antigravity/AntigravityRuntime.ts"; +import type { + AntigravityInstalledRuntime, + AntigravityRuntime, +} from "../antigravity/AntigravityRuntime.ts"; +import { + type AntigravityUsageReader, + withAntigravityUsage, +} from "../antigravity/AntigravityUsage.ts"; import { detectionAt } from "../providerDetection.ts"; import type { ProviderMaintenanceCapabilities, ProviderMaintenanceCommandAction, } from "../providerMaintenance.ts"; +import { THREADLINES_ACP_CLIENT_INFO } from "./acpClientInfo.ts"; import type { AcpProviderDescriptor, AcpProviderProbeOutcome } from "./AcpProviderDescriptor.ts"; import { flattenSessionConfigSelectOptions, selectConfigOptionCurrentValue, } from "./AcpProviderModels.ts"; -import { findModelConfigOption } from "./AcpRuntimeModel.ts"; +import { type AcpToolCallState, findModelConfigOption } from "./AcpRuntimeModel.ts"; import { ProviderSetupError } from "../Errors.ts"; const decodeAntigravitySettings = Schema.decodeSync(AntigravitySettings); @@ -96,30 +129,92 @@ const VALIDATE_TIMEOUT_MS = 90_000; export const ANTIGRAVITY_PRESENTATION = { displayName: DISPLAY_NAME, showInteractionModeToggle: true, + // Auto runs the CLI's own `auto` where the session offers it, else + // Auto-accept edits (`antigravityAgentMode`). + supportedRuntimeModes: ["approval-required", "auto-accept-edits", "auto", "full-access"], } as const; /** - * The agent's own mode for a thread's access level. Antigravity has no Auto, - * so Auto runs at the next safer level, Auto-accept edits - * (`effectiveRuntimeMode`, the rule the composer shows). + * The agent's own mode for a thread's access level. Auto is the CLI's own + * `auto` where the session offers it, else Auto-accept edits. Full access has + * no CLI mode (the CLI refuses `yolo`): it runs in `default`, and Threadlines + * answers each request itself, as the ACP core does for full access. */ export function antigravityAgentMode( runtimeMode: RuntimeMode, interactionMode: ProviderInteractionMode | undefined, -): "default" | "auto_edit" | "yolo" { + availableModeIds: ReadonlyArray, +): "default" | "accept-edits" | "auto" { // `/plan` only writes a plan; nothing else should run unasked. if (interactionMode === "plan") return "default"; switch (runtimeMode) { case "full-access": - return "yolo"; - case "auto": - case "auto-accept-edits": - return "auto_edit"; case "approval-required": return "default"; + case "auto": + return availableModeIds.includes("auto") ? "auto" : "accept-edits"; + case "auto-accept-edits": + return "accept-edits"; } } +/** + * Whether `version` is at least the minimum, by its numbers: `1.5.9+local` + * is 1.5.9, and a prerelease of the minimum (`1.5.14-rc.1`) is below it. + * Undefined when it isn't a version. + */ +/** + * Antigravity's commands that Threadlines does itself: plan mode is the + * composer's `/plan` (sent as the CLI's `/plan`), and signing in or out is on + * the provider's row in Settings, where it stops the account's chats. + */ +const ANTIGRAVITY_AGENT_COMMANDS = { + hidden: new Set(["plan", "login", "logout"]), + slashSkills: true, +} as const; + +export function meetsAntigravityMinimum(version: string): boolean | undefined { + const parse = (value: string) => { + const match = /^v?(\d+)\.(\d+)\.(\d+)(-[0-9A-Za-z.-]+)?(\+[0-9A-Za-z.-]+)?$/u.exec( + value.trim(), + ); + return match + ? { core: [Number(match[1]), Number(match[2]), Number(match[3])], prerelease: !!match[4] } + : undefined; + }; + const got = parse(version); + const floor = parse(ANTIGRAVITY_MIN_VERSION)!; + if (!got) return undefined; + for (let index = 0; index < 3; index += 1) { + const difference = got.core[index]! - floor.core[index]!; + if (difference !== 0) return difference > 0; + } + return !got.prerelease; +} + +/** Why an agent can't run sessions, by its `initialize` answer; undefined when it can. */ +export function antigravityAgentProblem( + response: Pick, +): string | undefined { + const version = response.agentInfo?.version?.trim() ?? ""; + const meets = meetsAntigravityMinimum(version); + if (meets === undefined) { + return `This Antigravity doesn't say its version. Threadlines needs Google's Antigravity CLI ${ANTIGRAVITY_MIN_VERSION} or newer.`; + } + return meets + ? undefined + : `This Antigravity is ${version}. Threadlines needs ${ANTIGRAVITY_MIN_VERSION} or newer: update Google's Antigravity CLI (\`agy update\`), or clear the custom path to use the copy Threadlines installs.`; +} + +/** A path to Google's old ACP server, which the CLI replaced. */ +export const isLegacyAntigravityServerPath = (path: string) => + /^(agy_acp_server|localharness_external)(\.(par|exe))?$/iu.test( + path.trim().split(/[\\/]/u).at(-1) ?? "", + ); + +const LEGACY_PATH_MESSAGE = + "This path is Google's old Antigravity server, which no longer works. Point it at Google's Antigravity CLI (`agy`), or clear it to use the copy Threadlines installs."; + // ── Sign-in URL ────────────────────────────────────────────────────── const SIGN_IN_PREFIX = "Open the following link to authenticate the ACP server: "; @@ -232,6 +327,96 @@ export function antigravityModelsFromChoices( const modelChoices = (configOptions: ReadonlyArray) => flattenSessionConfigSelectOptions(findModelConfigOption(configOptions)); +/** The session's `thought_level` option: the selected model's reasoning levels. */ +export function antigravityThoughtLevels( + configOptions: ReadonlyArray, +): AntigravityThoughtLevels | undefined { + const option = configOptions.find( + (candidate) => candidate.category === "thought_level" && candidate.type === "select", + ); + const options = flattenSessionConfigSelectOptions(option); + if (!option || options.length === 0) return undefined; + const currentValue = selectConfigOptionCurrentValue(option); + return { + configId: option.id, + name: option.name.trim() || "Reasoning", + options, + ...(currentValue ? { currentValue } : {}), + }; +} + +function thoughtLevelCapabilities(levels: AntigravityThoughtLevels | null): ModelCapabilities { + if (!levels || levels.options.length < 2) + return createModelCapabilities({ optionDescriptors: [] }); + const preferred = levels.currentValue ?? levels.options[0]!.value; + return createModelCapabilities({ + optionDescriptors: [ + { + // The session option's own id: the generic mapping sends a selection back to it. + id: levels.configId, + label: levels.name, + type: "select", + options: levels.options.map((option) => + option.value === preferred + ? { id: option.value, label: option.name || option.value, isDefault: true as const } + : { id: option.value, label: option.name || option.value }, + ), + currentValue: preferred, + }, + ], + }); +} + +/** + * The picker's models from a saved list. With reasoning levels as their own + * option, each model shows the levels seen for it, or the current model's + * until it has been seen; without them (older agents), models fold by name. + */ +export function antigravityModelsFromCatalog( + catalog: Pick, +): ReadonlyArray { + const levels = catalog.thoughtLevels ?? {}; + if (Object.keys(levels).length === 0) return antigravityModelsFromChoices(catalog.choices); + const shared = (catalog.currentValue ? levels[catalog.currentValue] : undefined) ?? null; + return catalog.choices.map((choice) => ({ + slug: choice.value, + name: choice.name || choice.value, + isCustom: false, + capabilities: thoughtLevelCapabilities( + choice.value in levels ? (levels[choice.value] ?? null) : shared, + ), + })); +} + +/** + * The saved list after a session reported `configOptions`: its models, and + * the reasoning levels of the one selected, kept with what earlier sessions + * saw of the others. + */ +export function nextAntigravityCatalog( + previous: AntigravityCatalogCache | undefined, + configOptions: ReadonlyArray, +): Pick | undefined { + const choices: ReadonlyArray = modelChoices(configOptions); + if (choices.length === 0) return undefined; + const currentValue = selectConfigOptionCurrentValue(findModelConfigOption(configOptions)); + const listed = new Set(choices.map((choice) => choice.value)); + const thoughtLevels: Record = {}; + for (const [model, levels] of Object.entries(previous?.thoughtLevels ?? {})) { + if (listed.has(model)) thoughtLevels[model] = levels; + } + const current = antigravityThoughtLevels(configOptions); + // A model whose levels aren't an option of their own (older agents) records nothing. + if (currentValue && (current || Object.keys(thoughtLevels).length > 0)) { + thoughtLevels[currentValue] = current ?? null; + } + return { + choices, + ...(currentValue ? { currentValue } : {}), + ...(Object.keys(thoughtLevels).length > 0 ? { thoughtLevels } : {}), + }; +} + /** * The agent's model id for a family slug and the selected effort; agent ids * (custom models) pass through. @@ -310,8 +495,9 @@ function antigravityOptionWarning(option: EffectAcpSchema.PermissionOption): str function toolCallPaths(data: Record): ReadonlyArray { const paths: string[] = []; + // As given: a padded name is another file, never trimmed into the plan's. const push = (value: unknown) => { - if (typeof value === "string" && value.trim()) paths.push(value.trim()); + if (typeof value === "string" && value !== "") paths.push(value); }; if (Array.isArray(data.content)) { for (const entry of data.content) { @@ -331,39 +517,89 @@ function toolCallPaths(data: Record): ReadonlyArray { return paths; } -const isInside = (path: string, dir: string) => { - const target = resolvePath(path); - const root = resolvePath(dir); - return target.startsWith(root.endsWith(sep) ? root : `${root}${sep}`); -}; - /** The agent's artifact store (plans, task lists): inside the profile, never the workspace. */ const brainDir = (profileDir: string) => join(profileDir, "antigravity-acp", "brain"); +/** Input fields that say a call runs a command (as the core reads them). */ +const COMMAND_FIELDS = ["command", "commandLine", "CommandLine", "command_line", "cmd"]; + +/** A session id as the CLI names its folders: nothing that walks a path. */ +const PLAN_SESSION_ID = /^[\w-]{1,128}$/u; + +/** + * Whether a tool call is this session writing its own plan, and nothing + * else: an edit whose every change is a diff of exactly + * `brain//plan.md` (where `/plan` writes it), naming no other + * path and no command. Such a write is approved without asking and shows as + * the plan card, so a call that runs anything, touches any other file, or + * writes another session's plan never passes. Paths are compared as given, + * never trimmed. + */ +export function isAntigravityPlanFileEdit( + toolCall: AcpToolCallState, + brain: string, + sessionId: string | undefined, +): boolean { + if (sessionId === undefined || !PLAN_SESSION_ID.test(sessionId)) return false; + if (toolCall.kind !== "edit" || toolCall.command !== undefined) return false; + const { content, rawInput } = toolCall.data; + if ( + typeof rawInput === "object" && + rawInput !== null && + COMMAND_FIELDS.some((field) => field in rawInput) + ) { + return false; + } + const planPath = join(brain, sessionId, "plan.md"); + // A path with `.` or `..` steps is never the plan: through a link inside + // the session's folder, `link/../plan.md` reads as this plan and opens + // another file. + const isPlanPath = (path: string) => + isAbsolute(path) && + !path.split(/[\\/]/u).some((step) => step === "." || step === "..") && + normalize(path) === planPath; + // Every change is a diff, and every path the call names (diffs, + // locations, its target) is the plan file. + const diffsOnly = + Array.isArray(content) && + content.length > 0 && + content.every( + (entry) => + typeof entry === "object" && + entry !== null && + (entry as { type?: unknown }).type === "diff", + ); + const paths = toolCallPaths(toolCall.data); + return diffsOnly && paths.length > 0 && paths.every(isPlanPath); +} + // ── Install check ──────────────────────────────────────────────────── /** - * Proves an unpacked runtime is Google's Antigravity ACP server: one - * `initialize` in a throwaway profile, then the process is stopped and - * reaped before returning (Windows cannot move a dir with a running exe). + * Proves an unpacked executable is Google's Antigravity CLI at the release's + * version: one `agy acp` `initialize` in a throwaway profile, then the + * process is stopped and reaped before returning (Windows cannot move a dir + * with a running exe). */ export const validateAntigravityRuntime = ( - paths: { readonly executable: string; readonly harness: string }, + paths: { readonly executable: string }, release: AntigravityPlatformRelease, ) => Effect.tryPromise({ try: async () => { const scratch = await fs.mkdtemp(join(tmpdir(), "agy-check-")); try { + const profileDir = join(scratch, "profile"); + await fs.mkdir(profileDir, { mode: 0o700 }); const env = antigravityEnvironment({ base: process.env, - profileDir: join(scratch, "profile"), + profileDir, tempDir: scratch, platform: process.platform, }); - const child = spawnChild(paths.executable, [...antigravityLaunchArgs(process.platform)], { + const child = spawnChild(paths.executable, [...antigravityLaunchArgs(profileDir)], { cwd: scratch, - env: { ...withUsualCommandLookup(env), ANTIGRAVITY_HARNESS_PATH: paths.harness }, + env: withUsualCommandLookup(env), stdio: ["pipe", "pipe", "ignore"], windowsHide: true, }); @@ -404,19 +640,17 @@ export const validateAntigravityRuntime = ( params: { protocolVersion: 1, clientCapabilities: { fs: { readTextFile: false, writeTextFile: false } }, - clientInfo: { name: "threadlines", version: "0.0.0" }, + clientInfo: THREADLINES_ACP_CLIENT_INFO, }, })}\n`, ); }); const problems = [ - response.agentInfo?.name !== "antigravity-acp" && - "it is not the Antigravity ACP server", + !/antigravity/iu.test(response.agentInfo?.name ?? "") && + "it is not Google's Antigravity", response.agentInfo?.version !== release.version && `it reports version ${response.agentInfo?.version ?? "unknown"}, not ${release.version}`, !response.agentCapabilities?.sessionCapabilities?.resume && "it cannot resume sessions", - !response.authMethods?.some((method) => method.id === "oauth-personal") && - "it offers no Google sign-in", ].filter((problem): problem is string => typeof problem === "string"); if (problems.length > 0) { throw new Error(`The downloaded Antigravity failed its check: ${problems.join("; ")}.`); @@ -448,9 +682,6 @@ export const validateAntigravityRuntime = ( // ── Descriptor ─────────────────────────────────────────────────────── -const HARNESS_NAME = (platform: NodeJS.Platform) => - platform === "win32" ? "localharness_external.exe" : "localharness_external"; - const MANUAL_ONLY: ProviderMaintenanceCapabilities = { provider: ANTIGRAVITY_DRIVER_KIND, packageName: null, @@ -460,40 +691,92 @@ const MANUAL_ONLY: ProviderMaintenanceCapabilities = { advisoryMessage: null, }; +const NOT_INSTALLED_MESSAGE = "Antigravity is not installed. Install it to use it in Threadlines."; +const UPDATE_NEEDED_MESSAGE = + "Antigravity now runs on Google's Antigravity CLI. Update it to keep using it."; + +/** Whether an installed copy can run sessions: Google's CLI at the minimum version or newer. */ +const runsSessions = (installed: AntigravityInstalledRuntime) => + installed.kind === "cli" && meetsAntigravityMinimum(installed.version) === true; + export interface AntigravityDescriptorInput { readonly paths: AntigravityInstancePaths; /** Undefined where Google publishes no runtime for this machine. */ readonly runtime: AntigravityRuntime | undefined; - readonly release: AntigravityPlatformRelease | undefined; + /** The release to install or update to; undefined where there is no runtime. */ + readonly releases: AntigravityReleaseSource | undefined; /** While busy (signing in or out), no agent process starts; each one holds it while it runs. */ readonly gate?: LaunchGate; /** The instance's sign-in method, project and key (fixed for an instance build). */ readonly signIn: AntigravitySignInConfig; + /** The folder whose project skills the status lists (the server's, as for other agents). */ + readonly skillsCwd?: string; + /** Plan limits and email for a Google sign-in; the status check shows its last reading. */ + readonly usage?: AntigravityUsageReader; } export function makeAntigravityDescriptor( input: AntigravityDescriptorInput, ): AcpProviderDescriptor { - const { paths, runtime, release, gate, signIn } = input; + const { paths, runtime, releases, gate, signIn, usage } = input; const platform = process.platform; + const listSkills = makeAntigravitySkillsLister(); + const userHomeFor = (environment: NodeJS.ProcessEnv | undefined) => + antigravityUserHome(platform, environment ?? process.env, homedir()); const fingerprint = antigravityCredentialFingerprint(signIn); + const isGoogleAccount = signIn.method === "oauth-personal"; - const runtimeAction = (verb: "Install" | "Update"): ProviderMaintenanceCommandAction | null => - runtime && release - ? { - command: `${verb} Antigravity ${release.version} (Threadlines downloads and checks it)`, - executable: "threadlines", - args: [], - lockKey: "antigravity-runtime", - run: runtime.install().pipe( - Effect.as({ output: `Antigravity ${release.version} is installed.` }), - Effect.mapError((error) => ({ message: error.message })), - ), - } - : null; + const runtimeAction = ( + runtime: AntigravityRuntime, + verb: "Install" | "Update", + offer: AntigravityPlatformRelease, + ): ProviderMaintenanceCommandAction => ({ + command: `${verb} Antigravity ${offer.version} (Threadlines downloads and checks it)`, + executable: "threadlines", + args: [], + lockKey: "antigravity-runtime", + // Actions run one at a time (`lockKey`), so a button shown before + // another install finished can't put an older version back. An install + // from before the CLI is always replaced. + run: Effect.gen(function* () { + const installed = yield* runtime.installed; + if ( + installed?.kind === "cli" && + compareSemverVersions(installed.version, offer.version) >= 0 + ) { + return { output: `Antigravity ${installed.version} is already installed.` }; + } + yield* runtime.install(offer); + return { output: `Antigravity ${offer.version} is installed.` }; + }).pipe(Effect.mapError((error) => ({ message: error.message }))), + }); + + /** + * What the next agent is, to tag the saved model list + * (`readAntigravityCatalog`) and a refusal: the managed version, or for a + * custom binary its path, size and change time, so replacing the file + * lists models afresh. + */ + const agentTag = (settings: AntigravitySettings) => { + const custom = settings.binaryPath.trim(); + if (custom) { + return Effect.promise(() => + fs.stat(custom).then( + (stat) => `custom:${resolvePath(custom)}:${stat.size}:${Math.trunc(stat.mtimeMs)}`, + () => undefined, + ), + ); + } + return runtime + ? runtime.installed.pipe(Effect.map((installed) => installed?.version)) + : Effect.succeed(undefined); + }; + + const readCatalog = (agentVersion: string | undefined) => + readAntigravityCatalog(paths.profileDir, { fingerprint, isGoogleAccount, agentVersion }); const spawnFailure = (cause: unknown) => - new EffectAcpErrors.AcpSpawnError({ command: "agy_acp_server", cause }); + new EffectAcpErrors.AcpSpawnError({ command: "agy acp", cause }); return { driverKind: ANTIGRAVITY_DRIVER_KIND, @@ -503,12 +786,16 @@ export function makeAntigravityDescriptor( maintenance: MANUAL_ONLY, resolveMaintenance: (settings) => Effect.gen(function* () { - if (settings.binaryPath.trim() || !runtime || !release) return MANUAL_ONLY; + if (settings.binaryPath.trim() || !runtime || !releases) return MANUAL_ONLY; const installed = yield* runtime.installed; - if (!installed) return { ...MANUAL_ONLY, install: runtimeAction("Install") }; - return installed.version === release.version - ? MANUAL_ONLY - : { ...MANUAL_ONLY, update: runtimeAction("Update") }; + const offer = yield* releases.newest; + if (!installed) + return { ...MANUAL_ONLY, install: runtimeAction(runtime, "Install", offer) }; + // Never back: a newer copy stays when only an older release is offered. + return installed.kind === "legacy" || + compareSemverVersions(installed.version, offer.version) < 0 + ? { ...MANUAL_ONLY, update: runtimeAction(runtime, "Update", offer) } + : MANUAL_ONLY; }), spawn: (settings, cwd, environment) => Effect.gen(function* () { @@ -523,10 +810,11 @@ export function makeAntigravityDescriptor( } const custom = settings.binaryPath.trim(); let executable: string; - let harness: string; if (custom) { + if (isLegacyAntigravityServerPath(custom)) { + return yield* spawnFailure(new Error(LEGACY_PATH_MESSAGE)); + } executable = custom; - harness = join(dirname(custom), HARNESS_NAME(platform)); } else { if (!runtime) { return yield* spawnFailure( @@ -534,52 +822,71 @@ export function makeAntigravityDescriptor( ); } const leased = yield* runtime.acquire.pipe(Effect.mapError(spawnFailure)); + if (!runsSessions(leased)) { + return yield* spawnFailure(new Error(UPDATE_NEEDED_MESSAGE)); + } executable = leased.executable; - harness = leased.harness; } - yield* prepareAntigravityProfile(paths.profileDir); + yield* prepareAntigravityProfile(paths.profileDir, { + userHome: userHomeFor(environment), + platform, + }); const tempDir = yield* acquireAntigravityTempDir(paths.tempRoot).pipe( Effect.mapError(spawnFailure), ); return { command: executable, - args: [...antigravityLaunchArgs(platform)], + args: [...antigravityLaunchArgs(paths.profileDir)], cwd, - env: { - ...antigravityEnvironment({ - base: environment ?? process.env, - profileDir: paths.profileDir, - tempDir, - platform, - credentials: antigravityCredentialEnvironment(signIn, environment ?? process.env), - }), - ANTIGRAVITY_HARNESS_PATH: harness, - }, + env: antigravityEnvironment({ + base: environment ?? process.env, + profileDir: paths.profileDir, + tempDir, + platform, + credentials: antigravityCredentialEnvironment(signIn, environment ?? process.env), + }), inheritEnv: false, shell: false, onSpawned: (pid: number) => recordAntigravityAgent(tempDir, pid), }; }), + // A custom `agy` too old to run is refused before a session opens, and + // the row says so until that file changes. + verifyAgent: (settings, response) => + Effect.gen(function* () { + const problem = antigravityAgentProblem(response); + if (settings.binaryPath.trim()) { + const tag = yield* agentTag(settings); + if (tag) yield* writeAntigravityAgentRefusal(paths.profileDir, { tag, problem }); + } + if (problem) { + return yield* Effect.fail(EffectAcpErrors.AcpRequestError.invalidParams(problem)); + } + }), signInUrlFromStderr: parseAntigravitySignInUrl, // Key methods sign in from the environment with no browser; Google - // accounts use the saved sign-in (a missing one prints a sign-in URL). + // accounts use the profile's saved sign-in. ...(signIn.method === "gemini-api-key" || signIn.method === "agent-platform" ? { authMethodId: signIn.method } : {}), - agentModeFor: ({ runtimeMode, interactionMode }) => - antigravityAgentMode(runtimeMode, interactionMode), + agentModeFor: ({ runtimeMode, interactionMode, availableModeIds }) => + antigravityAgentMode(runtimeMode, interactionMode, availableModeIds), classifyPermissionRequest: antigravityQuestion, permissionOptionWarning: antigravityOptionWarning, cancellationNotice: "The request was cancelled by the client.", + // Tool text bounded, no inline images, `call_mcp_tool` shown as the MCP tool. + normalizeSessionUpdate: normalizeAntigravitySessionUpdate, + normalizeToolCall: normalizeAntigravityToolCall, + // Images and audio inline, PDFs linked, text files embedded. + attachmentDelivery: antigravityAttachmentDelivery, + // Each launch shows as a subagent, read from the CLI's own records. + subagents: antigravitySubagents(paths.profileDir), + // Work that outlives a prompt, steering, hidden failures, turn tokens. + ...antigravityTurnBehavior(paths.profileDir, usage?.usageLimitFor), planMode: { promptPrefix: "/plan ", - isPlanFile: (toolCall) => { - const filePaths = toolCallPaths(toolCall.data); - return ( - filePaths.length > 0 && - filePaths.every((filePath) => isInside(filePath, brainDir(paths.profileDir))) - ); - }, + isPlanFile: (toolCall, sessionId) => + isAntigravityPlanFileEdit(toolCall, brainDir(paths.profileDir), sessionId), planMarkdown: (toolCall) => { const content = toolCall.data.content; if (!Array.isArray(content)) return undefined; @@ -602,19 +909,24 @@ export function makeAntigravityDescriptor( return undefined; }, }, + // The session's own `/` commands and skills reach the composer. + agentCommands: ANTIGRAVITY_AGENT_COMMANDS, + // The CLI can't rewind its conversation: a revert starts a new one. + rollbackByNewSession: true, diffEvidence: true, isolateTextGeneration: true, - onSessionConfigOptions: (_settings, configOptions) => { - const choices = modelChoices(configOptions); - if (choices.length === 0) return Effect.void; - const currentValue = selectConfigOptionCurrentValue(findModelConfigOption(configOptions)); - return writeAntigravityCatalog(paths.profileDir, { - choices, - ...(currentValue ? { currentValue } : {}), - fingerprint, - }); - }, - notInstalledMessage: "Antigravity is not installed. Install it to use it in Threadlines.", + onSessionConfigOptions: (settings, configOptions) => + Effect.gen(function* () { + const agentVersion = yield* agentTag(settings); + const next = nextAntigravityCatalog(yield* readCatalog(agentVersion), configOptions); + if (!next) return; + yield* writeAntigravityCatalog(paths.profileDir, { + ...next, + fingerprint, + ...(agentVersion ? { agentVersion } : {}), + }); + }), + notInstalledMessage: NOT_INSTALLED_MESSAGE, // The same test the probe makes: a custom binary only has to exist; the // managed runtime is found when a complete copy is on disk. Both read the // filesystem only. @@ -628,7 +940,7 @@ export function makeAntigravityDescriptor( probe: (settings, environment) => Effect.gen(function* () { const custom = settings.binaryPath.trim(); - if (!custom && (!runtime || !release)) { + if (!custom && (!runtime || !releases)) { return { installed: false, version: null, @@ -637,27 +949,61 @@ export function makeAntigravityDescriptor( message: `Google does not publish Antigravity for this computer (${platform}, ${process.arch}).`, } satisfies AcpProviderProbeOutcome; } - const installed = custom ? existsSync(custom) : (yield* runtime!.installed) !== undefined; - const version = custom ? null : ((yield* runtime!.installed)?.version ?? null); - if (!installed) { + if (custom && isLegacyAntigravityServerPath(custom)) { + return { + installed: true, + version: null, + status: "error", + auth: { status: "unknown" }, + message: LEGACY_PATH_MESSAGE, + skipModelDiscovery: true, + } satisfies AcpProviderProbeOutcome; + } + const managed = custom ? undefined : yield* runtime!.installed; + if (custom ? !existsSync(custom) : managed === undefined) { return { installed: false, version: null, status: "error", auth: { status: "unknown" }, - message: custom - ? `Antigravity was not found at ${custom}.` - : "Antigravity is not installed. Install it to use it in Threadlines.", + message: custom ? `Antigravity was not found at ${custom}.` : NOT_INSTALLED_MESSAGE, + } satisfies AcpProviderProbeOutcome; + } + const version = managed?.version ?? null; + const tag = yield* agentTag(settings); + const latest = custom ? {} : { latestVersion: (yield* releases!.newest).version }; + const refusal = + custom && tag ? yield* readAntigravityAgentRefusal(paths.profileDir, tag) : undefined; + if (refusal) { + return { + installed: true, + version: null, + status: "error", + auth: { status: "unknown" }, + message: refusal, + skipModelDiscovery: true, + } satisfies AcpProviderProbeOutcome; + } + if (managed && !runsSessions(managed)) { + return { + installed: true, + version, + status: "error", + auth: { status: "unknown" }, + message: UPDATE_NEEDED_MESSAGE, + skipModelDiscovery: true, + ...latest, } satisfies AcpProviderProbeOutcome; } - const latest = custom ? {} : { latestVersion: ANTIGRAVITY_RELEASE.version }; const usesGoogleSignIn = signIn.method === "oauth-personal" || signIn.method === "oauth-business"; + const google = usesGoogleSignIn + ? yield* readAntigravityGoogleSignIn(paths.profileDir) + : undefined; const signInStatus = antigravitySignInStatus({ config: signIn, - signedIn: usesGoogleSignIn - ? (yield* readAntigravityGoogleSignIn(paths.profileDir)) === signIn.method - : false, + signedIn: google?.method === signIn.method, + legacySignIn: google?.legacyOnly === true, check: yield* readAntigravitySignInCheck(paths.profileDir, fingerprint), adc: signIn.method === "agent-platform" && !signIn.key @@ -673,24 +1019,38 @@ export function makeAntigravityDescriptor( ...latest, } satisfies AcpProviderProbeOutcome; } - const catalog = yield* readAntigravityCatalog(paths.profileDir, { - fingerprint, - isGoogleAccount: signIn.method === "oauth-personal", - }); - return { + const catalog = yield* readCatalog(tag); + const outcome = { installed: true, version, ...signInStatus, ...latest, - ...(catalog ? { models: antigravityModelsFromChoices(catalog.choices) } : {}), + ...(catalog ? { models: antigravityModelsFromCatalog(catalog) } : {}), } satisfies AcpProviderProbeOutcome; + return usage ? withAntigravityUsage(outcome, yield* usage.status) : outcome; }), + // What the agent would see: the profile is brought up to date first, as + // a start would, and global skills are read through it. + listSkills: (_settings, environment) => + prepareAntigravityProfile(paths.profileDir, { + userHome: userHomeFor(environment), + platform, + }).pipe( + Effect.andThen( + listSkills({ cwd: input.skillsCwd ?? process.cwd(), profileDir: paths.profileDir }), + ), + ), modelDiscoveryTimeoutMs: ANTIGRAVITY_DISCOVERY_TIMEOUT_MS, + // Discovery mirrors the selected model's options (its reasoning levels) + // onto every model; the next status check reads each model's own from + // the saved list. Older agents name the level in the model: fold those. enrichDiscoveredModels: (models) => Effect.succeed( - antigravityModelsFromChoices( - models.map((model) => ({ value: model.slug, name: model.name })), - ), + models.some((model) => EFFORT_NAME.test(model.name.trim())) + ? antigravityModelsFromChoices( + models.map((model) => ({ value: model.slug, name: model.name })), + ) + : models, ), modelCapabilitiesVaryByModel: false, resolveModelId: resolveAntigravityModelId, diff --git a/apps/server/src/provider/acp/acpClientInfo.ts b/apps/server/src/provider/acp/acpClientInfo.ts new file mode 100644 index 000000000..1b306ed57 --- /dev/null +++ b/apps/server/src/provider/acp/acpClientInfo.ts @@ -0,0 +1,13 @@ +/** + * How Threadlines introduces itself to an ACP agent in `initialize`: under + * its own name and version, never as another editor. + * + * @module provider/acp/acpClientInfo + */ +import packageJson from "../../../package.json" with { type: "json" }; + +export const THREADLINES_ACP_CLIENT_INFO = { + name: "threadlines", + title: "Threadlines", + version: packageJson.version, +} as const; diff --git a/apps/server/src/provider/antigravity/AntigravityAttachments.ts b/apps/server/src/provider/antigravity/AntigravityAttachments.ts new file mode 100644 index 000000000..05871a5f8 --- /dev/null +++ b/apps/server/src/provider/antigravity/AntigravityAttachments.ts @@ -0,0 +1,67 @@ +/** + * How each attachment reaches Antigravity (`AcpProviderDescriptor.attachmentDelivery`). + * + * `agy acp` reads images and audio inline, PDFs through a link to the file, + * and text files embedded as text (1.5.13 honors attached file contents). + * Everything else, and anything the agent's `initialize` answer doesn't + * offer, goes as a note naming the staged file for the agent to open, as for + * every ACP agent. MIME parameters (`; charset=utf-8`) are dropped before + * deciding. The lists follow T3 Code's (AntigravityAcpSupport.ts, commits + * 29a33f8827 and ff8a831067). + * + * @module provider/antigravity/AntigravityAttachments + */ +import type { ChatAttachment } from "@threadlines/contracts"; +import type * as EffectAcpSchema from "effect-acp/schema"; + +import { type AcpAttachmentDelivery, bareMimeType } from "../acp/AcpPromptAttachments.ts"; + +const IMAGE_MIME_TYPES = new Set(["image/bmp", "image/jpeg", "image/png", "image/webp"]); +const AUDIO_MIME_TYPES = new Set([ + "audio/aac", + "audio/flac", + "audio/mp3", + "audio/mpeg", + "audio/mp4", + "audio/m4a", + "audio/x-m4a", + "audio/ogg", + "audio/wav", + "audio/x-wav", + "audio/webm", +]); +/** Application types that hold text, beyond `text/*`. */ +const TEXT_APPLICATION_MIME_TYPES = new Set([ + "application/json", + "application/ld+json", + "application/javascript", + "application/typescript", + "application/xml", + "application/yaml", + "application/x-yaml", + "application/x-sh", +]); + +/** + * Text the server stored as some other kind: a UTF-16 file reads as binary + * to the server's UTF-8 check, so it arrives as `other` with its text type. + * The core decodes it (with its byte order mark) or falls back to the note. + */ +const isTextType = (mimeType: string) => + mimeType.startsWith("text/") || TEXT_APPLICATION_MIME_TYPES.has(mimeType); + +export function antigravityAttachmentDelivery( + attachment: ChatAttachment, + capabilities: EffectAcpSchema.PromptCapabilities | null | undefined, +): AcpAttachmentDelivery { + const mimeType = bareMimeType(attachment.mimeType); + if (attachment.type === "image") { + return IMAGE_MIME_TYPES.has(mimeType) && capabilities?.image === true ? "inline" : "note"; + } + if (AUDIO_MIME_TYPES.has(mimeType)) return capabilities?.audio === true ? "inline" : "note"; + // Every ACP agent reads a `resource_link`; `embeddedContext` is only for embedded text. + if (attachment.kind === "pdf" || mimeType === "application/pdf") return "link"; + if (capabilities?.embeddedContext !== true) return "note"; + if (attachment.kind === "text" || isTextType(mimeType)) return "text"; + return "note"; +} diff --git a/apps/server/src/provider/antigravity/AntigravityAuth.test.ts b/apps/server/src/provider/antigravity/AntigravityAuth.test.ts index d43f05b90..4a298a162 100644 --- a/apps/server/src/provider/antigravity/AntigravityAuth.test.ts +++ b/apps/server/src/provider/antigravity/AntigravityAuth.test.ts @@ -1,38 +1,280 @@ -import { describe, expect, it } from "vite-plus/test"; +// @effect-diagnostics nodeBuiltinImport:off - writes a stand-in `agy` and reads the profile it signs in +import * as NodeFS from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; -import { checkAntigravityRedirect } from "./AntigravityAuth.ts"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { assert, describe, expect, it } from "@effect/vitest"; +import { AntigravitySettings } from "@threadlines/contracts"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Schema from "effect/Schema"; +import { HttpClient } from "effect/http"; +import { ChildProcessSpawner } from "effect/process"; -describe("checkAntigravityRedirect", () => { - const pending = { redirect: new URL("http://127.0.0.1:53789/"), state: "8Jy4kHH5tYZC" }; - const accepted = (raw: string) => typeof checkAntigravityRedirect(raw, pending) !== "string"; +import { makeAntigravityDescriptor } from "../acp/AntigravityAcpSupport.ts"; +import { makeLaunchGate } from "../managedRuntime/LaunchGate.ts"; +import { + ANTIGRAVITY_CODE_REDIRECT_URI, + antigravityLoginResponse, + antigravitySignInErrorMessage, + makeAntigravityAuthFlows, + parseAntigravityCodeSignInLink, +} from "./AntigravityAuth.ts"; +import { antigravityInstancePaths, antigravityTokenPath } from "./AntigravityProfile.ts"; +import { antigravitySignInConfig, readAntigravityGoogleSignIn } from "./AntigravitySignInMethod.ts"; - it("accepts the address a browser on another device ended on", () => { - // Shape of the real redirect Google sent (code shortened). +const STATE = "c3RhdGUtMTIz"; +const LINK = `https://accounts.google.com/o/oauth2/auth?client_id=1071006060591.apps.googleusercontent.com&redirect_uri=${encodeURIComponent(ANTIGRAVITY_CODE_REDIRECT_URI)}&response_type=code&scope=openid&state=${STATE}`; +const CODE = "4/0AeaYSHB-xyz_123"; + +describe("parseAntigravityCodeSignInLink", () => { + it("takes Google's code sign-in link that `agy acp --login` prints", () => { + expect(parseAntigravityCodeSignInLink(` ${LINK} `)).toEqual({ url: LINK, state: STATE }); + }); + + it("refuses a link that would send the code anywhere but Antigravity's page", () => { + const refused = (url: string) => parseAntigravityCodeSignInLink(url) === undefined; + expect(refused(LINK.replace("accounts.google.com", "accounts.google.com.evil.test"))).toBe( + true, + ); + expect(refused(LINK.replace("antigravity.google", "evil.test"))).toBe(true); + expect(refused(LINK.replace("%2Foauth-callback", "%2Foauth-callback%2Fx"))).toBe(true); + expect(refused(LINK.replace("response_type=code", "response_type=token"))).toBe(true); + expect(refused(`${LINK}&state=second`)).toBe(true); + expect(refused("Open this link: something else")).toBe(true); + }); +}); + +describe("antigravityLoginResponse", () => { + const link = { url: LINK, state: STATE }; + + it("takes the code, or the Antigravity page's address for this sign-in", () => { + expect(antigravityLoginResponse(link, ` ${CODE}\n`)).toBe(CODE); + const page = `${ANTIGRAVITY_CODE_REDIRECT_URI}?state=${STATE}&code=${encodeURIComponent(CODE)}`; + expect(antigravityLoginResponse(link, page)).toBe(page); + }); + + it("never hands the CLI a second line or another sign-in's page", () => { + expect(antigravityLoginResponse(link, `${CODE}\nmore`)).toBeUndefined(); + expect(antigravityLoginResponse(link, "two words")).toBeUndefined(); + expect( + antigravityLoginResponse(link, `${ANTIGRAVITY_CODE_REDIRECT_URI}?state=other&code=x`), + ).toBeUndefined(); + expect( + antigravityLoginResponse(link, `https://evil.test/oauth-callback?state=${STATE}&code=x`), + ).toBeUndefined(); + }); +}); + +describe("antigravitySignInErrorMessage", () => { + it("names what went wrong in the user's words", () => { + expect(antigravitySignInErrorMessage("error: SUBSCRIPTION_REQUIRED")).toContain( + "eligible plan", + ); + expect(antigravitySignInErrorMessage("oauth2: invalid_grant")).toContain( + "Google didn't accept", + ); expect( - accepted( - "http://127.0.0.1:53789/?state=8Jy4kHH5tYZC&iss=https%3A%2F%2Faccounts.google.com&code=4%2F0AXlqoi6&scope=email", + antigravitySignInErrorMessage("dial tcp [2001:db8::1]:443: connect: network is unreachable"), + ).toContain("IPv6"); + expect( + antigravitySignInErrorMessage( + 'PERMISSION_DENIED: Verify your account to continue. {"reason":"VALIDATION_REQUIRED","metadata":{"validation_url":"https://accounts.google.com/v3/signin/continue?plt=abc"}}', + ), + ).toContain("https://accounts.google.com/v3/signin/continue?plt=abc"); + // A link anywhere else is never shown as Google's. + expect( + antigravitySignInErrorMessage( + "VALIDATION_REQUIRED https://accounts.google.com.evil.test/v3/signin/continue", ), - ).toBe(true); - expect(accepted("http://127.0.0.1:53789/?state=8Jy4kHH5tYZC&error=access_denied")).toBe(true); + ).not.toContain("evil"); }); +}); + +const mockAgentPath = path.join( + path.dirname(fileURLToPath(import.meta.url)), + "../../../scripts/acp-mock-agent.ts", +); + +/** + * A stand-in `agy`: with `--login` it prints Google's link and signs the + * profile in when it reads `CODE`, as Google's CLI does; otherwise it is the + * mock ACP agent, reporting Antigravity's name and version. + */ +const makeStandInAgy = Effect.acquireRelease( + Effect.promise(async () => { + const dir = await NodeFS.mkdtemp(path.join(os.tmpdir(), "threadlines-agy-")); + const login = path.join(dir, "login.mjs"); + await NodeFS.writeFile( + login, + `import { mkdirSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +import { createInterface } from "node:readline"; +const args = process.argv.slice(2); +const profile = args[args.indexOf("--gemini-dir") + 1]; +console.log("Sign in to continue:"); +console.log(${JSON.stringify(LINK)}); +if (process.env.STANDIN_EXIT_AFTER_LINK === "1") { + console.error("dial tcp: lookup oauth2.googleapis.com: no such host"); + process.exit(1); +} +const lines = createInterface({ input: process.stdin }); +for await (const line of lines) { + if (line !== ${JSON.stringify(CODE)}) { + console.error("oauth2: cannot fetch token: invalid_grant"); + process.exit(1); + } + mkdirSync(join(profile, "antigravity-acp"), { recursive: true }); + writeFileSync(join(profile, "antigravity-acp", "antigravity-oauth-token"), JSON.stringify({ token: { access_token: "ya29.test" } })); + console.log("Signed in."); + process.exit(0); +} +process.exit(2); +`, + ); + const agy = path.join(dir, "agy"); + await NodeFS.writeFile( + agy, + `#!/bin/sh +for arg in "$@"; do + if [ "$arg" = "--login" ]; then exec ${JSON.stringify(process.execPath)} ${JSON.stringify(login)} "$@"; fi +done +export T3_ACP_AGENT_INFO='{"name":"Antigravity ACP Server","version":"1.5.14"}' +exec ${JSON.stringify(process.execPath)} ${JSON.stringify(mockAgentPath)} "$@" +`, + { mode: 0o755 }, + ); + return { dir, agy }; + }), + ({ dir }) => Effect.promise(() => NodeFS.rm(dir, { recursive: true, force: true })), +); + +/** Real processes and files; a Google sign-in check never reaches the network. */ +const services = Layer.mergeAll( + NodeServices.layer, + Layer.succeed( + HttpClient.HttpClient, + HttpClient.make(() => Effect.die("A Google sign-in doesn't use Threadlines' HTTP client")), + ), +); - it("refuses anything that isn't this sign-in's redirect", () => { - const refused = [ - // Another host, port, or path: the replay must only ever reach the agent. - "http://localhost:53789/?state=8Jy4kHH5tYZC&code=x", - "http://127.0.0.1:8080/?state=8Jy4kHH5tYZC&code=x", - "http://127.0.0.1:53789/admin?state=8Jy4kHH5tYZC&code=x", - "https://127.0.0.1:53789/?state=8Jy4kHH5tYZC&code=x", - // Another sign-in attempt, or a duplicated state. - "http://127.0.0.1:53789/?state=other&code=x", - "http://127.0.0.1:53789/?state=8Jy4kHH5tYZC&state=8Jy4kHH5tYZC&code=x", - // No result, or two. - "http://127.0.0.1:53789/?state=8Jy4kHH5tYZC", - "http://127.0.0.1:53789/?state=8Jy4kHH5tYZC&code=x&error=y", - // Not issued by Google. - "http://127.0.0.1:53789/?state=8Jy4kHH5tYZC&code=x&iss=https%3A%2F%2Fevil.example", - "not a url", - ]; - for (const raw of refused) expect(accepted(raw), raw).toBe(false); +const DEFAULT_SETTINGS = Schema.decodeSync(AntigravitySettings)({}); + +const makeFlows = ( + answers: ReadonlyArray, + extraEnv: Readonly> = {}, +) => + Effect.gen(function* () { + const { dir, agy } = yield* makeStandInAgy; + const settings = { ...DEFAULT_SETTINGS, binaryPath: agy }; + const paths = antigravityInstancePaths(dir, "antigravity-test"); + const signIn = antigravitySignInConfig(settings, undefined); + const gate = makeLaunchGate(); + const descriptor = makeAntigravityDescriptor({ + paths, + runtime: undefined, + releases: undefined, + signIn, + }); + const flows = makeAntigravityAuthFlows({ + descriptor, + settings, + environment: { ...process.env, ...extraEnv }, + childProcessSpawner: yield* ChildProcessSpawner.ChildProcessSpawner, + profileDir: paths.profileDir, + gate, + stopSessions: Effect.void, + signIn, + httpClient: yield* HttpClient.HttpClient, + }); + const lines: Array = []; + const asked: Array = []; + const pending = [...answers]; + const run = (flow: "login" | "logout") => + flows.run({ + flow, + report: (line) => Effect.sync(() => void lines.push(line)), + requestPage: () => Effect.succeed(true), + showCode: () => Effect.void, + ask: (question) => + Effect.sync(() => { + asked.push(question.message); + return pending.shift() ?? null; + }), + }); + const runAskingForever = flows.run({ + flow: "login", + report: (line) => Effect.sync(() => void lines.push(line)), + requestPage: () => Effect.succeed(true), + showCode: () => Effect.void, + ask: () => Effect.never, + }); + return { run, runAskingForever, lines, asked, profileDir: paths.profileDir }; }); + +const makeFlowsAskingForever = (flows: { + readonly runAskingForever: Effect.Effect; +}) => Effect.succeed(flows.runAskingForever.pipe(Effect.timeout("20 seconds"))); + +describe.skipIf(process.platform === "win32")("Antigravity Google sign-in", () => { + it.live("signs the profile in with the code from the Antigravity page", () => + Effect.gen(function* () { + // A pasted line that isn't a code is asked again, never sent to the CLI. + const flows = yield* makeFlows(["not a code", CODE]); + yield* flows.run("login"); + assert.include(flows.lines, LINK); + assert.strictEqual(flows.asked.length, 2); + const signedIn = yield* readAntigravityGoogleSignIn(flows.profileDir); + assert.strictEqual(signedIn.method, "oauth-personal"); + assert.include(flows.lines, "Signed in."); + }).pipe(Effect.scoped, Effect.provide(services)), + ); + + it.live("fails in plain words when Google refuses the code, and stays signed out", () => + Effect.gen(function* () { + const flows = yield* makeFlows(["4/0Wrong-code"]); + const failure = yield* Effect.flip(flows.run("login")); + expect(failure.message).toContain("Google didn't accept the sign-in"); + const signedIn = yield* readAntigravityGoogleSignIn(flows.profileDir); + assert.isUndefined(signedIn.method); + }).pipe(Effect.scoped, Effect.provide(services)), + ); + + it.live("stops waiting for a code when the CLI gives up after printing its link", () => + Effect.gen(function* () { + // Nobody answers: only the CLI's exit can end the wait. + const flows = yield* makeFlows([], { STANDIN_EXIT_AFTER_LINK: "1" }); + const neverAnswered = yield* makeFlowsAskingForever(flows); + const failure = yield* Effect.flip(neverAnswered); + expect(failure.message).toContain("couldn't reach Google"); + }).pipe(Effect.scoped, Effect.provide(services)), + ); + + it.live("stays signed out when Google refuses a session on the new sign-in", () => + Effect.gen(function* () { + const flows = yield* makeFlows([CODE], { T3_ACP_AUTH_REQUIRED: "1" }); + yield* Effect.flip(flows.run("login")); + const signedIn = yield* readAntigravityGoogleSignIn(flows.profileDir); + assert.isUndefined(signedIn.method); + }).pipe(Effect.scoped, Effect.provide(services)), + ); + + it.live("signs out by removing only the profile's own sign-in", () => + Effect.gen(function* () { + const flows = yield* makeFlows([CODE]); + yield* flows.run("login"); + yield* flows.run("logout"); + const signedIn = yield* readAntigravityGoogleSignIn(flows.profileDir); + assert.isUndefined(signedIn.method); + const token = yield* Effect.promise(() => + NodeFS.stat(antigravityTokenPath(flows.profileDir)).then( + () => true, + () => false, + ), + ); + assert.isFalse(token); + }).pipe(Effect.scoped, Effect.provide(services)), + ); }); diff --git a/apps/server/src/provider/antigravity/AntigravityAuth.ts b/apps/server/src/provider/antigravity/AntigravityAuth.ts index 033e18c96..197edf5a8 100644 --- a/apps/server/src/provider/antigravity/AntigravityAuth.ts +++ b/apps/server/src/provider/antigravity/AntigravityAuth.ts @@ -1,85 +1,203 @@ +// @effect-diagnostics nodeBuiltinImport:off - runs `agy acp --login` and talks to it over its pipes /** * AntigravityAuth — sign-in and sign-out for one Antigravity instance, per * its sign-in method. * - * Google account and Gemini Enterprise sign in inside the agent's own - * process (below). The key methods have nothing to sign in to: "login" - * checks what can be checked without spending (Google accepting a Gemini - * API key; Vertex AI's project and Google Cloud sign-in) and records the - * verdict for the status. They don't stop running sessions. + * Google account and Gemini Enterprise sign in with the CLI's own + * `agy acp --login`, run in the instance's profile: it prints a Google link, + * Google ends on an antigravity.google page that shows a code, and the CLI + * reads that code back on its input. The link opens on the device that + * started sign-in (a phone, another computer, this one), and the code is + * asked for in the same panel, tied to this run; Threadlines checks it and + * hands it to the waiting process only. The sign-in is kept in the + * profile's own file (`antigravityEnvironment`), so extra accounts don't + * share one, and success is a real session opening on it afterwards. * - * Sign-in: the agent prints a Google URL and listens on a 127.0.0.1 port of - * the machine it runs on for the browser's redirect. A client on the same - * machine just opens the URL; a client elsewhere (a phone, another - * computer) ends on an unreachable 127.0.0.1 page and pastes its address - * back, which is checked against this sign-in and replayed once from here. - * Success is the agent's own `authenticate` and `session/new` returning, - * never the replay alone. + * Sign-out removes that file and nothing else: no agent is asked to log + * out, so the OS keyring and the user's own terminal `agy` are never + * touched. * - * Both flows close the instance first: no new agent process starts, its - * sessions stop (they hold the old credentials in memory), and the flow waits - * for every other process of the instance (a session still starting, a title - * being written) to end before it touches the profile. + * The key methods have nothing to sign in to: "login" checks what can be + * checked without spending (Google accepting a Gemini API key; Vertex AI's + * project and Google Cloud sign-in) and records the verdict for the status. + * They don't stop running sessions. + * + * Google sign-in and sign-out close the instance first: no new agent + * process starts, its sessions stop (they hold the old credentials in + * memory), and the flow waits for every other process of the instance to + * end before it touches the profile. * * @module provider/antigravity/AntigravityAuth */ +import { type ChildProcessWithoutNullStreams, spawn as spawnChild } from "node:child_process"; +import { createInterface } from "node:readline"; -import type { AntigravitySettings } from "@threadlines/contracts"; +import type { AntigravitySettings, ProviderAuthQuestionKind } from "@threadlines/contracts"; +import * as Data from "effect/Data"; import * as DateTime from "effect/DateTime"; +import * as Deferred from "effect/Deferred"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import { HttpClient } from "effect/http"; import type { ChildProcessSpawner } from "effect/process"; +import { THREADLINES_ACP_CLIENT_INFO } from "../acp/acpClientInfo.ts"; import type { AcpProviderDescriptor } from "../acp/AcpProviderDescriptor.ts"; import { makeAcpProviderRuntime } from "../acp/AcpProviderRuntime.ts"; import { type LaunchGate, withLaunchGateClosed } from "../managedRuntime/LaunchGate.ts"; import type { ProviderInstanceAuthFlows } from "../ProviderDriver.ts"; -import type { LoopbackRedirect } from "@threadlines/shared/signInRedirect"; -import { checkLoopbackRedirect, replayLoopbackRedirect } from "../auth/loopbackRedirect.ts"; import { antigravityCredentialFingerprint, antigravityMissingSetup, type AntigravitySignInConfig, checkGeminiApiKey, + removeAntigravityGoogleSignIn, resolveAntigravityAdc, + writeAntigravityGoogleSignIn, writeAntigravityProfileSettings, writeAntigravitySignInCheck, } from "./AntigravitySignInMethod.ts"; import { ProviderSetupError } from "../Errors.ts"; -const SIGN_IN_TIMEOUT = Duration.minutes(5); +/** How long the CLI may take to print its link: Windows cold starts unpack first. */ +const LINK_TIMEOUT = Duration.seconds(90); +/** How long the user has to sign in and paste the code. */ +const CODE_TIMEOUT = Duration.minutes(10); +/** How long the CLI may take to trade the code for a sign-in. */ +const FINISH_TIMEOUT = Duration.minutes(2); +/** Opening a session on the new sign-in. */ +const VERIFY_TIMEOUT = Duration.minutes(2); const SIGN_OUT_TIMEOUT = Duration.seconds(90); +/** Wrong codes accepted before sign-in gives up. */ +const CODE_ATTEMPTS = 5; +/** Lines of the CLI's output kept to explain a failure. */ +const OUTPUT_TAIL_LINES = 40; +const MAX_URL_LENGTH = 16_384; + +/** Where `agy acp --login` sends Google: a page that shows the code to paste back. */ +export const ANTIGRAVITY_CODE_REDIRECT_URI = "https://antigravity.google/oauth-callback"; -interface PendingSignIn { - readonly redirect: URL; +const failure = (message: string) => ({ message }); + +export interface AntigravityCodeSignInLink { + readonly url: string; readonly state: string; - consumed: boolean; } -const failure = (message: string) => ({ message }); +/** + * The Google link `agy acp --login` prints, if `line` is one: Google's + * OAuth page, a code request, one state, and Antigravity's code page as the + * redirect. Anything else is not a link Threadlines opens. + */ +export function parseAntigravityCodeSignInLink( + line: string, +): AntigravityCodeSignInLink | undefined { + const raw = line.trim(); + if (!raw.startsWith("https://accounts.google.com/")) return undefined; + if (raw.length > MAX_URL_LENGTH || /\s/u.test(raw)) return undefined; + const url = URL.parse(raw); + if ( + url === null || + url.origin !== "https://accounts.google.com" || + url.pathname !== "/o/oauth2/auth" || + url.username !== "" || + url.password !== "" || + url.hash !== "" || + url.searchParams.getAll("redirect_uri").length !== 1 || + url.searchParams.get("redirect_uri") !== ANTIGRAVITY_CODE_REDIRECT_URI || + url.searchParams.getAll("response_type").length !== 1 || + url.searchParams.get("response_type") !== "code" || + url.searchParams.getAll("state").length !== 1 + ) { + return undefined; + } + const state = url.searchParams.get("state") ?? ""; + if (state.length === 0 || state.length > 512) return undefined; + return { url: url.toString(), state }; +} + +/** + * What to hand `agy acp --login` for a pasted answer: the code the + * Antigravity page shows, or that page's whole address when it belongs to + * this sign-in. Undefined for anything else, a line break included, so a + * paste can never feed the CLI a second line. + */ +export function antigravityLoginResponse( + link: AntigravityCodeSignInLink, + pasted: string, +): string | undefined { + const value = pasted.trim(); + if (/^[\w./~-]{1,2048}$/u.test(value)) return value; + if (value.length > MAX_URL_LENGTH || /\s/u.test(value)) return undefined; + const url = URL.parse(value); + if ( + url === null || + `${url.origin}${url.pathname}` !== ANTIGRAVITY_CODE_REDIRECT_URI || + url.username !== "" || + url.password !== "" || + url.searchParams.getAll("state").length !== 1 || + url.searchParams.get("state") !== link.state || + url.searchParams.getAll("code").length !== 1 || + !url.searchParams.get("code") + ) { + return undefined; + } + return value; +} + +const VERIFICATION_HOST = "https://accounts.google.com"; +const VERIFICATION_PATHS = new Set(["/v3/signin/continue", "/signin/continue"]); + +/** A Google account verification page named in `text`, if it is one on Google's own sign-in host. */ +export function antigravityVerificationUrl(text: string): string | undefined { + for (const match of text.matchAll(/https:\/\/accounts\.google\.com\/[^\s"'<>\\]+/gu)) { + const url = URL.parse(match[0]); + if ( + url !== null && + url.origin === VERIFICATION_HOST && + VERIFICATION_PATHS.has(url.pathname) && + url.username === "" && + url.password === "" && + !Array.from(match[0]).some( + (character) => character.charCodeAt(0) < 0x20 || character.charCodeAt(0) === 0x7f, + ) + ) { + return url.toString(); + } + } + return undefined; +} -function friendlySignInError(error: unknown): string { - const text = error instanceof Error ? error.message : String(error); +/** The words a failed Google sign-in shows, from what the CLI or Google said. */ +export function antigravitySignInErrorMessage(text: string): string { + if (/VALIDATION_REQUIRED|verify your account/iu.test(text)) { + const url = antigravityVerificationUrl(text); + return url + ? `Google needs you to verify this account before Antigravity can use it. Verify it at ${url}, then sign in again.` + : "Google needs you to verify this account before Antigravity can use it. Sign in to Google in your browser to verify it, then sign in again."; + } if (/SUBSCRIPTION_REQUIRED/u.test(text)) { return "This Google account can't use Antigravity yet: it needs an eligible plan."; } - if (/access_denied|cancelled|onboarding_failed|did not complete/iu.test(text)) { - return "Sign-in didn't finish. Try again and approve the request in your browser."; + if (/access_denied|invalid_grant|denied access|cancelled|onboarding_failed/iu.test(text)) { + return "Google didn't accept the sign-in. Start again, approve it in your browser, and paste the newest code."; + } + if ( + /AF_INET6|enforce_kernel_ipv6_support|network is unreachable|no such host|i\/o timeout|connection refused|dial tcp|TLS handshake|deadline exceeded/iu.test( + text, + ) + ) { + return "Antigravity couldn't reach Google. Check this computer's network connection. Broken IPv6 is a common cause."; } - return text || "Sign-in failed."; + return "Antigravity couldn't finish signing in with Google. Try again."; } -/** - * The pasted address, if it is this sign-in's redirect (see - * `checkLoopbackRedirect`), with Google as the issuer when one is named. - * Otherwise the reason, worded for the user. - */ -export function checkAntigravityRedirect(raw: string, pending: LoopbackRedirect): URL | string { - return checkLoopbackRedirect(raw, pending, { - issuer: { url: "https://accounts.google.com", name: "Google" }, - }); -} +/** A sign-in step that failed, with the words for the user. */ +class SignInFailed extends Data.TaggedError("AntigravitySignInFailed")<{ + readonly message: string; +}> {} + +const signInFailed = (message: string) => new SignInFailed({ message }); export function makeAntigravityAuthFlows(input: { /** A descriptor that ignores the gate: the flow's own process must start. */ @@ -95,10 +213,11 @@ export function makeAntigravityAuthFlows(input: { readonly httpClient: HttpClient.HttpClient; }): ProviderInstanceAuthFlows { const { signIn: method } = input; - const googleSignIn = method.method === "oauth-personal" || method.method === "oauth-business"; + const googleMethod = + method.method === "oauth-personal" || method.method === "oauth-business" + ? method.method + : undefined; const enterprise = method.method === "oauth-business"; - let pending: PendingSignIn | undefined; - let report: ((line: string) => Effect.Effect) | undefined; // The instance closed and every process of it gone, for as long as // `effect` runs. @@ -112,84 +231,206 @@ export function makeAntigravityAuthFlows(input: { stop: input.stopSessions, onWaiting: emit("Waiting for Antigravity to finish its current work…"), }, - effect.pipe( - Effect.ensuring( - Effect.sync(() => { - pending = undefined; - report = undefined; + effect, + ); + + /** `agy acp --login` in the instance's profile, its link, and what it printed. */ + const startLogin = Effect.gen(function* () { + const planned = input.descriptor.spawn(input.settings, input.profileDir, input.environment); + const launch = Effect.isEffect(planned) ? yield* planned : planned; + // Without a display the CLI only prints its link, never opening a + // browser on the computer that runs Threadlines. + const { DISPLAY: _display, WAYLAND_DISPLAY: _wayland, ...env } = launch.env ?? {}; + const output: Array = []; + const link = yield* Deferred.make(); + const exited = yield* Deferred.make(); + const child = yield* Effect.acquireRelease( + Effect.try({ + try: (): ChildProcessWithoutNullStreams => + spawnChild(launch.command, [...launch.args, "--login"], { + cwd: input.profileDir, + env, + stdio: ["pipe", "pipe", "pipe"], + windowsHide: true, }), + catch: () => + signInFailed("Antigravity didn't start. Check that it's installed, then try again."), + }), + // Our own child, by the handle we spawned it with. + (process) => Effect.sync(() => (process.exitCode === null ? process.kill() : undefined)), + ); + if (child.pid !== undefined && launch.onSpawned) yield* launch.onSpawned(child.pid); + const remember = (line: string) => { + output.push(line.slice(0, 2_000)); + if (output.length > OUTPUT_TAIL_LINES) output.shift(); + }; + createInterface({ input: child.stdout }).on("line", (line) => { + remember(line); + const parsed = parseAntigravityCodeSignInLink(line); + if (parsed) Deferred.doneUnsafe(link, Effect.succeed(parsed)); + }); + createInterface({ input: child.stderr }).on("line", remember); + child.once("error", () => + Deferred.doneUnsafe( + link, + Effect.fail( + signInFailed("Antigravity didn't start. Check that it's installed, then try again."), ), ), ); + child.once("close", (code) => { + Deferred.doneUnsafe(exited, Effect.succeed(code)); + Deferred.doneUnsafe( + link, + Effect.fail( + signInFailed( + output.length > 0 + ? antigravitySignInErrorMessage(output.join("\n")) + : "Antigravity didn't start. Check that it's installed, then try again.", + ), + ), + ); + }); + return { child, link, exited, output }; + }); - const runtime = (options: { - readonly onSignInUrl?: (url: string) => Effect.Effect; - readonly authMethodId?: string; - }) => - makeAcpProviderRuntime(input.descriptor, { - settings: input.settings, - environment: input.environment, - childProcessSpawner: input.childProcessSpawner, - cwd: input.profileDir, - clientInfo: { name: "threadlines", version: "0.0.0" }, - ...options, + const askForCode = ( + ask: (question: { + readonly kind: ProviderAuthQuestionKind; + readonly message: string; + readonly placeholder?: string; + }) => Effect.Effect, + link: AntigravityCodeSignInLink, + ) => + Effect.gen(function* () { + let message = enterprise + ? "Sign in with your work Google account in the page that opened, then paste the code the Antigravity page shows." + : "Sign in with Google in the page that opened, then paste the code the Antigravity page shows."; + for (let attempt = 0; attempt < CODE_ATTEMPTS; attempt += 1) { + const answer = yield* ask({ kind: "text", message, placeholder: "Code" }); + if (answer === null) return yield* Effect.fail(signInFailed("Sign-in was cancelled.")); + const response = antigravityLoginResponse(link, answer); + if (response !== undefined) return response; + message = + "That isn't a code from the Antigravity page. Paste the code it shows, or the page's whole address."; + } + return yield* Effect.fail( + signInFailed("Too many codes that didn't fit. Start sign-in again."), + ); }); - const signIn = (emit: (line: string) => Effect.Effect) => + const signInWithGoogle = ( + googleMethod: "oauth-personal" | "oauth-business", + emit: (line: string) => Effect.Effect, + ask: Parameters[0], + requestPage: (request: { + readonly url: string; + readonly message: string | null; + }) => Effect.Effect, + ) => Effect.gen(function* () { - // Nothing of the instance runs now: the agent reads the method and + // Nothing of the instance runs now: the CLI reads the method and // project from the profile when it starts. - yield* writeAntigravityProfileSettings(input.profileDir, method); - const acp = yield* runtime({ - authMethodId: method.method, - onSignInUrl: (url) => - Effect.gen(function* () { - const parsed = new URL(url); - const redirect = parsed.searchParams.get("redirect_uri"); - const state = parsed.searchParams.get("state"); - if (!redirect || !state) return; - pending = { redirect: new URL(redirect), state, consumed: false }; - // The URL on its own line: clients open it from the output. The - // line after it is what their one-line status shows. - yield* emit(url); - yield* emit( - enterprise - ? "Finish signing in with your work Google account in your browser." - : "Finish signing in with Google in your browser.", - ); - }), - }); + yield* writeAntigravityProfileSettings(input.profileDir, method).pipe( + Effect.mapError((error) => signInFailed(error.message)), + ); yield* emit("Starting Antigravity…"); - // initialize, authenticate (waits for the browser), then session/new - // proves the credentials work. - yield* acp.start().pipe( + const login = yield* startLogin; + const link = yield* Deferred.await(login.link).pipe( + Effect.timeoutOrElse({ + duration: LINK_TIMEOUT, + orElse: () => + Effect.fail( + signInFailed( + login.output.length > 0 + ? antigravitySignInErrorMessage(login.output.join("\n")) + : "Antigravity didn't start within 90 seconds. Try again.", + ), + ), + }), + ); + // The link on its own line: clients open it from the output. + yield* emit(link.url); + // A CLI that gives up after printing its link (a network error) ends + // the wait for a code rather than leaving the user to sign in for nothing. + const exitedEarly = Deferred.await(login.exited).pipe( + Effect.flatMap(() => + Effect.fail(signInFailed(antigravitySignInErrorMessage(login.output.join("\n")))), + ), + ); + const response = yield* Effect.raceFirst(askForCode(ask, link), exitedEarly).pipe( + Effect.timeoutOrElse({ + duration: CODE_TIMEOUT, + orElse: () => + Effect.fail(signInFailed("Sign-in timed out waiting for the code. Try again.")), + }), + ); + login.child.stdin.end(`${response}\n`); + yield* emit("Got the code. Finishing sign-in…"); + const exitCode = yield* Deferred.await(login.exited).pipe( Effect.timeoutOrElse({ - duration: SIGN_IN_TIMEOUT, + duration: FINISH_TIMEOUT, + orElse: () => Effect.fail(signInFailed("Google didn't answer in time. Try again.")), + }), + ); + if (exitCode !== 0) { + return yield* Effect.fail( + signInFailed(antigravitySignInErrorMessage(login.output.join("\n"))), + ); + } + // A session opening on the new sign-in is the proof, and lists the + // account's models for the status. Only then is it recorded as this + // method's sign-in: one Google refuses a session (no plan, unverified) + // stays signed out. + yield* emit("Checking the sign-in…"); + yield* Effect.scoped( + Effect.gen(function* () { + const acp = yield* makeAcpProviderRuntime(input.descriptor, { + settings: input.settings, + environment: input.environment, + childProcessSpawner: input.childProcessSpawner, + cwd: input.profileDir, + clientInfo: THREADLINES_ACP_CLIENT_INFO, + }); + yield* acp.start(); + }), + ).pipe( + Effect.timeoutOrElse({ + duration: VERIFY_TIMEOUT, orElse: () => Effect.fail( - new ProviderSetupError({ detail: "Sign-in timed out after 5 minutes. Try again." }), + signInFailed("Antigravity signed in but didn't open a session. Try again."), ), }), + Effect.mapError((error) => + error instanceof SignInFailed + ? error + : signInFailed(antigravitySignInErrorMessage(String(error))), + ), ); + yield* writeAntigravityGoogleSignIn(input.profileDir, googleMethod); yield* emit("Signed in."); }).pipe( Effect.scoped, - Effect.mapError((error) => failure(friendlySignInError(error))), + // Google's verification page is offered as a page to open (a button on + // a phone too), not only named in the error. + Effect.tapError((error) => { + const url = antigravityVerificationUrl(error.message); + return url + ? requestPage({ url, message: "Verify your Google account, then sign in again." }) + : Effect.void; + }), + Effect.mapError((error) => + failure(error instanceof SignInFailed ? error.message : "Sign-in failed. Try again."), + ), ); const signOut = (emit: (line: string) => Effect.Effect) => Effect.gen(function* () { - const acp = yield* runtime({}); yield* emit("Signing out of Antigravity…"); - yield* acp.request("initialize", { - protocolVersion: 1, - clientCapabilities: { fs: { readTextFile: false, writeTextFile: false }, terminal: false }, - clientInfo: { name: "threadlines", version: "0.0.0" }, - }); - yield* acp.request("logout", {}); + yield* removeAntigravityGoogleSignIn(input.profileDir); yield* emit("Signed out."); }).pipe( - Effect.scoped, Effect.timeoutOrElse({ duration: SIGN_OUT_TIMEOUT, orElse: () => @@ -197,9 +438,7 @@ export function makeAntigravityAuthFlows(input: { new ProviderSetupError({ detail: "Antigravity did not finish signing out." }), ), }), - Effect.mapError((error) => - failure(error instanceof Error ? error.message : "Sign-out failed."), - ), + Effect.mapError((error) => failure(error.message || "Sign-out failed.")), ); const recordCheck = (accepted: boolean, message?: string) => @@ -258,7 +497,7 @@ export function makeAntigravityAuthFlows(input: { : "Add your Google Cloud project and location, or a Vertex AI key, first."; return { - flows: googleSignIn ? ["login", "logout"] : ["login"], + flows: googleMethod ? ["login", "logout"] : ["login"], describe: (flow) => { if (flow === "logout") return "Sign out of Google"; switch (method.method) { @@ -272,46 +511,25 @@ export function makeAntigravityAuthFlows(input: { return "Sign in with Google"; } }, - run: ({ flow, report: emit }) => { - if (flow !== "login" && !(flow === "logout" && googleSignIn)) { + run: ({ flow, report: emit, ask, requestPage }) => { + if (flow !== "login" && !(flow === "logout" && googleMethod)) { return Effect.fail(failure("Antigravity has no such sign-in flow.")); } if (flow === "login" && missing) return Effect.fail(failure(missingMessage)); // Checks touch neither the profile nor the agent: sessions keep running. if (method.method === "gemini-api-key") return checkKey(emit); if (method.method === "agent-platform") return checkVertex(emit); + if (!googleMethod) return Effect.fail(failure("Antigravity has no such sign-in flow.")); return closed( emit, - Effect.gen(function* () { - report = emit; - if (flow === "logout") return yield* signOut(emit); - return yield* signIn(emit); - }), + flow === "logout" ? signOut(emit) : signInWithGoogle(googleMethod, emit, ask, requestPage), ); }, - completeRedirect: (raw) => - Effect.gen(function* () { - const current = pending; - if (!current) { - return yield* Effect.fail( - failure("No sign-in is waiting for a browser address. Start sign-in first."), - ); - } - if (current.consumed) { - return yield* Effect.fail(failure("This sign-in already received its address.")); - } - const checked = checkAntigravityRedirect(raw, current); - if (typeof checked === "string") return yield* Effect.fail(failure(checked)); - const url = checked; - current.consumed = true; - const status = yield* Effect.tryPromise({ - try: () => replayLoopbackRedirect(url), - catch: () => failure("The sign-in stopped listening. Start sign-in again."), - }); - if (status < 200 || status >= 300) { - return yield* Effect.fail(failure("Antigravity didn't accept that address.")); - } - if (report) yield* report("Got the address; finishing sign-in…"); - }), + // The code from the Antigravity page is asked for in the panel; there is + // no browser address to replay. + completeRedirect: () => + Effect.fail( + failure("Antigravity signs in with the code its page shows. Paste that code instead."), + ), }; } diff --git a/apps/server/src/provider/antigravity/AntigravityChildRecords.test.ts b/apps/server/src/provider/antigravity/AntigravityChildRecords.test.ts new file mode 100644 index 000000000..9bc511e5b --- /dev/null +++ b/apps/server/src/provider/antigravity/AntigravityChildRecords.test.ts @@ -0,0 +1,294 @@ +// @effect-diagnostics nodeBuiltinImport:off +import * as os from "node:os"; +import * as path from "node:path"; +import { mkdir, mkdtemp, rename, rm, symlink, writeFile } from "node:fs/promises"; + +import { it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import { describe, expect } from "vite-plus/test"; + +import { + type AntigravityChildrenReading, + antigravityChildOf, + antigravityChildTranscript, + readAntigravityChildren, +} from "./AntigravityChildRecords.ts"; +import { openAntigravityProfileFile } from "./AntigravitySessionLog.ts"; + +const PARENT = "7d40e54d-5977-4239-940b-246cdd81a12b"; + +/** A profile with the CLI's records as agy 1.5.12+ writes them (shapes from T3 Code's fixtures). */ +async function makeProfile() { + const profile = await mkdtemp(path.join(os.tmpdir(), "agy-child-records-")); + const brain = path.join(profile, "antigravity-acp", "brain"); + const write = async (segments: ReadonlyArray, value: unknown) => { + const file = path.join(brain, ...segments); + await mkdir(path.dirname(file), { recursive: true }); + await writeFile(file, typeof value === "string" ? value : JSON.stringify(value)); + }; + const child = async (id: string, callId: string, state = "SUBAGENT_STATE_ALIVE") => { + await write([PARENT, ".system_generated", "subagents", `${id}.json`], { + conversationId: id, + subagentDescriptor: { typeName: "research", role: "Line Counter" }, + state, + }); + await write([id, ".system_generated", "messages", "launch.json"], { + sender: PARENT, + content: "Count lines in README.md", + sourceMetadata: { + tool: { conversationId: PARENT, toolCall: { id: callId, name: "invoke_subagent" } }, + }, + }); + await write([id, ".system_generated", "messages", "read.json"], { launch: true }); + }; + const report = (child: string, content: string) => + write([PARENT, ".system_generated", "messages", `${child}-report.json`], { + sender: child, + content, + }); + return { profile, brain, write, child, report }; +} + +const withProfile = ( + use: (records: Awaited>) => Effect.Effect, +) => + Effect.acquireUseRelease(Effect.promise(makeProfile), use, (records) => + Effect.promise(() => rm(records.profile, { recursive: true, force: true })), + ); + +/** Each bucket as `conversationId:launchCallId`, for comparing a whole reading at once. */ +const summary = (reading: AntigravityChildrenReading) => + reading.available + ? Object.fromEntries( + (["running", "reported", "killed"] as const).map((state) => [ + state, + reading[state].map((child) => `${child.conversationId}:${child.launchCallId ?? "?"}`), + ]), + ) + : reading; + +describe("readAntigravityChildren", () => { + it.live("sorts a session's children into running, reported and killed, by their launch", () => + withProfile((records) => + Effect.gen(function* () { + yield* Effect.promise(async () => { + await records.child("child-working", "call_working"); + await records.child("child-reported", "call_reported"); + await records.child("child-killed", "call_killed", "SUBAGENT_STATE_KILLED"); + await records.report("child-reported", "README.md has 42 lines."); + // A follow-up message is not a launch. + await records.write(["child-working", ".system_generated", "messages", "followup.json"], { + sender: PARENT, + content: "Also check LICENSE", + sourceMetadata: { tool: { toolCall: { id: "call_followup", name: "send_message" } } }, + }); + }); + const reading = yield* readAntigravityChildren(records.profile, PARENT); + expect(summary(reading)).toEqual({ + running: ["child-working:call_working"], + reported: ["child-reported:call_reported"], + killed: ["child-killed:call_killed"], + }); + expect(antigravityChildOf(reading, "call_reported")?.report).toBe( + "README.md has 42 lines.", + ); + // Without argumentsJson the role is the entry's and the prompt the launch message's. + expect(antigravityChildOf(reading, "call_working")?.launch).toEqual({ + role: "Line Counter", + prompt: "Count lines in README.md", + }); + expect(antigravityChildOf(reading, "call_followup")).toBeUndefined(); + }), + ), + ); + + it.live("ties no child to a launch two children claim", () => + withProfile((records) => + Effect.gen(function* () { + yield* Effect.promise(async () => { + await records.child("child-a", "call_twin"); + await records.child("child-b", "call_twin"); + }); + const reading = yield* readAntigravityChildren(records.profile, PARENT); + expect(summary(reading)).toEqual({ + running: ["child-a:?", "child-b:?"], + reported: [], + killed: [], + }); + expect(antigravityChildOf(reading, "call_twin")).toBeUndefined(); + }), + ), + ); + + it.live("says when there are no records, and when they can't be trusted", () => + withProfile((records) => + Effect.gen(function* () { + expect(yield* readAntigravityChildren(records.profile, PARENT)).toEqual({ + available: false, + reason: "no-records", + }); + // A session id that walks a path is refused outright. + expect(yield* readAntigravityChildren(records.profile, "../x")).toEqual({ + available: false, + reason: "unreadable", + }); + yield* Effect.promise(() => records.child("child-a", "call_a")); + expect((yield* readAntigravityChildren(records.profile, PARENT)).available).toBe(true); + }), + ), + ); + + it.live("doesn't follow a link out of the profile", () => + withProfile((records) => + Effect.gen(function* () { + const elsewhere = yield* Effect.promise(() => + mkdtemp(path.join(os.tmpdir(), "agy-child-elsewhere-")), + ); + yield* Effect.promise(async () => { + await records.child("child-a", "call_a"); + await writeFile(path.join(elsewhere, "transcript.jsonl"), '{"step_index":1}\n'); + await mkdir(path.join(records.brain, "child-a", ".system_generated"), { + recursive: true, + }); + await symlink( + elsewhere, + path.join(records.brain, "child-a", ".system_generated", "logs"), + ); + }); + // The linked transcript is not read: only the instruction shows. + const transcript = yield* antigravityChildTranscript(records.profile, PARENT, "call_a"); + expect(transcript?.entries.map((entry) => entry.id)).toEqual(["launch"]); + // A linked subagents folder is no records at all. + yield* Effect.promise(async () => { + await rm(path.join(records.brain, PARENT, ".system_generated", "subagents"), { + recursive: true, + }); + await symlink( + elsewhere, + path.join(records.brain, PARENT, ".system_generated", "subagents"), + ); + }); + expect((yield* readAntigravityChildren(records.profile, PARENT)).available).toBe(false); + yield* Effect.promise(() => rm(elsewhere, { recursive: true, force: true })); + }), + ), + ); + + it.live("skips a message it can't read instead of giving up on the session", () => + withProfile((records) => + Effect.gen(function* () { + yield* Effect.promise(async () => { + await records.child("child-a", "call_a"); + await records.child("child-b", "call_b"); + await records.report("child-b", "Done."); + // A report the CLI is still writing. + await records.write([PARENT, ".system_generated", "messages", "partial.json"], '{"sen'); + }); + const reading = yield* readAntigravityChildren(records.profile, PARENT); + expect(summary(reading)).toEqual({ + running: ["child-a:call_a"], + reported: ["child-b:call_b"], + killed: [], + }); + expect(reading.available && reading.unreadable).toBe(1); + }), + ), + ); + + it.live("counts every entry of a folder toward its limit, read one at a time", () => + withProfile((records) => + Effect.gen(function* () { + yield* Effect.promise(async () => { + await records.child("child-a", "call_a"); + const inbox = path.join(records.brain, PARENT, ".system_generated", "messages"); + await mkdir(inbox, { recursive: true }); + for (let index = 0; index < 300; index += 1) { + await writeFile(path.join(inbox, `${index}.tmp`), ""); + } + }); + expect(yield* readAntigravityChildren(records.profile, PARENT)).toEqual({ + available: false, + reason: "unreadable", + }); + }), + ), + ); +}); + +describe("readAntigravityChildren, refused folders", () => { + it.live("counts a child inbox that is a link as unread, not as empty", () => + withProfile((records) => + Effect.gen(function* () { + const elsewhere = yield* Effect.promise(() => + mkdtemp(path.join(os.tmpdir(), "agy-child-elsewhere-")), + ); + yield* Effect.promise(async () => { + await records.child("child-a", "call_a"); + const inbox = path.join(records.brain, "child-a", ".system_generated", "messages"); + await rm(inbox, { recursive: true }); + await symlink(elsewhere, inbox); + }); + const reading = yield* readAntigravityChildren(records.profile, PARENT); + // The child is still running, tied to no launch, and the reading says it's incomplete. + expect(summary(reading)).toEqual({ running: ["child-a:?"], reported: [], killed: [] }); + expect(reading.available && reading.unreadable).toBe(1); + // A parent inbox that is a link makes the whole reading unavailable. + yield* Effect.promise(() => + symlink(elsewhere, path.join(records.brain, PARENT, ".system_generated", "messages")), + ); + expect(yield* readAntigravityChildren(records.profile, PARENT)).toEqual({ + available: false, + reason: "unreadable", + }); + yield* Effect.promise(() => rm(elsewhere, { recursive: true, force: true })); + }), + ), + ); +}); + +describe("openAntigravityProfileFile", () => { + it.live("refuses a file reached through a folder swapped for a link after the check", () => + withProfile((records) => + Effect.gen(function* () { + const elsewhere = yield* Effect.promise(() => + mkdtemp(path.join(os.tmpdir(), "agy-child-elsewhere-")), + ); + const logs = path.join(records.brain, "child-a", ".system_generated", "logs"); + yield* Effect.promise(async () => { + await records.write( + ["child-a", ".system_generated", "logs", "transcript.jsonl"], + "ours\n", + ); + await mkdir(path.join(elsewhere, "logs"), { recursive: true }); + await writeFile(path.join(elsewhere, "logs", "transcript.jsonl"), "theirs\n"); + }); + const segments = ["brain", "child-a", ".system_generated", "logs", "transcript.jsonl"]; + // The path checks out, then a folder on it becomes a link out of the profile. + const swapped = yield* Effect.promise(() => + openAntigravityProfileFile(records.profile, segments, async () => { + await rename(logs, `${logs}.moved`); + await symlink(path.join(elsewhere, "logs"), logs); + }), + ); + expect(swapped).toBe("refused"); + // Put back, the same file opens, and is told apart once swapped again. + const opened = yield* Effect.promise(async () => { + await rm(logs); + await rename(`${logs}.moved`, logs); + return openAntigravityProfileFile(records.profile, segments); + }); + if (typeof opened === "string") throw new Error(`expected a file, got ${opened}`); + expect(yield* Effect.promise(() => opened.stillHeld())).toBe(true); + yield* Effect.promise(async () => { + await rename(logs, `${logs}.moved`); + await symlink(path.join(elsewhere, "logs"), logs); + }); + expect(yield* Effect.promise(() => opened.stillHeld())).toBe(false); + yield* Effect.promise(async () => { + await opened.handle.close(); + await rm(elsewhere, { recursive: true, force: true }); + }); + }), + ), + ); +}); diff --git a/apps/server/src/provider/antigravity/AntigravityChildRecords.ts b/apps/server/src/provider/antigravity/AntigravityChildRecords.ts new file mode 100644 index 000000000..831109c6d --- /dev/null +++ b/apps/server/src/provider/antigravity/AntigravityChildRecords.ts @@ -0,0 +1,532 @@ +// @effect-diagnostics nodeBuiltinImport:off -- reads the agent's own subagent records with bounded fs reads. +/** + * Reads what Antigravity's subagents did from the CLI's own records. + * THIS READS A PRIVATE FORMAT: Google documents none of it, and a CLI update + * can change it without notice. ACP tells a client only that the agent ran + * an `invoke_subagent` tool call and that the call returned at once; which + * child it started, whether that child has reported, and what it did are + * only in these files. + * + * Layout as of `agy` 1.5.12 to 1.5.14, matching T3 Code's reader + * (apps/server/src/provider/acp/AntigravityChildWork.ts, commits 066be30005 + * and 194726492b), all under `/antigravity-acp/brain/`: + * - `/.system_generated/subagents/.json`: one per child the + * session started, `{ conversationId, subagentDescriptor: { role }, state }`. + * `manage_subagents` kill only rewrites `state` to `SUBAGENT_STATE_KILLED`. + * - `/.system_generated/messages/*.json`: the child's inbox. Its launch + * is a message from the parent whose `sourceMetadata.tool.toolCall` is the + * parent's `invoke_subagent` call (the ACP tool call id) with its arguments. + * `read.json` there is read receipts, not a message. + * - `/.system_generated/messages/*.json`: the parent's inbox. A + * message whose `sender` is a child is that child's report. + * - `/.system_generated/logs/transcript.jsonl`: the child's steps, one + * JSON line each (`step_index`, `type`, `content`, `tool_calls`). + * + * Every path is checked the way the session-log reader checks its own (no + * links, the expected file or folder, inside the profile Threadlines made), + * files are opened read-only without blocking or following a link + * (`AntigravityFileReads`), and every read is bounded. A record this + * cannot read proves nothing: callers fall back to what ACP said. + * + * @module provider/antigravity/AntigravityChildRecords + */ +import * as NodeFSP from "node:fs/promises"; + +import type { ProviderSubagentTranscriptEntry } from "@threadlines/contracts"; +import * as Effect from "effect/Effect"; + +import { antigravityProfileEntry, openAntigravityProfileFile } from "./AntigravitySessionLog.ts"; +import { boundAntigravityText } from "./AntigravityToolCalls.ts"; + +/** Ids as the CLI names conversations: nothing that walks a path. */ +const NATIVE_ID = /^[A-Za-z0-9-]{1,64}$/u; +const MAX_CHILDREN = 64; +const MAX_INBOX_MESSAGES = 256; +const MAX_RECORD_BYTES = 1024 * 1024; +/** All the records one read of a session's children may take together. */ +const MAX_READ_BYTES = 16 * 1024 * 1024; +/** The end of a child's transcript that is read: its recent steps. */ +const TRANSCRIPT_TAIL_BYTES = 256 * 1024; +const STEP_TEXT_LIMIT = 4_000; +const TOOL_SUMMARY_LIMIT = 1_000; +const KILLED_STATE = "SUBAGENT_STATE_KILLED"; +const LAUNCH_TOOLS = new Set(["invoke_subagent", "start_subagent"]); + +/** A subagent's role and prompt, as its launch named them. */ +export interface AntigravityChildLaunch { + readonly role: string; + readonly prompt: string; +} + +/** One child the session started, as its records describe it. */ +export interface AntigravityChild { + readonly conversationId: string; + /** + * The parent's `invoke_subagent` tool call (the ACP tool call id) that + * started it, when the records tie exactly this child to one call. + */ + readonly launchCallId: string | undefined; + readonly launch: AntigravityChildLaunch; + /** `reported`: its report is in the parent's inbox. */ + readonly state: "working" | "reported" | "killed"; + /** The report it sent the parent, bounded. */ + readonly report: string | undefined; +} + +const isRecord = (value: unknown): value is Record => + typeof value === "object" && value !== null && !Array.isArray(value); +const stringField = (value: unknown, key: string): string | undefined => + isRecord(value) && typeof value[key] === "string" ? value[key] : undefined; + +const parseJson = (text: string): unknown => { + try { + return JSON.parse(text); + } catch { + return undefined; + } +}; + +/** A launch's input: one subagent (`Role`, `Prompt`), or a batch (`Subagents`, before 1.5). */ +export function antigravityChildLaunches( + input: unknown, +): ReadonlyArray | undefined { + if (!isRecord(input)) return undefined; + const one = (entry: unknown): AntigravityChildLaunch | undefined => { + const role = stringField(entry, "Role"); + const prompt = stringField(entry, "Prompt"); + return role !== undefined && prompt !== undefined ? { role, prompt } : undefined; + }; + const single = one(input); + if (single !== undefined) return [single]; + if (!Array.isArray(input.Subagents) || input.Subagents.length === 0) return undefined; + const batch = input.Subagents.map(one); + return batch.every((entry) => entry !== undefined) ? batch : undefined; +} + +/** What one read of the records may still take, in bytes. */ +interface ReadBudget { + bytes: number; +} + +/** The bytes of a file held open, at most `maxBytes`; `undefined` past that. */ +async function readHeld( + handle: NodeFSP.FileHandle, + maxBytes: number, + from = 0, +): Promise { + // One byte past the cap: a file that grew since it was checked is refused. + const buffer = Buffer.alloc(maxBytes + 1); + let total = 0; + while (total < buffer.length) { + const { bytesRead } = await handle.read(buffer, total, buffer.length - total, from + total); + if (bytesRead === 0) break; + total += bytesRead; + } + return total > maxBytes ? undefined : buffer.subarray(0, total); +} + +/** + * A small JSON record of the CLI's, or `undefined` when it is missing, not + * the file at its place in the profile, too big, past the read's budget, or + * not JSON. Every byte read is charged to the budget. + */ +async function readRecord(profileDir: string, segments: ReadonlyArray, budget: ReadBudget) { + const file = await openAntigravityProfileFile(profileDir, segments); + if (typeof file === "string") return undefined; + try { + const maxBytes = Math.min(MAX_RECORD_BYTES, budget.bytes); + if (file.size > maxBytes) return undefined; + const bytes = await readHeld(file.handle, maxBytes); + if (bytes === undefined) return undefined; + budget.bytes -= bytes.length; + return parseJson(bytes.toString("utf8")); + } finally { + await file.handle.close(); + } +} + +/** + * A folder's file names, read one entry at a time: `undefined` past `limit` + * entries (of any kind), so a huge folder costs no more than the limit. + */ +async function listNames(path: string, limit: number): Promise | undefined> { + const dir = await NodeFSP.opendir(path, { bufferSize: 32 }).catch(() => undefined); + if (dir === undefined) return undefined; + const names: Array = []; + try { + for await (const entry of dir) { + if (names.length >= limit) return undefined; + names.push(entry.name); + } + } catch { + return undefined; + } + return names; +} + +const generated = (conversationId: string, ...rest: ReadonlyArray) => [ + "brain", + conversationId, + ".system_generated", + ...rest, +]; + +/** + * A conversation's inbox: the messages that read, and how many didn't (one + * the CLI is still writing reads as broken JSON). `undefined` when the inbox + * itself can't be listed, is a link or not a folder, or holds more than the + * limit. No inbox at all is an empty one. + */ +async function readInbox( + profileDir: string, + conversationId: string, + budget: ReadBudget, +): Promise<{ readonly messages: ReadonlyArray; readonly unreadable: number } | undefined> { + const segments = generated(conversationId, "messages"); + const inbox = await antigravityProfileEntry(profileDir, segments, "directory"); + // No inbox is an empty one; one that isn't what it should be is unread. + if (inbox === "missing") return { messages: [], unreadable: 0 }; + if (inbox === "refused") return undefined; + // `read.json` (read receipts) and the odd stray file count toward the limit too. + const names = await listNames(inbox.path, MAX_INBOX_MESSAGES + 1); + if (names === undefined) return undefined; + const messages: Array = []; + let unreadable = 0; + for (const name of names) { + if (!name.endsWith(".json") || name === "read.json") continue; + const message = await readRecord(profileDir, [...segments, name], budget); + if (isRecord(message)) messages.push(message); + else unreadable += 1; + } + return { messages, unreadable }; +} + +/** The parent's launching call in a child's inbox message, when it is one. */ +function launchCall(message: unknown, parentId: string) { + if (stringField(message, "sender") !== parentId) return undefined; + const tool = isRecord(message) ? message.sourceMetadata : undefined; + const source = isRecord(tool) ? tool.tool : undefined; + if (!isRecord(source)) return undefined; + const fromSession = stringField(source, "conversationId"); + if (fromSession !== undefined && fromSession !== parentId) return undefined; + const call = source.toolCall; + const id = stringField(call, "id"); + const name = stringField(call, "name"); + if (id === undefined || name === undefined || !LAUNCH_TOOLS.has(name)) return undefined; + const args = stringField(call, "argumentsJson"); + return { id, args: args === undefined ? undefined : parseJson(args) }; +} + +/** + * What a session's records say about its children. + * - `available: false, reason: "no-records"`: the session has no subagent + * records at all, so they can't tell "none started" from "not written". + * - `available: false, reason: "unreadable"`: some record is missing, a + * link, too big, not what the layout says, or the session id is not one + * the CLI would write. Nothing is proven then. + * - `available: true`: every child the session started, sorted by state. + * A child reported once its report is in the parent's inbox (it may + * still be answering a follow-up), and was killed when its entry says so. + * A child whose entry doesn't read is `running`, with nothing else known. + */ +export type AntigravityChildrenReading = + | { readonly available: false; readonly reason: "no-records" | "unreadable" } + | { + readonly available: true; + readonly running: ReadonlyArray; + readonly reported: ReadonlyArray; + readonly killed: ReadonlyArray; + /** + * Messages and entries that didn't read (one the CLI is still writing, + * say). A report among them leaves its child `running` until a later + * reading sees it; nothing is ever marked done for want of a record. + */ + readonly unreadable: number; + }; + +const UNREADABLE = { available: false, reason: "unreadable" } as const; + +/** Every child the session started, or why the records can't say. */ +async function readChildren( + profileDir: string, + parentId: string, +): Promise< + | { readonly children: ReadonlyArray; readonly unreadable: number } + | { readonly reason: "no-records" | "unreadable" } +> { + if (!NATIVE_ID.test(parentId)) return { reason: "unreadable" }; + const folder = await antigravityProfileEntry( + profileDir, + generated(parentId, "subagents"), + "directory", + ); + if (folder === "missing") return { reason: "no-records" }; + if (folder === "refused") return { reason: "unreadable" }; + const names = await listNames(folder.path, MAX_CHILDREN + 1); + if (names === undefined) return { reason: "unreadable" }; + const childIds = names.flatMap((name) => + name.endsWith(".json") && NATIVE_ID.test(name.slice(0, -5)) ? [name.slice(0, -5)] : [], + ); + const budget: ReadBudget = { bytes: MAX_READ_BYTES }; + const parentInbox = await readInbox(profileDir, parentId, budget); + if (parentInbox === undefined) return { reason: "unreadable" }; + let unreadable = parentInbox.unreadable; + const children: Array = []; + for (const childId of childIds) { + const record = await readRecord( + profileDir, + generated(parentId, "subagents", `${childId}.json`), + budget, + ); + const recordedId = stringField(record, "conversationId"); + const inbox = await readInbox(profileDir, childId, budget); + // An entry that doesn't read (or names another child) proves nothing: + // the child counts as running, tied to no launch. + if (!isRecord(record) || (recordedId !== undefined && recordedId !== childId) || !inbox) { + unreadable += 1; + children.push({ + conversationId: childId, + launchCallId: undefined, + launch: { role: "", prompt: "" }, + state: "working", + report: undefined, + }); + continue; + } + unreadable += inbox.unreadable; + const launches = inbox.messages.flatMap((message) => { + const call = launchCall(message, parentId); + return call === undefined ? [] : [{ call, content: stringField(message, "content") }]; + }); + // Two launches in one inbox can't both be this child's. + const launch = launches.length === 1 ? launches[0] : undefined; + const [fromArgs] = antigravityChildLaunches(launch?.call.args) ?? []; + const descriptor = record.subagentDescriptor; + const reports = parentInbox.messages.flatMap((message) => + stringField(message, "sender") === childId ? [stringField(message, "content") ?? ""] : [], + ); + children.push({ + conversationId: childId, + launchCallId: launch?.call.id, + launch: fromArgs ?? { + role: stringField(descriptor, "role") ?? "", + prompt: launch?.content ?? "", + }, + state: + reports.length > 0 + ? "reported" + : stringField(record, "state") === KILLED_STATE + ? "killed" + : "working", + report: reports.length > 0 ? boundAntigravityText(reports.join("\n\n").trim()) : undefined, + }); + } + // Two children claiming one call: neither is proven to be its child. + const claims = new Map(); + for (const child of children) { + if (child.launchCallId !== undefined) { + claims.set(child.launchCallId, (claims.get(child.launchCallId) ?? 0) + 1); + } + } + return { + unreadable, + children: children.map((child) => + child.launchCallId !== undefined && claims.get(child.launchCallId) !== 1 + ? { ...child, launchCallId: undefined } + : child, + ), + }; +} + +/** + * Which of a session's children are still running, which have reported and + * which were killed, each with the launching call that started it where the + * records tie it to one, or why the records can't say. Never fails. + */ +export const readAntigravityChildren = (profileDir: string, sessionId: string) => + Effect.tryPromise(async (): Promise => { + const read = await readChildren(profileDir, sessionId); + if ("reason" in read) return { available: false, reason: read.reason }; + const inState = (state: AntigravityChild["state"]) => + read.children.filter((child) => child.state === state); + return { + available: true, + running: inState("working"), + reported: inState("reported"), + killed: inState("killed"), + unreadable: read.unreadable, + }; + }).pipe(Effect.orElseSucceed((): AntigravityChildrenReading => UNREADABLE)); + +/** The child a launching call started, in a reading, when the records tie it to that call. */ +export function antigravityChildOf( + reading: AntigravityChildrenReading, + launchCallId: string, +): AntigravityChild | undefined { + if (!reading.available) return undefined; + return [...reading.running, ...reading.reported, ...reading.killed].find( + (child) => child.launchCallId === launchCallId, + ); +} + +// ── A child's steps ────────────────────────────────────────────────── + +interface TranscriptLine { + readonly index: number; + readonly type: string; + readonly status: string | undefined; + readonly content: string | undefined; + readonly error: string | undefined; + readonly toolCalls: ReadonlyArray<{ readonly name: string; readonly args: unknown }>; +} + +function parseTranscriptLine(line: string): TranscriptLine | undefined { + const value = parseJson(line); + if (!isRecord(value)) return undefined; + const index = value.step_index; + const type = stringField(value, "type"); + if (typeof index !== "number" || !Number.isInteger(index) || index < 0 || type === undefined) + return undefined; + const calls = Array.isArray(value.tool_calls) ? value.tool_calls : []; + return { + index, + type, + status: stringField(value, "status"), + content: stringField(value, "content"), + error: stringField(value, "error"), + toolCalls: calls.flatMap((call) => { + const name = stringField(call, "name"); + return name === undefined ? [] : [{ name, args: isRecord(call) ? call.args : undefined }]; + }), + }; +} + +/** Fields that say what a call works on, in the order worth showing. */ +const SUMMARY_FIELDS = [ + "CommandLine", + "AbsolutePath", + "TargetFile", + "Path", + "SearchPath", + "Query", + "Url", +]; + +/** A tool call's one-line summary. The CLI records each argument value as JSON text. */ +function toolSummary(args: unknown): string { + if (!isRecord(args)) return ""; + const values = Object.fromEntries( + Object.entries(args).map(([key, value]) => [ + key, + typeof value === "string" ? (parseJson(value) ?? value) : value, + ]), + ); + for (const field of SUMMARY_FIELDS) { + const value = values[field]; + if (typeof value === "string" && value.trim()) { + return boundAntigravityText(value.trim(), TOOL_SUMMARY_LIMIT); + } + } + return boundAntigravityText(JSON.stringify(values), TOOL_SUMMARY_LIMIT); +} + +/** A child's steps as transcript entries, its launch prompt first as its instruction. */ +export function antigravityTranscriptEntries( + lines: ReadonlyArray, + prompt: string, +): ReadonlyArray { + const launchPrompt = prompt.trim(); + const entries: Array = launchPrompt + ? [{ id: "launch", role: "user", text: launchPrompt, toolUses: [] }] + : []; + for (const line of lines) { + const id = `step-${line.index}`; + const text = boundAntigravityText((line.content ?? line.error ?? "").trim(), STEP_TEXT_LIMIT); + if (line.type === "PLANNER_RESPONSE") { + entries.push({ + id, + role: "assistant", + text: line.content ? text : "", + toolUses: line.toolCalls.map((call) => ({ + name: call.name, + summary: toolSummary(call.args), + })), + }); + continue; + } + if (line.type === "SYSTEM_MESSAGE" || line.type === "USER_INPUT") { + // The opening envelope around the launch prompt already shown above. + if (line.index === 0 && launchPrompt && line.content?.includes(launchPrompt)) continue; + if (text) entries.push({ id, role: "user", text, toolUses: [] }); + continue; + } + // A tool's result (`VIEW_FILE`, `RUN_COMMAND`, `GENERIC`, ...). + if (!text) continue; + entries.push({ + id, + role: "system", + text: "", + toolUses: [], + outputPreview: text, + ...(line.error !== undefined || line.status === "ERROR" ? { outputIsError: true } : {}), + }); + } + return entries; +} + +/** The end of a child's transcript, parsed; `undefined` when it has none. */ +async function readTranscriptTail(profileDir: string, childId: string) { + const file = await openAntigravityProfileFile( + profileDir, + generated(childId, "logs", "transcript.jsonl"), + ); + if (typeof file === "string") return undefined; + const { handle, size } = file; + try { + const start = Math.max(0, size - TRANSCRIPT_TAIL_BYTES); + // One byte more says whether the window starts on a line boundary. + const readFrom = Math.max(0, start - 1); + // A bounded window; a file still growing is read as far as it was checked. + const buffer = Buffer.alloc(size - readFrom); + const { bytesRead } = await handle.read(buffer, 0, buffer.length, readFrom); + const bytes = buffer.subarray(0, bytesRead); + const firstLine = start > 0 ? bytes.indexOf(0x0a) + 1 : 0; + if (start > 0 && firstLine === 0) return { lines: [], truncated: true }; + const lines = bytes + .toString("utf8", firstLine) + .split("\n") + .flatMap((line) => { + const parsed = parseTranscriptLine(line); + return parsed === undefined ? [] : [parsed]; + }); + return { lines, truncated: start > 0 }; + } finally { + await handle.close(); + } +} + +/** + * The child a launching call started and its recent steps, or `undefined` + * when the records don't name exactly one child for it. + */ +export const antigravityChildTranscript = ( + profileDir: string, + parentId: string, + launchCallId: string, +) => + Effect.tryPromise(async () => { + const read = await readChildren(profileDir, parentId); + const child = + "reason" in read + ? undefined + : read.children.find((candidate) => candidate.launchCallId === launchCallId); + if (child === undefined) return undefined; + const transcript = await readTranscriptTail(profileDir, child.conversationId).catch( + () => undefined, + ); + return { + child, + entries: antigravityTranscriptEntries(transcript?.lines ?? [], child.launch.prompt), + truncated: transcript?.truncated ?? false, + }; + }).pipe(Effect.orElseSucceed(() => undefined)); diff --git a/apps/server/src/provider/antigravity/AntigravityFileReads.ts b/apps/server/src/provider/antigravity/AntigravityFileReads.ts new file mode 100644 index 000000000..f62a38e83 --- /dev/null +++ b/apps/server/src/provider/antigravity/AntigravityFileReads.ts @@ -0,0 +1,64 @@ +/** + * Reads of files Threadlines doesn't control (the user's `~/.gemini`, a + * project's skills, the agent's profile) that can never hang or balloon. + * + * The open never blocks: a FIFO or device opens at once and is then refused + * because only a regular file is read, judged from the open handle, so a + * path swapped after a check can't slip anything else in. Reads stop at a + * byte cap. + * + * @module provider/antigravity/AntigravityFileReads + */ +import { constants } from "node:fs"; +import * as fs from "node:fs/promises"; + +const OPEN_FOLLOW = constants.O_RDONLY | (constants.O_NONBLOCK ?? 0); +const OPEN_NO_FOLLOW = OPEN_FOLLOW | (constants.O_NOFOLLOW ?? 0); + +export interface OpenedRegularFile { + readonly handle: fs.FileHandle; + readonly size: number; +} + +/** + * Opens `path` when it is a regular file; undefined for anything else, a + * missing file, or (with `followLink: false`) a link at the last step. + */ +export async function openRegularFile( + path: string, + options: { readonly followLink: boolean }, +): Promise { + const handle = await fs + .open(path, options.followLink ? OPEN_FOLLOW : OPEN_NO_FOLLOW) + .catch(() => undefined); + if (!handle) return undefined; + const stat = await handle.stat().catch(() => undefined); + if (!stat?.isFile()) { + await handle.close(); + return undefined; + } + return { handle, size: stat.size }; +} + +/** The bytes of a regular file of at most `maxBytes`; undefined otherwise. */ +export async function readRegularFile( + path: string, + options: { readonly maxBytes: number; readonly followLink: boolean }, +): Promise { + const opened = await openRegularFile(path, options); + if (!opened) return undefined; + try { + if (opened.size > options.maxBytes) return undefined; + // Read one byte past the cap: a file that grew since `stat` is refused too. + const buffer = Buffer.alloc(options.maxBytes + 1); + let total = 0; + while (total < buffer.length) { + const { bytesRead } = await opened.handle.read(buffer, total, buffer.length - total, total); + if (bytesRead === 0) break; + total += bytesRead; + } + return total > options.maxBytes ? undefined : buffer.subarray(0, total); + } finally { + await opened.handle.close(); + } +} diff --git a/apps/server/src/provider/antigravity/AntigravityProfile.ts b/apps/server/src/provider/antigravity/AntigravityProfile.ts index 0a014a3a9..0f22e2523 100644 --- a/apps/server/src/provider/antigravity/AntigravityProfile.ts +++ b/apps/server/src/provider/antigravity/AntigravityProfile.ts @@ -2,24 +2,25 @@ * AntigravityProfile — where one Antigravity provider instance keeps its * state, and the environment its agent processes run with. * - * Each instance gets its own `GEMINI_HOME` (credentials, conversations, - * settings) under Threadlines' state dir, isolated from the user's own - * `~/.gemini`, and a temp root its processes unpack into. Antigravity's - * Windows build is a PyInstaller one-file exe that unpacks ~1 GB per launch - * into `TEMP` and can leave it behind; every process therefore gets a private - * `run-*` dir that is removed when the process ends, and the instance's temp - * root is swept on start for dirs whose owner is gone. + * Each instance gets its own profile (`agy acp --gemini-dir`: sign-in, + * conversations, settings) under Threadlines' state dir, isolated from the + * user's own `~/.gemini`, and a temp root its processes unpack into. Every + * process gets a private `run-*` dir that is removed when the process ends, + * and the instance's temp root is swept on start for dirs whose owner is + * gone. * * @module provider/antigravity/AntigravityProfile */ import { createHash, randomBytes } from "node:crypto"; import * as fs from "node:fs/promises"; -import { join } from "node:path"; +import { join, resolve } from "node:path"; import { resolveCommandPath } from "@threadlines/shared/shell"; import * as Effect from "effect/Effect"; import type * as Scope from "effect/Scope"; import { ProviderSetupError } from "../Errors.ts"; +import { ANTIGRAVITY_APP_DATA_DIR } from "./AntigravityRelease.ts"; +import { shareAntigravityUserConfig } from "./AntigravityUserConfig.ts"; export interface AntigravityInstancePaths { /** `GEMINI_HOME` for this instance. */ @@ -42,17 +43,36 @@ export function antigravityInstancePaths( }; } +/** The Threadlines data folder a profile from `antigravityInstancePaths` sits in. */ +export const antigravityStateDirOf = (profileDir: string) => resolve(profileDir, "..", "..", ".."); + /** The agent's own state dir inside the profile. */ -export const antigravityAgentDir = (profileDir: string) => join(profileDir, "antigravity-acp"); +export const antigravityAgentDir = (profileDir: string) => + join(profileDir, ANTIGRAVITY_APP_DATA_DIR); -/** Written by the agent after a successful Google sign-in (file storage). */ +/** + * Where the CLI keeps a Google sign-in when it uses file storage (see + * `antigravityEnvironment`): `{ token: { access_token, refresh_token, expiry } }`. + */ export const antigravityTokenPath = (profileDir: string) => + join(antigravityAgentDir(profileDir), "antigravity-oauth-token"); + +/** Where Google's old ACP server kept its sign-in. The CLI doesn't read it. */ +export const antigravityLegacyTokenPath = (profileDir: string) => join(antigravityAgentDir(profileDir), "acp_token.json"); /** Credentials and project settings that would steer the agent away from this profile. */ const STRIPPED_ENV_KEY = /^(GEMINI_|GOOGLE_|GCLOUD_|CLOUDSDK_|AGY_|ANTIGRAVITY_)|^(BROWSER|PYTHONUNBUFFERED|PYTHONHOME|PYTHONPATH)$/iu; +/** + * What the CLI takes for a session over SSH. It then keeps a Google sign-in + * in the profile's own file instead of the one OS keyring entry every + * profile (and the user's own terminal `agy`) shares, and signs in with + * `agy acp --login`, which prints a link and reads back a code. + */ +const SSH_CONNECTION_STAND_IN = "127.0.0.1 0 127.0.0.1 0"; + /** * A `BROWSER` that opens nothing: the agent prints its sign-in URL, and the * Threadlines client (which may be another machine) opens it. Python splits @@ -65,10 +85,10 @@ function noopBrowser(platform: NodeJS.Platform, env: NodeJS.ProcessEnv): string /** * The complete environment for an Antigravity process: the server's own, - * minus ambient Google credentials and Python settings, plus the sign-in - * method's own credentials (`AntigravitySignInMethod`), the profile, - * file-based credential storage (no shared OS keychain entry) and the - * process's temp dir. + * minus ambient Google credentials, plus the sign-in method's own + * credentials (`AntigravitySignInMethod`), the profile, file-based sign-in + * storage (no shared OS keyring entry), no self-update, and the process's + * temp dir. */ export function antigravityEnvironment(input: { readonly base: NodeJS.ProcessEnv; @@ -84,7 +104,8 @@ export function antigravityEnvironment(input: { Object.assign(env, input.credentials); env.GEMINI_HOME = input.profileDir; env.AGY_ACP_FORCE_FILE_STORAGE = "1"; - env.PYTHONUNBUFFERED = "1"; + env.AGY_CLI_DISABLE_AUTO_UPDATE = "1"; + env.SSH_CONNECTION = input.base.SSH_CONNECTION?.trim() || SSH_CONNECTION_STAND_IN; env.BROWSER = noopBrowser(input.platform, input.base); if (input.platform === "win32") { env.TEMP = input.tempDir; @@ -188,44 +209,106 @@ export const sweepAntigravityTempRoot = (tempRoot: string) => } }); -/** - * Whether the profile holds a Google sign-in: a token file with something in - * it (an interrupted write leaves an empty or cut-off one). - */ -export const hasAntigravityCredentials = (profileDir: string) => - Effect.promise(async () => { - const raw = await fs.readFile(antigravityTokenPath(profileDir), "utf8").catch(() => ""); - try { - const parsed = JSON.parse(raw) as unknown; - return typeof parsed === "object" && parsed !== null && Object.keys(parsed).length > 0; - } catch { - return false; - } - }); +/** Whether a file holds a JSON object with something in it (an interrupted write leaves less). */ +const holdsJsonObject = async (path: string) => { + const raw = await fs.readFile(path, "utf8").catch(() => ""); + try { + const parsed = JSON.parse(raw) as unknown; + return typeof parsed === "object" && parsed !== null && Object.keys(parsed).length > 0; + } catch { + return false; + } +}; + +/** What the profile holds of a Google sign-in: the CLI's, the old server's, or neither. */ +export const readAntigravitySavedSignIn = (profileDir: string) => + Effect.promise(async () => ({ + cli: await holdsJsonObject(antigravityTokenPath(profileDir)), + legacy: await holdsJsonObject(antigravityLegacyTokenPath(profileDir)), + })); export interface AntigravityModelChoice { readonly value: string; readonly name: string; } +/** A model's reasoning levels, as the session's `thought_level` option lists them. */ +export interface AntigravityThoughtLevels { + /** The session option's id, which a selection is sent back to. */ + readonly configId: string; + readonly name: string; + readonly options: ReadonlyArray; + readonly currentValue?: string; +} + export interface AntigravityCatalogCache { readonly choices: ReadonlyArray; readonly currentValue?: string; + /** + * Each model's reasoning levels, by model id, as seen when it was the + * session's model (the agent lists them for that model only); null when + * it had none. Models not seen yet are missing. + */ + readonly thoughtLevels?: Readonly>; /** The sign-in it was listed for (`antigravityCredentialFingerprint`). */ readonly fingerprint?: string; + /** The managed runtime version that listed it; absent for a custom binary. */ + readonly agentVersion?: string; } const catalogPath = (profileDir: string) => join(profileDir, "threadlines-models.json"); +const modelChoicesOf = (raw: unknown): ReadonlyArray => + Array.isArray(raw) + ? raw.filter( + (choice): choice is AntigravityModelChoice => + typeof choice?.value === "string" && typeof choice?.name === "string", + ) + : []; + +/** The saved reasoning levels of listed models; anything malformed is left out. */ +function thoughtLevelsOf( + raw: unknown, + choices: ReadonlyArray, +): Record | undefined { + if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return undefined; + const levels: Record = {}; + for (const choice of choices) { + const entry = (raw as Record)[choice.value]; + if (entry === null) { + levels[choice.value] = null; + continue; + } + if (typeof entry !== "object" || entry === undefined) continue; + const { configId, name, options, currentValue } = entry as Partial; + const parsedOptions = modelChoicesOf(options); + if (typeof configId !== "string" || typeof name !== "string" || parsedOptions.length === 0) { + continue; + } + levels[choice.value] = { + configId, + name, + options: parsedOptions, + ...(typeof currentValue === "string" ? { currentValue } : {}), + }; + } + return Object.keys(levels).length > 0 ? levels : undefined; +} + /** * The model list from the last session, so status checks need not start the * agent. A list from another sign-in (method, project or key) doesn't count: * what a sign-in may use differs. Lists saved before sign-in methods existed - * count for a Google account. + * count for a Google account. A list from another agent version doesn't count + * either: each release names its own models, so an update lists them afresh. */ export const readAntigravityCatalog = ( profileDir: string, - sign: { readonly fingerprint: string; readonly isGoogleAccount: boolean }, + sign: { + readonly fingerprint: string; + readonly isGoogleAccount: boolean; + readonly agentVersion: string | undefined; + }, ) => Effect.promise(async (): Promise => { const raw = await fs.readFile(catalogPath(profileDir), "utf8").catch(() => undefined); @@ -236,20 +319,18 @@ export const readAntigravityCatalog = ( parsed.fingerprint === undefined ? sign.isGoogleAccount : parsed.fingerprint === sign.fingerprint; - if (!matches) return undefined; - const choices = Array.isArray(parsed.choices) - ? parsed.choices.filter( - (choice): choice is AntigravityModelChoice => - typeof choice?.value === "string" && typeof choice?.name === "string", - ) - : []; + if (!matches || parsed.agentVersion !== sign.agentVersion) return undefined; + const choices = modelChoicesOf(parsed.choices); + const thoughtLevels = thoughtLevelsOf(parsed.thoughtLevels, choices); return choices.length > 0 ? { choices, ...(typeof parsed.currentValue === "string" ? { currentValue: parsed.currentValue } : {}), + ...(thoughtLevels ? { thoughtLevels } : {}), fingerprint: sign.fingerprint, + ...(sign.agentVersion ? { agentVersion: sign.agentVersion } : {}), } : undefined; } catch { @@ -266,8 +347,55 @@ export const writeAntigravityCatalog = (profileDir: string, catalog: Antigravity await fs.rename(temp, target); }).pipe(Effect.ignore); -/** Creates the profile dirs the agent expects, private to the user. */ -export const prepareAntigravityProfile = (profileDir: string) => +/** + * Creates the profile dirs the agent expects, private to the user, and + * brings in the user's own global rules and skills from `~/.gemini` + * (`AntigravityUserConfig`). Runs before every agent start. + */ +export const prepareAntigravityProfile = ( + profileDir: string, + user: { readonly userHome: string; readonly platform: NodeJS.Platform }, +) => Effect.promise(() => fs.mkdir(antigravityAgentDir(profileDir), { recursive: true, mode: 0o700 }), - ).pipe(Effect.asVoid); + ).pipe( + Effect.andThen( + shareAntigravityUserConfig({ + profileDir, + userHome: user.userHome, + platform: user.platform, + threadlinesDir: antigravityStateDirOf(profileDir), + }), + ), + ); + +const agentRefusalPath = (profileDir: string) => join(profileDir, "threadlines-agent-check.json"); + +/** + * Records why a custom `agy` was refused (or that it wasn't), for the status + * to show without starting it again. `tag` names the file as it was then. + */ +export const writeAntigravityAgentRefusal = ( + profileDir: string, + check: { readonly tag: string; readonly problem: string | undefined }, +) => + Effect.tryPromise(async () => { + await fs.mkdir(profileDir, { recursive: true, mode: 0o700 }); + const target = agentRefusalPath(profileDir); + const temp = `${target}.${randomBytes(4).toString("hex")}.tmp`; + await fs.writeFile(temp, JSON.stringify(check)); + await fs.rename(temp, target); + }).pipe(Effect.ignore); + +/** Why the custom `agy` `tag` names was refused, if it was. */ +export const readAntigravityAgentRefusal = (profileDir: string, tag: string) => + Effect.promise(async () => { + const raw = await fs.readFile(agentRefusalPath(profileDir), "utf8").catch(() => undefined); + try { + const parsed = + raw === undefined ? undefined : (JSON.parse(raw) as { tag?: unknown; problem?: unknown }); + return parsed?.tag === tag && typeof parsed.problem === "string" ? parsed.problem : undefined; + } catch { + return undefined; + } + }); diff --git a/apps/server/src/provider/antigravity/AntigravityRelease.ts b/apps/server/src/provider/antigravity/AntigravityRelease.ts index 6251cf74b..e2fa69f34 100644 --- a/apps/server/src/provider/antigravity/AntigravityRelease.ts +++ b/apps/server/src/provider/antigravity/AntigravityRelease.ts @@ -1,37 +1,53 @@ /** - * AntigravityRelease — the pinned Antigravity ACP server release Threadlines - * installs, one zip per platform. + * AntigravityRelease — which build of Google's Antigravity CLI (`agy`) + * Threadlines installs, and how it launches it as an ACP agent (`agy acp`). * - * Each zip holds exactly two files: the ACP server and the local harness it - * starts. The sizes and hashes below were taken from the published archives; - * the runtime refuses anything that differs. + * Google publishes one build per platform through the CLI's own update feed + * (`antigravityFeedUrl`): a manifest naming the version, the download and + * its sha512. Unix builds are a tar.gz holding one executable, `antigravity`; + * Windows builds are the bare `.exe`. The built-in release below is what + * installs when the feed can't be read, and the oldest version offered; its + * sizes were measured from Google's downloads. A newer one the feed lists is + * offered as an update (`parseAntigravityFeedManifest`), checked by its + * sha512 and capped in size, since the feed lists no sizes. + * + * This module has no runtime imports: `scripts/check-upstream-drift.ts` + * loads it with plain Node. * * @module provider/antigravity/AntigravityRelease */ +/** + * The oldest `agy` Threadlines starts sessions with, managed or custom. + * From Google's changelog: 1.5.10 delivers what the agent does after a turn + * ends (a background task or subagent waking it), 1.5.13 honors attached + * file contents and runs commands in the session's folder, and 1.5.14 + * stops a network path in a file mention or rule from sending Windows + * credentials to a remote host. + */ +export const ANTIGRAVITY_MIN_VERSION = "1.5.14"; + export type AntigravityAssetKey = | "darwin-arm64" | "darwin-x64" | "linux-arm64" | "linux-x64" + | "linux-arm64-musl" + | "linux-x64-musl" | "win32-arm64" | "win32-x64"; -export interface AntigravityReleaseFile { - /** Entry name in the zip and file name on disk. */ - readonly name: string; - readonly bytes: number; -} +export type AntigravityArchiveFormat = "tar.gz" | "exe"; export interface AntigravityReleaseAsset { readonly url: string; - /** Lowercase hex sha256 of the zip. */ - readonly sha256: string; - readonly archiveBytes: number; - /** The ACP server Threadlines launches. */ - readonly executable: AntigravityReleaseFile; - /** The local harness the ACP server starts. */ - readonly harness: AntigravityReleaseFile; + /** Lowercase hex sha512 of the download. */ + readonly sha512: string; + readonly format: AntigravityArchiveFormat; + /** Exact download size when known (the built-in release); otherwise capped. */ + readonly archiveBytes?: number; + /** The executable's file name on disk, and its exact size when known. */ + readonly executable: { readonly name: string; readonly bytes?: number }; } export interface AntigravityRelease { @@ -39,76 +55,186 @@ export interface AntigravityRelease { readonly assets: Readonly>; } -/** One platform's pinned download, as `makeAntigravityRuntime` installs it. */ +/** One platform's download, as `makeAntigravityRuntime` installs it. */ export interface AntigravityPlatformRelease { readonly version: string; readonly asset: AntigravityReleaseAsset; } -const POSIX_FILES = (executableBytes: number, harnessBytes: number) => ({ - executable: { name: "agy_acp_server.par", bytes: executableBytes }, - harness: { name: "localharness_external", bytes: harnessBytes }, -}); +/** The only host Antigravity is downloaded from. */ +export const ANTIGRAVITY_DOWNLOAD_HOST = "storage.googleapis.com"; +const DOWNLOAD_ROOT = `https://${ANTIGRAVITY_DOWNLOAD_HOST}/antigravity-public/antigravity-cli`; + +/** The host of Google's update feed for the CLI. */ +export const ANTIGRAVITY_FEED_HOST = + "antigravity-cli-auto-updater-974169037036.us-central1.run.app"; + +/** + * Per build: the feed's manifest name, Google's download folder, and the + * download's file name. + */ +const BUILDS: Readonly< + Record< + AntigravityAssetKey, + { readonly feed: string; readonly folder: string; readonly file: string } + > +> = { + "darwin-arm64": { feed: "darwin_arm64", folder: "darwin-arm", file: "cli_mac_arm64.tar.gz" }, + "darwin-x64": { feed: "darwin_amd64", folder: "darwin-x64", file: "cli_mac_x64.tar.gz" }, + "linux-arm64": { feed: "linux_arm64", folder: "linux-arm", file: "cli_linux_arm64.tar.gz" }, + "linux-x64": { feed: "linux_amd64", folder: "linux-x64", file: "cli_linux_x64.tar.gz" }, + "linux-arm64-musl": { + feed: "linux_arm64_musl", + folder: "linux-arm-musl", + file: "cli_linux_arm64_musl.tar.gz", + }, + "linux-x64-musl": { + feed: "linux_amd64_musl", + folder: "linux-x64-musl", + file: "cli_linux_x64_musl.tar.gz", + }, + "win32-arm64": { feed: "windows_arm64", folder: "windows-arm", file: "cli_windows_arm64.exe" }, + "win32-x64": { feed: "windows_amd64", folder: "windows-x64", file: "cli_windows_x64.exe" }, +}; + +/** Where Google's update feed describes the newest build for this asset. */ +export function antigravityFeedUrl(assetKey: AntigravityAssetKey): string { + return `https://${ANTIGRAVITY_FEED_HOST}/manifests/${BUILDS[assetKey].feed}.json`; +} + +const isWindowsKey = (assetKey: AntigravityAssetKey) => assetKey.startsWith("win32-"); + +/** The executable's name: the tarball's one entry, or `agy.exe` for the Windows download. */ +export const antigravityExecutableName = (assetKey: AntigravityAssetKey) => + isWindowsKey(assetKey) ? "agy.exe" : "antigravity"; + +const BUILD_NUMBER = /^\d{1,24}$/u; + +/** Whether `url` is Google's download of `version` for this build (any build number). */ +export function isAntigravityDownloadUrl( + url: string, + version: string, + assetKey: AntigravityAssetKey, +): boolean { + const prefix = `${DOWNLOAD_ROOT}/${version}-`; + if (!url.startsWith(prefix)) return false; + const [build, folder, file, ...rest] = url.slice(prefix.length).split("/"); + const { folder: wantFolder, file: wantFile } = BUILDS[assetKey]; + return ( + rest.length === 0 && + build !== undefined && + BUILD_NUMBER.test(build) && + folder === wantFolder && + file === wantFile + ); +} -const WINDOWS_FILES = (executableBytes: number, harnessBytes: number) => ({ - executable: { name: "agy_acp_server.exe", bytes: executableBytes }, - harness: { name: "localharness_external.exe", bytes: harnessBytes }, -}); +const asset = ( + assetKey: AntigravityAssetKey, + build: string, + sha512: string, + archiveBytes: number, + executableBytes: number | undefined, +): AntigravityReleaseAsset => { + const { folder, file } = BUILDS[assetKey]; + const windows = isWindowsKey(assetKey); + return { + url: `${DOWNLOAD_ROOT}/${build}/${folder}/${file}`, + sha512, + format: windows ? "exe" : "tar.gz", + archiveBytes, + // The Windows download is the executable itself. + executable: { + name: antigravityExecutableName(assetKey), + ...((windows ? archiveBytes : executableBytes) !== undefined + ? { bytes: windows ? archiveBytes : executableBytes! } + : {}), + }, + }; +}; -const RELEASES_URL = "https://dl.google.com/agy-extensions/releases"; +const BUILD_1_5_14 = "1.5.14-5302690847260672"; -/** Registry entry `antigravity-acp` 1.3.0. */ +/** + * Google's 1.5.14 builds, from the update feed on 2026-11-23. Sizes were + * measured from the downloads, which matched the feed's sha512. + */ export const ANTIGRAVITY_RELEASE: AntigravityRelease = { - version: "1.3.0", + version: "1.5.14", assets: { - "darwin-arm64": { - url: `${RELEASES_URL}/macos/agy-acp-server-1.3.0-darwin-arm64.zip`, - sha256: "7cd97045f7b4fe81175a107cdf16f9c51484e3c78a5162cae415338bb6aa5b88", - archiveBytes: 111_456_962, - ...POSIX_FILES(278_535_456, 118_611_392), - }, - "darwin-x64": { - url: `${RELEASES_URL}/macos/agy-acp-server-1.3.0-darwin-x86_64.zip`, - sha256: "bb23956b89984bf5d354af2c3725e6c57f0cc1b7228e77a0e91c9c2bc1d47646", - archiveBytes: 117_245_544, - ...POSIX_FILES(282_840_688, 124_175_392), - }, - "linux-arm64": { - url: `${RELEASES_URL}/linux/agy-acp-server-1.3.0-linux-arm64.zip`, - sha256: "500b0bc0fb858e88f4df404d4cedf80bf9298c178291e39e383d6c50b111cbdf", - archiveBytes: 321_690_363, - ...POSIX_FILES(930_848_992, 123_224_968), - }, - "linux-x64": { - url: `${RELEASES_URL}/linux/agy-acp-server-1.3.0-linux-x86_64.zip`, - sha256: "9fb60956af0a9d76220a4db91ca9ac88e2a2372ad68f985ab5fceace6b825b96", - archiveBytes: 333_727_150, - ...POSIX_FILES(926_533_965, 130_388_040), - }, - "win32-arm64": { - url: `${RELEASES_URL}/windows/agy-acp-server-1.3.0-windows-arm64.zip`, - sha256: "4a0f469720e9beb9438a979f543fdbfad5022ebe0992c052c590bd78b3144ca3", - archiveBytes: 124_654_803, - ...WINDOWS_FILES(85_893_472, 135_640_216), - }, - "win32-x64": { - url: `${RELEASES_URL}/windows/agy-acp-server-1.3.0-windows-x86_64.zip`, - sha256: "65215e0688681fa3116e048a9eab27ef53af1bbd6f3da3f1c52bd4911d8b17f9", - archiveBytes: 124_509_787, - ...WINDOWS_FILES(81_437_336, 145_548_952), - }, + "darwin-arm64": asset( + "darwin-arm64", + BUILD_1_5_14, + "26830fd46bfb9200d073cf3e71bf94b707552557b4380ec01afd6e99f3a2b030e65422dab1867f77318078692defc859a7547d17ec4b0b1e9369f13c9c3caea6", + 85_943_943, + 229_152_672, + ), + "darwin-x64": asset( + "darwin-x64", + BUILD_1_5_14, + "1b6a1fc6dbe46ba6d9d0405d1b6095189f35ebfc4c3c33ceb1fd1b6d0c9fd702b52ac10b64b8b52aed0d8d71ae02c5df3cffd5e3e3d37549c2daffcce2a853c7", + 91_613_810, + 238_884_352, + ), + "linux-arm64": asset( + "linux-arm64", + BUILD_1_5_14, + "c9b29bba475f63a1a80161ae93ba72b221c7a586d9851e4d0061546704bab66d6b2760b25d716d191724fc7564f3246456ee151e28aa37af48dbcd72bdc6c463", + 92_116_379, + 256_070_320, + ), + "linux-x64": asset( + "linux-x64", + BUILD_1_5_14, + "83311d3f354567612dc16c1ae2ea9b503d6f6833aa4e138d39aa229da3f3bb99b0e4d7cca0bce4796b0060d6a51d8113eb7449ed5dc0e7900bf217107ea5bff9", + 101_195_950, + 273_240_776, + ), + "linux-arm64-musl": asset( + "linux-arm64-musl", + BUILD_1_5_14, + "f6e35fc3dab2cd49fd4296ddee0841b9cc4c7020b6c6aaea6452c5b3452b0ad8d66451c9098e418ad6b2f6eabcc81cdf13105ed043903248b11d6fb24ae709ab", + 87_901_519, + 231_767_616, + ), + "linux-x64-musl": asset( + "linux-x64-musl", + BUILD_1_5_14, + "1da24922727c5b4e84369d0843575d7d6f180a1946e2dc4289171ad1e3ca92594e687724d1902a7d83e407f98f0a8d3b7c3e976f03680fd80dbed2d2da00c0ed", + 93_553_347, + 244_676_552, + ), + "win32-arm64": asset( + "win32-arm64", + BUILD_1_5_14, + "b2ce5462cf1845b25c05ca651b5bd93735fd807f8e7b40c61d0e99445df1a76b97ee24c890d5f5ba0453f848ca174f74d492ad1901a2ddcba5d7a9b4399ddfef", + 226_082_456, + undefined, + ), + "win32-x64": asset( + "win32-x64", + BUILD_1_5_14, + "785548b23242ec9112759bb4b525d94a3d4d2e9868e5cedb9ea34e5ce01dbb00abf5de66c41d8f4903e8a4379445f685483f999ece91867bfbd9d4812760d835", + 238_615_704, + undefined, + ), }, }; -/** The asset key for a Node platform and `process.arch`, or undefined when there is no build. */ +/** + * The asset key for a Node platform, `process.arch` and C library, or + * undefined when Google publishes no build for it. + */ export function antigravityAssetKey( platform: NodeJS.Platform, arch: string, + libc: "glibc" | "musl" = "glibc", ): AntigravityAssetKey | undefined { if (arch !== "arm64" && arch !== "x64") return undefined; switch (platform) { - case "darwin": case "linux": + return libc === "musl" ? `linux-${arch}-musl` : `linux-${arch}`; + case "darwin": case "win32": return `${platform}-${arch}`; default: @@ -116,12 +242,13 @@ export function antigravityAssetKey( } } -/** The pinned release for this machine, or undefined when there is no build for it. */ +/** The built-in release for this machine, or undefined when there is no build for it. */ export function antigravityReleaseFor( platform: NodeJS.Platform, arch: string, + libc: "glibc" | "musl" = "glibc", ): (AntigravityPlatformRelease & { readonly assetKey: AntigravityAssetKey }) | undefined { - const assetKey = antigravityAssetKey(platform, arch); + const assetKey = antigravityAssetKey(platform, arch, libc); if (!assetKey) return undefined; return { assetKey, @@ -131,14 +258,60 @@ export function antigravityReleaseFor( } /** - * Short, path-safe id for an asset: the first 16 hex digits of its sha256. + * Short, path-safe id for an asset: the first 16 hex digits of its sha512. * Names the version directory, so it stays short for Windows MAX_PATH. */ -export function antigravityReleaseId(asset: Pick): string { - return asset.sha256.slice(0, 16).toLowerCase(); +export function antigravityReleaseId(asset: Pick): string { + return asset.sha512.slice(0, 16).toLowerCase(); +} + +/** The agent's state folder inside the profile, as `--app-data-dir` names it. */ +export const ANTIGRAVITY_APP_DATA_DIR = "antigravity-acp"; + +/** + * `agy acp` for one instance's profile. The CLI joins `--app-data-dir` + * beneath `--gemini-dir`, so a bare name keeps the agent's state there. + */ +export function antigravityLaunchArgs(profileDir: string): ReadonlyArray { + return ["acp", "--gemini-dir", profileDir, "--app-data-dir", ANTIGRAVITY_APP_DATA_DIR]; } -/** Arguments the ACP server is launched with. Linux builds take an empty `--uid=`. */ -export function antigravityLaunchArgs(platform: NodeJS.Platform): ReadonlyArray { - return platform === "linux" ? ["--uid="] : []; +const PLAIN_VERSION = /^\d{1,4}\.\d{1,4}\.\d{1,6}$/u; +const SHA512_HEX = /^[0-9a-fA-F]{128}$/u; + +const isRecord = (value: unknown): value is Record => + typeof value === "object" && value !== null && !Array.isArray(value); + +/** + * A feed manifest (`{ version, url, sha512 }`) as a release Threadlines can + * install for this build, or undefined when it isn't one: a plain version, + * a sha512, and a download in Google's own folder for that version and + * build, under the name Google uses. Anything else waits for a Threadlines + * release that knows it. Sizes stay unknown: the install caps them. + */ +export function parseAntigravityFeedManifest( + manifest: unknown, + assetKey: AntigravityAssetKey, +): AntigravityPlatformRelease | undefined { + if (!isRecord(manifest)) return undefined; + const { version, url, sha512 } = manifest; + if ( + typeof version !== "string" || + typeof url !== "string" || + typeof sha512 !== "string" || + !PLAIN_VERSION.test(version) || + !SHA512_HEX.test(sha512) || + !isAntigravityDownloadUrl(url, version, assetKey) + ) { + return undefined; + } + return { + version, + asset: { + url, + sha512: sha512.toLowerCase(), + format: isWindowsKey(assetKey) ? "exe" : "tar.gz", + executable: { name: antigravityExecutableName(assetKey) }, + }, + }; } diff --git a/apps/server/src/provider/antigravity/AntigravityReleaseSource.ts b/apps/server/src/provider/antigravity/AntigravityReleaseSource.ts new file mode 100644 index 000000000..054340d55 --- /dev/null +++ b/apps/server/src/provider/antigravity/AntigravityReleaseSource.ts @@ -0,0 +1,134 @@ +/** + * AntigravityReleaseSource — which Antigravity release Threadlines offers. + * + * Google's CLI update feed names the newest build for each platform. When it + * is newer than the built-in release and fits what Threadlines knows how to + * install (`parseAntigravityFeedManifest`), it is offered, so a new version + * (and the models it brings) reaches users without waiting for a Threadlines + * release. Otherwise, and whenever the feed can't be read, the built-in + * release is offered. Nothing installs on its own: the offer becomes the + * Install or Update button. + * + * @module provider/antigravity/AntigravityReleaseSource + */ +import { compareSemverVersions } from "@threadlines/shared/semver"; +import * as Clock from "effect/Clock"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; + +import { makeHttpsFetch } from "../managedRuntime/HttpsFetch.ts"; +import type { DownloadFetch } from "../managedRuntime/VerifiedDownload.ts"; +import { + ANTIGRAVITY_FEED_HOST, + type AntigravityAssetKey, + type AntigravityPlatformRelease, + antigravityFeedUrl, + parseAntigravityFeedManifest, +} from "./AntigravityRelease.ts"; + +export interface AntigravityReleaseSource { + /** + * The release to offer. Never fails. Asks the feed at most once an hour + * and waits for it at most a few seconds; a slow answer is used by the + * next call. + */ + readonly newest: Effect.Effect; +} + +/** Like the other providers' newest-version checks (`providerMaintenance`). */ +const ASK_EVERY_MS = 60 * 60 * 1000; +/** After the feed couldn't be read, the last answer (or the built-in release) is used until then. */ +const RETRY_AFTER_FAILURE_MS = 10 * 60 * 1000; +const WAIT_AT_MOST = Duration.seconds(4); +const READ_TIMEOUT_MS = 30_000; +/** A manifest is three short fields. */ +const MAX_MANIFEST_BYTES = 16 * 1024; + +/** Reads Google's feed only, on every redirect hop too. */ +export const makeAntigravityFeedFetch = (): DownloadFetch => + makeHttpsFetch({ publicAddressesOnly: true, allowedHosts: [ANTIGRAVITY_FEED_HOST] }); + +/** The feed's manifest for `assetKey`, or undefined when it can't be read. */ +async function readManifest( + fetchFeed: DownloadFetch, + assetKey: AntigravityAssetKey, +): Promise { + const response = await fetchFeed(antigravityFeedUrl(assetKey), { + headers: { accept: "application/json" }, + redirect: "follow", + signal: AbortSignal.timeout(READ_TIMEOUT_MS), + }); + if (!response.ok || response.body === null) { + await response.body?.cancel().catch(() => undefined); + throw new Error(`the feed answered ${response.status}`); + } + const reader = response.body.getReader(); + const chunks: Array = []; + let total = 0; + try { + for (;;) { + const { done, value } = await reader.read(); + if (done) break; + total += value.byteLength; + if (total > MAX_MANIFEST_BYTES) throw new Error("the manifest is too large"); + chunks.push(value); + } + } finally { + await reader.cancel().catch(() => undefined); + } + // `parseAntigravityFeedManifest` checks every field. + return JSON.parse(Buffer.concat(chunks).toString("utf8")) as unknown; +} + +export function makeAntigravityReleaseSource(input: { + readonly builtIn: AntigravityPlatformRelease; + readonly assetKey: AntigravityAssetKey; + /** Test seam for reading the feed. */ + readonly fetch?: DownloadFetch; +}): AntigravityReleaseSource { + const { builtIn, assetKey } = input; + const fetchFeed = input.fetch ?? makeAntigravityFeedFetch(); + + /** What the feed offers now, or the built-in release when that is newer or the feed's isn't usable. */ + const ask = async () => { + const listed = parseAntigravityFeedManifest(await readManifest(fetchFeed, assetKey), assetKey); + return listed && compareSemverVersions(listed.version, builtIn.version) > 0 ? listed : builtIn; + }; + + let last: { readonly offer: AntigravityPlatformRelease; readonly askedAtMs: number } | undefined; + let failedAtMs: number | undefined; + /** One read at a time: a slow one is shared, and its answer kept for the next call. */ + let inFlight: Promise | undefined; + const within = (sinceMs: number | undefined, nowMs: number, spanMs: number) => + sinceMs !== undefined && nowMs - sinceMs >= 0 && nowMs - sinceMs < spanMs; + + const refresh = (nowMs: number) => + Effect.promise(() => { + inFlight ??= ask() + .then( + (offer) => { + last = { offer, askedAtMs: nowMs }; + failedAtMs = undefined; + }, + () => { + failedAtMs = nowMs; + }, + ) + .finally(() => { + inFlight = undefined; + }); + return inFlight; + }); + + const newest = Effect.gen(function* () { + const nowMs = yield* Clock.currentTimeMillis; + const fresh = last && within(last.askedAtMs, nowMs, ASK_EVERY_MS); + // While the feed is down, every refresh would ask again: wait a while. + if (!fresh && !within(failedAtMs, nowMs, RETRY_AFTER_FAILURE_MS)) { + yield* refresh(nowMs).pipe(Effect.timeoutOption(WAIT_AT_MOST)); + } + return last?.offer ?? builtIn; + }); + + return { newest }; +} diff --git a/apps/server/src/provider/antigravity/AntigravityRuntime.test.ts b/apps/server/src/provider/antigravity/AntigravityRuntime.test.ts index 5dbb8b663..b93ae4280 100644 --- a/apps/server/src/provider/antigravity/AntigravityRuntime.test.ts +++ b/apps/server/src/provider/antigravity/AntigravityRuntime.test.ts @@ -1,5 +1,5 @@ -// @effect-diagnostics nodeBuiltinImport:off - builds zip fixtures and inspects the runtime's files -// @effect-diagnostics preferSchemaOverJson:off - reads active.json back as plain JSON +// @effect-diagnostics nodeBuiltinImport:off - builds tarball fixtures and inspects the runtime's files +// @effect-diagnostics preferSchemaOverJson:off - writes old markers and reads active.json as plain JSON import { createHash } from "node:crypto"; import { existsSync } from "node:fs"; import * as NodeFS from "node:fs/promises"; @@ -8,10 +8,21 @@ import path from "node:path"; import * as zlib from "node:zlib"; import { assert, describe, it } from "@effect/vitest"; +import * as Data from "effect/Data"; import * as Effect from "effect/Effect"; import * as Fiber from "effect/Fiber"; +import { TestClock } from "effect/testing"; -import type { AntigravityPlatformRelease } from "./AntigravityRelease.ts"; +import type { DownloadFetch } from "../managedRuntime/VerifiedDownload.ts"; +import { makeTar, type TarEntry } from "../testUtils/archiveFixtures.ts"; +import { + ANTIGRAVITY_RELEASE, + type AntigravityPlatformRelease, + antigravityFeedUrl, + antigravityReleaseFor, + parseAntigravityFeedManifest, +} from "./AntigravityRelease.ts"; +import { makeAntigravityReleaseSource } from "./AntigravityReleaseSource.ts"; import { type AntigravityFetch, type AntigravityInstallProgress, @@ -19,89 +30,41 @@ import { makeAntigravityRuntime, } from "./AntigravityRuntime.ts"; -const EXECUTABLE = "agy_acp_server.par"; -const HARNESS = "localharness_external"; +const EXECUTABLE = "antigravity"; const CHUNK_BYTES = 16 * 1024; -interface ZipEntry { - readonly name: string; - readonly data: Buffer; - readonly deflate?: boolean; -} - -/** A minimal zip writer: local headers and data, then the central directory and end record. */ -function makeZip(entries: ReadonlyArray): Buffer { - const parts: Array = []; - const central: Array = []; - let offset = 0; - for (const entry of entries) { - const name = Buffer.from(entry.name, "utf8"); - const body = entry.deflate ? zlib.deflateRawSync(entry.data) : entry.data; - const method = entry.deflate ? 8 : 0; - const crc = zlib.crc32(entry.data); - const local = Buffer.alloc(30); - local.writeUInt32LE(0x04034b50, 0); - local.writeUInt16LE(20, 4); - local.writeUInt16LE(0x0800, 6); - local.writeUInt16LE(method, 8); - local.writeUInt16LE(0x21, 12); - local.writeUInt32LE(crc, 14); - local.writeUInt32LE(body.length, 18); - local.writeUInt32LE(entry.data.length, 22); - local.writeUInt16LE(name.length, 26); - const header = Buffer.alloc(46); - header.writeUInt32LE(0x02014b50, 0); - header.writeUInt16LE((3 << 8) | 20, 4); - header.writeUInt16LE(20, 6); - header.writeUInt16LE(0x0800, 8); - header.writeUInt16LE(method, 10); - header.writeUInt16LE(0x21, 14); - header.writeUInt32LE(crc, 16); - header.writeUInt32LE(body.length, 20); - header.writeUInt32LE(entry.data.length, 24); - header.writeUInt16LE(name.length, 28); - header.writeUInt32LE((0o100755 << 16) >>> 0, 38); - header.writeUInt32LE(offset, 42); - parts.push(local, name, body); - central.push(header, name); - offset += local.length + name.length + body.length; - } - const directory = Buffer.concat(central); - const end = Buffer.alloc(22); - end.writeUInt32LE(0x06054b50, 0); - end.writeUInt16LE(entries.length, 8); - end.writeUInt16LE(entries.length, 10); - end.writeUInt32LE(directory.length, 12); - end.writeUInt32LE(offset, 16); - return Buffer.concat([...parts, directory, end]); -} +class HandshakeFailed extends Data.TaggedError("HandshakeFailed")<{ readonly message: string }> {} -const sha256 = (data: Buffer) => createHash("sha256").update(data).digest("hex"); +const sha512 = (data: Buffer) => createHash("sha512").update(data).digest("hex"); -/** A release whose zip holds the two expected files, or `entries` built from them. */ +/** + * A release whose tarball holds the one expected executable, or `entries` + * built from it. `sizes: "feed"` leaves the sizes out, as a release read + * from Google's update feed does. + */ function makeFixture( seed: string, - entries?: (files: { readonly executable: Buffer; readonly harness: Buffer }) => Array, + options: { + readonly entries?: (executable: Buffer) => Array; + readonly sizes?: "known" | "feed"; + } = {}, ) { - const executable = Buffer.from(`#!/bin/sh\necho ${seed}\n`); - const harness = Buffer.from(`harness ${seed}\n`.repeat(64)); - const zip = makeZip( - entries?.({ executable, harness }) ?? [ - { name: EXECUTABLE, data: executable }, - { name: HARNESS, data: harness, deflate: true }, - ], + const executable = Buffer.from(`#!/bin/sh\necho ${seed}\n${"#".repeat(40_000)}\n`); + const tarball = zlib.gzipSync( + makeTar(options.entries?.(executable) ?? [{ name: EXECUTABLE, data: executable, mode: 0o755 }]), ); + const known = options.sizes !== "feed"; const release: AntigravityPlatformRelease = { version: `1.0.0-${seed}`, asset: { - url: `https://downloads.test/${seed}.zip`, - sha256: sha256(zip), - archiveBytes: zip.length, - executable: { name: EXECUTABLE, bytes: executable.length }, - harness: { name: HARNESS, bytes: harness.length }, + url: `https://downloads.test/${seed}.tar.gz`, + sha512: sha512(tarball), + format: "tar.gz", + ...(known ? { archiveBytes: tarball.length } : {}), + executable: { name: EXECUTABLE, ...(known ? { bytes: executable.length } : {}) }, }, }; - return { zip, release, executable, harness, releaseId: release.asset.sha256.slice(0, 16) }; + return { tarball, release, executable, releaseId: release.asset.sha512.slice(0, 16) }; } /** Serves archives from memory in small chunks, with no content-length, like a chunked response. */ @@ -148,55 +111,50 @@ const tempRoot = Effect.acquireRelease( const listDir = (dir: string) => Effect.promise(() => NodeFS.readdir(dir).catch(() => [] as Array)); +const readFile = (file: string) => Effect.promise(() => NodeFS.readFile(file)); + describe("makeAntigravityRuntime", () => { - it.live("installs, activates and reports the installed files", () => + it.live("installs a tarball, activates it and reports a read-only executable", () => Effect.gen(function* () { const root = yield* tempRoot; const fixture = makeFixture("a"); - const server = makeServer({ [fixture.release.asset.url]: fixture.zip }); + const server = makeServer({ [fixture.release.asset.url]: fixture.tarball }); const { calls, validate } = recordingValidate(); - const runtime = makeAntigravityRuntime({ - root, - release: fixture.release, - validate, - fetch: server.fetch, - }); + const runtime = makeAntigravityRuntime({ root, validate, fetch: server.fetch }); assert.isUndefined(yield* runtime.installed); const progress: Array = []; - const result = yield* runtime.install((update) => progress.push(update)); + const result = yield* runtime.install(fixture.release, (update) => progress.push(update)); const { releaseId } = fixture; const versionDir = path.join(root, "versions", releaseId); + const executablePath = path.join(versionDir, EXECUTABLE); assert.deepStrictEqual(result, { releaseId, version: fixture.release.version }); assert.deepStrictEqual(yield* runtime.installed, { releaseId, version: fixture.release.version, - executable: path.join(versionDir, EXECUTABLE), - harness: path.join(versionDir, HARNESS), + executable: executablePath, + kind: "cli", }); - const executable = yield* Effect.promise(() => - NodeFS.readFile(path.join(versionDir, EXECUTABLE)), - ); - const harness = yield* Effect.promise(() => NodeFS.readFile(path.join(versionDir, HARNESS))); - assert.isTrue(executable.equals(fixture.executable)); - assert.isTrue(harness.equals(fixture.harness)); + assert.isTrue((yield* readFile(executablePath)).equals(fixture.executable)); if (process.platform !== "win32") { - for (const name of [EXECUTABLE, HARNESS]) { - const stats = yield* Effect.promise(() => NodeFS.stat(path.join(versionDir, name))); - assert.equal(stats.mode & 0o777, 0o755); - } + const stats = yield* Effect.promise(() => NodeFS.stat(executablePath)); + assert.equal(stats.mode & 0o777, 0o555); } const active = yield* Effect.promise(() => NodeFS.readFile(path.join(root, "active.json"), "utf8"), ); assert.deepStrictEqual(JSON.parse(active), { releaseId, version: fixture.release.version }); - // Staging is gone; only the version is left. + // Staging is gone; only the version is left, holding the executable and its marker. assert.deepStrictEqual(yield* listDir(path.join(root, "versions")), [releaseId]); + assert.deepStrictEqual((yield* listDir(versionDir)).toSorted(), [ + ".install-complete.json", + EXECUTABLE, + ]); assert.deepStrictEqual(server.requests, [ { url: fixture.release.asset.url, acceptEncoding: "identity" }, ]); - assert.equal(calls.length, 1); + assert.lengthOf(calls, 1); const phases = progress .map((update) => update.phase) .filter((phase, index, all) => phase !== all[index - 1]); @@ -205,72 +163,164 @@ describe("makeAntigravityRuntime", () => { progress.findLast((update) => update.phase === "downloading"), { phase: "downloading", - receivedBytes: fixture.zip.length, - totalBytes: fixture.zip.length, + receivedBytes: fixture.tarball.length, + totalBytes: fixture.tarball.length, }, ); // Installing again reuses the files on disk: validated, not downloaded. - yield* runtime.install(); - assert.equal(server.requests.length, 1); - assert.equal(calls.length, 2); + yield* runtime.install(fixture.release); + assert.lengthOf(server.requests, 1); + assert.lengthOf(calls, 2); }), ); - it.live("rejects a download whose hash does not match and leaves nothing behind", () => + it.live("installs a Windows build, whose download is the executable", () => Effect.gen(function* () { const root = yield* tempRoot; - const fixture = makeFixture("a"); - const tampered = Buffer.from(fixture.zip); - tampered[40] = tampered[40]! ^ 0xff; - const server = makeServer({ [fixture.release.asset.url]: tampered }); - const { calls, validate } = recordingValidate(); + const exe = Buffer.from(`MZ${"x".repeat(50_000)}`); + const release: AntigravityPlatformRelease = { + version: "1.0.0-win", + asset: { + url: "https://downloads.test/cli_windows_x64.exe", + sha512: sha512(exe), + format: "exe", + archiveBytes: exe.length, + executable: { name: "agy.exe", bytes: exe.length }, + }, + }; + const server = makeServer({ [release.asset.url]: exe }); const runtime = makeAntigravityRuntime({ root, - release: fixture.release, - validate, + validate: recordingValidate().validate, fetch: server.fetch, + platform: "win32", }); - const error = yield* Effect.flip(runtime.install()); + yield* runtime.install(release); + + const installed = yield* runtime.installed; + const versionDir = path.join(root, "versions", release.asset.sha512.slice(0, 16)); + assert.equal(installed?.kind, "cli"); + assert.equal(installed?.executable, path.join(versionDir, "agy.exe")); + assert.isTrue((yield* readFile(path.join(versionDir, "agy.exe"))).equals(exe)); + assert.deepStrictEqual((yield* listDir(versionDir)).toSorted(), [ + ".install-complete.json", + "agy.exe", + ]); + }), + ); + + it.live("installs a release listed without sizes and keeps it installed", () => + Effect.gen(function* () { + const root = yield* tempRoot; + const fixture = makeFixture("feed", { sizes: "feed" }); + const server = makeServer({ [fixture.release.asset.url]: fixture.tarball }); + const runtime = makeAntigravityRuntime({ + root, + validate: recordingValidate().validate, + fetch: server.fetch, + }); + + const progress: Array = []; + yield* runtime.install(fixture.release, (update) => progress.push(update)); + + // `installed` checks the executable against the size the marker + // recorded, so this holds only if the real size was recorded. + const installed = yield* runtime.installed; + assert.equal(installed?.releaseId, fixture.releaseId); + assert.isTrue((yield* readFile(installed!.executable)).equals(fixture.executable)); + assert.isTrue( + progress.every((update) => update.totalBytes === undefined), + "no total is reported for a download of unknown size", + ); + // And a later process still finds it complete, so it isn't downloaded again. + yield* makeAntigravityRuntime({ + root, + validate: recordingValidate().validate, + fetch: server.fetch, + }).install(fixture.release); + assert.lengthOf(server.requests, 1); + }), + ); + + it.live("installs nothing when the download's sha512 does not match", () => + Effect.gen(function* () { + const root = yield* tempRoot; + const fixture = makeFixture("a"); + const tampered = Buffer.from(fixture.tarball); + tampered[40] = tampered[40]! ^ 0xff; + const server = makeServer({ [fixture.release.asset.url]: tampered }); + const { calls, validate } = recordingValidate(); + const runtime = makeAntigravityRuntime({ root, validate, fetch: server.fetch }); + + const error = yield* Effect.flip(runtime.install(fixture.release)); assert.equal(error.reason, "checksum"); assert.deepStrictEqual(yield* listDir(path.join(root, "versions")), []); assert.isUndefined(yield* runtime.installed); - assert.equal(calls.length, 0); + assert.lengthOf(calls, 0); }), ); - it.live("rejects archives that hold anything but the two expected files", () => + it.live("refuses tarballs that hold anything but the one executable", () => Effect.gen(function* () { const root = yield* tempRoot; const fixtures = [ - makeFixture("extra", ({ executable, harness }) => [ - { name: EXECUTABLE, data: executable }, - { name: HARNESS, data: harness }, - { name: "README", data: Buffer.from("hello") }, - ]), - makeFixture("escape", ({ executable, harness }) => [ - { name: `../${EXECUTABLE}`, data: executable }, - { name: HARNESS, data: harness }, - ]), + makeFixture("two-entries", { + entries: (executable) => [ + { name: EXECUTABLE, data: executable }, + { name: "README", data: Buffer.from("hello") }, + ], + }), + makeFixture("wrong-name", { + entries: (executable) => [{ name: "agy", data: executable }], + }), + makeFixture("symlink", { + entries: () => [{ name: EXECUTABLE, type: "2", linkname: "/bin/sh" }], + }), + makeFixture("directory", { + entries: () => [{ name: `${EXECUTABLE}/`, type: "5", mode: 0o755 }], + }), + makeFixture("bigger-than-listed", { + entries: (executable) => [ + { name: EXECUTABLE, data: Buffer.concat([executable, Buffer.from("extra")]) }, + ], + }), ]; const server = makeServer( - Object.fromEntries(fixtures.map((fixture) => [fixture.release.asset.url, fixture.zip])), + Object.fromEntries(fixtures.map((fixture) => [fixture.release.asset.url, fixture.tarball])), ); const { calls, validate } = recordingValidate(); for (const fixture of fixtures) { - const runtime = makeAntigravityRuntime({ - root, - release: fixture.release, - validate, - fetch: server.fetch, - }); - const error = yield* Effect.flip(runtime.install()); + const runtime = makeAntigravityRuntime({ root, validate, fetch: server.fetch }); + const error = yield* Effect.flip(runtime.install(fixture.release)); assert.equal(error.reason, "archive", fixture.release.version); + assert.isUndefined(yield* runtime.installed, fixture.release.version); } assert.deepStrictEqual(yield* listDir(path.join(root, "versions")), []); - assert.equal(calls.length, 0); + assert.lengthOf(calls, 0); + }), + ); + + it.live("installs nothing when the executable fails validation", () => + Effect.gen(function* () { + const root = yield* tempRoot; + const fixture = makeFixture("a"); + const server = makeServer({ [fixture.release.asset.url]: fixture.tarball }); + const runtime = makeAntigravityRuntime({ + root, + validate: () => Effect.fail(new HandshakeFailed({ message: "initialize timed out" })), + fetch: server.fetch, + }); + + const error = yield* Effect.flip(runtime.install(fixture.release)); + + assert.equal(error.reason, "validate"); + assert.equal(error.detail, "initialize timed out"); + assert.isUndefined(yield* runtime.installed); + assert.deepStrictEqual(yield* listDir(path.join(root, "versions")), []); + assert.isFalse(existsSync(path.join(root, "active.json"))); }), ); @@ -278,19 +328,18 @@ describe("makeAntigravityRuntime", () => { Effect.gen(function* () { const root = yield* tempRoot; const fixture = makeFixture("a"); - const oversized = Buffer.concat([fixture.zip, Buffer.alloc(4 * 1024 * 1024)]); + const oversized = Buffer.concat([fixture.tarball, Buffer.alloc(4 * 1024 * 1024)]); const server = makeServer({ [fixture.release.asset.url]: oversized }); const runtime = makeAntigravityRuntime({ root, - release: fixture.release, validate: recordingValidate().validate, fetch: server.fetch, }); - const error = yield* Effect.flip(runtime.install()); + const error = yield* Effect.flip(runtime.install(fixture.release)); assert.equal(error.reason, "checksum"); - assert.isBelow(server.pulledBytes(), fixture.zip.length + 1024 * 1024); + assert.isBelow(server.pulledBytes(), fixture.tarball.length + 1024 * 1024); assert.deepStrictEqual(yield* listDir(path.join(root, "versions")), []); }), ); @@ -305,7 +354,7 @@ describe("makeAntigravityRuntime", () => { new Response( new ReadableStream({ start(controller) { - controller.enqueue(new Uint8Array(fixture.zip.subarray(0, 64))); + controller.enqueue(new Uint8Array(fixture.tarball.subarray(0, 64))); }, cancel() { cancelled = true; @@ -314,7 +363,6 @@ describe("makeAntigravityRuntime", () => { ); const runtime = makeAntigravityRuntime({ root, - release: fixture.release, validate: recordingValidate().validate, fetch, }); @@ -324,7 +372,7 @@ describe("makeAntigravityRuntime", () => { }); const fiber = yield* runtime - .install((update) => { + .install(fixture.release, (update) => { if (update.receivedBytes) markStarted(); }) .pipe(Effect.forkChild); @@ -341,30 +389,24 @@ describe("makeAntigravityRuntime", () => { const root = yield* tempRoot; const a = makeFixture("a"); const b = makeFixture("b"); - const server = makeServer({ [a.release.asset.url]: a.zip, [b.release.asset.url]: b.zip }); - const { validate } = recordingValidate(); - const runtimeA = makeAntigravityRuntime({ - root, - release: a.release, - validate, - fetch: server.fetch, - }); - const runtimeB = makeAntigravityRuntime({ - root, - release: b.release, - validate, - fetch: server.fetch, + const server = makeServer({ + [a.release.asset.url]: a.tarball, + [b.release.asset.url]: b.tarball, }); + const { validate } = recordingValidate(); + const runtimeA = makeAntigravityRuntime({ root, validate, fetch: server.fetch }); + const runtimeB = makeAntigravityRuntime({ root, validate, fetch: server.fetch }); const versionsDir = path.join(root, "versions"); const leasesA = path.join(versionsDir, a.releaseId, ".leases"); - yield* runtimeA.install(); + yield* runtimeA.install(a.release); yield* Effect.scoped( Effect.gen(function* () { const leased = yield* runtimeA.acquire; assert.equal(leased.releaseId, a.releaseId); + assert.equal(leased.kind, "cli"); // Activating B prunes, but A is in use. - yield* runtimeB.install(); + yield* runtimeB.install(b.release); assert.equal((yield* runtimeB.installed)?.releaseId, b.releaseId); assert.isTrue(existsSync(leased.executable)); assert.lengthOf(yield* listDir(leasesA), 1); @@ -386,6 +428,7 @@ describe("makeAntigravityRuntime", () => { yield* runtimeB.prune; assert.deepStrictEqual(yield* listDir(versionsDir), [b.releaseId]); + // The executable is read-only, and remove still deletes it. yield* runtimeB.remove; assert.isFalse(existsSync(root)); assert.isUndefined(yield* runtimeB.installed); @@ -397,24 +440,17 @@ describe("makeAntigravityRuntime", () => { const root = yield* tempRoot; const a = makeFixture("a"); const b = makeFixture("b"); - const server = makeServer({ [a.release.asset.url]: a.zip, [b.release.asset.url]: b.zip }); - const { validate } = recordingValidate(); - const runtimeA = makeAntigravityRuntime({ - root, - release: a.release, - validate, - fetch: server.fetch, - }); - const runtimeB = makeAntigravityRuntime({ - root, - release: b.release, - validate, - fetch: server.fetch, + const server = makeServer({ + [a.release.asset.url]: a.tarball, + [b.release.asset.url]: b.tarball, }); + const { validate } = recordingValidate(); + const runtimeA = makeAntigravityRuntime({ root, validate, fetch: server.fetch }); + const runtimeB = makeAntigravityRuntime({ root, validate, fetch: server.fetch }); const versionsDir = path.join(root, "versions"); // Both versions on disk, A active. - yield* runtimeB.install(); - yield* Effect.scoped(runtimeB.acquire.pipe(Effect.andThen(runtimeA.install()))); + yield* runtimeB.install(b.release); + yield* Effect.scoped(runtimeB.acquire.pipe(Effect.andThen(runtimeA.install(a.release)))); assert.equal((yield* runtimeA.installed)?.releaseId, a.releaseId); assert.lengthOf(yield* listDir(versionsDir), 2); @@ -423,13 +459,12 @@ describe("makeAntigravityRuntime", () => { let raced = false; const racing = makeAntigravityRuntime({ root, - release: a.release, validate, fetch: server.fetch, beforeLeaseWritten: () => { if (raced) return Effect.void; raced = true; - return runtimeB.install().pipe(Effect.orDie, Effect.asVoid); + return runtimeB.install(b.release).pipe(Effect.orDie, Effect.asVoid); }, }); const leasesB = path.join(versionsDir, b.releaseId, ".leases"); @@ -452,32 +487,24 @@ describe("makeAntigravityRuntime", () => { const root = yield* tempRoot; const a = makeFixture("a"); const b = makeFixture("b"); - const server = makeServer({ [a.release.asset.url]: a.zip, [b.release.asset.url]: b.zip }); - const { validate } = recordingValidate(); - const runtimeA = makeAntigravityRuntime({ - root, - release: a.release, - validate, - fetch: server.fetch, - }); - const runtimeB = makeAntigravityRuntime({ - root, - release: b.release, - validate, - fetch: server.fetch, + const server = makeServer({ + [a.release.asset.url]: a.tarball, + [b.release.asset.url]: b.tarball, }); + const { validate } = recordingValidate(); + const runtimeA = makeAntigravityRuntime({ root, validate, fetch: server.fetch }); + const runtimeB = makeAntigravityRuntime({ root, validate, fetch: server.fetch }); const versionsDir = path.join(root, "versions"); const activeFile = path.join(root, "active.json"); - yield* runtimeB.install(); + yield* runtimeB.install(b.release); const pointerB = yield* Effect.promise(() => NodeFS.readFile(activeFile, "utf8")); - yield* Effect.scoped(runtimeB.acquire.pipe(Effect.andThen(runtimeA.install()))); + yield* Effect.scoped(runtimeB.acquire.pipe(Effect.andThen(runtimeA.install(a.release)))); // Another server switches to B, A stays on disk, and its prune has not // run yet: a lease on A now would be one that prune can miss. let raced = false; const racing = makeAntigravityRuntime({ root, - release: a.release, validate, fetch: server.fetch, beforeLeaseWritten: () => @@ -501,3 +528,265 @@ describe("makeAntigravityRuntime", () => { }), ); }); + +describe("makeAntigravityRuntime with an install from before the CLI", () => { + const LEGACY_ID = "0123456789abcdef"; + + /** Writes what an install of Google's old ACP server left on disk, active. */ + const writeLegacyInstall = (root: string) => + Effect.promise(async () => { + const versionDir = path.join(root, "versions", LEGACY_ID); + await NodeFS.mkdir(versionDir, { recursive: true }); + const server = Buffer.from("old server"); + const harness = Buffer.from("old harness"); + await NodeFS.writeFile(path.join(versionDir, "agy_acp_server.par"), server); + await NodeFS.writeFile(path.join(versionDir, "localharness_external"), harness); + await NodeFS.writeFile( + path.join(versionDir, ".install-complete.json"), + `${JSON.stringify({ + releaseId: LEGACY_ID, + version: "1.0.4", + executable: { name: "agy_acp_server.par", bytes: server.length }, + harness: { name: "localharness_external", bytes: harness.length }, + })}\n`, + ); + await NodeFS.writeFile( + path.join(root, "active.json"), + `${JSON.stringify({ releaseId: LEGACY_ID, version: "1.0.4" })}\n`, + ); + return versionDir; + }); + + it.live("reports it as legacy, never starts it, and prunes it once the CLI replaces it", () => + Effect.gen(function* () { + const root = yield* tempRoot; + const legacyDir = yield* writeLegacyInstall(root); + const fixture = makeFixture("cli"); + const server = makeServer({ [fixture.release.asset.url]: fixture.tarball }); + const runtime = makeAntigravityRuntime({ + root, + validate: recordingValidate().validate, + fetch: server.fetch, + }); + + // Shown as installed, so the row offers Update. + assert.deepStrictEqual(yield* runtime.installed, { + releaseId: LEGACY_ID, + version: "1.0.4", + executable: path.join(legacyDir, "agy_acp_server.par"), + kind: "legacy", + }); + const refused = yield* Effect.flip(Effect.scoped(runtime.acquire)); + assert.equal(refused.reason, "notInstalled"); + + // An old process still running on it keeps it through the update. + const leasesDir = path.join(legacyDir, ".leases"); + const otherLiveProcess = path.join(leasesDir, `${process.ppid}-deadbeef`); + yield* Effect.promise(async () => { + await NodeFS.mkdir(leasesDir, { recursive: true }); + await NodeFS.writeFile(otherLiveProcess, ""); + }); + yield* runtime.install(fixture.release); + const installed = yield* runtime.installed; + assert.equal(installed?.kind, "cli"); + assert.equal(installed?.releaseId, fixture.releaseId); + assert.isTrue(existsSync(legacyDir)); + + // Once that process is done with it, a prune removes it. + yield* Effect.promise(() => NodeFS.rm(otherLiveProcess)); + yield* runtime.prune; + assert.deepStrictEqual(yield* listDir(path.join(root, "versions")), [fixture.releaseId]); + const leased = yield* Effect.scoped(runtime.acquire); + assert.equal(leased.kind, "cli"); + }), + ); +}); + +describe("makeAntigravityReleaseSource", () => { + const builtIn = antigravityReleaseFor("darwin", "arm64")!; + const FEED_SHA512 = "ab".repeat(64); + const downloadUrl = (version: string, folder = "darwin-arm", file = "cli_mac_arm64.tar.gz") => + `https://storage.googleapis.com/antigravity-public/antigravity-cli/${version}-123456/${folder}/${file}`; + const manifest = (overrides: Record = {}) => ({ + version: "9.0.0", + url: downloadUrl("9.0.0"), + sha512: FEED_SHA512, + ...overrides, + }); + + /** Answers every read of the feed with `answer()`, counting the reads. */ + function feed(answer: () => Response | Promise) { + const urls: Array = []; + const fetch: DownloadFetch = async (url) => { + urls.push(url); + return answer(); + }; + return { fetch, urls }; + } + const json = (body: unknown) => () => new Response(JSON.stringify(body)); + + it.effect("offers the feed's release when it is newer than the built-in one", () => + Effect.gen(function* () { + const server = feed(json(manifest())); + const source = makeAntigravityReleaseSource({ + builtIn, + assetKey: "darwin-arm64", + fetch: server.fetch, + }); + + assert.deepStrictEqual(yield* source.newest, { + version: "9.0.0", + asset: { + url: downloadUrl("9.0.0"), + sha512: FEED_SHA512, + format: "tar.gz", + executable: { name: EXECUTABLE }, + }, + }); + assert.deepStrictEqual(server.urls, [antigravityFeedUrl("darwin-arm64")]); + }), + ); + + it.effect("keeps the built-in release unless the feed lists a newer one it can install", () => + Effect.gen(function* () { + const answers: Record Response | Promise> = { + "same version": json( + manifest({ version: builtIn.version, url: downloadUrl(builtIn.version) }), + ), + "older version": json(manifest({ version: "1.5.13", url: downloadUrl("1.5.13") })), + "not JSON": () => new Response(""), + "no sha512": json(manifest({ sha512: undefined })), + "another host": json( + manifest({ url: downloadUrl("9.0.0").replace("storage.googleapis.com", "example.com") }), + ), + "another build's folder": json(manifest({ url: downloadUrl("9.0.0", "darwin-x64") })), + "an HTTP error": () => new Response("busy", { status: 503 }), + "a network error": () => Promise.reject(new Error("offline")), + }; + for (const [label, answer] of Object.entries(answers)) { + const source = makeAntigravityReleaseSource({ + builtIn, + assetKey: "darwin-arm64", + fetch: feed(answer).fetch, + }); + assert.deepStrictEqual(yield* source.newest, builtIn, label); + } + }), + ); + + it.effect("asks the feed at most once an hour, and waits 10 minutes after a failure", () => + Effect.gen(function* () { + const server = feed(json(manifest())); + const source = makeAntigravityReleaseSource({ + builtIn, + assetKey: "darwin-arm64", + fetch: server.fetch, + }); + assert.equal((yield* source.newest).version, "9.0.0"); + yield* TestClock.adjust("59 minutes"); + assert.equal((yield* source.newest).version, "9.0.0"); + assert.lengthOf(server.urls, 1); + yield* TestClock.adjust("2 minutes"); + yield* source.newest; + assert.lengthOf(server.urls, 2); + + let down = true; + const flaky = feed(() => (down ? Promise.reject(new Error("offline")) : json(manifest())())); + const recovering = makeAntigravityReleaseSource({ + builtIn, + assetKey: "darwin-arm64", + fetch: flaky.fetch, + }); + assert.equal((yield* recovering.newest).version, builtIn.version); + down = false; + yield* TestClock.adjust("9 minutes"); + assert.equal((yield* recovering.newest).version, builtIn.version); + assert.lengthOf(flaky.urls, 1); + yield* TestClock.adjust("2 minutes"); + assert.equal((yield* recovering.newest).version, "9.0.0"); + assert.lengthOf(flaky.urls, 2); + }), + ); +}); + +describe("parseAntigravityFeedManifest", () => { + const builtInAsset = ANTIGRAVITY_RELEASE.assets["darwin-arm64"]; + // Google's manifest for 1.5.14 on Apple silicon, as the feed served it. + const google = { + version: "1.5.14", + url: "https://storage.googleapis.com/antigravity-public/antigravity-cli/1.5.14-5302690847260672/darwin-arm/cli_mac_arm64.tar.gz", + sha512: builtInAsset.sha512, + }; + + it("accepts Google's manifest as the built-in release, without its sizes", () => { + assert.deepStrictEqual(parseAntigravityFeedManifest(google, "darwin-arm64"), { + version: "1.5.14", + asset: { + url: builtInAsset.url, + sha512: builtInAsset.sha512, + format: "tar.gz", + executable: { name: EXECUTABLE }, + }, + }); + // The hash may come in uppercase; the release id is the same either way. + assert.equal( + parseAntigravityFeedManifest( + { ...google, sha512: google.sha512.toUpperCase() }, + "darwin-arm64", + )?.asset.sha512, + builtInAsset.sha512, + ); + }); + + it("reads a Windows manifest as the bare executable", () => { + const windows = ANTIGRAVITY_RELEASE.assets["win32-x64"]; + assert.deepStrictEqual( + parseAntigravityFeedManifest( + { version: "1.5.14", url: windows.url, sha512: windows.sha512 }, + "win32-x64", + ), + { + version: "1.5.14", + asset: { + url: windows.url, + sha512: windows.sha512, + format: "exe", + executable: { name: "agy.exe" }, + }, + }, + ); + }); + + it("refuses a manifest it can't be sure is Google's build for this machine", () => { + const refused: Record = { + "another build's folder": { + ...google, + url: google.url.replace("/darwin-arm/", "/darwin-x64/"), + }, + "another file name": { ...google, url: google.url.replace("cli_mac_arm64", "cli_mac_x64") }, + "a query string": { ...google, url: `${google.url}?alt=media` }, + "plain http": { ...google, url: google.url.replace("https:", "http:") }, + "a version the url doesn't name": { ...google, version: "1.5.15" }, + "a prerelease version": { + ...google, + version: "1.5.14-beta", + url: google.url.replace("1.5.14-", "1.5.14-beta-"), + }, + "a two-part version": { + ...google, + version: "1.5", + url: google.url.replace("1.5.14-", "1.5-"), + }, + "a short sha512": { ...google, sha512: google.sha512.slice(0, 64) }, + "a sha512 that isn't hex": { ...google, sha512: `${google.sha512.slice(0, 127)}g` }, + "a missing url": { version: google.version, sha512: google.sha512 }, + "an array": [google], + null: null, + }; + for (const [label, manifest] of Object.entries(refused)) { + assert.isUndefined(parseAntigravityFeedManifest(manifest, "darwin-arm64"), label); + } + // Google's Apple silicon manifest is not a Linux build. + assert.isUndefined(parseAntigravityFeedManifest(google, "linux-arm64")); + }); +}); diff --git a/apps/server/src/provider/antigravity/AntigravityRuntime.ts b/apps/server/src/provider/antigravity/AntigravityRuntime.ts index 3af6fb2ff..e9a18f13f 100644 --- a/apps/server/src/provider/antigravity/AntigravityRuntime.ts +++ b/apps/server/src/provider/antigravity/AntigravityRuntime.ts @@ -1,34 +1,41 @@ -// @effect-diagnostics nodeBuiltinImport:off - streams the download and zip entries to disk +// @effect-diagnostics nodeBuiltinImport:off - moves the download and its unpacked file on disk /** - * AntigravityRuntime — Threadlines' own copy of the Antigravity ACP server. - * It downloads the pinned release, verifies and unpacks it, and keeps it in a + * AntigravityRuntime — Threadlines' own copy of Google's Antigravity CLI. + * It downloads a release, verifies and unpacks it, and keeps it in a * `ManagedRuntimeStore`, which activates it, leases it to running processes * and prunes versions nobody uses (the layout and its invariants are * described there). * - * A version's folder holds the release's two files next to the store's - * marker, which also records their names and sizes. + * A version's folder holds one executable next to the store's marker, which + * records its name and size. The executable is made read-only (on macOS and + * Linux), so the CLI can't update itself in place; the folder stays + * writable, since the store keeps its leases there. + * + * Installs from before the move to the CLI (Google's `agy_acp_server` and + * its harness) are still recognized, as `legacy`: they show as installed so + * the row offers Update, keep their leases while an old process runs, and + * are pruned once the CLI is active and nothing runs on them. They never + * start a session. * * @module provider/antigravity/AntigravityRuntime */ -import { createWriteStream } from "node:fs"; import * as NodeFS from "node:fs/promises"; import * as NodePath from "node:path"; -import { pipeline } from "node:stream/promises"; import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; import type * as Scope from "effect/Scope"; -import yauzl from "yauzl"; +import { ArchiveError, extractArchive } from "../managedRuntime/ArchiveExtractor.ts"; +import { makeHttpsFetch } from "../managedRuntime/HttpsFetch.ts"; import { abortable, type ManagedInstallProgress, MANAGED_RELEASE_ID_PATTERN, managedFsTry, managedIoError, - ManagedRuntimeError, + type ManagedRuntimeError, managedRuntimeError, type ManagedVersion, makeManagedRuntimeStore, @@ -36,20 +43,20 @@ import { } from "../managedRuntime/ManagedRuntimeStore.ts"; import { type DownloadFetch, downloadVerified } from "../managedRuntime/VerifiedDownload.ts"; import { + ANTIGRAVITY_DOWNLOAD_HOST, type AntigravityPlatformRelease, - type AntigravityReleaseAsset, - type AntigravityReleaseFile, antigravityReleaseId, } from "./AntigravityRelease.ts"; export interface AntigravityRuntimePaths { readonly executable: string; - readonly harness: string; } export interface AntigravityInstalledRuntime extends AntigravityRuntimePaths { readonly releaseId: string; readonly version: string; + /** `legacy`: Google's old ACP server, installed before the move to the CLI. It never runs. */ + readonly kind: "cli" | "legacy"; } export type AntigravityInstallProgress = ManagedInstallProgress; @@ -57,17 +64,28 @@ export type AntigravityInstallProgress = ManagedInstallProgress; /** The part of `fetch` the runtime uses; tests pass a stub. */ export type AntigravityFetch = DownloadFetch; +/** + * Downloads from Google's storage host only, on every redirect hop too, so + * a release can't be fetched from anywhere else whatever the server answers. + */ +export const makeAntigravityDownloadFetch = (): AntigravityFetch => + makeHttpsFetch({ publicAddressesOnly: true, allowedHosts: [ANTIGRAVITY_DOWNLOAD_HOST] }); + export interface AntigravityRuntimeOptions { /** Directory the runtime owns, e.g. `/tools/agy/`. */ readonly root: string; - readonly release: AntigravityPlatformRelease; /** - * Proves unpacked files work (the ACP `initialize` handshake). It must stop - * every process it starts before it returns: Windows cannot move a - * directory holding a running program. + * Proves an unpacked executable is `release` and works (the ACP + * `initialize` handshake). It must stop every process it starts before it + * returns: Windows cannot move a directory holding a running program. */ - readonly validate: (paths: AntigravityRuntimePaths) => Effect.Effect; + readonly validate: ( + paths: AntigravityRuntimePaths, + release: AntigravityPlatformRelease, + ) => Effect.Effect; readonly fetch?: AntigravityFetch; + /** Test seam: the system the files are made read-only for. */ + readonly platform?: NodeJS.Platform; /** Test seam: runs in `acquire` after the active version is resolved, before its lease is written. */ readonly beforeLeaseWritten?: (versionDir: string) => Effect.Effect; } @@ -76,16 +94,18 @@ export interface AntigravityRuntime { /** The active version, if it is complete on disk. Never fails. */ readonly installed: Effect.Effect; /** - * Installs and activates `options.release`, then prunes. A complete copy - * already on disk is validated again and reused. Interruptible until the - * final activation. + * Installs and activates `release`, then prunes. A complete copy already + * on disk is validated again and reused. Interruptible until the final + * activation. */ readonly install: ( + release: AntigravityPlatformRelease, onProgress?: (progress: AntigravityInstallProgress) => void, ) => Effect.Effect<{ readonly releaseId: string; readonly version: string }, ManagedRuntimeError>; /** * Leases the active version until the scope closes, so prune and remove - * leave it alone. Launch from the returned paths. + * leave it alone. Launch from the returned path. A legacy install is + * refused (`notInstalled`): it needs the update first. */ readonly acquire: Effect.Effect; /** @@ -98,26 +118,63 @@ export interface AntigravityRuntime { } const LABEL = "Antigravity"; -const ARCHIVE_FILE = "a.zip"; +const ARCHIVE_FILE = "a.download"; +const UNPACK_SCRATCH = "x"; +/** + * Caps for a release the feed lists without sizes, far above any real build + * (1.5.14: the largest download is 239 MB, the largest executable 273 MB). + */ +export const MAX_ANTIGRAVITY_DOWNLOAD_BYTES = 768 * 1024 ** 2; +export const MAX_ANTIGRAVITY_EXECUTABLE_BYTES = 1024 ** 3; +/** + * What the free-space check budgets for such a release: half again the + * largest 1.5.14 build. The caps above still stop anything bigger, and a disk + * that fills anyway fails the install cleanly. + */ +const ESTIMATED_DOWNLOAD_BYTES = 360 * 1024 ** 2; +const ESTIMATED_EXECUTABLE_BYTES = 420 * 1024 ** 2; const ReleaseId = Schema.String.check(Schema.isPattern(MANAGED_RELEASE_ID_PATTERN)); /** A flat file name: no separators, not `.` or `..`. */ const FlatFileName = Schema.String.check(Schema.isPattern(/^(?!\.\.?$)[\w.-]+$/u)); const ReleaseFileSchema = Schema.Struct({ name: FlatFileName, bytes: Schema.Int }); -const InstallMarker = Schema.Struct({ +const CliMarker = Schema.Struct({ + releaseId: ReleaseId, + version: Schema.String, + kind: Schema.Literal("cli"), + executable: ReleaseFileSchema, +}); +/** What an install of the old ACP server wrote. Read, never written. */ +const LegacyMarker = Schema.Struct({ releaseId: ReleaseId, version: Schema.String, executable: ReleaseFileSchema, harness: ReleaseFileSchema, }); -type InstallMarker = typeof InstallMarker.Type; -const InstallMarkerJson = Schema.fromJsonString(InstallMarker); -const decodeInstallMarker = Schema.decodeUnknownOption(InstallMarkerJson); -const encodeInstallMarker = Schema.encodeSync(InstallMarkerJson); +type CliMarker = typeof CliMarker.Type; +type InstallMarker = CliMarker | (typeof LegacyMarker.Type & { readonly kind: "legacy" }); +const decodeCliMarker = Schema.decodeUnknownOption(Schema.fromJsonString(CliMarker)); +const decodeLegacyMarker = Schema.decodeUnknownOption(Schema.fromJsonString(LegacyMarker)); +const encodeCliMarker = Schema.encodeSync(Schema.fromJsonString(CliMarker)); +const encodeLegacyMarker = Schema.encodeSync(Schema.fromJsonString(LegacyMarker)); + +const decodeInstallMarker = (raw: string): InstallMarker | undefined => { + const cli = decodeCliMarker(raw); + if (Option.isSome(cli)) return cli.value; + const legacy = decodeLegacyMarker(raw); + return Option.isSome(legacy) ? { ...legacy.value, kind: "legacy" } : undefined; +}; + +const encodeInstallMarker = (marker: InstallMarker): string => { + if (marker.kind === "cli") return encodeCliMarker(marker); + const { kind: _kind, ...legacy } = marker; + return encodeLegacyMarker(legacy); +}; const MESSAGES = { archive: "The Antigravity download wasn't in the expected format, so nothing was installed.", validate: "Antigravity was downloaded but didn't start correctly.", + legacy: "This Antigravity predates Google's CLI. Update it in Settings to keep using it.", } as const; const runtimeError = managedRuntimeError; @@ -129,155 +186,90 @@ export const unsupportedAntigravityPlatform = (platform: NodeJS.Platform, arch: const ioError = (action: string, cause: unknown) => managedIoError(LABEL, action, cause); const fsTry = (action: string, run: () => Promise) => managedFsTry(LABEL, action, run); -const pathsOf = (version: ManagedVersion): AntigravityRuntimePaths => ({ - executable: NodePath.join(version.dir, version.marker.executable.name), - harness: NodePath.join(version.dir, version.marker.harness.name), -}); - const installedRuntimeOf = ( version: ManagedVersion, ): AntigravityInstalledRuntime => ({ releaseId: version.releaseId, version: version.version, - ...pathsOf(version), + executable: NodePath.join(version.dir, version.marker.executable.name), + kind: version.marker.kind, }); -/** Both files are there with the sizes the marker recorded. */ -async function filesIntact(versionDir: string, marker: InstallMarker): Promise { - const [executableStat, harnessStat] = await Promise.all([ - statIfExists(NodePath.join(versionDir, marker.executable.name)), - statIfExists(NodePath.join(versionDir, marker.harness.name)), - ]); - return ( - executableStat?.isFile() === true && - executableStat.size === marker.executable.bytes && - harnessStat?.isFile() === true && - harnessStat.size === marker.harness.bytes - ); -} - -const S_IFMT = 0o170000; -const S_IFREG = 0o100000; -const DOS_DIRECTORY_ATTRIBUTE = 0x10; -const UNIX_HOSTS = new Set([3, 19]); +const fileIntact = async (path: string, bytes: number) => { + const stat = await statIfExists(path); + return stat?.isFile() === true && stat.size === bytes; +}; -/** Why a zip entry is not the expected regular file, or undefined when it is. */ -function entryProblem( - entry: yauzl.Entry, - file: AntigravityReleaseFile | undefined, -): string | undefined { - if (!file) return `unexpected entry "${entry.fileName}"`; - if (entry.isEncrypted()) return `${file.name} is encrypted`; - if (entry.compressionMethod !== 0 && entry.compressionMethod !== 8) { - return `${file.name} uses compression method ${entry.compressionMethod}`; - } - const unixMode = entry.externalFileAttributes >>> 16; - const notRegular = - (entry.externalFileAttributes & DOS_DIRECTORY_ATTRIBUTE) !== 0 || - (UNIX_HOSTS.has(entry.versionMadeBy >>> 8) && - unixMode !== 0 && - (unixMode & S_IFMT) !== S_IFREG); - if (notRegular) return `${file.name} is not a regular file`; - if (entry.uncompressedSize !== file.bytes) { - return `${file.name} is ${entry.uncompressedSize} bytes, expected ${file.bytes}`; +/** The files the marker names are there with the sizes it recorded. */ +async function filesIntact(versionDir: string, marker: InstallMarker): Promise { + const checks = [ + fileIntact(NodePath.join(versionDir, marker.executable.name), marker.executable.bytes), + ]; + if (marker.kind === "legacy") { + checks.push(fileIntact(NodePath.join(versionDir, marker.harness.name), marker.harness.bytes)); } - return undefined; + return (await Promise.all(checks)).every(Boolean); } /** - * Unpacks the two expected files into `outDir`. The archive must hold exactly - * those entries, by exact name, so nothing can land outside `outDir`. + * Unpacks the tarball's one executable to `target`. The archive must hold + * exactly one entry, a regular file named `name` within the size limit; + * the shared extractor refuses links and paths that leave its folder. */ -async function extractArchive(input: { +async function unpackTarball(input: { readonly archivePath: string; - readonly outDir: string; - readonly asset: AntigravityReleaseAsset; + readonly scratchDir: string; + readonly name: string; + readonly expectedBytes: number | undefined; + readonly target: string; readonly signal: AbortSignal; -}): Promise { +}): Promise { const malformed = (detail: string, cause?: unknown) => runtimeError("archive", MESSAGES.archive, cause === undefined ? { detail } : { detail, cause }); - const expected = new Map( - [input.asset.executable, input.asset.harness].map((file) => [file.name, file] as const), - ); - let zip: yauzl.ZipFile; + await NodeFS.mkdir(input.scratchDir, { mode: 0o700 }); try { - zip = await yauzl.openPromise(input.archivePath, { - autoClose: false, - lazyEntries: true, - strictFileNames: true, - validateEntrySizes: true, + await extractArchive({ + archivePath: input.archivePath, + kind: "tar.gz", + outDir: input.scratchDir, + signal: input.signal, + limits: { maxBytes: input.expectedBytes ?? MAX_ANTIGRAVITY_EXECUTABLE_BYTES, maxEntries: 1 }, }); } catch (cause) { - throw malformed("not a readable zip", cause); + if (cause instanceof ArchiveError) throw malformed(cause.message, cause); + throw cause; } - try { - if (zip.entryCount !== expected.size) { - throw malformed(`${zip.entryCount} entries, expected ${expected.size}`); - } - const entries = new Map(); - try { - for await (const entry of zip.eachEntry()) { - const problem = entries.has(entry.fileName) - ? `duplicate entry "${entry.fileName}"` - : entryProblem(entry, expected.get(entry.fileName)); - if (problem) throw malformed(problem); - entries.set(entry.fileName, entry); - } - } catch (cause) { - if (cause instanceof ManagedRuntimeError) throw cause; - throw malformed("unreadable entry list", cause); - } - for (const file of expected.values()) { - const entry = entries.get(file.name); - if (!entry) throw malformed(`missing ${file.name}`); - const target = NodePath.join(input.outDir, file.name); - const source = await zip.openReadStreamPromise(entry).catch((cause: unknown) => { - throw malformed(`unreadable ${file.name}`, cause); - }); - await pipeline( - source, - async function* (chunks: AsyncIterable) { - try { - for await (const chunk of chunks) yield chunk; - } catch (cause) { - throw malformed(`corrupt ${file.name}`, cause); - } - }, - createWriteStream(target, { flags: "wx", mode: 0o700 }), - { signal: input.signal }, - ); - if (process.platform !== "win32") await NodeFS.chmod(target, 0o755); - const written = await NodeFS.stat(target); - if (written.size !== file.bytes) { - throw malformed(`${file.name} unpacked to ${written.size} bytes, expected ${file.bytes}`); - } - } - } finally { - zip.close(); + const entries = await NodeFS.readdir(input.scratchDir); + if (entries.length !== 1 || entries[0] !== input.name) { + throw malformed(`holds ${entries.join(", ") || "nothing"}, expected ${input.name}`); + } + const unpacked = NodePath.join(input.scratchDir, input.name); + const stat = await NodeFS.lstat(unpacked); + if (!stat.isFile()) throw malformed(`${input.name} is not a regular file`); + if (stat.size === 0) throw malformed(`${input.name} is empty`); + if (input.expectedBytes !== undefined && stat.size !== input.expectedBytes) { + throw malformed(`${input.name} is ${stat.size} bytes, expected ${input.expectedBytes}`); } + await NodeFS.rename(unpacked, input.target); + return stat.size; } -/** Builds the runtime for one root and release. Cheap; holds no resources. */ +/** Builds the runtime for one root. Cheap; holds no resources. */ export function makeAntigravityRuntime( options: AntigravityRuntimeOptions, ): AntigravityRuntime { - const { release } = options; - const { asset } = release; - const fetchArchive: AntigravityFetch = options.fetch ?? ((url, init) => fetch(url, init)); - const releaseId = antigravityReleaseId(asset); + const fetchArchive: AntigravityFetch = options.fetch ?? makeAntigravityDownloadFetch(); + const platform = options.platform ?? process.platform; const store = makeManagedRuntimeStore({ root: options.root, label: LABEL, - marker: { - decode: (raw) => Option.getOrUndefined(decodeInstallMarker(raw)), - encode: encodeInstallMarker, - }, + marker: { decode: decodeInstallMarker, encode: encodeInstallMarker }, intact: filesIntact, ...(options.beforeLeaseWritten ? { beforeLeaseWritten: options.beforeLeaseWritten } : {}), }); - const validatePaths = (paths: AntigravityRuntimePaths) => - options.validate(paths).pipe( + const validatePaths = (paths: AntigravityRuntimePaths, release: AntigravityPlatformRelease) => + options.validate(paths, release).pipe( Effect.mapError((cause) => runtimeError("validate", MESSAGES.validate, { detail: cause instanceof Error ? cause.message : String(cause), @@ -286,50 +278,90 @@ export function makeAntigravityRuntime( ), ); - /** Downloads the zip into the staging folder and unpacks its two files. */ + /** Downloads into the staging folder and puts the executable in place. */ const build = - (report: (progress: AntigravityInstallProgress) => void) => + (release: AntigravityPlatformRelease, report: (progress: AntigravityInstallProgress) => void) => (staging: { readonly dir: string; readonly unpackDir: string }) => Effect.gen(function* () { + const { asset } = release; const archivePath = NodePath.join(staging.dir, ARCHIVE_FILE); + const totalBytes = asset.archiveBytes; - report({ phase: "downloading", receivedBytes: 0, totalBytes: asset.archiveBytes }); - let reportedPercent = 0; - yield* abortable( + report({ phase: "downloading", receivedBytes: 0, ...(totalBytes ? { totalBytes } : {}) }); + let reported = 0; + const receivedBytes = yield* abortable( (signal) => downloadVerified({ fetch: fetchArchive, label: LABEL, url: asset.url, - sha256: asset.sha256, - bytes: asset.archiveBytes, + sha512: asset.sha512, + ...(asset.archiveBytes !== undefined + ? { bytes: asset.archiveBytes } + : { maxBytes: MAX_ANTIGRAVITY_DOWNLOAD_BYTES }), destination: archivePath, signal, - onReceived: (receivedBytes) => { - const percent = Math.floor((receivedBytes * 100) / asset.archiveBytes); - if (percent === reportedPercent) return; - reportedPercent = percent; - report({ phase: "downloading", receivedBytes, totalBytes: asset.archiveBytes }); + onReceived: (received) => { + // A percent when the size is known, else every 4 MB. + const step = totalBytes + ? Math.floor((received * 100) / totalBytes) + : Math.floor(received / (4 * 1024 ** 2)); + if (step === reported) return; + reported = step; + report({ + phase: "downloading", + receivedBytes: received, + ...(totalBytes ? { totalBytes } : {}), + }); }, }), (cause) => ioError("save the Antigravity download", cause), ); report({ phase: "extracting" }); - yield* abortable( - (signal) => extractArchive({ archivePath, outDir: staging.unpackDir, asset, signal }), - (cause) => ioError("save Antigravity's files", cause), - ); - yield* fsTry("save Antigravity's files", () => NodeFS.rm(archivePath, { force: true })); + const target = NodePath.join(staging.unpackDir, asset.executable.name); + const executableBytes = + asset.format === "exe" + ? yield* fsTry("save Antigravity's files", async () => { + await NodeFS.rename(archivePath, target); + return receivedBytes; + }) + : yield* abortable( + (signal) => + unpackTarball({ + archivePath, + scratchDir: NodePath.join(staging.dir, UNPACK_SCRATCH), + name: asset.executable.name, + expectedBytes: asset.executable.bytes, + target, + signal, + }), + (cause) => ioError("save Antigravity's files", cause), + ); + if (asset.format === "exe" && asset.executable.bytes !== undefined) { + // The download's size was checked already; this names it as the executable's. + if (executableBytes !== asset.executable.bytes) { + return yield* runtimeError("archive", MESSAGES.archive, { + detail: `${asset.executable.name} is ${executableBytes} bytes, expected ${asset.executable.bytes}`, + }); + } + } + yield* fsTry("save Antigravity's files", async () => { + await NodeFS.rm(archivePath, { force: true }); + // Read-only, so the CLI can't replace itself. Windows keeps the + // default: a read-only file there can't be deleted by a prune. + if (platform !== "win32") await NodeFS.chmod(target, 0o555); + }); return { - releaseId, + releaseId: antigravityReleaseId(asset), version: release.version, - executable: { name: asset.executable.name, bytes: asset.executable.bytes }, - harness: { name: asset.harness.name, bytes: asset.harness.bytes }, - }; + kind: "cli" as const, + executable: { name: asset.executable.name, bytes: executableBytes }, + } satisfies CliMarker; }); - const install: AntigravityRuntime["install"] = (onProgress) => { + const install: AntigravityRuntime["install"] = (release, onProgress) => { + const { asset } = release; const report = (progress: AntigravityInstallProgress) => { try { onProgress?.(progress); @@ -337,12 +369,18 @@ export function makeAntigravityRuntime( // Progress reporting never fails an install. } }; + const downloadBytes = asset.archiveBytes ?? ESTIMATED_DOWNLOAD_BYTES; + // A tarball sits beside what it unpacks to; the Windows download is the executable. + const neededBytes = + asset.format === "exe" + ? downloadBytes + : downloadBytes + (asset.executable.bytes ?? ESTIMATED_EXECUTABLE_BYTES); return store.install({ - releaseId, + releaseId: antigravityReleaseId(asset), version: release.version, - neededBytes: asset.archiveBytes + asset.executable.bytes + asset.harness.bytes, - build: build(report), - validate: (version) => validatePaths(pathsOf(version)), + neededBytes, + build: build(release, report), + validate: (version) => validatePaths(installedRuntimeOf(version), release), onPhase: (phase) => report({ phase }), }); }; @@ -352,7 +390,13 @@ export function makeAntigravityRuntime( Effect.map((version) => (version ? installedRuntimeOf(version) : undefined)), ), install, - acquire: store.acquire.pipe(Effect.map(installedRuntimeOf)), + acquire: store.acquire.pipe( + Effect.flatMap((version) => + version.marker.kind === "legacy" + ? Effect.fail(runtimeError("notInstalled", MESSAGES.legacy)) + : Effect.succeed(installedRuntimeOf(version)), + ), + ), prune: store.prune, remove: store.remove, }; diff --git a/apps/server/src/provider/antigravity/AntigravitySessionLog.ts b/apps/server/src/provider/antigravity/AntigravitySessionLog.ts new file mode 100644 index 000000000..d85f7b950 --- /dev/null +++ b/apps/server/src/provider/antigravity/AntigravitySessionLog.ts @@ -0,0 +1,231 @@ +// @effect-diagnostics nodeBuiltinImport:off -- node:sqlite and lstat read the agent's own session log. +/** + * Reads the error that ended an Antigravity turn from the agent's own session + * log. THIS READS A PRIVATE FORMAT: Google documents none of it, and a CLI + * update can change it without notice. With `AntigravityChildRecords` (its + * subagents' records) it is where Threadlines reads the CLI's session files, + * and only for what ACP gives no word of. + * + * `agy acp` reports an upstream failure (a 5xx, an exhausted quota, a history + * the model refuses) as a chat message and a normal `end_turn`. The CLI keeps + * each conversation in `/antigravity-acp/conversations/.db`, an + * SQLite file whose `steps` table holds one row per step: `step_type` 17 is + * an error (its payload starts with the API's error text), 15 a model reply. + * The read looks only at steps the current turn added, opens the file + * read-only, and refuses a path that is a link or anything but a plain file + * inside the profile Threadlines made. + * + * What this can't rule out, and accepts: SQLite opens the database by its + * path, on its own, so a folder swapped and swapped back within that one + * open isn't seen (the file is held open meanwhile and checked again after, + * which catches a swap that stays). Folder listings (`AntigravityChildRecords`) + * read names by path the same way; every file named is then opened through + * `openAntigravityProfileFile`, so a swapped listing yields only names. Both + * need write access to the agent's own profile and a swap timed inside one + * open. The worst result is one wrong failure reading: a turn failed with + * words read from another SQLite file. + * + * Layout as of `agy` 1.5.14, matching T3 Code's reader + * (apps/server/src/provider/acp/AntigravityTurnOutcome.ts). + * + * @module provider/antigravity/AntigravitySessionLog + */ +import * as NodeFSP from "node:fs/promises"; +import * as NodePath from "node:path"; +import { DatabaseSync } from "node:sqlite"; + +import * as Effect from "effect/Effect"; + +import { openRegularFile } from "./AntigravityFileReads.ts"; +import { ANTIGRAVITY_APP_DATA_DIR } from "./AntigravityRelease.ts"; + +/** CORTEX_STEP_TYPE_ERROR_MESSAGE. */ +const ERROR_STEP_TYPE = 17; +/** CORTEX_STEP_TYPE_PLANNER_RESPONSE: the model answered within the turn. */ +const MODEL_REPLY_STEP_TYPE = 15; +/** The error text leads the payload; a stack trace follows it. */ +const MAX_ERROR_PAYLOAD_BYTES = 16_384; +/** A conversation id as the CLI names its files: nothing that walks a path. */ +const SESSION_ID = /^[\w-]{1,128}$/u; + +/** How a turn's steps ended, as far as the log says. */ +export interface AntigravityTurnSteps { + /** The error text when the turn's last step is an error. */ + readonly errorText: string | undefined; + /** The model answered at least once in the turn. */ + readonly reachedModel: boolean; +} + +/** + * An entry of the CLI's own data in the profile (`antigravity-acp/...`), when + * every step of its path exists with the expected type and none is a link, + * with its size. Otherwise `missing` (nothing there) or `refused` (a link, + * or not the expected type): a reader must not take a refused entry for an + * empty one. A link could point at another session's records, or out of + * the profile. Shared by every reader of the CLI's private files (this one + * and `AntigravityChildRecords`). + */ +export async function antigravityProfileEntry( + profileDir: string, + segments: ReadonlyArray, + kind: "file" | "directory", +): Promise<{ readonly path: string; readonly size: number } | "missing" | "refused"> { + return profileEntry(profileDir, segments, kind); +} + +/** The entry, or whether it is missing or not what the layout says (a link, another type). */ +async function profileEntry( + profileDir: string, + segments: ReadonlyArray, + kind: "file" | "directory", +): Promise<{ readonly path: string; readonly size: number } | "missing" | "refused"> { + const root = await NodeFSP.realpath(profileDir).catch(() => undefined); + if (root === undefined) return "missing"; + let current = root; + let size = 0; + const path = [ANTIGRAVITY_APP_DATA_DIR, ...segments]; + for (const [index, segment] of path.entries()) { + current = NodePath.join(current, segment); + const info = await NodeFSP.lstat(current).catch(() => undefined); + const last = index === path.length - 1; + if (info === undefined) return "missing"; + if (info.isSymbolicLink()) return "refused"; + if (last && kind === "file" ? !info.isFile() : !info.isDirectory()) return "refused"; + size = info.size; + } + return { path: current, size }; +} + +/** A file of the CLI's, open, and proven to be the one at its place in the profile. */ +export interface AntigravityProfileFile { + readonly path: string; + readonly handle: NodeFSP.FileHandle; + readonly size: number; + /** Whether the file at `path` is still the one this holds (nothing swapped since). */ + readonly stillHeld: () => Promise; +} + +/** + * Opens a file of the CLI's data in the profile (`antigravity-acp/...`). The + * path is checked step by step first (no links, the expected types), then + * opened without following a link or blocking, and then checked again from + * the handle: the path must still resolve to itself inside the profile, and + * the file held must be the one at that path now. A directory on the way + * that was swapped for a link between the check and the open would + * otherwise hand over a file from anywhere. `missing` when there is no such + * file; `refused` for anything else that isn't it. Close the handle. + */ +export async function openAntigravityProfileFile( + profileDir: string, + segments: ReadonlyArray, + /** Runs between the path check and the open: tests swap a folder here. */ + beforeOpen?: () => Promise, +): Promise { + const entry = await profileEntry(profileDir, segments, "file"); + if (typeof entry === "string") return entry; + await beforeOpen?.(); + const opened = await openRegularFile(entry.path, { followLink: false }); + if (opened === undefined) return "refused"; + const held = await opened.handle.stat().catch(() => undefined); + const stillHeld = async () => { + const [real, now] = await Promise.all([ + NodeFSP.realpath(entry.path).catch(() => undefined), + NodeFSP.lstat(entry.path).catch(() => undefined), + ]); + // `entry.path` is built on the profile's real path, so resolving to + // itself means it is inside the profile with no link anywhere on it. + return ( + held !== undefined && + real === entry.path && + now !== undefined && + now.dev === held.dev && + now.ino === held.ino + ); + }; + if (!(await stillHeld())) { + await opened.handle.close(); + return "refused"; + } + return { path: entry.path, handle: opened.handle, size: opened.size, stillHeld }; +} + +/** + * Reads the session's log, holding the file open meanwhile and confirming + * afterwards that SQLite read the file that was checked (it opens the path + * itself). `missing` when there is no log yet, `refused` when the file + * can't be trusted; `read` gets `undefined` for a log with no steps yet. + */ +async function withSessionLog( + profileDir: string, + sessionId: string, + read: (database: DatabaseSync) => A, +): Promise<{ readonly value: A | undefined } | "missing" | "refused"> { + const file = await openAntigravityProfileFile(profileDir, ["conversations", `${sessionId}.db`]); + if (typeof file === "string") return file; + try { + const value = readLog(file.path, read); + return (await file.stillHeld()) ? { value } : "refused"; + } finally { + await file.handle.close(); + } +} + +function readLog(file: string, read: (database: DatabaseSync) => A): A | undefined { + const database = new DatabaseSync(file, { readOnly: true }); + try { + database.exec("PRAGMA busy_timeout = 100"); + const hasSteps = + database + .prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'steps'") + .get() !== undefined; + return hasSteps ? read(database) : undefined; + } finally { + database.close(); + } +} + +/** + * Where the session's log stands before a prompt goes out: the index of its + * last step (-1 for a log not written yet), or `undefined` when it can't be + * read and the turn's end can't be told from it. + */ +export const antigravityLogPosition = (profileDir: string, sessionId: string) => + Effect.tryPromise(async () => { + if (!SESSION_ID.test(sessionId)) return undefined; + const index = await withSessionLog(profileDir, sessionId, (database) => { + const value = database.prepare("SELECT max(idx) AS idx FROM steps").get()?.idx; + return typeof value === "number" ? value : -1; + }); + if (index === "missing") return -1; + return index === "refused" ? undefined : (index.value ?? -1); + }).pipe(Effect.orElseSucceed(() => undefined)); + +/** How the steps after `afterIndex` ended; `undefined` when the log can't be read. */ +export const antigravityTurnSteps = (profileDir: string, sessionId: string, afterIndex: number) => + Effect.tryPromise(async (): Promise => { + if (!SESSION_ID.test(sessionId)) return undefined; + const steps = await withSessionLog(profileDir, sessionId, (database) => { + const last = database + .prepare( + `SELECT step_type AS type, substr(step_payload, 1, ?) AS payload + FROM steps WHERE idx > ? ORDER BY idx DESC LIMIT 1`, + ) + .get(MAX_ERROR_PAYLOAD_BYTES, afterIndex); + if (typeof last?.type !== "number") return { errorText: undefined, reachedModel: false }; + const reachedModel = + database + .prepare("SELECT 1 FROM steps WHERE idx > ? AND step_type = ? LIMIT 1") + .get(afterIndex, MODEL_REPLY_STEP_TYPE) !== undefined; + const payload = last.payload; + const errorText = + last.type === ERROR_STEP_TYPE + ? payload instanceof Uint8Array + ? new TextDecoder().decode(payload) + : typeof payload === "string" + ? payload + : "" + : undefined; + return { errorText, reachedModel }; + }); + return typeof steps === "string" ? undefined : steps.value; + }).pipe(Effect.orElseSucceed(() => undefined)); diff --git a/apps/server/src/provider/antigravity/AntigravitySignInMethod.test.ts b/apps/server/src/provider/antigravity/AntigravitySignInMethod.test.ts index 321fe96c6..44570f526 100644 --- a/apps/server/src/provider/antigravity/AntigravitySignInMethod.test.ts +++ b/apps/server/src/provider/antigravity/AntigravitySignInMethod.test.ts @@ -3,11 +3,15 @@ import * as fs from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { assert, describe, expect, it } from "@effect/vitest"; +import { assert, describe, it } from "@effect/vitest"; import * as Effect from "effect/Effect"; import { FetchHttpClient } from "effect/http"; -import { antigravityEnvironment } from "./AntigravityProfile.ts"; +import { + antigravityEnvironment, + readAntigravityCatalog, + writeAntigravityCatalog, +} from "./AntigravityProfile.ts"; import { antigravityAdcPath, antigravityCredentialEnvironment, @@ -15,7 +19,6 @@ import { antigravitySignInStatus, type AntigravitySignInConfig, checkGeminiApiKey, - classifyAntigravityGoogleToken, mergeAntigravityProfileSettings, resolveAntigravityAdc, } from "./AntigravitySignInMethod.ts"; @@ -90,6 +93,15 @@ describe("antigravity process environment", () => { assert.equal(vertexKey.GOOGLE_API_KEY, "vertex-key"); }); + it("keeps the sign-in in the profile's own file and stops the CLI updating itself", () => { + const value = env(config({})); + // What the CLI takes for SSH: a Google sign-in then lives in the + // profile, never in the OS keyring the user's own `agy` shares. + assert.equal(value.SSH_CONNECTION, "127.0.0.1 0 127.0.0.1 0"); + assert.equal(value.AGY_CLI_DISABLE_AUTO_UPDATE, "1"); + assert.equal(value.GEMINI_HOME, "/state/profile"); + }); + it("passes the computer's Google Cloud sign-in only to keyless Vertex AI", () => { const vertex = env(config({ method: "agent-platform", project: "p", location: "l" })); assert.deepEqual(google(vertex).sort(), ["CLOUDSDK_CONFIG", "GOOGLE_APPLICATION_CREDENTIALS"]); @@ -186,39 +198,6 @@ describe("Application Default Credentials", () => { ); }); -describe("classifyAntigravityGoogleToken", () => { - it("tells a Google account sign-in from a Gemini Enterprise one by the token alone", () => { - // Field shapes of the agent's acp_token.json (values made up). - const token = { - client_secret: "x", - refresh_token: "x", - token_uri: "https://oauth2.googleapis.com/token", - }; - expect( - classifyAntigravityGoogleToken({ - ...token, - client_id: "1071006060591-tmhssin2h21lcre235vtolojh4g403ep.apps.googleusercontent.com", - }), - ).toBe("oauth-personal"); - expect( - classifyAntigravityGoogleToken({ - ...token, - client_id: "884354919052-36trc1jjb3tguiac32ov6cod268c5blh.apps.googleusercontent.com", - }), - ).toBe("oauth-business"); - // An unknown client: only a Google account asks for Code Assist. - expect( - classifyAntigravityGoogleToken({ - ...token, - client_id: "other", - scopes: ["https://www.googleapis.com/auth/cloud-platform"], - }), - ).toBe("oauth-business"); - expect(classifyAntigravityGoogleToken({})).toBeUndefined(); - expect(classifyAntigravityGoogleToken(null)).toBeUndefined(); - }); -}); - describe("antigravitySignInStatus", () => { const status = ( signIn: Partial, @@ -267,6 +246,20 @@ describe("antigravitySignInStatus", () => { assert.equal(status({ method: "gemini-api-key" }).auth.type, "gemini-api-key"); }); + it("asks once to sign in again when only the old server's sign-in is there", () => { + for (const method of ["oauth-personal", "oauth-business"] as const) { + const result = status( + { method, project: "acme", location: "global" }, + { legacySignIn: true }, + ); + assert.equal(result.auth.status, "unauthenticated"); + assert.equal( + result.message, + "Antigravity now runs on Google's CLI. Sign in again to keep using it.", + ); + } + }); + it("labels a working sign-in without needing an email, and never shows more than four characters of a key", () => { assert.equal(status({}, { signedIn: true }).auth.label, "Google account"); assert.equal( @@ -336,3 +329,24 @@ describe("checkGeminiApiKey", () => { }), ); }); + +describe("readAntigravityCatalog", () => { + it.live("drops a model list another sign-in or agent version saved", () => + Effect.gen(function* () { + const dir = yield* Effect.promise(() => fs.mkdtemp(join(tmpdir(), "agy-catalog-"))); + const choices = [{ value: "gemini-4-neon", name: "Gemini 4 Neon" }]; + const sign = { fingerprint: "fp-a", isGoogleAccount: true, agentVersion: "1.5.2" }; + yield* writeAntigravityCatalog(dir, { choices, fingerprint: "fp-a", agentVersion: "1.5.2" }); + assert.deepEqual((yield* readAntigravityCatalog(dir, sign))?.choices, choices); + assert.isUndefined(yield* readAntigravityCatalog(dir, { ...sign, fingerprint: "fp-b" })); + assert.isUndefined(yield* readAntigravityCatalog(dir, { ...sign, agentVersion: "1.6.0" })); + + // A list saved before versions were recorded came from an older agent. + yield* Effect.promise(() => + fs.writeFile(join(dir, "threadlines-models.json"), JSON.stringify({ choices })), + ); + assert.isUndefined(yield* readAntigravityCatalog(dir, sign)); + yield* Effect.promise(() => fs.rm(dir, { recursive: true, force: true })); + }), + ); +}); diff --git a/apps/server/src/provider/antigravity/AntigravitySignInMethod.ts b/apps/server/src/provider/antigravity/AntigravitySignInMethod.ts index c8014a2ea..95e871fd0 100644 --- a/apps/server/src/provider/antigravity/AntigravitySignInMethod.ts +++ b/apps/server/src/provider/antigravity/AntigravitySignInMethod.ts @@ -18,11 +18,13 @@ * - What a check found (a key Google rejected) is kept per credential, so a * new key starts fresh and an old verdict never sticks to it. * - * Verified against Antigravity 1.3.0: the agent picks the method from the - * settings file at start, `authenticate` with a key method never tests the - * key, and a keyless Vertex AI session opens without ADC (the first prompt - * fails). So a key or ADC is only proven by a request; status says - * "configured" until a check passes. + * - A Google sign-in is the CLI's token file in the profile, and the method + * it was made with, which Threadlines records itself: the file doesn't say. + * + * Verified against Antigravity's ACP server 1.3.0, and assumed of the CLI + * (1.5.14) until a signed-in check says otherwise: the agent picks the method + * from the settings file at start, and a key is only proven by a request. + * So status says "configured" until a check passes. * * @module provider/antigravity/AntigravitySignInMethod */ @@ -44,7 +46,7 @@ import { import * as Effect from "effect/Effect"; import { checkApiKeyWithModelList } from "../apiKeyCheck.ts"; -import { antigravityAgentDir, antigravityTokenPath } from "./AntigravityProfile.ts"; +import { antigravityAgentDir, readAntigravitySavedSignIn } from "./AntigravityProfile.ts"; import { ProviderSetupError } from "../Errors.ts"; export interface AntigravitySignInConfig { @@ -308,40 +310,71 @@ export const writeAntigravitySignInCheck = (profileDir: string, check: Antigravi // ── Which Google sign-in the profile holds ────────────────────────── -/** The OAuth clients Antigravity 1.3.0 signs in with, per method. */ -const GOOGLE_ACCOUNT_CLIENT_ID = - "1071006060591-tmhssin2h21lcre235vtolojh4g403ep.apps.googleusercontent.com"; -const GEMINI_ENTERPRISE_CLIENT_ID = - "884354919052-36trc1jjb3tguiac32ov6cod268c5blh.apps.googleusercontent.com"; -/** Gemini Code Assist's scope: only a Google account sign-in asks for it. */ -const CODE_ASSIST_SCOPE = "https://www.googleapis.com/auth/aicode"; +const googleSignInRecordPath = (profileDir: string) => + join(profileDir, "threadlines-google-sign-in.json"); + +type GoogleMethod = "oauth-personal" | "oauth-business"; + +/** Records which Google method the profile's sign-in was made with. */ +export const writeAntigravityGoogleSignIn = (profileDir: string, method: GoogleMethod) => + Effect.tryPromise(async () => { + await fs.mkdir(profileDir, { recursive: true, mode: 0o700 }); + await writePrivateFileAtomically( + googleSignInRecordPath(profileDir), + JSON.stringify({ method }), + ); + }).pipe(Effect.ignore); /** - * Which Google method a saved token belongs to. Google account and Gemini - * Enterprise share one token file; the token names the OAuth client that - * issued it, and only a Google account's carries the Code Assist scope. + * Forgets the profile's Google sign-in: the CLI's token file, the old + * server's, and the record. Only files in this profile are touched, never + * the OS keyring, so the user's own `agy` stays signed in. */ -export function classifyAntigravityGoogleToken( - token: unknown, -): "oauth-personal" | "oauth-business" | undefined { - if (!isRecord(token) || Object.keys(token).length === 0) return undefined; - if (token.client_id === GOOGLE_ACCOUNT_CLIENT_ID) return "oauth-personal"; - if (token.client_id === GEMINI_ENTERPRISE_CLIENT_ID) return "oauth-business"; - if (!Array.isArray(token.scopes)) return "oauth-personal"; - // Exact scope names, never a substring of one. - const codeAssist = token.scopes.some((scope: unknown) => scope === CODE_ASSIST_SCOPE); - return codeAssist ? "oauth-personal" : "oauth-business"; +export const removeAntigravityGoogleSignIn = (profileDir: string) => + Effect.tryPromise({ + try: async () => { + for (const path of [ + join(antigravityAgentDir(profileDir), "antigravity-oauth-token"), + join(antigravityAgentDir(profileDir), "acp_token.json"), + googleSignInRecordPath(profileDir), + ]) { + await fs.rm(path, { force: true }); + } + }, + catch: (cause) => + new ProviderSetupError({ + detail: `Couldn't remove Antigravity's sign-in: ${String(cause)}`, + cause, + }), + }); + +export interface AntigravityGoogleSignIn { + /** The Google method the CLI's saved sign-in was made with; undefined when it holds none. */ + readonly method: GoogleMethod | undefined; + /** Only the old ACP server's sign-in is there, which the CLI doesn't read. */ + readonly legacyOnly: boolean; } -/** The Google method the profile's saved sign-in belongs to, or `undefined` when it holds none. */ +/** The profile's Google sign-in, as the status shows it. */ export const readAntigravityGoogleSignIn = (profileDir: string) => - Effect.promise(async () => { - const raw = await fs.readFile(antigravityTokenPath(profileDir), "utf8").catch(() => ""); - try { - return classifyAntigravityGoogleToken(JSON.parse(raw)); - } catch { - return undefined; - } + Effect.gen(function* () { + const saved = yield* readAntigravitySavedSignIn(profileDir); + const recorded = yield* Effect.promise(async () => { + const raw = await fs + .readFile(googleSignInRecordPath(profileDir), "utf8") + .catch(() => undefined); + try { + const method = + raw === undefined ? undefined : (JSON.parse(raw) as { method?: unknown }).method; + return method === "oauth-personal" || method === "oauth-business" ? method : undefined; + } catch { + return undefined; + } + }); + return { + method: saved.cli ? recorded : undefined, + legacyOnly: !saved.cli && saved.legacy, + } satisfies AntigravityGoogleSignIn; }); // ── Gemini API key check ───────────────────────────────────────────── @@ -388,12 +421,15 @@ export function antigravitySignInStatus(input: { readonly config: AntigravitySignInConfig; /** Whether the profile holds a Google sign-in made with this method (Google methods). */ readonly signedIn: boolean; + /** Only a sign-in from before the move to Google's CLI is there. */ + readonly legacySignIn?: boolean; readonly check: AntigravitySignInCheck | undefined; /** ADC as found for keyless Vertex AI. */ readonly adc: AntigravityAdcState | undefined; }): AntigravitySignInStatus { const { config, signedIn, check, adc } = input; const type = config.method; + const signInAgain = "Antigravity now runs on Google's CLI. Sign in again to keep using it."; const signedOut = (message: string, status: "warning" | "error" = "warning") => ({ status, auth: { status: "unauthenticated", type }, message }) as const; const signedInAs = (label: string, chat?: "verified" | "configured", detail?: string) => @@ -411,16 +447,20 @@ export function antigravitySignInStatus(input: { switch (config.method) { case "oauth-personal": - return signedIn - ? signedInAs("Google account") - : signedOut("Sign in with Google to use Antigravity."); + if (signedIn) return signedInAs("Google account"); + return signedOut( + input.legacySignIn ? signInAgain : "Sign in with Google to use Antigravity.", + ); case "oauth-business": if (antigravityMissingSetup(config)) { return signedOut("Add your Google Cloud project and location to use Gemini Enterprise."); } - return signedIn - ? signedInAs(`Gemini Enterprise · ${config.project}`) - : signedOut("Sign in with your work Google account to use Gemini Enterprise."); + if (signedIn) return signedInAs(`Gemini Enterprise · ${config.project}`); + return signedOut( + input.legacySignIn + ? signInAgain + : "Sign in with your work Google account to use Gemini Enterprise.", + ); case "gemini-api-key": { if (!config.key) return signedOut("Add a Gemini API key to use Antigravity."); if (check && !check.accepted) { diff --git a/apps/server/src/provider/antigravity/AntigravitySkills.test.ts b/apps/server/src/provider/antigravity/AntigravitySkills.test.ts new file mode 100644 index 000000000..710800bd2 --- /dev/null +++ b/apps/server/src/provider/antigravity/AntigravitySkills.test.ts @@ -0,0 +1,378 @@ +// @effect-diagnostics nodeBuiltinImport:off - builds fake homes and projects on disk +import * as NodeFS from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; + +import { afterEach, describe, expect, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; + +import { + listAntigravitySkillsNow as listInProfile, + makeAntigravitySkillsLister, + MAX_SKILL_DESCRIPTION_LENGTH, +} from "./AntigravitySkills.ts"; +import { shareAntigravityUserConfigNow } from "./AntigravityUserConfig.ts"; + +/** Lists as a status check does: the profile is prepared first, then read through. */ +async function listAntigravitySkillsNow(workspace: { + readonly cwd: string; + readonly userHome: string; + readonly profileDir: string; +}) { + await shareAntigravityUserConfigNow({ ...workspace, platform: "linux" }); + return listInProfile(workspace); +} + +const roots: Array = []; + +afterEach(async () => { + await Promise.all(roots.splice(0).map((root) => NodeFS.rm(root, { recursive: true }))); +}); + +async function makeWorkspace() { + const root = await NodeFS.realpath(await NodeFS.mkdtemp(path.join(os.tmpdir(), "agy-skills-"))); + roots.push(root); + const userHome = path.join(root, "home"); + const cwd = path.join(root, "repo", "app"); + await NodeFS.mkdir(path.join(root, "repo", ".git"), { recursive: true }); + await NodeFS.mkdir(cwd, { recursive: true }); + return { + root, + userHome, + cwd, + repo: path.join(root, "repo"), + gemini: path.join(userHome, ".gemini"), + profileDir: path.join(root, "profile"), + }; +} + +async function writeFile(file: string, content: string) { + await NodeFS.mkdir(path.dirname(file), { recursive: true }); + await NodeFS.writeFile(file, content); + return file; +} + +const writeSkill = (dir: string, name: string | undefined, description?: string) => + writeFile( + path.join(dir, "SKILL.md"), + `---\n${name === undefined ? "" : `name: ${name}\n`}${description ? `description: ${description}\n` : ""}---\n# Body\n`, + ); + +const writeJson = (file: string, value: unknown) => writeFile(file, JSON.stringify(value)); + +const names = (skills: ReadonlyArray<{ readonly name: string }>) => skills.map((s) => s.name); + +describe("listAntigravitySkillsNow", () => { + it("lists nothing when there is no ~/.gemini and no project skills", async () => { + const workspace = await makeWorkspace(); + expect(await listAntigravitySkillsNow(workspace)).toEqual({ skills: [], truncated: false }); + }); + + it("reads name, description, path and scope from each place the agent looks", async () => { + const w = await makeWorkspace(); + const review = await writeSkill( + path.join(w.gemini, "config", "skills", "review"), + "review", + "Review changes.", + ); + await writeSkill(path.join(w.cwd, ".gemini", "skills", "a"), "gemini-project"); + await writeSkill(path.join(w.gemini, "antigravity-cli", "skills", "b"), "cli-global"); + await writeSkill(path.join(w.cwd, ".agents", "skills", "c"), "agents-project"); + await writeSkill(path.join(w.cwd, ".agent", "skills", "d"), "legacy-project"); + // The agent never reads ~/.agents/skills on its own. + await writeSkill(path.join(w.userHome, ".agents", "skills", "e"), "home-agents"); + + const { skills } = await listAntigravitySkillsNow(w); + + expect(names(skills)).toEqual([ + "agents-project", + "cli-global", + "gemini-project", + "legacy-project", + "review", + ]); + expect(skills.find((skill) => skill.name === "review")).toEqual({ + name: "review", + description: "Review changes.", + path: review, + scope: "user", + enabled: true, + }); + expect(skills.find((skill) => skill.name === "agents-project")?.scope).toBe("project"); + }); + + it("keeps the first copy of a name in the agent's own order", async () => { + const w = await makeWorkspace(); + const order = [ + path.join(w.gemini, "config", "skills"), + path.join(w.cwd, ".gemini", "skills"), + path.join(w.gemini, "antigravity-cli", "skills"), + path.join(w.cwd, ".agents", "skills"), + path.join(w.cwd, ".agent", "skills"), + ]; + for (const [index, root] of order.entries()) { + await writeSkill(path.join(root, `copy-${index}`), "review", `Copy ${index}.`); + } + for (const root of order) { + const { skills } = await listAntigravitySkillsNow(w); + expect(skills).toHaveLength(1); + expect(path.dirname(path.dirname(skills[0]!.path))).toBe(root); + await NodeFS.rm(root, { recursive: true }); + } + }); + + it("treats a root with its own SKILL.md as one skill, names a nameless skill after its folder", async () => { + const w = await makeWorkspace(); + const root = path.join(w.cwd, ".agents", "skills"); + await writeSkill(root, "root-skill"); + await writeSkill(path.join(root, "child"), "child-skill"); + await writeSkill(path.join(w.gemini, "config", "skills", "nameless"), undefined, "No name."); + await writeFile( + path.join(w.gemini, "config", "skills", "broken", "SKILL.md"), + "---\nname: [x\n---\n", + ); + await writeFile( + path.join(w.gemini, "config", "skills", "plain", "SKILL.md"), + "no front matter", + ); + await writeSkill(path.join(w.gemini, "config", "skills", "deep", "nested"), "too-deep"); + + expect(names((await listAntigravitySkillsNow(w)).skills)).toEqual(["nameless", "root-skill"]); + }); + + it("follows skills.json: inherits, literal include_only and exclude, null lists, no ~ expansion", async () => { + const w = await makeWorkspace(); + const shared = path.join(w.userHome, ".agents", "skills"); + await writeSkill(path.join(shared, "yagni"), "yagni", "Keep it simple."); + await writeSkill(path.join(shared, "experimental-draft"), "experimental-draft"); + await writeSkill(path.join(shared, "dropped"), "dropped"); + await writeSkill(path.join(shared, "category", "nested"), "nested"); + const inherited = path.join(w.userHome, "inherited-skills"); + await writeSkill(path.join(inherited, "linter"), "linter"); + await writeSkill(path.join(inherited, "lint-draft"), "lint-draft"); + await writeSkill(path.join(inherited, "skipped"), "skipped"); + await writeSkill(path.join(w.userHome, "tilde-skills", "tilde"), "tilde"); + + const globalManifest = path.join(w.gemini, "config", "skills.json"); + const inheritedManifest = path.join(w.userHome, "shared-skills.json"); + await writeJson(inheritedManifest, { + // A loop back to the first manifest is read once. + inherits: [{ path: globalManifest }], + entries: [{ path: inherited }], + }); + await writeJson(globalManifest, { + inherits: [{ path: inheritedManifest, include_only: ["linter", "lint-.*"] }], + entries: [ + { path: shared, exclude: ["experimental-.*", "dropped"], include_only: null }, + { path: shared, include_only: ["category/nested"] }, + { path: "~/tilde-skills" }, + ], + }); + + expect(names((await listAntigravitySkillsNow(w)).skills)).toEqual([ + "experimental-draft", + "linter", + "nested", + "yagni", + ]); + }); + + it("reads project manifests up to the repository root, and only inside it", async () => { + const w = await makeWorkspace(); + await writeSkill(path.join(w.repo, "tools", "skills", "deploy"), "deploy"); + await writeSkill(path.join(w.repo, "tools", "skills", "internal"), "internal"); + await writeSkill(path.join(w.cwd, "local", "here"), "here"); + const outside = path.join(w.root, "outside"); + await writeSkill(path.join(outside, "escape"), "escape"); + await NodeFS.symlink(outside, path.join(w.repo, "linked-out")); + + await writeJson(path.join(w.cwd, ".agents", "skills.json"), { + entries: null, + inherits: [{ path: "../workspace-skills.json", include_only: null }], + }); + await writeJson(path.join(w.repo, "workspace-skills.json"), { + inherits: null, + entries: [ + { path: "tools/skills/deploy/SKILL.md", exclude: null }, + { path: "tools/skills/internal/SKILL.md", exclude: ["internal"] }, + ], + }); + // A parent's manifest counts; paths resolve against its own folder. + await writeJson(path.join(w.repo, ".agents", "skills.json"), { + entries: [ + { path: "app/local" }, + { path: outside }, + { path: "linked-out" }, + { path: "../outside" }, + ], + }); + // Above the repository root: not read. + await writeJson(path.join(w.root, ".agents", "skills.json"), { entries: [{ path: outside }] }); + + expect(names((await listAntigravitySkillsNow(w)).skills)).toEqual(["deploy", "here"]); + }); + + it("lists skills of plugins installed in the profile unless turned off", async () => { + const w = await makeWorkspace(); + const plugins = path.join(w.profileDir, "config", "plugins"); + await writeSkill(path.join(plugins, "demo", "skills", "demo-skill"), "demo-skill"); + await writeSkill(path.join(plugins, "off", "skills", "off-skill"), "off-skill"); + await writeJson(path.join(w.profileDir, "config", "config.json"), { + plugins: { off: { enabled: false } }, + }); + + expect(names((await listAntigravitySkillsNow(w)).skills)).toEqual(["demo-skill"]); + }); + + it("reads only front matter, skips one oversized file, and stops at the entry budget", async () => { + const w = await makeWorkspace(); + const skills = path.join(w.gemini, "config", "skills"); + // A long body costs nothing past the front matter. + for (let index = 0; index < 20; index += 1) { + await writeFile( + path.join(skills, `big-${index}`, "SKILL.md"), + `---\nname: big-${index}\n---\n${"x".repeat(900_000)}`, + ); + } + // Front matter that never closes within a skill's limit: that skill is skipped. + await writeFile(path.join(skills, "endless", "SKILL.md"), `---\n${"y".repeat(1_100_000)}`); + let listing = await listAntigravitySkillsNow(w); + expect(listing.skills).toHaveLength(20); + expect(listing.truncated).toBe(false); + + const crowded = path.join(w.cwd, ".agents", "skills"); + await NodeFS.mkdir(crowded, { recursive: true }); + await Promise.all( + Array.from({ length: 10_001 }, (_, index) => + NodeFS.writeFile(path.join(crowded, `f${index}`), ""), + ), + ); + listing = await listAntigravitySkillsNow(w); + expect(listing.truncated).toBe(true); + expect(listing.skills).toHaveLength(20); + }); + + it("charges every lookup, plugin and manifest entry to the budget", async () => { + const w = await makeWorkspace(); + await writeSkill(path.join(w.gemini, "config", "skills", "kept"), "kept"); + // Manifest entries that don't exist still cost a lookup each. + await writeJson(path.join(w.gemini, "config", "skills.json"), { + entries: Array.from({ length: 12_000 }, (_, index) => ({ path: `missing-${index}` })), + }); + const first = await listAntigravitySkillsNow(w); + expect(first.truncated).toBe(true); + expect(names(first.skills)).toEqual(["kept"]); + + await NodeFS.rm(path.join(w.gemini, "config", "skills.json")); + // Plugin names cost an entry each, even for plugins that are turned off. + const plugins = path.join(w.profileDir, "config", "plugins"); + await NodeFS.mkdir(plugins, { recursive: true }); + const off = Array.from({ length: 10_001 }, (_, index) => `p${index}`); + await Promise.all(off.map((name) => NodeFS.writeFile(path.join(plugins, name), ""))); + await writeJson(path.join(w.profileDir, "config", "config.json"), { + plugins: Object.fromEntries(off.map((name) => [name, { enabled: false }])), + }); + expect((await listAntigravitySkillsNow(w)).truncated).toBe(true); + }); + + it("stops at its deadline, and the lister then answers with the last complete list", async () => { + const w = await makeWorkspace(); + await writeSkill(path.join(w.gemini, "config", "skills", "review"), "review"); + await shareAntigravityUserConfigNow({ ...w, platform: "linux" }); + expect(await listInProfile(w, { timeLimitMs: -1 })).toEqual({ skills: [], truncated: true }); + + const list = makeAntigravitySkillsLister(); + expect(names(await Effect.runPromise(list(w)))).toEqual(["review"]); + const crowded = path.join(w.cwd, ".agents", "skills"); + await NodeFS.mkdir(crowded, { recursive: true }); + await Promise.all( + Array.from({ length: 10_001 }, (_, index) => + NodeFS.writeFile(path.join(crowded, `f${index}`), ""), + ), + ); + await writeSkill(path.join(w.gemini, "config", "skills", "later"), "later"); + // Cut short now: the last complete list stands in. + expect(names(await Effect.runPromise(list(w)))).toEqual(["review"]); + }); + + it("never lists or opens a project skill that leads outside the project", async () => { + const w = await makeWorkspace(); + const outside = path.join(w.root, "outside"); + await writeSkill(path.join(outside, "escape"), "escape"); + await writeSkill(path.join(outside, "whole-root", "inner"), "inner"); + await writeSkill(path.join(w.cwd, ".agents", "skills", "inside"), "inside"); + await NodeFS.symlink( + path.join(outside, "escape"), + path.join(w.cwd, ".agents", "skills", "escape"), + ); + await NodeFS.mkdir(path.join(w.cwd, ".gemini"), { recursive: true }); + await NodeFS.symlink(path.join(outside, "whole-root"), path.join(w.cwd, ".gemini", "skills")); + // A manifest folder inside the project with a linked child. + const listed = path.join(w.repo, "listed"); + await writeSkill(path.join(listed, "fine"), "fine"); + await NodeFS.symlink(path.join(outside, "escape"), path.join(listed, "linked")); + // Reading this one through the link would spend the whole budget. + const crowd = path.join(outside, "crowd"); + await NodeFS.mkdir(crowd); + await Promise.all( + Array.from({ length: 10_001 }, (_, index) => + NodeFS.writeFile(path.join(crowd, `f${index}`), ""), + ), + ); + await NodeFS.symlink(crowd, path.join(listed, "crowd")); + await writeJson(path.join(w.repo, ".agents", "skills.json"), { entries: [{ path: "listed" }] }); + + const listing = await listAntigravitySkillsNow(w); + expect(names(listing.skills)).toEqual(["fine", "inside"]); + expect(listing.truncated).toBe(false); + }); + + it("lists what the agent sees through its profile, not the user's folder beside it", async () => { + const w = await makeWorkspace(); + await writeSkill(path.join(w.gemini, "config", "skills", "deploy"), "deploy"); + // The agent's own skills folder in the profile, which sharing leaves alone. + await writeSkill(path.join(w.profileDir, "config", "skills", "local-review"), "local-review"); + expect(names((await listAntigravitySkillsNow(w)).skills)).toEqual(["local-review"]); + + // On Windows skills.json is a copy, so a path relative to it leads where + // the copy is, as it does for the agent. + const v = await makeWorkspace(); + await writeSkill(path.join(v.gemini, "shared", "sibling"), "sibling"); + await writeJson(path.join(v.gemini, "config", "skills.json"), { + entries: [{ path: "../shared" }], + }); + await shareAntigravityUserConfigNow({ ...v, platform: "win32" }); + expect(names((await listInProfile(v)).skills)).toEqual([]); + }); + + it("applies a manifest's filters to a skill folder named directly, as to its SKILL.md", async () => { + const w = await makeWorkspace(); + const tools = path.join(w.repo, "tools"); + await writeSkill(path.join(tools, "internal"), "internal"); + await writeSkill(path.join(tools, "public"), "public"); + await writeJson(path.join(w.cwd, ".agents", "skills.json"), { + entries: [ + { path: "../tools/internal", exclude: ["internal"] }, + { path: "../tools/public/SKILL.md", include_only: ["other"] }, + { path: "../tools/public", include_only: ["public"] }, + ], + }); + expect(names((await listAntigravitySkillsNow(w)).skills)).toEqual(["public"]); + }); + + it("caps descriptions without splitting a character, and leaves out absurd names", async () => { + const w = await makeWorkspace(); + const skills = path.join(w.gemini, "config", "skills"); + // An emoji straddles the cap: it is dropped whole. + const description = `${"d".repeat(MAX_SKILL_DESCRIPTION_LENGTH - 1)}\u{1F600}tail`; + await writeFile( + path.join(skills, "long", "SKILL.md"), + `---\nname: long\ndescription: "${description}"\n---\n`, + ); + await writeSkill(path.join(skills, "huge-name"), "n".repeat(300)); + + const { skills: listed } = await listAntigravitySkillsNow(w); + expect(names(listed)).toEqual(["long"]); + expect(listed[0]!.description).toBe("d".repeat(MAX_SKILL_DESCRIPTION_LENGTH - 1)); + }); +}); diff --git a/apps/server/src/provider/antigravity/AntigravitySkills.ts b/apps/server/src/provider/antigravity/AntigravitySkills.ts new file mode 100644 index 000000000..53188ac80 --- /dev/null +++ b/apps/server/src/provider/antigravity/AntigravitySkills.ts @@ -0,0 +1,519 @@ +/** + * AntigravitySkills — the skills Google's Antigravity CLI loads for a + * folder, read from disk the way the CLI finds them, for the provider + * snapshot's `skills`. + * + * Global skills are read through the instance's profile, which is what the + * agent sees: the user's own folders arrive there as links or copies + * (`AntigravityUserConfig`), and a folder the agent made in the profile + * counts as it does for the agent. Where the CLI looks, in the order that + * decides which copy of a name wins (T3 Code's native root order, checked + * against its tests): + * + * 1. `/config/skills` + * 2. `/.gemini/skills` + * 3. `/antigravity-cli/skills` + * 4. `/.agents/skills`, then the legacy `/.agent/skills` + * 5. Folders a manifest declares: the project's `.agents/skills.json` (and + * legacy `.agent/skills.json`) in every folder from the project up to its + * repository root, then `/config/skills.json`. A project + * manifest's paths resolve against the folder holding `.agents`, any + * other manifest's against its own folder. + * 6. Plugins installed in the profile + * + * A root holding a `SKILL.md` is one skill; otherwise each folder directly + * inside it is. Manifests follow the CLI's rules (changelog 1.4 to 1.5.2): + * `inherits` reads another manifest, `include_only` and `exclude` match + * names literally (no patterns), may be null, and apply to a named skill + * folder or `SKILL.md` alike, a nested item loads only when `include_only` + * names it (`category/my-skill`), and `~` is not expanded. + * + * Project files are untrusted, so nothing outside the project or its + * repository root is listed or even opened for a project: the CLI skips + * manifest entries that leave it, and a project skill folder linked from + * outside is not listed either (the agent may still load that one). + * + * Every directory entry, lookup and byte read is charged to a budget, and + * the scan stops at a deadline, so a huge or hostile tree can't stall a + * status check; past either it keeps what it found. + * + * @module provider/antigravity/AntigravitySkills + */ +import * as fs from "node:fs/promises"; +import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path"; + +import type { ServerProviderSkill } from "@threadlines/contracts"; +import { fromYaml } from "@threadlines/shared/schemaYaml"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; + +import { openRegularFile, readRegularFile } from "./AntigravityFileReads.ts"; + +const MAX_SKILL_BYTES = 1_000_000; +const MAX_SCAN_BYTES = 8_000_000; +const MAX_SCAN_ENTRIES = 10_000; +const MAX_INHERIT_DEPTH = 10; +const READ_CHUNK_BYTES = 4096; +/** A longer name is no name the CLI offers; it is left out rather than cut. */ +const MAX_NAME_LENGTH = 256; +/** What is kept of a description: it is sent to every client and searched (as registry agents). */ +export const MAX_SKILL_DESCRIPTION_LENGTH = 1024; +/** The longest a listing may run; past it the scan stops where it is. */ +const LIST_TIME_LIMIT = Duration.seconds(5); + +const SkillFrontMatter = fromYaml( + Schema.Struct({ + name: Schema.optional(Schema.NullOr(Schema.String)), + description: Schema.optional(Schema.NullOr(Schema.String)), + }), +); +const decodeFrontMatter = Schema.decodeUnknownOption(SkillFrontMatter); + +const NullableNames = Schema.optional(Schema.NullOr(Schema.Array(Schema.String))); +const ManifestEntry = Schema.Struct({ + path: Schema.String, + include_only: NullableNames, + exclude: NullableNames, +}); +type ManifestEntry = typeof ManifestEntry.Type; +const decodeManifest = Schema.decodeUnknownOption( + Schema.fromJsonString( + Schema.Struct({ + inherits: Schema.optional(Schema.NullOr(Schema.Array(ManifestEntry))), + entries: Schema.optional(Schema.NullOr(Schema.Array(ManifestEntry))), + }), + ), +); +const decodePluginSettings = Schema.decodeUnknownOption( + Schema.fromJsonString( + Schema.Struct({ + plugins: Schema.optional( + Schema.Record(Schema.String, Schema.Struct({ enabled: Schema.optional(Schema.Boolean) })), + ), + }), + ), +); + +type Scope = "user" | "project"; + +/** Whether a path may be opened; a project's scan only reaches inside the project. */ +type Confine = (path: string) => Promise; + +/** Names a manifest lets through: in every `include_only` list met on the way, in no `exclude`. */ +interface NameFilter { + readonly includeGroups: ReadonlyArray>; + readonly exclude: ReadonlyArray; +} + +const NO_FILTER: NameFilter = { includeGroups: [], exclude: [] }; + +const narrowFilter = (parent: NameFilter, entry: ManifestEntry): NameFilter => ({ + includeGroups: + entry.include_only && entry.include_only.length > 0 + ? [...parent.includeGroups, entry.include_only] + : parent.includeGroups, + exclude: entry.exclude ? [...parent.exclude, ...entry.exclude] : parent.exclude, +}); + +const passesFilter = (name: string, filter: NameFilter) => + filter.includeGroups.every((group) => group.includes(name)) && !filter.exclude.includes(name); + +/** The CLI orders a folder's children by their escaped URL path (Go's `URL.EscapedPath`). */ +const escapedPathKey = (name: string) => + encodeURI(name).replace( + /[!'()*?#]/gu, + (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`, + ); + +const byEscapedPath = (left: string, right: string) => { + const a = escapedPathKey(left); + const b = escapedPathKey(right); + return a < b ? -1 : a > b ? 1 : 0; +}; + +const isInside = (root: string, path: string) => { + const rel = relative(root, path); + return rel === "" || (!isAbsolute(rel) && rel !== ".." && !rel.startsWith(`..${sep}`)); +}; + +/** At most `max` UTF-16 units, never ending on half of a surrogate pair. */ +export function capText(text: string, max: number): string { + if (text.length <= max) return text; + const cut = text.slice(0, max); + const last = cut.charCodeAt(cut.length - 1); + return last >= 0xd800 && last <= 0xdbff ? cut.slice(0, -1) : cut; +} + +/** Front matter between the first two `---`, as the CLI finds them (text may come before). */ +function frontMatterOf(text: string): string | undefined { + const start = text.indexOf("---"); + if (start === -1) return undefined; + const end = text.indexOf("---", start + 3); + return end === -1 ? undefined : text.slice(start + 3, end).trim(); +} + +class SkillScan { + private remainingBytes = MAX_SCAN_BYTES; + private remainingEntries = MAX_SCAN_ENTRIES; + /** Set once the budget or the time runs out; the scan stops and keeps what it found. */ + exhausted = false; + readonly skills = new Map(); + + private readonly deadline: number; + + constructor(deadline: number) { + this.deadline = deadline; + } + + /** Charges `count` entries or lookups; false (and the scan over) when they don't fit. */ + private spend(count: number) { + if (this.exhausted || count > this.remainingEntries || Date.now() > this.deadline) { + this.exhausted = true; + return false; + } + this.remainingEntries -= count; + return true; + } + + private async stat(path: string) { + return this.spend(1) ? fs.stat(path).catch(() => undefined) : undefined; + } + + realpath(path: string) { + return this.spend(1) ? fs.realpath(path).catch(() => undefined) : Promise.resolve(undefined); + } + + /** A folder's names, read one entry at a time so a huge folder costs only the budget. */ + private async readDir(dir: string): Promise | undefined> { + if (!this.spend(1)) return undefined; + const handle = await fs.opendir(dir, { bufferSize: 32 }).catch(() => undefined); + if (!handle) return undefined; + const names: Array = []; + try { + for await (const entry of handle) { + if (!this.spend(1)) return undefined; + names.push(entry.name); + } + } catch { + return undefined; + } + return names; + } + + /** Reads a skill file up to the end of its front matter, within the budget. */ + private async readHead(path: string): Promise { + if (!this.spend(1)) return undefined; + const limit = Math.min(MAX_SKILL_BYTES, this.remainingBytes); + const opened = await openRegularFile(path, { followLink: true }); + if (!opened) return undefined; + try { + const chunks: Array = []; + let total = 0; + let markers = 0; + let dashes = 0; + while (total <= limit) { + const buffer = Buffer.alloc(READ_CHUNK_BYTES); + const { bytesRead } = await opened.handle.read(buffer, 0, READ_CHUNK_BYTES, total); + if (bytesRead === 0) break; + let end = bytesRead; + for (let index = 0; index < bytesRead && markers < 2; index += 1) { + dashes = buffer[index] === 0x2d ? dashes + 1 : 0; + if (dashes === 3) { + dashes = 0; + markers += 1; + if (markers === 2) end = index + 1; + } + } + chunks.push(buffer.subarray(0, end)); + total += end; + if (markers === 2) break; + } + this.remainingBytes -= Math.min(total, limit); + if (total > limit) { + // One oversized file is skipped; a spent budget ends the scan. + if (limit < MAX_SKILL_BYTES) this.exhausted = true; + return undefined; + } + return Buffer.concat(chunks).toString("utf8"); + } finally { + await opened.handle.close(); + } + } + + /** Reads a small JSON file (a manifest, plugin settings) within the budget. */ + async readSmall(path: string): Promise { + if (!this.spend(1)) return undefined; + const maxBytes = Math.min(MAX_SKILL_BYTES, this.remainingBytes); + const opened = await openRegularFile(path, { followLink: true }); + if (!opened) return undefined; + await opened.handle.close(); + if (opened.size > maxBytes) { + if (maxBytes < MAX_SKILL_BYTES) this.exhausted = true; + return undefined; + } + const bytes = await readRegularFile(path, { maxBytes, followLink: true }); + if (bytes === undefined) return undefined; + this.remainingBytes -= bytes.byteLength; + return bytes.toString("utf8"); + } + + /** Adds the skill at `skillFile` unless a copy with its name came first. */ + private async addSkill(skillFile: string, scope: Scope) { + const head = await this.readHead(skillFile); + const frontMatter = head === undefined ? undefined : frontMatterOf(head); + if (frontMatter === undefined) return; + const parsed = decodeFrontMatter(frontMatter || "{}"); + if (Option.isNone(parsed)) return; + // A skill without a name is named after its folder (CLI 1.5.10). + const name = parsed.value.name || basename(dirname(skillFile)); + // The CLI keeps names as written; one with outer spaces can't be offered by name. + if (!name || name !== name.trim() || name.length > MAX_NAME_LENGTH) return; + if (this.skills.has(name)) return; + const description = capText( + parsed.value.description?.trim() ?? "", + MAX_SKILL_DESCRIPTION_LENGTH, + ).trim(); + this.skills.set(name, { + name, + // Where it really is: for a global skill, the user's own folder rather + // than the link in the profile. + path: (await this.realpath(skillFile)) ?? skillFile, + scope, + enabled: true, + ...(description ? { description } : {}), + }); + } + + /** The `SKILL.md` directly in `dir` (any case), if there is one. */ + private async skillFileIn(dir: string, names?: ReadonlyArray) { + const listed = names ?? (await this.readDir(dir)); + const found = listed?.toSorted().find((name) => name.toLowerCase() === "skill.md"); + if (found === undefined) return undefined; + const path = join(dir, found); + return (await this.stat(path))?.isFile() ? path : undefined; + } + + /** + * A skills folder: a skill itself when it holds a `SKILL.md` (and `filter` + * lets its name through), otherwise each folder directly inside it that + * `filter` lets through, plus nested items `include_only` names. With + * `confine`, nothing outside it is listed or opened. + */ + async scanFolder(dir: string, scope: Scope, filter: NameFilter, confine?: Confine) { + if (this.exhausted) return; + if (confine && !(await confine(dir))) return; + if (!(await this.stat(dir))?.isDirectory()) return; + const names = await this.readDir(dir); + if (names === undefined) return; + const own = await this.skillFileIn(dir, names); + if (own) { + if (passesFilter(basename(dir), filter) && (!confine || (await confine(own)))) { + await this.addSkill(own, scope); + } + return; + } + const nested = filter.includeGroups + .flat() + .filter((name) => name.includes("/") && !name.split("/").includes("..")); + const candidates = [...new Set([...names, ...nested])] + .filter((name) => passesFilter(name, filter)) + .toSorted(byEscapedPath); + for (const name of candidates) { + if (this.exhausted) return; + const child = join(dir, ...name.split("/")); + if (confine && !(await confine(child))) continue; + if (!(await this.stat(child))?.isDirectory()) continue; + const skillFile = await this.skillFileIn(child); + if (skillFile && (!confine || (await confine(skillFile)))) { + await this.addSkill(skillFile, scope); + } + } + } + + /** A manifest entry: a skills folder, or a `SKILL.md` named directly. */ + private async scanEntry(path: string, scope: Scope, filter: NameFilter, confine?: Confine) { + if (confine && !(await confine(path))) return; + const stat = await this.stat(path); + if (stat?.isFile()) { + if (basename(path).toLowerCase() !== "skill.md") return; + if (!passesFilter(basename(dirname(path)), filter)) return; + await this.addSkill(path, scope); + return; + } + await this.scanFolder(path, scope, filter, confine); + } + + /** A `skills.json`: its `inherits` first, then its `entries`. */ + async scanManifest(input: { + readonly path: string; + /** What its relative paths resolve against; the manifest's own folder by default. */ + readonly baseDir?: string; + readonly scope: Scope; + readonly filter: NameFilter; + readonly confine?: Confine; + readonly visited?: ReadonlySet; + readonly depth?: number; + }): Promise { + const depth = input.depth ?? 0; + const visited = input.visited ?? new Set(); + const path = resolve(input.path); + if (this.exhausted || depth > MAX_INHERIT_DEPTH || visited.has(path)) return; + if (input.confine && !(await input.confine(path))) return; + const raw = await this.readSmall(path); + if (raw === undefined) return; + const manifest = decodeManifest(raw); + if (Option.isNone(manifest)) return; + const baseDir = input.baseDir ?? dirname(path); + // The CLI does not expand `~`, so `~/x` is a folder named `~` next to the manifest. + const resolveEntry = (entryPath: string) => + isAbsolute(entryPath) ? resolve(entryPath) : resolve(baseDir, entryPath); + const nextVisited = new Set(visited).add(path); + for (const inherited of manifest.value.inherits ?? []) { + await this.scanManifest({ + path: resolveEntry(inherited.path), + scope: input.scope, + filter: narrowFilter(input.filter, inherited), + ...(input.confine ? { confine: input.confine } : {}), + visited: nextVisited, + depth: depth + 1, + }); + } + for (const entry of manifest.value.entries ?? []) { + if (this.exhausted) return; + await this.scanEntry( + resolveEntry(entry.path), + input.scope, + narrowFilter(input.filter, entry), + input.confine, + ); + } + } + + /** Skills of plugins installed in the profile, unless turned off in its settings. */ + async scanPlugins(profileDir: string) { + const pluginsDir = join(profileDir, "config", "plugins"); + const plugins = await this.readDir(pluginsDir); + if (!plugins || plugins.length === 0) return; + const settings = await this.readSmall(join(profileDir, "config", "config.json")); + const parsed = settings === undefined ? Option.none() : decodePluginSettings(settings); + const states = Option.isSome(parsed) ? (parsed.value.plugins ?? {}) : {}; + for (const plugin of plugins.toSorted()) { + if (this.exhausted) return; + if (states[plugin]?.enabled === false) continue; + await this.scanFolder(join(pluginsDir, plugin, "skills"), "user", NO_FILTER); + } + } +} + +/** The nearest folder at or above `cwd` holding `.git`, or `cwd` when there is none. */ +async function repositoryRoot(scan: SkillScan, cwd: string): Promise { + for (let dir = cwd; ; dir = dirname(dir)) { + if (scan.exhausted) return cwd; + if (await fs.lstat(join(dir, ".git")).catch(() => undefined)) return dir; + if (dirname(dir) === dir) return cwd; + } +} + +export interface ListAntigravitySkillsInput { + /** The folder a session would run in. */ + readonly cwd: string; + /** The instance's profile (`GEMINI_HOME`), already prepared (`prepareAntigravityProfile`). */ + readonly profileDir: string; +} + +export interface AntigravitySkillListing { + readonly skills: ReadonlyArray; + /** The scan hit its budget or its deadline, so the list may be missing skills. */ + readonly truncated: boolean; +} + +/** Lists the skills Antigravity would load in `cwd`, sorted by name. */ +export async function listAntigravitySkillsNow( + input: ListAntigravitySkillsInput, + options: { readonly timeLimitMs?: number } = {}, +): Promise { + const cwd = resolve(input.cwd); + const profile = resolve(input.profileDir); + const scan = new SkillScan( + Date.now() + (options.timeLimitMs ?? Duration.toMillis(LIST_TIME_LIMIT)), + ); + + // Nothing outside the project or its repository root is opened for it. + const root = await repositoryRoot(scan, cwd); + const realRoot = (await scan.realpath(root)) ?? root; + const insideProject: Confine = async (path) => { + const real = await scan.realpath(path); + return real !== undefined && isInside(realRoot, real); + }; + + const roots: ReadonlyArray = [ + [join(profile, "config", "skills"), "user"], + [join(cwd, ".gemini", "skills"), "project"], + [join(profile, "antigravity-cli", "skills"), "user"], + [join(cwd, ".agents", "skills"), "project"], + [join(cwd, ".agent", "skills"), "project"], + ]; + for (const [dir, scope] of roots) { + await scan.scanFolder(dir, scope, NO_FILTER, scope === "project" ? insideProject : undefined); + } + + // The CLI skips project manifest entries leaving the project or its repository root. + for (let dir = cwd; ; dir = dirname(dir)) { + for (const folder of [".agents", ".agent"]) { + await scan.scanManifest({ + path: join(dir, folder, "skills.json"), + baseDir: dir, + scope: "project", + filter: NO_FILTER, + confine: insideProject, + }); + } + if (dir === root || dirname(dir) === dir || scan.exhausted) break; + } + await scan.scanManifest({ + path: join(profile, "config", "skills.json"), + scope: "user", + filter: NO_FILTER, + }); + await scan.scanPlugins(profile); + + return { + skills: [...scan.skills.values()].toSorted((left, right) => + left.name.localeCompare(right.name), + ), + truncated: scan.exhausted, + }; +} + +/** + * A skills lister for one instance. It never fails and never runs past its + * time limit; when a scan is cut short it answers with the last complete + * list for the same folders, or what it found if there is none yet. + */ +export function makeAntigravitySkillsLister() { + const lastComplete = new Map>(); + return (input: ListAntigravitySkillsInput) => { + const key = `${resolve(input.cwd)}\0${resolve(input.profileDir)}`; + return Effect.promise(() => + listAntigravitySkillsNow(input).catch((): AntigravitySkillListing => ({ + skills: [], + truncated: true, + })), + ).pipe( + // The scan stops itself at its deadline; this bounds a stuck file call. + Effect.timeoutOption(Duration.sum(LIST_TIME_LIMIT, Duration.seconds(1))), + Effect.flatMap((result) => { + const listing = Option.getOrUndefined(result); + if (listing && !listing.truncated) { + lastComplete.set(key, listing.skills); + return Effect.succeed(listing.skills); + } + return Effect.logWarning("Antigravity's skill list was cut short.", { + cwd: input.cwd, + }).pipe(Effect.as(lastComplete.get(key) ?? listing?.skills ?? [])); + }), + ); + }; +} diff --git a/apps/server/src/provider/antigravity/AntigravitySubagents.ts b/apps/server/src/provider/antigravity/AntigravitySubagents.ts new file mode 100644 index 000000000..f44f1f968 --- /dev/null +++ b/apps/server/src/provider/antigravity/AntigravitySubagents.ts @@ -0,0 +1,83 @@ +/** + * Antigravity's subagents for the generic ACP core (`AcpProviderDescriptor.subagents`). + * + * The agent launches a subagent with an `invoke_subagent` tool call (older + * builds: `start_subagent`) that returns at once; the child works on and + * later reports to the parent, which wakes and replies (1.5.10). ACP carries + * nothing more, so which child a call started, whether it reported or was + * killed, and its steps come from the CLI's own records + * (`AntigravityChildRecords`). + * + * @module provider/antigravity/AntigravitySubagents + */ +import * as Effect from "effect/Effect"; + +import type { AcpSubagentState, AcpSubagents } from "../acp/AcpProviderDescriptor.ts"; +import type { AcpToolCallState } from "../acp/AcpRuntimeModel.ts"; +import { + antigravityChildLaunches, + antigravityChildOf, + antigravityChildTranscript, + readAntigravityChildren, +} from "./AntigravityChildRecords.ts"; + +/** The titles a subagent launch arrives under, asked or auto-approved. */ +const LAUNCH_TITLES = new Set([ + "Running start_subagent", + "Run start_subagent?", + "Running invoke_subagent", + "Run invoke_subagent?", + // agy 1.5 titles an auto-approved call this way (T3 Code 43b37b6d3c). + "Run invoke_subagent", +]); + +/** Whether this tool call launches subagents: its title, and an input naming them. */ +export function isAntigravitySubagentLaunch(toolCall: AcpToolCallState): boolean { + return ( + (toolCall.kind === undefined || toolCall.kind === "other") && + toolCall.title !== undefined && + LAUNCH_TITLES.has(toolCall.title) && + antigravityChildLaunches(toolCall.data.rawInput) !== undefined + ); +} + +/** The subagent hooks, reading the records in this instance's profile. */ +export function antigravitySubagents(profileDir: string): AcpSubagents { + return { + launches: (toolCall) => + isAntigravitySubagentLaunch(toolCall) + ? antigravityChildLaunches(toolCall.data.rawInput) + : undefined, + states: ({ sessionId, launchCallIds }) => + readAntigravityChildren(profileDir, sessionId).pipe( + Effect.map((reading) => { + if (!reading.available) return undefined; + const states = new Map(); + for (const id of launchCallIds) { + const child = antigravityChildOf(reading, id); + if (child === undefined) continue; + states.set(id, { + state: child.state, + ...(child.report !== undefined ? { report: child.report } : {}), + }); + } + return { byLaunch: states, complete: reading.unreadable === 0 }; + }), + ), + transcript: ({ sessionId, launchCallId }) => + antigravityChildTranscript(profileDir, sessionId, launchCallId).pipe( + Effect.map((read) => + read === undefined + ? undefined + : { + childId: read.child.conversationId, + launch: read.child.launch, + entries: read.entries, + truncated: read.truncated, + }, + ), + ), + unrecordedMessage: + "Antigravity did not record which subagent this started, so its steps can't be shown.", + }; +} diff --git a/apps/server/src/provider/antigravity/AntigravityToolCalls.test.ts b/apps/server/src/provider/antigravity/AntigravityToolCalls.test.ts new file mode 100644 index 000000000..d151066c3 --- /dev/null +++ b/apps/server/src/provider/antigravity/AntigravityToolCalls.test.ts @@ -0,0 +1,251 @@ +import * as Schema from "effect/Schema"; +import * as EffectAcpSchema from "effect-acp/schema"; +import { describe, expect, it } from "vite-plus/test"; + +import { + type AcpToolCallState, + makeToolCallState, + mergeToolCallState, +} from "../acp/AcpRuntimeModel.ts"; +import { + ANTIGRAVITY_TOOL_TEXT_LIMIT, + antigravityProxiedMcpTool, + boundAntigravityCommandLine, + boundAntigravityText, + normalizeAntigravitySessionUpdate, + normalizeAntigravityToolCall, +} from "./AntigravityToolCalls.ts"; + +const decodeNotification = Schema.decodeUnknownSync(EffectAcpSchema.SessionNotification); + +const toolUpdate = (fields: Record) => + decodeNotification({ + sessionId: "s", + update: { sessionUpdate: "tool_call", toolCallId: "call", ...fields }, + }); + +const wrapper = { + title: "MCP Tool list_issues", + kind: "execute", + rawInput: { ServerName: "github", ToolName: "list_issues", Arguments: { repo: "x/y" } }, +} as const; + +const state = (data: Record): AcpToolCallState => ({ + toolCallId: "call", + kind: "execute", + command: "rm -rf build", + data: { kind: "execute", command: "rm -rf build", item: { command: "rm -rf build" }, ...data }, +}); + +describe("Antigravity tool text", () => { + it("cuts within its limit, marker included, and never in half a character", () => { + // "😀" is two UTF-16 units; a cut between them would leave half a character. + const tail = boundAntigravityText(`a😀${"b".repeat(60)}`, 40); + expect(tail.length).toBeLessThanOrEqual(40); + expect(tail.startsWith("[Earlier output truncated]")).toBe(true); + expect(tail.endsWith("b")).toBe(true); + const head = boundAntigravityCommandLine(`${"c".repeat(20)}😀${"d".repeat(40)}`, 41); + expect(head.length).toBeLessThanOrEqual(41); + expect(head).toBe(`${"c".repeat(20)}\n\n[Command truncated]`); + expect(boundAntigravityText("short")).toBe("short"); + }); + + it("keeps every content block valid ACP, whatever its text", () => { + const big = "x".repeat(70_000); + const out = normalizeAntigravitySessionUpdate( + toolUpdate({ + title: "Ran it", + content: [ + // Text that looks like an image is still text. + { type: "content", content: { type: "text", text: "data:image/png;base64,AAAA" } }, + ...Array.from({ length: 12 }, () => ({ + type: "content", + content: { type: "text", text: big }, + })), + { type: "content", content: { type: "resource", resource: { uri: "f", blob: "AA" } } }, + { type: "content", content: { type: "resource_link", uri: "file:///a", name: big } }, + { type: "content", content: { type: "image", data: "AAAA", mimeType: "image/png" } }, + { type: "diff", path: "/a.ts", oldText: "data:image/png,a", newText: big }, + { type: "terminal", terminalId: "t1" }, + ], + }), + ); + // The whole update still decodes, so the core can read what it expects. + expect(() => decodeNotification(out)).not.toThrow(); + const content = (out.update as { content: ReadonlyArray> }).content; + expect(content[0]).toEqual({ + type: "content", + content: { type: "text", text: "data:image/png;base64,AAAA" }, + }); + for (const entry of content.slice(1, 13)) { + const text = (entry.content as { text: string }).text; + expect(text.length).toBeLessThanOrEqual(ANTIGRAVITY_TOOL_TEXT_LIMIT); + } + // The binary resource and the image are left out; the edit stays whole. + expect(content.map((entry) => entry.type)).toEqual([ + ...Array.from({ length: 13 }, () => "content"), + "content", + "diff", + "terminal", + ]); + expect(content.at(-2)).toEqual({ + type: "diff", + path: "/a.ts", + oldText: "data:image/png,a", + newText: big, + }); + }); + + it("budgets output fields named like an edit's text, and keeps a long `cmd`'s start", () => { + const out = normalizeAntigravitySessionUpdate( + toolUpdate({ + title: "Running make", + kind: "execute", + rawInput: { cmd: `make ${"y".repeat(9_000)}` }, + rawOutput: { newText: "z".repeat(9_000) }, + }), + ).update as { rawInput: { cmd: string }; rawOutput: { newText: string } }; + expect(out.rawInput.cmd.startsWith("make ")).toBe(true); + expect(out.rawInput.cmd.length).toBeLessThanOrEqual(ANTIGRAVITY_TOOL_TEXT_LIMIT); + expect(out.rawOutput.newText.length).toBeLessThanOrEqual(ANTIGRAVITY_TOOL_TEXT_LIMIT); + }); +}); + +describe("Antigravity call_mcp_tool", () => { + it("is the MCP tool only when the update says so positively", () => { + expect(antigravityProxiedMcpTool(wrapper)).toEqual({ + server: "github", + tool: "list_issues", + arguments: { repo: "x/y" }, + }); + const notWrappers = [ + // A command line beside the names. + { ...wrapper, rawInput: { ...wrapper.rawInput, CommandLine: "rm -rf build" } }, + { ...wrapper, rawInput: { ...wrapper.rawInput, cmd: "rm -rf build" } }, + // Any other input field. + { ...wrapper, rawInput: { ...wrapper.rawInput, Cwd: "/" } }, + // Another title, or another kind. + { ...wrapper, title: "MCP Tool delete_repo" }, + { ...wrapper, title: "Running rm -rf build" }, + { ...wrapper, kind: "edit" }, + { ...wrapper, kind: "other" }, + // An edit's diff or a file location. + { ...wrapper, content: [{ type: "diff" }] }, + { ...wrapper, locations: [{ path: "/a" }] }, + // Arguments that aren't an object. + { ...wrapper, rawInput: { ...wrapper.rawInput, Arguments: "rm -rf build" } }, + ]; + for (const update of notWrappers) expect(antigravityProxiedMcpTool(update)).toBeUndefined(); + }); + + it("leaves a command that names an MCP tool a command, and drops the MCP look on conflict", () => { + const spoof = state({ + rawInput: { ServerName: "github", ToolName: "list_issues", CommandLine: "rm -rf build" }, + }); + expect( + normalizeAntigravityToolCall(spoof, { + ...wrapper, + rawInput: spoof.data.rawInput, + }), + ).toBe(spoof); + + const shown = normalizeAntigravityToolCall(state({ rawInput: wrapper.rawInput }), wrapper); + expect(shown).toMatchObject({ + itemType: "mcp_tool_call", + detail: 'MCP tool github · list_issues {"repo":"x/y"}', + data: { server: "github", tool: "list_issues" }, + }); + expect(shown.data).not.toHaveProperty("command"); + // A completion that adds nothing keeps it the MCP tool. + expect(normalizeAntigravityToolCall(shown, { kind: "execute" }).itemType).toBe("mcp_tool_call"); + // One that says it runs a command, or edits, makes it what it says. + const conflicted = normalizeAntigravityToolCall(shown, { + rawInput: { CommandLine: "rm -rf build" }, + }); + expect(conflicted.itemType).toBeUndefined(); + expect(conflicted.kind).toBe("execute"); + expect(conflicted.data).not.toHaveProperty("server"); + expect(normalizeAntigravityToolCall(shown, { kind: "edit" }).itemType).toBeUndefined(); + }); +}); + +describe("Antigravity call_mcp_tool, exactly", () => { + it("holds the stated rule: an object Arguments, and the title as sent", () => { + const { Arguments: _arguments, ...withoutArguments } = wrapper.rawInput; + expect(antigravityProxiedMcpTool({ ...wrapper, rawInput: withoutArguments })).toBeUndefined(); + expect(antigravityProxiedMcpTool({ ...wrapper, title: ` ${wrapper.title} ` })).toBeUndefined(); + expect( + antigravityProxiedMcpTool({ ...wrapper, rawInput: { ...wrapper.rawInput, ToolName: "" } }), + ).toBeUndefined(); + }); + + it("follows later updates: the newest arguments, and an edit when a diff arrives", () => { + const first = makeToolCallState({ + toolCallId: "call", + title: wrapper.title, + kind: "execute", + status: "in_progress", + rawInput: wrapper.rawInput, + })!; + const shown = normalizeAntigravityToolCall(first, wrapper); + // The same tool, restated with new arguments: the label says the new ones. + const restated = { rawInput: { ...wrapper.rawInput, Arguments: { repo: "a/b" } } }; + const next = normalizeAntigravityToolCall( + mergeToolCallState(shown, makeToolCallState({ toolCallId: "call", ...restated })!), + restated, + ); + expect(next.detail).toBe('MCP tool github · list_issues {"repo":"a/b"}'); + // A completion with a diff and no kind is the edit it shows, not the wrapper's command. + const diff = { + status: "completed", + content: [{ type: "diff", path: "/repo/a.ts", oldText: "a", newText: "b" }], + } as const; + const edited = normalizeAntigravityToolCall( + mergeToolCallState(next, makeToolCallState({ toolCallId: "call", ...diff })!), + diff, + ); + expect(edited.kind).toBe("edit"); + expect(edited.itemType).toBeUndefined(); + expect(edited.title).not.toBe("list_issues"); + expect(edited.detail ?? "").not.toContain("MCP tool"); + }); +}); + +describe("Antigravity tool text, storage", () => { + it("drops inline data links, bounds long links and terminal ids, and budgets the command first", () => { + const big = "x".repeat(70_000); + const out = normalizeAntigravitySessionUpdate( + toolUpdate({ + title: "Running make", + kind: "execute", + // Large fields before the command line in the input itself. + rawInput: { Notes: big, More: big, CommandLine: "make build" }, + rawOutput: { output: big }, + content: [ + { + type: "content", + content: { type: "resource_link", uri: "data:text/plain,AAAA", name: "a" }, + }, + { + type: "content", + content: { type: "resource_link", uri: `file:///${big}`, name: "b" }, + }, + { type: "terminal", terminalId: big }, + ], + }), + ); + expect(() => decodeNotification(out)).not.toThrow(); + const update = out.update as { + rawInput: { CommandLine: string }; + content: ReadonlyArray>; + }; + expect(update.rawInput.CommandLine).toBe("make build"); + expect(update.content).toHaveLength(2); + const link = update.content[0]!.content as { uri: string }; + expect(link.uri.startsWith("file:///xxx")).toBe(true); + expect(link.uri.length).toBeLessThanOrEqual(ANTIGRAVITY_TOOL_TEXT_LIMIT); + expect((update.content[1] as { terminalId: string }).terminalId.length).toBeLessThanOrEqual( + 256, + ); + }); +}); diff --git a/apps/server/src/provider/antigravity/AntigravityToolCalls.ts b/apps/server/src/provider/antigravity/AntigravityToolCalls.ts new file mode 100644 index 000000000..3b46f8032 --- /dev/null +++ b/apps/server/src/provider/antigravity/AntigravityToolCalls.ts @@ -0,0 +1,428 @@ +/** + * How Antigravity's tool calls reach the timeline: bounded text, no inline + * image data, and an MCP call made through `call_mcp_tool` shown as that + * tool rather than as a shell command. + * + * `agy acp` puts whole command output, file text and screenshots on its tool + * updates. Each update is bounded here before the ACP core reads it, so the + * runtime events (what is stored and shown) never carry more than + * `ANTIGRAVITY_TOOL_TEXT_LIMIT` characters per field, marker included. An + * edit's `diff` block is the exception: the core counts the edit's lines + * from its old and new text, so they stay whole. Content blocks keep the + * shape ACP gives them, so the core can read every field it expects. + * Rules follow T3 Code's (AntigravityProtocol.ts, commits df67c4f7f9, + * c4dc9ed55b, 7f928416b2): a command line keeps its start (the program and + * its target are there), output and other text keep their end, and a cut + * never splits a character. + * + * @module provider/antigravity/AntigravityToolCalls + */ +import * as Schema from "effect/Schema"; +import * as EffectAcpSchema from "effect-acp/schema"; + +import { type AcpToolCallState, makeToolCallState } from "../acp/AcpRuntimeModel.ts"; + +/** The most characters one tool text field keeps, its cut marker included. */ +export const ANTIGRAVITY_TOOL_TEXT_LIMIT = 8_000; +/** All text kept from one tool update, across its fields. */ +const UPDATE_TEXT_BUDGET = 64_000; +/** Values kept from one payload, so a huge array or object can't flood it. */ +const PAYLOAD_NODE_BUDGET = 512; +const MAX_DEPTH = 12; + +const OUTPUT_CUT = "[Earlier output truncated]\n\n"; +const COMMAND_CUT = "\n\n[Command truncated]"; + +/** Fields that hold a command line: the start says what runs. The core reads the same ones. */ +const COMMAND_LINE_FIELDS = new Set([ + "CommandLine", + "command_line", + "commandLine", + "command", + "cmd", +]); + +const isRecord = (value: unknown): value is Record => + typeof value === "object" && value !== null && !Array.isArray(value); + +/** A fresh copy, so the engine can't keep the large original alive through a slice. */ +const copyText = (text: string) => Buffer.from(text, "utf16le").toString("utf16le"); + +/** Keeps the end of long text, within `limit` with its marker; never half a character. */ +export function boundAntigravityText(text: string, limit = ANTIGRAVITY_TOOL_TEXT_LIMIT): string { + if (text.length <= limit) return text; + const room = Math.max(0, limit - OUTPUT_CUT.length); + const tail = room === 0 ? "" : text.slice(-room).replace(/^[\uDC00-\uDFFF]/u, ""); + return copyText(`${OUTPUT_CUT}${tail}`); +} + +/** Keeps the start of a long command line, within `limit` with its marker; never half a character. */ +export function boundAntigravityCommandLine( + text: string, + limit = ANTIGRAVITY_TOOL_TEXT_LIMIT, +): string { + if (text.length <= limit) return text; + const room = Math.max(0, limit - COMMAND_CUT.length); + const head = text.slice(0, room).replace(/[\uD800-\uDBFF]$/u, ""); + return copyText(`${head}${COMMAND_CUT}`); +} + +interface Budget { + nodes: number; + text: number; +} + +/** One text field within the update's budget; a field past it keeps only its marker. */ +function boundField(value: string, budget: { text: number }, field?: string): string { + const limit = Math.min(ANTIGRAVITY_TOOL_TEXT_LIMIT, Math.max(0, budget.text)); + const text = + field !== undefined && COMMAND_LINE_FIELDS.has(field) + ? boundAntigravityCommandLine(value, limit) + : boundAntigravityText(value, limit); + budget.text -= text.length; + return text; +} + +const isInlineImage = (record: Record) => + record.type === "image" || + (typeof record.mimeType === "string" && record.mimeType.toLowerCase().startsWith("image/")); + +/** + * A free-form payload value (`rawInput`, `rawOutput`, `_meta`: any JSON to + * ACP) with its text bounded and inline image data left out. `undefined` + * means "drop it". + */ +function boundValue(value: unknown, budget: Budget, depth: number, field?: string): unknown { + if (depth > MAX_DEPTH || budget.nodes-- <= 0) return undefined; + if (typeof value === "string") { + if (/^data:image\//iu.test(value)) return undefined; + return boundField(value, budget, field); + } + if (Array.isArray(value)) { + const kept: Array = []; + for (const entry of value) { + if (budget.nodes <= 0) break; + const bounded = boundValue(entry, budget, depth + 1); + if (bounded !== undefined) kept.push(bounded); + } + return kept; + } + if (!isRecord(value)) return value; + const image = isInlineImage(value); + // A command line is budgeted before any other field, so a large field + // beside it can never leave it just the cut marker. The keys keep their order. + const entries = Object.entries(value); + const bounded = new Map(); + for (const [key, entry] of [ + ...entries.filter(([key]) => COMMAND_LINE_FIELDS.has(key)), + ...entries.filter(([key]) => !COMMAND_LINE_FIELDS.has(key)), + ]) { + if (budget.nodes <= 0) break; + if (image && (key === "data" || key === "blob")) continue; + bounded.set(key, boundValue(entry, budget, depth + 1, key)); + } + const kept: Record = {}; + for (const [key] of entries) { + const entry = bounded.get(key); + if (entry !== undefined) kept[key] = entry; + } + return kept; +} + +/** A tool payload (`rawInput`, `rawOutput`, `_meta`) with its text bounded and images left out. */ +export function boundAntigravityToolPayload( + payload: unknown, + budget: { text: number } = { text: UPDATE_TEXT_BUDGET }, +): unknown { + const nodes: Budget = { nodes: PAYLOAD_NODE_BUDGET, text: budget.text }; + const bounded = boundValue(payload, nodes, 0); + budget.text = nodes.text; + return bounded; +} + +const isToolCallContent = Schema.is(EffectAcpSchema.ToolCallContent); + +/** + * One tool content block, bounded field by field in its own shape, or + * `undefined` for a block that is only bytes (an image, audio, a binary + * resource). A diff stays whole. A block this can't rebuild as valid ACP + * content is left as it came. + */ +function boundContentEntry( + entry: EffectAcpSchema.ToolCallContent, + budget: { text: number }, +): EffectAcpSchema.ToolCallContent | undefined { + if (entry.type === "terminal") { + const terminalId = boundAntigravityCommandLine(entry.terminalId, 256); + budget.text -= terminalId.length; + return { type: "terminal", terminalId }; + } + if (entry.type !== "content") return entry; + const block = entry.content; + let bounded: EffectAcpSchema.ToolCallContent; + switch (block.type) { + case "image": + case "audio": + return undefined; + case "text": + bounded = { + type: "content", + content: { type: "text", text: boundField(block.text, budget) }, + }; + break; + case "resource_link": + // A `data:` link is the bytes themselves, like an image. + if (/^data:/iu.test(block.uri)) return undefined; + bounded = { + type: "content", + content: { + type: "resource_link", + uri: boundField(block.uri, budget, "command"), + name: boundField(block.name, budget), + ...(typeof block.mimeType === "string" ? { mimeType: block.mimeType } : {}), + ...(typeof block.title === "string" ? { title: boundField(block.title, budget) } : {}), + ...(typeof block.size === "number" ? { size: block.size } : {}), + }, + }; + break; + case "resource": { + const resource = block.resource; + if (!("text" in resource) || /^data:/iu.test(resource.uri)) return undefined; + bounded = { + type: "content", + content: { + type: "resource", + resource: { + uri: boundField(resource.uri, budget, "command"), + text: boundField(resource.text, budget), + ...(typeof resource.mimeType === "string" ? { mimeType: resource.mimeType } : {}), + }, + }, + }; + break; + } + default: + return entry; + } + return isToolCallContent(bounded) ? bounded : entry; +} + +/** + * Bounds one session update before the ACP core reads it: a tool call's + * title, payloads and content. Other updates pass through. + */ +export function normalizeAntigravitySessionUpdate( + notification: EffectAcpSchema.SessionNotification, +): EffectAcpSchema.SessionNotification { + const update = notification.update; + if (update.sessionUpdate !== "tool_call" && update.sessionUpdate !== "tool_call_update") { + return notification; + } + // What says what runs (the input) is budgeted first, then what it printed. + const budget = { text: UPDATE_TEXT_BUDGET }; + const rawInput = + update.rawInput !== undefined + ? boundAntigravityToolPayload(update.rawInput, budget) + : undefined; + const rawOutput = + update.rawOutput !== undefined + ? boundAntigravityToolPayload(update.rawOutput, budget) + : undefined; + const content = update.content?.flatMap((entry) => { + const bounded = boundContentEntry(entry, budget); + return bounded === undefined ? [] : [bounded]; + }); + const meta = + update._meta !== undefined && update._meta !== null + ? boundAntigravityToolPayload(update._meta, budget) + : undefined; + return { + ...notification, + update: { + ...update, + ...(typeof update.title === "string" ? { title: boundAntigravityText(update.title) } : {}), + ...(update.rawInput !== undefined ? { rawInput } : {}), + ...(update.rawOutput !== undefined ? { rawOutput } : {}), + ...(update.content !== undefined && update.content !== null + ? { content: content ?? [] } + : {}), + ...(update._meta !== undefined && update._meta !== null + ? { _meta: isRecord(meta) ? meta : null } + : {}), + }, + } as EffectAcpSchema.SessionNotification; +} + +// ── MCP tools reached through `call_mcp_tool` ──────────────────────── + +/** An MCP tool call through `call_mcp_tool`, as its input names it. */ +export interface AntigravityProxiedMcpTool { + readonly server: string; + readonly tool: string; + readonly arguments?: Record; +} + +/** The fields of a tool call update the wrapper check reads. */ +export interface AntigravityToolCallUpdate { + readonly title?: string | null | undefined; + readonly kind?: string | null | undefined; + readonly rawInput?: unknown; + readonly content?: ReadonlyArray<{ readonly type: string }> | null | undefined; + readonly locations?: ReadonlyArray | null | undefined; +} + +/** The input of a `call_mcp_tool` call holds these and nothing else. */ +const WRAPPER_INPUT_KEYS = new Set(["ServerName", "ToolName", "Arguments"]); + +/** A sign that the call runs a command or changes a file: never an MCP wrapper then. */ +function commandOrEditEvidence(update: AntigravityToolCallUpdate): boolean { + if (update.kind === "edit" || update.kind === "delete" || update.kind === "move") return true; + if (update.content?.some((entry) => entry.type === "diff" || entry.type === "terminal")) + return true; + if ((update.locations?.length ?? 0) > 0) return true; + return ( + isRecord(update.rawInput) && + Object.keys(update.rawInput).some((key) => COMMAND_LINE_FIELDS.has(key)) + ); +} + +/** Server and tool names kept, at most this long. */ +const NAME_LIMIT = 256; + +/** + * The MCP tool this update positively says it runs through `call_mcp_tool`, + * read from the update exactly as the agent sent it (before any bounding): + * an `execute` call titled exactly "MCP Tool ", whose input holds + * exactly `ServerName` and `ToolName` (non-empty text) and `Arguments` (an + * object), with no command or edit about it (agy 1.5.12, T3 Code + * 7f928416b2). Anything else is `undefined` and stays what the agent + * called it. + */ +export function antigravityProxiedMcpTool( + update: AntigravityToolCallUpdate, +): AntigravityProxiedMcpTool | undefined { + const input = update.rawInput; + if (!isRecord(input) || commandOrEditEvidence(update)) return undefined; + if (update.kind !== "execute") return undefined; + const keys = Object.keys(input); + if (keys.length !== WRAPPER_INPUT_KEYS.size || !keys.every((key) => WRAPPER_INPUT_KEYS.has(key))) + return undefined; + const { ServerName: server, ToolName: tool, Arguments: args } = input; + if (typeof server !== "string" || typeof tool !== "string" || !server || !tool) return undefined; + if (!isRecord(args)) return undefined; + if (update.title !== `MCP Tool ${tool}`) return undefined; + return { server, tool, arguments: args }; +} + +/** + * What an approval for the call shows: the server and the tool first, then + * its arguments, so a cut short loses the arguments' tail, never the target. + */ +export function antigravityMcpToolLabel(mcp: AntigravityProxiedMcpTool): string { + const args = mcp.arguments === undefined ? "" : ` ${JSON.stringify(mcp.arguments)}`; + return boundAntigravityCommandLine(`MCP tool ${mcp.server} · ${mcp.tool}${args}`); +} + +/** The MCP tool a call was already shown as, from the fields `asMcpToolCall` set. */ +function shownMcpTool(toolCall: AcpToolCallState): { server: string; tool: string } | undefined { + const { server, tool } = toolCall.data; + return typeof server === "string" && typeof tool === "string" ? { server, tool } : undefined; +} + +/** + * The call as that MCP tool. Its arguments come from the merged, bounded + * input (the newest restatement of them), never from the unbounded report. + */ +function asMcpToolCall( + toolCall: AcpToolCallState, + names: { readonly server: string; readonly tool: string }, +): AcpToolCallState { + const { item: _item, command: _command, ...data } = toolCall.data; + const { command: _shown, ...rest } = toolCall; + const input = isRecord(data.rawInput) ? data.rawInput : undefined; + const mcp: AntigravityProxiedMcpTool = { + server: boundAntigravityCommandLine(names.server, NAME_LIMIT), + tool: boundAntigravityCommandLine(names.tool, NAME_LIMIT), + ...(isRecord(input?.Arguments) ? { arguments: input.Arguments } : {}), + }; + const { arguments: _old, ...withoutArguments } = data; + return { + ...rest, + kind: "other", + itemType: "mcp_tool_call", + // The approval panel names a tool call by its title. + title: mcp.tool, + detail: antigravityMcpToolLabel(mcp), + data: { + ...withoutArguments, + kind: "other", + server: mcp.server, + tool: mcp.tool, + ...(mcp.arguments !== undefined ? { arguments: mcp.arguments } : {}), + }, + }; +} + +/** + * The merged call as the core would show it without the MCP look an earlier + * update gave it: rebuilt from its merged data, so neither the MCP title nor + * its label stays. Its kind is the report's, else an edit when a diff says + * it changed a file (so the diff still counts as file-change evidence), else + * the `execute` a wrapper was. + */ +function withoutMcpTool( + toolCall: AcpToolCallState, + update: AntigravityToolCallUpdate, +): AcpToolCallState { + const { server: _server, tool: _tool, arguments: _args, item: _item, ...data } = toolCall.data; + const diff = + (update.content ?? []).some((entry) => entry.type === "diff") || + (Array.isArray(data.content) && + data.content.some((entry) => isRecord(entry) && entry.type === "diff")); + const kind = update.kind ?? (diff ? "edit" : "execute"); + const rebuilt = makeToolCallState({ + toolCallId: toolCall.toolCallId, + title: update.title, + kind: kind as EffectAcpSchema.ToolKind, + ...(toolCall.status !== undefined + ? { status: toolCall.status === "inProgress" ? "in_progress" : toolCall.status } + : {}), + rawInput: data.rawInput, + rawOutput: data.rawOutput, + content: data.content as ReadonlyArray | undefined, + locations: data.locations as ReadonlyArray | undefined, + }); + const { itemType: _itemType, ...rest } = toolCall; + return rebuilt ?? { ...rest, kind, data: { ...data, kind } }; +} + +/** + * A tool call as the timeline should show it, given the update that just + * arrived, as the agent sent it. A call the update positively shows to be + * `call_mcp_tool` is that MCP tool, with its server and tool, not a command; + * a later update with no command or edit about it keeps it so, with the + * newest arguments. Anything else stays, or goes back to, what the agent + * described. + */ +export function normalizeAntigravityToolCall( + toolCall: AcpToolCallState, + update: AntigravityToolCallUpdate, +): AcpToolCallState { + const named = antigravityProxiedMcpTool(update); + if (named !== undefined) return asMcpToolCall(toolCall, named); + const shown = shownMcpTool(toolCall); + if (shown === undefined) return toolCall; + const restated = isRecord(update.rawInput) ? update.rawInput : undefined; + const conflicting = + commandOrEditEvidence(update) || + (update.kind !== undefined && update.kind !== null && update.kind !== "execute") || + (update.title !== undefined && + update.title !== null && + update.title !== `MCP Tool ${shown.tool}`) || + (restated !== undefined && + (!Object.keys(restated).every((key) => WRAPPER_INPUT_KEYS.has(key)) || + restated.ServerName !== shown.server || + restated.ToolName !== shown.tool || + (restated.Arguments !== undefined && !isRecord(restated.Arguments)))); + return conflicting ? withoutMcpTool(toolCall, update) : asMcpToolCall(toolCall, shown); +} diff --git a/apps/server/src/provider/antigravity/AntigravityTurns.test.ts b/apps/server/src/provider/antigravity/AntigravityTurns.test.ts new file mode 100644 index 000000000..b327f4d2a --- /dev/null +++ b/apps/server/src/provider/antigravity/AntigravityTurns.test.ts @@ -0,0 +1,1903 @@ +// @effect-diagnostics nodeBuiltinImport:off +import * as os from "node:os"; +import * as path from "node:path"; +import { chmod, mkdir, mkdtemp, readFile, writeFile } from "node:fs/promises"; +import { fileURLToPath } from "node:url"; + +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { it } from "@effect/vitest"; +import { + AntigravitySettings, + ApprovalRequestId, + type ChatAttachment, + ProviderDriverKind, + type ProviderRuntimeEvent, + type ThreadContextSeed, + ThreadId, + type TurnId, +} from "@threadlines/contracts"; +import * as Deferred from "effect/Deferred"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; +import * as Fiber from "effect/Fiber"; +import * as Layer from "effect/Layer"; +import * as Schema from "effect/Schema"; +import * as Stream from "effect/Stream"; +import { describe, expect } from "vite-plus/test"; + +import { resolveAttachmentPath } from "../../attachmentStore.ts"; +import { ServerConfig } from "../../config.ts"; +import type { UsageLedgerEntry } from "../../usage/usageLedger.ts"; +import { type AcpTurnMachineSeam, makeAcpAdapter } from "../acp/AcpAdapter.ts"; +import type { AcpToolCallState } from "../acp/AcpRuntimeModel.ts"; +import { makeAntigravityDescriptor } from "../acp/AntigravityAcpSupport.ts"; +import { + antigravityFailure, + antigravityTurnBehavior, + antigravityTurnUsageTotals, + antigravityWorkAfterPrompt, +} from "./AntigravityTurns.ts"; +import { normalizeAntigravityToolCall } from "./AntigravityToolCalls.ts"; + +const decodeSettings = Schema.decodeSync(AntigravitySettings); +const mockAgentPath = path.join( + path.dirname(fileURLToPath(import.meta.url)), + "../../../scripts/antigravity-mock-agent.ts", +); +const isWindows = process.platform === "win32"; + +/** An `agy` stand-in playing `scenario`: the mock behind a wrapper the descriptor launches. */ +async function makeAgyMock(scenario: string) { + const dir = await mkdtemp(path.join(os.tmpdir(), "agy-acp-mock-")); + const log = path.join(dir, "frames.jsonl"); + const wrapper = path.join(dir, isWindows ? "agy.cmd" : "agy"); + await writeFile( + wrapper, + isWindows + ? `@echo off\r\nset "AGYMOCK_SCENARIO=${scenario}"\r\nset "AGYMOCK_LOG=${log}"\r\n"${process.execPath}" "${mockAgentPath}" %*\r\n` + : `#!/bin/sh\nexport AGYMOCK_SCENARIO=${JSON.stringify(scenario)}\nexport AGYMOCK_LOG=${JSON.stringify(log)}\nexec ${JSON.stringify(process.execPath)} ${JSON.stringify(mockAgentPath)} "$@"\n`, + "utf8", + ); + await chmod(wrapper, 0o755); + return { dir, wrapper, log }; +} + +async function readFrames(file: string): Promise>> { + const raw = await readFile(file, "utf8").catch(() => ""); + return raw + .split("\n") + .filter((line) => line.trim().length > 0) + .map((line) => JSON.parse(line) as Record); +} + +type AgyDescriptor = ReturnType; + +/** + * Starts an Antigravity session on the stand-in, collecting every runtime + * event. `adjust` changes the real descriptor for one test (a paused outcome + * check, a shorter limit); `newAdapter` makes another adapter on the same + * profile and state, as a server restart would. + */ +const startAgy = ( + scenario: string, + adjust?: (descriptor: AgyDescriptor) => AgyDescriptor, + runtimeMode: "full-access" | "approval-required" | "auto-accept-edits" = "full-access", + turnMachineSeams?: (seam: AcpTurnMachineSeam) => Effect.Effect, + contextSeed?: ThreadContextSeed, +) => + Effect.gen(function* () { + const mock = yield* Effect.promise(() => makeAgyMock(scenario)); + const base = makeAntigravityDescriptor({ + paths: { profileDir: path.join(mock.dir, "profile"), tempRoot: path.join(mock.dir, "tmp") }, + runtime: undefined, + releases: undefined, + signIn: { method: "oauth-personal", project: "", location: "", key: "" }, + }); + const descriptor = adjust ? adjust(base) : base; + const usage: Array = []; + const events: Array = []; + // What the adapter put on the provider status (`onSessionCommands`). + const commandReports: Array | undefined> = []; + const newAdapter = Effect.gen(function* () { + const made = yield* makeAcpAdapter( + descriptor, + decodeSettings({ enabled: true, binaryPath: mock.wrapper }), + { + recordTurnUsage: (entry) => Effect.sync(() => void usage.push(entry)), + onSessionCommands: (_sessionKey, commands) => + Effect.sync(() => void commandReports.push(commands?.map((command) => command.name))), + // The status lists one skill. + skillNames: Effect.succeed(new Set(["review"])), + ...(turnMachineSeams !== undefined ? { turnMachineSeams } : {}), + }, + ); + yield* made.streamEvents.pipe( + Stream.runForEach((event) => Effect.sync(() => void events.push(event))), + Effect.forkScoped, + ); + return made; + }); + const adapter = yield* newAdapter; + const threadId = ThreadId.make(`agy-${scenario}`); + const session = yield* adapter.startSession({ + threadId, + provider: ProviderDriverKind.make("antigravity"), + cwd: process.cwd(), + runtimeMode, + ...(contextSeed !== undefined ? { contextSeed } : {}), + }); + const waitFor = ( + predicate: (events: ReadonlyArray) => boolean, + attempts = 1_000, + ) => + Effect.gen(function* () { + for (let attempt = 0; attempt < attempts; attempt += 1) { + if (predicate(events)) return; + yield* Effect.sleep("10 millis"); + } + throw new Error(`Timed out; saw ${events.map((event) => event.type).join(", ")}`); + }); + return { + adapter, + events, + usage, + commandReports, + threadId, + session, + waitFor, + newAdapter, + frames: () => Effect.promise(() => readFrames(mock.log)), + }; + }); + +/** Steering, which Antigravity ships without (`ANTIGRAVITY_STEERS`), on for one test. */ +const withSteering = (descriptor: AgyDescriptor): AgyDescriptor => ({ + ...descriptor, + turnMachine: { ...descriptor.turnMachine!, steer: true }, +}); + +const completedTurns = (events: ReadonlyArray) => + events.flatMap((event) => (event.type === "turn.completed" ? [event] : [])); + +const replyTo = (events: ReadonlyArray, turnId: TurnId) => + events + .flatMap((event) => + event.type === "content.delta" && event.turnId === turnId ? [event.payload.delta] : [], + ) + .join(""); + +/** Each subagent's latest status, by its launching call. */ +const subagentStatuses = (events: ReadonlyArray) => + Object.fromEntries( + events.flatMap((event) => + event.type === "subagent.metadata.updated" && + event.payload.callId !== undefined && + event.payload.status !== undefined + ? [[event.payload.callId, event.payload.status] as const] + : [], + ), + ); + +const testServices = Layer.provideMerge( + ServerConfig.layerTest(process.cwd(), { prefix: "threadlines-agy-adapter-test-" }), + NodeServices.layer, +); + +describe("Antigravity turns", () => { + it.live( + "keeps a turn working while its command runs, then shows the reply the agent starts by itself", + () => + Effect.gen(function* () { + const agy = yield* startAgy("background"); + const { turnId } = yield* agy.adapter.sendTurn({ + threadId: agy.threadId, + input: "build it", + attachments: [], + }); + // The prompt has answered, the command still runs: the turn is open. + yield* agy.waitFor((events) => replyTo(events, turnId).includes("I'll report")); + yield* Effect.sleep("200 millis"); + expect(completedTurns(agy.events)).toHaveLength(0); + const [running] = yield* agy.adapter.listSessions(); + expect(running?.status).toBe("running"); + // The prompt's tokens are written as it answers, not when the hold ends. + expect(agy.usage.map((entry) => entry.turnId)).toEqual([turnId]); + + yield* agy.waitFor((events) => completedTurns(events).length === 1); + expect(replyTo(agy.events, turnId)).toContain("The build passed."); + expect(completedTurns(agy.events)[0]).toMatchObject({ + turnId, + payload: { state: "completed" }, + }); + // One turn: the agent's reply did not open a second. + expect(agy.events.filter((event) => event.type === "turn.started")).toHaveLength(1); + // Input is input plus cached reads; thinking sits inside output. + expect(agy.usage).toEqual([ + expect.objectContaining({ + turnId, + totals: { + uncachedInputTokens: 1_000, + cachedInputTokens: 4_000, + cacheCreationTokens: 0, + outputTokens: 50, + reasoningTokens: 20, + }, + }), + ]); + // The context meter reads Antigravity's usage_update. + expect( + agy.events.find((event) => event.type === "thread.token-usage.updated"), + ).toMatchObject({ payload: { usage: { usedTokens: 9_000, maxTokens: 1_048_576 } } }); + }).pipe(Effect.scoped, Effect.provide(testServices)), + ); + + it.live("stops a turn held by a running command, once, and cancels the command", () => + Effect.gen(function* () { + const agy = yield* startAgy("hang"); + const { turnId } = yield* agy.adapter.sendTurn({ + threadId: agy.threadId, + input: "build it", + attachments: [], + }); + yield* agy.waitFor((events) => replyTo(events, turnId).includes("I'll report")); + yield* Effect.sleep("300 millis"); + expect(completedTurns(agy.events)).toHaveLength(0); + + yield* agy.adapter.interruptTurn(agy.threadId); + yield* agy.waitFor((events) => completedTurns(events).length === 1); + // Long enough for a second settle to show if there were one. + yield* Effect.sleep("2500 millis"); + expect(completedTurns(agy.events)).toEqual([ + expect.objectContaining({ + turnId, + payload: { state: "cancelled", stopReason: "cancelled" }, + }), + ]); + // The CLI's cancellation notice, after the stop, opens no turn of its own. + expect(agy.events.filter((event) => event.type === "turn.started")).toHaveLength(1); + expect(JSON.stringify(agy.events)).not.toContain("cancelled by the client"); + const frames = yield* agy.frames(); + expect(frames.filter((frame) => frame.method === "session/cancel")).toHaveLength(1); + const [idle] = yield* agy.adapter.listSessions(); + expect(idle?.status).toBe("ready"); + }).pipe(Effect.scoped, Effect.provide(testServices)), + ); + + it.live( + "holds a turn for a launched subagent until its report ends, with no records to read", + () => + Effect.gen(function* () { + const agy = yield* startAgy("subagent"); + const { turnId } = yield* agy.adapter.sendTurn({ + threadId: agy.threadId, + input: "find the flaky test", + attachments: [], + }); + yield* agy.waitFor((events) => completedTurns(events).length === 1); + expect(replyTo(agy.events, turnId)).toContain("The researcher found it."); + expect(completedTurns(agy.events)[0]?.turnId).toBe(turnId); + }).pipe(Effect.scoped, Effect.provide(testServices)), + ); + + it.live("shows each subagent with its role, prompt, report and steps", () => + Effect.gen(function* () { + const agy = yield* startAgy("subagent-records"); + const { turnId } = yield* agy.adapter.sendTurn({ + threadId: agy.threadId, + input: "find and review the flaky test", + attachments: [], + }); + // The first report and the reply to it leave the second subagent at work. + yield* agy.waitFor((events) => replyTo(events, turnId).includes("The researcher found it.")); + yield* Effect.sleep("2500 millis"); + expect(completedTurns(agy.events)).toHaveLength(0); + expect(subagentStatuses(agy.events)).toEqual({ + call_research: "completed", + call_review: "running", + }); + + yield* agy.waitFor((events) => completedTurns(events).length === 1); + expect(completedTurns(agy.events)[0]).toMatchObject({ + turnId, + payload: { state: "completed" }, + }); + expect(replyTo(agy.events, turnId)).toContain("The reviewer agreed."); + expect(subagentStatuses(agy.events)).toEqual({ + call_research: "completed", + call_review: "completed", + }); + // Each launch shows as a subagent with its role, prompt and report. + const started = agy.events.filter( + (event) => event.type === "subagent.metadata.updated" && event.payload.status === "running", + ); + expect(started.map((event) => event.payload)).toEqual([ + expect.objectContaining({ + callId: "call_research", + agentRole: "Researcher", + objective: "Find the flaky test", + isBackgrounded: true, + }), + expect.objectContaining({ callId: "call_review", agentRole: "Reviewer" }), + ]); + expect( + agy.events.find( + (event) => + event.type === "subagent.metadata.updated" && + event.payload.callId === "call_research" && + event.payload.status === "completed", + ), + ).toMatchObject({ turnId, payload: { resultBody: "The flaky test is api.test.ts." } }); + // Nothing is left running in the task snapshot. + const snapshots = agy.events.flatMap((event) => + event.type === "task.snapshot.updated" ? [event.payload.tasks.length] : [], + ); + expect(snapshots.at(-1)).toBe(0); + + // The subagent view reads the child's steps from the CLI's records. + const transcript = yield* agy.adapter.readSubagentTranscript!(agy.threadId, { + threadId: agy.threadId, + agentId: "call_research", + }); + expect(transcript.agent).toMatchObject({ id: "child-research", agentType: "Researcher" }); + expect(transcript.entries).toEqual([ + { id: "launch", role: "user", text: "Find the flaky test", toolUses: [] }, + { + id: "step-1", + role: "assistant", + text: "", + toolUses: [{ name: "view_file", summary: "/project/api.test.ts" }], + }, + { + id: "step-2", + role: "system", + text: "", + toolUses: [], + outputPreview: "1: it.skip('flaky')", + }, + { id: "step-3", role: "assistant", text: "Found it.", toolUses: [] }, + ]); + // A launch the records don't name says so. + const missing = yield* Effect.flip( + agy.adapter.readSubagentTranscript!(agy.threadId, { + threadId: agy.threadId, + agentId: "call_unknown", + }), + ); + expect(missing.message).toContain("Antigravity did not record which subagent this started"); + }).pipe(Effect.scoped, Effect.provide(testServices)), + ); + + it.live("opens a turn for a reply the agent starts after its turn ended", () => + Effect.gen(function* () { + const agy = yield* startAgy("wake"); + const { turnId } = yield* agy.adapter.sendTurn({ + threadId: agy.threadId, + input: "set a timer", + attachments: [], + }); + yield* agy.waitFor((events) => completedTurns(events).length === 1); + yield* agy.waitFor((events) => completedTurns(events).length === 2); + const [first, second] = completedTurns(agy.events); + expect(first?.turnId).toBe(turnId); + expect(second?.turnId).not.toBe(turnId); + expect(replyTo(agy.events, second!.turnId!)).toBe("Woke up by myself."); + expect(second?.payload.state).toBe("completed"); + }).pipe(Effect.scoped, Effect.provide(testServices)), + ); + + it.live("steers a running turn with a second prompt, never cancelling it", () => + Effect.gen(function* () { + const agy = yield* startAgy("steer", withSteering); + expect(agy.adapter.capabilities.activeTurnSteering).toBe("supported"); + const { turnId } = yield* agy.adapter.sendTurn({ + threadId: agy.threadId, + input: "go", + attachments: [], + }); + yield* agy.waitFor((events) => replyTo(events, turnId).includes("Working on it.")); + const steered = yield* agy.adapter.steerTurn!({ + threadId: agy.threadId, + expectedTurnId: turnId, + input: "also check the tests", + }); + expect(steered.turnId).toBe(turnId); + yield* agy.waitFor((events) => completedTurns(events).length === 1); + yield* Effect.sleep("300 millis"); + expect(completedTurns(agy.events)).toHaveLength(1); + expect(completedTurns(agy.events)[0]).toMatchObject({ + turnId, + payload: { state: "completed" }, + }); + expect(replyTo(agy.events, turnId)).toContain("Steered: also check the tests"); + const frames = yield* agy.frames(); + expect(frames.filter((frame) => frame.method === "session/prompt")).toHaveLength(2); + expect(frames.some((frame) => frame.method === "session/cancel")).toBe(false); + // Both prompts' tokens count, each under an id of its own. + expect( + agy.usage.map((entry) => [entry.turnId, entry.totals.uncachedInputTokens]).toSorted(), + ).toEqual([ + [turnId, 100], + [`${turnId}:2`, 300], + ]); + }).pipe(Effect.scoped, Effect.provide(testServices)), + ); + + it.live("fails a turn whose normal end hid an upstream error, with the error's words", () => + Effect.gen(function* () { + const agy = yield* startAgy("log-error"); + yield* agy.adapter.sendTurn({ threadId: agy.threadId, input: "hi", attachments: [] }); + yield* agy.waitFor((events) => completedTurns(events).length === 1); + expect(completedTurns(agy.events)[0]?.payload).toMatchObject({ + state: "failed", + failureCategory: "server_error", + errorMessage: + "Antigravity: Bad Gateway: Failed to connect to backend API (502 Bad Gateway)", + }); + }).pipe(Effect.scoped, Effect.provide(testServices)), + ); + + it.live("carries an exhausted quota's reset time to the usage-limit notice", () => + Effect.gen(function* () { + const agy = yield* startAgy("quota"); + yield* agy.adapter.sendTurn({ threadId: agy.threadId, input: "hi", attachments: [] }); + yield* agy.waitFor((events) => completedTurns(events).length === 1); + expect(completedTurns(agy.events)[0]?.payload).toMatchObject({ + state: "failed", + failureCategory: "rate_limit", + usageLimit: { resetsAt: "2026-11-24T01:05:00.000Z" }, + }); + }).pipe(Effect.scoped, Effect.provide(testServices)), + ); + + it.live("ends a session Google can't continue, saying its conversation is lost", () => + Effect.gen(function* () { + const agy = yield* startAgy("lost-signature"); + yield* agy.adapter.sendTurn({ threadId: agy.threadId, input: "hi", attachments: [] }); + yield* agy.waitFor((events) => completedTurns(events).length === 1); + expect(completedTurns(agy.events)[0]?.payload).toMatchObject({ state: "failed" }); + yield* agy.waitFor((events) => events.some((event) => event.type === "session.exited")); + // ProviderService forgets the conversation off this (see its tests), + // so the next start opens a new one seeded with the thread's history. + expect(agy.events.find((event) => event.type === "session.exited")).toMatchObject({ + // Named, so only a binding still on this session forgets it. + payload: { conversationLost: { sessionCreatedAt: agy.session.createdAt } }, + }); + }).pipe(Effect.scoped, Effect.provide(testServices)), + ); +}); + +describe("Antigravity turns, the hard cases", () => { + it.live("keeps a turn open for a scheduled wake whose call never changes until it fires", () => + Effect.gen(function* () { + const agy = yield* startAgy("schedule"); + const { turnId } = yield* agy.adapter.sendTurn({ + threadId: agy.threadId, + input: "remind me", + attachments: [], + }); + yield* agy.waitFor((events) => replyTo(events, turnId).includes("Timer set.")); + yield* Effect.sleep("2500 millis"); + expect(completedTurns(agy.events)).toHaveLength(0); + yield* agy.waitFor((events) => completedTurns(events).length === 1); + expect(replyTo(agy.events, turnId)).toContain("Timer fired."); + expect(agy.events.filter((event) => event.type === "turn.started")).toHaveLength(1); + }).pipe(Effect.scoped, Effect.provide(testServices)), + ); + + it.live("fails a held turn and stops the session when the agent exits", () => + Effect.gen(function* () { + const agy = yield* startAgy("exit"); + const { turnId } = yield* agy.adapter.sendTurn({ + threadId: agy.threadId, + input: "build it", + attachments: [], + }); + yield* agy.waitFor((events) => completedTurns(events).length === 1); + expect(completedTurns(agy.events)[0]).toMatchObject({ + turnId, + payload: { state: "failed", errorMessage: "Antigravity stopped before its work finished." }, + }); + yield* agy.waitFor((events) => events.some((event) => event.type === "session.exited")); + expect(agy.events.find((event) => event.type === "session.exited")).toMatchObject({ + payload: { exitKind: "error" }, + }); + expect(yield* agy.adapter.listSessions()).toEqual([]); + }).pipe(Effect.scoped, Effect.provide(testServices)), + ); + + it.live("ends a held turn when its session is stopped", () => + Effect.gen(function* () { + const agy = yield* startAgy("hang"); + const { turnId } = yield* agy.adapter.sendTurn({ + threadId: agy.threadId, + input: "build it", + attachments: [], + }); + yield* agy.waitFor((events) => replyTo(events, turnId).includes("I'll report")); + yield* Effect.sleep("300 millis"); + yield* agy.adapter.stopSession(agy.threadId); + expect(agy.events.filter((event) => event.type === "turn.aborted")).toEqual([ + expect.objectContaining({ turnId }), + ]); + expect(completedTurns(agy.events)).toEqual([]); + }).pipe(Effect.scoped, Effect.provide(testServices)), + ); + + it.live("recycles an agent that ignores Stop, even while another message waits", () => + Effect.gen(function* () { + const agy = yield* startAgy("ignore-cancel"); + const { turnId } = yield* agy.adapter.sendTurn({ + threadId: agy.threadId, + input: "think", + attachments: [], + }); + yield* agy.waitFor((events) => replyTo(events, turnId).includes("Thinking hard.")); + const waiting = yield* agy.adapter + .sendTurn({ threadId: agy.threadId, input: "next", attachments: [] }) + .pipe(Effect.exit, Effect.forkScoped); + yield* Effect.sleep("100 millis"); + yield* agy.adapter.interruptTurn(agy.threadId); + // The cancel deadline (15 seconds) passes and the agent is restarted. + yield* agy.waitFor((events) => completedTurns(events).length === 1, 2_500); + expect(completedTurns(agy.events)[0]).toMatchObject({ + turnId, + payload: { state: "cancelled" }, + }); + expect(Exit.isFailure(yield* Fiber.join(waiting))).toBe(true); + }).pipe(Effect.scoped, Effect.provide(testServices)), + ); + + it.live("takes a steer sent while the answer is read, and shows the steer's permission", () => + Effect.gen(function* () { + const reading = yield* Deferred.make(); + const release = yield* Deferred.make(); + let first = true; + // The first prompt's outcome check waits for the test. + const agy = yield* startAgy( + "permission-second", + (descriptor) => { + const machine = descriptor.turnMachine!; + const outcome = machine.outcome!; + return { + ...descriptor, + turnMachine: { + ...machine, + steer: true, + outcome: { + watch: (sessionId, model) => + outcome.watch(sessionId, model).pipe( + Effect.map((watch) => ({ + ...watch, + check: (answer: Parameters[0]) => { + if (!first) return watch.check(answer); + first = false; + return Deferred.succeed(reading, undefined).pipe( + Effect.andThen(Deferred.await(release)), + Effect.andThen(watch.check(answer)), + ); + }, + })), + ), + }, + }, + }; + }, + "approval-required", + ); + const { turnId } = yield* agy.adapter.sendTurn({ + threadId: agy.threadId, + input: "first", + attachments: [], + }); + yield* Deferred.await(reading); + // The steer lands while the first answer is read: it carries the turn on. + const steered = yield* agy.adapter.steerTurn!({ + threadId: agy.threadId, + expectedTurnId: turnId, + input: "second", + }); + expect(steered.turnId).toBe(turnId); + yield* agy.waitFor((events) => events.some((event) => event.type === "request.opened")); + const opened = agy.events.find((event) => event.type === "request.opened"); + expect(opened?.turnId).toBe(turnId); + yield* agy.adapter.respondToRequest(agy.threadId, opened!.requestId as never, "accept"); + // The first answer's reading finishes late: it settles nothing. + yield* Deferred.succeed(release, undefined); + yield* agy.waitFor((events) => completedTurns(events).length === 1); + yield* Effect.sleep("300 millis"); + expect(completedTurns(agy.events)).toEqual([ + expect.objectContaining({ + turnId, + payload: expect.objectContaining({ state: "completed" }), + }), + ]); + expect(replyTo(agy.events, turnId)).toContain("Second done."); + }).pipe(Effect.scoped, Effect.provide(testServices)), + ); + + it.live("steers without inheriting the error the earlier prompt left in the log", () => + Effect.gen(function* () { + const agy = yield* startAgy("steer-log-error", withSteering); + const { turnId } = yield* agy.adapter.sendTurn({ + threadId: agy.threadId, + input: "go", + attachments: [], + }); + yield* agy.waitFor((events) => replyTo(events, turnId).includes("Working on it.")); + yield* agy.adapter.steerTurn!({ + threadId: agy.threadId, + expectedTurnId: turnId, + input: "try again", + }); + yield* agy.waitFor((events) => completedTurns(events).length === 1); + expect(completedTurns(agy.events)[0]?.payload.state).toBe("completed"); + }).pipe(Effect.scoped, Effect.provide(testServices)), + ); + + it.live("steers without inheriting an error the earlier prompt writes late", () => + Effect.gen(function* () { + const agy = yield* startAgy("steer-late-log-error", withSteering); + const { turnId } = yield* agy.adapter.sendTurn({ + threadId: agy.threadId, + input: "go", + attachments: [], + }); + yield* agy.waitFor((events) => replyTo(events, turnId).includes("Working on it.")); + yield* agy.adapter.steerTurn!({ + threadId: agy.threadId, + expectedTurnId: turnId, + input: "try again", + }); + yield* agy.waitFor((events) => completedTurns(events).length === 1); + expect(completedTurns(agy.events)[0]?.payload.state).toBe("completed"); + }).pipe(Effect.scoped, Effect.provide(testServices)), + ); + + it.live( + "fails a steer whose own error is logged before the earlier prompt answers (finding 5)", + () => + Effect.gen(function* () { + const agy = yield* startAgy("steer-own-log-error", withSteering); + const { turnId } = yield* agy.adapter.sendTurn({ + threadId: agy.threadId, + input: "go", + attachments: [], + }); + yield* agy.waitFor((events) => replyTo(events, turnId).includes("Working on it.")); + yield* agy.adapter.steerTurn!({ + threadId: agy.threadId, + expectedTurnId: turnId, + input: "try again", + }); + yield* agy.waitFor((events) => completedTurns(events).length === 1); + // Moving the reading past the older prompt's answer would hide this. + expect(completedTurns(agy.events)[0]?.payload).toMatchObject({ + state: "failed", + errorMessage: expect.stringContaining("502"), + }); + }).pipe(Effect.scoped, Effect.provide(testServices)), + ); + + it.live("writes the cost the agent reports with the prompt that spent it", () => + Effect.gen(function* () { + const agy = yield* startAgy("cost"); + const { turnId } = yield* agy.adapter.sendTurn({ + threadId: agy.threadId, + input: "build it", + attachments: [], + }); + yield* agy.waitFor((events) => completedTurns(events).length === 1); + yield* Effect.sleep("100 millis"); + const lines = agy.usage.map((entry) => ({ + turnId: entry.turnId, + input: entry.totals.uncachedInputTokens, + cost: Math.round((entry.costUsd ?? -1) * 1000) / 1000, + })); + // The tokens and the cost spent up to the answer share one line; the + // cost of the agent's own reply after it has a line of its own. + expect(lines).toEqual([ + { turnId, input: 400, cost: 0.02 }, + { turnId: `${turnId}:after`, input: 0, cost: 0.03 }, + ]); + }).pipe(Effect.scoped, Effect.provide(testServices)), + ); + + it.live( + "opens a new conversation when the lost one is resumed before its binding forgets it", + () => + Effect.gen(function* () { + const agy = yield* startAgy("lost-signature"); + yield* agy.adapter.sendTurn({ threadId: agy.threadId, input: "hi", attachments: [] }); + yield* agy.waitFor((events) => events.some((event) => event.type === "session.exited")); + // A message sent at once restarts the thread on its old cursor, before + // ProviderService has written the forget into its binding. + const restarted = yield* agy.adapter.startSession({ + threadId: agy.threadId, + provider: ProviderDriverKind.make("antigravity"), + cwd: process.cwd(), + runtimeMode: "full-access", + resumeCursor: agy.session.resumeCursor, + }); + expect(restarted.resumeFailed).toBe(true); + const frames = yield* agy.frames(); + expect(frames.filter((frame) => frame.method === "session/new")).toHaveLength(2); + expect(frames.some((frame) => frame.method === "session/resume")).toBe(false); + }).pipe(Effect.scoped, Effect.provide(testServices)), + ); + + it.live("holds a turn until each subagent has reported", () => + Effect.gen(function* () { + const agy = yield* startAgy("subagents"); + const { turnId } = yield* agy.adapter.sendTurn({ + threadId: agy.threadId, + input: "research and test", + attachments: [], + }); + yield* agy.waitFor((events) => completedTurns(events).length === 1); + expect(replyTo(agy.events, turnId)).toContain("The tester reported."); + expect(agy.events.filter((event) => event.type === "turn.started")).toHaveLength(1); + }).pipe(Effect.scoped, Effect.provide(testServices)), + ); + + it.live("ends the hold when the records show every child reported in one reply", () => + Effect.gen(function* () { + const agy = yield* startAgy("records-one-reply"); + const { turnId } = yield* agy.adapter.sendTurn({ + threadId: agy.threadId, + input: "research and review", + attachments: [], + }); + // Counting one subagent per reply would hold the second for 30 minutes. + yield* agy.waitFor((events) => completedTurns(events).length === 1); + expect(replyTo(agy.events, turnId)).toContain("Both agents reported."); + }).pipe(Effect.scoped, Effect.provide(testServices)), + ); + + it.live("stops holding a child the agent killed", () => + Effect.gen(function* () { + const agy = yield* startAgy("records-killed"); + const { turnId } = yield* agy.adapter.sendTurn({ + threadId: agy.threadId, + input: "research and review", + attachments: [], + }); + yield* agy.waitFor((events) => completedTurns(events).length === 1); + expect(replyTo(agy.events, turnId)).toContain("I stopped the reviewer."); + }).pipe(Effect.scoped, Effect.provide(testServices)), + ); + + it.live("frees a subagent whose report never sends its closing usage update", () => + Effect.gen(function* () { + const agy = yield* startAgy("subagent-quiet", (descriptor) => ({ + ...descriptor, + turnMachine: { ...descriptor.turnMachine!, replyQuietLimit: Duration.seconds(1) }, + })); + const { turnId } = yield* agy.adapter.sendTurn({ + threadId: agy.threadId, + input: "research", + attachments: [], + }); + // Long before the 30-minute silent limit. + yield* agy.waitFor((events) => completedTurns(events).length === 1); + expect(replyTo(agy.events, turnId)).toContain("The researcher reported."); + }).pipe(Effect.scoped, Effect.provide(testServices)), + ); +}); + +const promptTexts = (frames: ReadonlyArray>) => + frames.flatMap((frame) => { + if (frame.method !== "session/prompt") return []; + const prompt = (frame.params as { prompt?: ReadonlyArray<{ type: string; text?: string }> }) + .prompt; + return [(prompt ?? []).flatMap((block) => (block.text ? [block.text] : [])).join("\n")]; + }); + +describe("Antigravity commands and edits", () => { + it.live( + "puts the session's own commands on the status, less Threadlines' own, and clears them", + () => + Effect.gen(function* () { + const agy = yield* startAgy("simple"); + yield* agy.waitFor(() => agy.commandReports.length > 0); + expect(agy.commandReports).toEqual([["goal", "compact"]]); + yield* agy.adapter.stopSession(agy.threadId); + expect(agy.commandReports.at(-1)).toBeUndefined(); + }).pipe(Effect.scoped, Effect.provide(testServices)), + ); + + it.live("reports a list that keeps changing at most once per interval, the newest last", () => + Effect.gen(function* () { + const agy = yield* startAgy("flapping"); + yield* agy.waitFor(() => agy.commandReports.length > 0); + yield* Effect.sleep("1 second"); + // The first list went at once; the nine changes after it wait. + expect(agy.commandReports).toHaveLength(1); + yield* agy.waitFor(() => agy.commandReports.length > 1, 700); + yield* Effect.sleep("500 millis"); + expect(agy.commandReports).toEqual([["goal", "compact"], ["goal"]]); + }).pipe(Effect.scoped, Effect.provide(testServices)), + ); + + it.live("runs only the person's typed command the session lists, as typed, in plan mode", () => + Effect.gen(function* () { + const agy = yield* startAgy("simple"); + yield* agy.waitFor(() => agy.commandReports.length > 0); + const send = (input: string, typed?: { text: string; context?: string }) => + Effect.gen(function* () { + const before = completedTurns(agy.events).length; + const turn = yield* agy.adapter.sendTurn({ + threadId: agy.threadId, + input, + interactionMode: "plan", + attachments: [], + ...(typed ? { typed } : {}), + }); + yield* agy.waitFor((events) => completedTurns(events).length === before + 1); + return turn; + }); + // Advertised, and a skill the status lists: commands. + yield* send("/compact", { text: "/compact" }); + yield* send("/review the diff", { text: "/review the diff" }); + // Not listed, a path and plain text: ordinary text. + yield* send("/etc is missing", { text: "/etc is missing" }); + yield* send("/tmp/out.log is empty", { text: "/tmp/out.log is empty" }); + yield* send("/compact"); + // Spaces in front change nothing: the trimmed text decides. + yield* send(" /compact", { text: " /compact" }); + // The server's context in front: the command goes alone, its context deferred. + const deferred = yield* send("Earlier turns\n\n---\n\n/compact", { + text: "/compact", + context: "Earlier turns", + }); + expect(deferred.contextDeferred).toBe(true); + expect(promptTexts(yield* agy.frames())).toEqual([ + "/compact", + "/review the diff", + "/plan /etc is missing", + "/plan /tmp/out.log is empty", + "/plan /compact", + "/compact", + "/compact", + ]); + }).pipe(Effect.scoped, Effect.provide(testServices)), + ); + + it.live("ends the session on a revert, its running work and turn stopped first", () => + Effect.gen(function* () { + const agy = yield* startAgy("hang"); + expect(agy.adapter.capabilities.conversationRollback).toBe("new-session"); + const { turnId } = yield* agy.adapter.sendTurn({ + threadId: agy.threadId, + input: "build it", + attachments: [], + }); + yield* agy.waitFor((events) => replyTo(events, turnId).includes("I'll report")); + yield* Effect.sleep("300 millis"); + + const rolledBack = yield* agy.adapter.rollbackThread(agy.threadId, 1); + expect(rolledBack.conversationRolledBack).toBe(true); + expect(completedTurns(agy.events)).toEqual([ + expect.objectContaining({ + turnId, + payload: { state: "cancelled", stopReason: "cancelled" }, + }), + ]); + const frames = yield* agy.frames(); + expect(frames.filter((frame) => frame.method === "session/cancel")).toHaveLength(1); + expect(agy.events.some((event) => event.type === "session.exited")).toBe(true); + expect(yield* agy.adapter.hasSession(agy.threadId)).toBe(false); + }).pipe(Effect.scoped, Effect.provide(testServices)), + ); +}); + +/** + * Holds the turn machine's driver at the first seam `matches` picks, until + * released (`AcpAdapterOptions.turnMachineSeams`); `reached` waits for it to + * get there. A seam can also just be watched (`seen`). + */ +const makeGate = (matches: (seam: AcpTurnMachineSeam) => boolean) => + Effect.gen(function* () { + const reached = yield* Deferred.make(); + const release = yield* Deferred.make(); + const seen: Array = []; + let held = false; + const seams = (seam: AcpTurnMachineSeam) => + Effect.suspend(() => { + seen.push(seam); + if (held || !matches(seam)) return Effect.void; + held = true; + return Deferred.succeed(reached, undefined).pipe(Effect.andThen(Deferred.await(release))); + }); + return { + seams, + seen, + reached: Deferred.await(reached), + release: Deferred.succeed(release, undefined), + }; + }); + +const eventIndex = (events: ReadonlyArray, type: string) => + events.findIndex((event) => event.type === type); + +describe("Antigravity turn driver, the orderings", () => { + it.live("publishes a turn's end that a session stop lands on (finding 1)", () => + Effect.gen(function* () { + const gate = yield* makeGate( + (seam) => seam.point === "stepCommitted" && seam.commands.includes("endTurn"), + ); + const agy = yield* startAgy("simple", undefined, "full-access", gate.seams); + const { turnId } = yield* agy.adapter.sendTurn({ + threadId: agy.threadId, + input: "hi", + attachments: [], + }); + // The step that ends the turn is committed; its commands haven't run. + yield* gate.reached; + const stopping = yield* agy.adapter.stopSession(agy.threadId).pipe(Effect.forkScoped); + yield* Effect.sleep("200 millis"); + yield* gate.release; + yield* Fiber.join(stopping); + expect(completedTurns(agy.events).map((event) => event.turnId)).toEqual([turnId]); + expect(agy.events.some((event) => event.type === "turn.aborted")).toBe(false); + expect(eventIndex(agy.events, "turn.completed")).toBeLessThan( + eventIndex(agy.events, "session.exited"), + ); + }).pipe(Effect.scoped, Effect.provide(testServices)), + ); + + it.live("sends a steer only after the prompt it steers, whose setup ran first (finding 2)", () => + Effect.gen(function* () { + const gate = yield* makeGate((seam) => seam.point === "promptSetup" && seam.prompt === 1); + const agy = yield* startAgy("steer", withSteering, "full-access", gate.seams); + // The send returns once its prompt is written, so it waits on the gate too. + const sending = yield* agy.adapter + .sendTurn({ threadId: agy.threadId, input: "first message", attachments: [] }) + .pipe(Effect.forkScoped); + yield* gate.reached; + const started = agy.events.find((event) => event.type === "turn.started"); + const turnId = started!.turnId!; + // The first prompt's setup hasn't returned; the steer is taken anyway. + yield* agy.adapter.steerTurn!({ + threadId: agy.threadId, + expectedTurnId: turnId, + input: "the steer", + }); + yield* Effect.sleep("200 millis"); + const prompts = (frames: ReadonlyArray>) => + frames.flatMap((frame) => + frame.method === "session/prompt" ? [JSON.stringify(frame.params)] : [], + ); + expect(prompts(yield* agy.frames())).toEqual([]); + yield* gate.release; + expect((yield* Fiber.join(sending)).turnId).toBe(turnId); + yield* agy.waitFor((events) => completedTurns(events).length === 1); + const sent = prompts(yield* agy.frames()); + expect(sent).toHaveLength(2); + expect(sent[0]).toContain("first message"); + expect(sent[1]).toContain("the steer"); + expect(replyTo(agy.events, turnId)).toContain("Steered:"); + }).pipe(Effect.scoped, Effect.provide(testServices)), + ); + + it.live("keeps a wake that follows the answer at once in the answered turn (finding 6)", () => + Effect.gen(function* () { + // The answer is read and held back while the command's end and the + // start of its wake sit behind it. + const gate = yield* makeGate((seam) => seam.point === "answerRead" && seam.prompt === 1); + const agy = yield* startAgy("background-quick", undefined, "full-access", gate.seams); + const { turnId } = yield* agy.adapter.sendTurn({ + threadId: agy.threadId, + input: "build it", + attachments: [], + }); + yield* gate.reached; + yield* Effect.sleep("150 millis"); + yield* gate.release; + yield* agy.waitFor((events) => completedTurns(events).length === 1); + yield* Effect.sleep("500 millis"); + expect(agy.events.filter((event) => event.type === "turn.started")).toHaveLength(1); + expect(completedTurns(agy.events).map((event) => event.turnId)).toEqual([turnId]); + expect(replyTo(agy.events, turnId)).toContain("The build passed."); + }).pipe(Effect.scoped, Effect.provide(testServices)), + ); + + it.live("writes an answered prompt's usage when the session stops right after (finding 8)", () => + Effect.gen(function* () { + // The reader is held on the reply's text; the answer queues behind it. + const gate = yield* makeGate( + (seam) => seam.point === "stepCommitted" && seam.event === "agentOutput", + ); + const agy = yield* startAgy("simple", undefined, "full-access", gate.seams); + const { turnId } = yield* agy.adapter.sendTurn({ + threadId: agy.threadId, + input: "hi", + attachments: [], + }); + yield* gate.reached; + yield* Effect.sleep("200 millis"); + const stopping = yield* agy.adapter.stopSession(agy.threadId).pipe(Effect.forkScoped); + yield* Effect.sleep("100 millis"); + yield* gate.release; + yield* Fiber.join(stopping); + yield* Effect.sleep("100 millis"); + expect(agy.usage.map((entry) => [entry.turnId, entry.totals.uncachedInputTokens])).toEqual([ + [turnId, 10], + ]); + }).pipe(Effect.scoped, Effect.provide(testServices)), + ); + + it.live("drops an older reading of the records that lands after a newer one (finding 4)", () => + Effect.gen(function* () { + // The first reading (both children at work) is held until the newer + // one (both reported) is in. + const gate = yield* makeGate( + (seam) => seam.point === "childrenRead" && seam.generation === 1, + ); + const agy = yield* startAgy("records-one-reply", undefined, "full-access", gate.seams); + const { turnId } = yield* agy.adapter.sendTurn({ + threadId: agy.threadId, + input: "research and review", + attachments: [], + }); + yield* gate.reached; + yield* agy.waitFor(() => + gate.seen.some( + (seam) => + seam.point === "stepCommitted" && + seam.event === "childrenAtWork" && + seam.commands.includes("armTimer"), + ), + ); + yield* gate.release; + yield* agy.waitFor((events) => completedTurns(events).length === 1); + expect(replyTo(agy.events, turnId)).toContain("Both agents reported."); + }).pipe(Effect.scoped, Effect.provide(testServices)), + ); + + it.live("counts a quiet limit from the agent's last activity (finding 7)", () => + Effect.gen(function* () { + const agy = yield* startAgy("quiet-activity", (descriptor) => ({ + ...descriptor, + turnMachine: { ...descriptor.turnMachine!, silentLimit: Duration.millis(1_500) }, + })); + const { turnId } = yield* agy.adapter.sendTurn({ + threadId: agy.threadId, + input: "build it", + attachments: [], + }); + yield* agy.waitFor((events) => replyTo(events, turnId).includes("I'll report")); + const answeredAt = Date.now(); + yield* agy.waitFor((events) => completedTurns(events).length === 1, 1_000); + const elapsed = Date.now() - answeredAt; + // Activity 100 ms in: the limit ends 1.6 s in, not after a second full wait (3 s). + expect(elapsed).toBeGreaterThanOrEqual(1_400); + expect(elapsed).toBeLessThan(2_500); + }).pipe(Effect.scoped, Effect.provide(testServices)), + ); + + it.live( + "keeps a stopped command until the agent ends it, recycling one that won't (finding 3)", + () => + Effect.gen(function* () { + const agy = yield* startAgy("stuck"); + const { turnId } = yield* agy.adapter.sendTurn({ + threadId: agy.threadId, + input: "build it", + attachments: [], + }); + yield* agy.waitFor((events) => replyTo(events, turnId).includes("I'll report")); + yield* Effect.sleep("300 millis"); + yield* agy.adapter.interruptTurn(agy.threadId); + // The turn shows cancelled at once. + yield* agy.waitFor((events) => completedTurns(events).length === 1); + expect(completedTurns(agy.events)[0]?.payload.state).toBe("cancelled"); + // A message sent now waits for the stop, which the agent never confirms. + const waiting = yield* agy.adapter + .sendTurn({ threadId: agy.threadId, input: "next", attachments: [] }) + .pipe(Effect.exit, Effect.forkScoped); + yield* Effect.sleep("500 millis"); + expect(agy.events.filter((event) => event.type === "turn.started")).toHaveLength(1); + // The cancel deadline (15 seconds) passes and the agent is restarted. + yield* agy.waitFor( + (events) => + events.some( + (event) => + event.type === "runtime.warning" && event.payload.warningKind === "cancel-timeout", + ), + 2_000, + ); + expect(Exit.isFailure(yield* Fiber.join(waiting))).toBe(true); + yield* agy.waitFor((events) => events.some((event) => event.type === "session.exited")); + }).pipe(Effect.scoped, Effect.provide(testServices)), + ); + + it.live( + "reports a send whose mode setup failed undelivered, keeping its history for the next", + () => + Effect.gen(function* () { + const agy = yield* startAgy("mode-fails-once", undefined, "auto-accept-edits", undefined, { + version: 1, + fromProvider: ProviderDriverKind.make("claudeAgent"), + entries: [{ kind: "message", role: "user", text: "the earlier conversation" }], + }); + // The first prompt after a handoff: plan mode asks for the `default` + // mode, and switching to it fails once. + const first = yield* agy.adapter.sendTurn({ + threadId: agy.threadId, + input: "plan it", + interactionMode: "plan", + attachments: [], + }); + expect(first.undelivered).toBe(true); + yield* agy.waitFor((events) => completedTurns(events).length === 1); + expect(completedTurns(agy.events)[0]?.payload.state).toBe("failed"); + const prompts = () => + agy + .frames() + .pipe( + Effect.map((frames) => frames.filter((frame) => frame.method === "session/prompt")), + ); + expect(yield* prompts()).toHaveLength(0); + + const second = yield* agy.adapter.sendTurn({ + threadId: agy.threadId, + input: "plan it again", + interactionMode: "plan", + attachments: [], + }); + expect(second.undelivered).toBeUndefined(); + yield* agy.waitFor((events) => completedTurns(events).length === 2); + const sent = yield* prompts(); + expect(sent).toHaveLength(1); + // The history the first send took went with the one that went out. + expect(JSON.stringify(sent[0])).toContain("the earlier conversation"); + }).pipe(Effect.scoped, Effect.provide(testServices)), + ); + + it.live( + "returns a send undelivered, never hanging, when the session stops before its prompt goes out", + () => + Effect.gen(function* () { + const gate = yield* makeGate((seam) => seam.point === "promptSetup" && seam.prompt === 1); + const agy = yield* startAgy("simple", undefined, "full-access", gate.seams); + // The send returns once its prompt is written: it waits on the gate. + const sending = yield* agy.adapter + .sendTurn({ threadId: agy.threadId, input: "hi", attachments: [] }) + .pipe(Effect.forkScoped); + yield* gate.reached; + yield* agy.adapter.stopSession(agy.threadId); + expect((yield* Fiber.join(sending)).undelivered).toBe(true); + const frames = yield* agy.frames(); + expect(frames.filter((frame) => frame.method === "session/prompt")).toHaveLength(0); + }).pipe(Effect.scoped, Effect.provide(testServices)), + ); + + it.live("returns a send undelivered when the agent stopped reading its stdin", () => + Effect.gen(function* () { + const agy = yield* startAgy("deaf", undefined, "full-access", undefined, { + version: 1, + fromProvider: ProviderDriverKind.make("claudeAgent"), + entries: [{ kind: "message", role: "user", text: "the earlier conversation" }], + }); + yield* Effect.sleep("300 millis"); + // The prompt can be queued, but never written: the send says so, and + // doesn't wait on an answer that can't come. + const sent = yield* agy.adapter.sendTurn({ + threadId: agy.threadId, + input: "hello", + attachments: [], + }); + expect(sent.undelivered).toBe(true); + const frames = yield* agy.frames(); + expect(frames.filter((frame) => frame.method === "session/prompt")).toHaveLength(0); + }).pipe(Effect.scoped, Effect.provide(testServices)), + ); + + it.live("lets go of each prompt's record once its answer is in, a steered one's too", () => + Effect.gen(function* () { + const gate = yield* makeGate(() => false); + const agy = yield* startAgy("steer", withSteering, "full-access", gate.seams); + const { turnId } = yield* agy.adapter.sendTurn({ + threadId: agy.threadId, + input: "go", + attachments: [], + }); + yield* agy.waitFor((events) => replyTo(events, turnId).includes("Working on it.")); + // The first prompt is answered after the steer that replaced it. + yield* agy.adapter.steerTurn!({ + threadId: agy.threadId, + expectedTurnId: turnId, + input: "try again", + }); + yield* agy.waitFor((events) => completedTurns(events).length === 1); + yield* Effect.sleep("200 millis"); + // The next message's first step finds no record left of either prompt. + const before = gate.seen.length; + yield* agy.adapter.sendTurn({ threadId: agy.threadId, input: "next", attachments: [] }); + const sendStep = gate.seen + .slice(before) + .find((seam) => seam.point === "stepCommitted" && seam.event === "send"); + expect(sendStep).toMatchObject({ promptsHeld: 0 }); + }).pipe(Effect.scoped, Effect.provide(testServices)), + ); + + it.live("sends a prompt whose log baseline can't be read in time, judged by its own answer", () => + Effect.gen(function* () { + // The profile's file system stalls: noting where the log stands never returns. + const agy = yield* startAgy("log-error", (descriptor) => ({ + ...descriptor, + turnMachine: { + ...descriptor.turnMachine!, + outcome: { watch: () => Effect.never }, + }, + })); + const { turnId } = yield* agy.adapter.sendTurn({ + threadId: agy.threadId, + input: "hi", + attachments: [], + }); + yield* agy.waitFor((events) => completedTurns(events).length === 1, 800); + // With no baseline the log's error can't be tied to the prompt: its own answer stands. + expect(completedTurns(agy.events)[0]).toMatchObject({ + turnId, + payload: { state: "completed" }, + }); + }).pipe(Effect.scoped, Effect.provide(testServices)), + ); + + it.live("lets a revert wait for a stop under way until the agent's process is gone", () => + Effect.gen(function* () { + const gate = yield* makeGate((seam) => seam.point === "processTeardown"); + const agy = yield* startAgy("simple", undefined, "full-access", gate.seams); + // The stand-in's session ids carry its process id. + const sessionId = (agy.session.resumeCursor as { readonly sessionId: string }).sessionId; + const pid = Number(sessionId.split("-")[1]); + const alive = () => { + try { + process.kill(pid, 0); + return true; + } catch { + return false; + } + }; + const stopping = yield* agy.adapter.stopSession(agy.threadId).pipe(Effect.forkScoped); + yield* gate.reached; + // The stop has begun: the session reads as gone, but its process isn't. + expect(yield* agy.adapter.hasSession(agy.threadId)).toBe(false); + expect(alive()).toBe(true); + const waiting = yield* agy.adapter.whenStopped!(agy.threadId).pipe(Effect.forkScoped); + yield* Effect.sleep("200 millis"); + expect(waiting.pollUnsafe()).toBeUndefined(); + yield* gate.release; + yield* Fiber.join(waiting); + expect(alive()).toBe(false); + yield* Fiber.join(stopping); + // With nothing running, it answers at once. + yield* agy.adapter.whenStopped!(agy.threadId); + }).pipe(Effect.scoped, Effect.provide(testServices)), + ); + + it.live("holds a turn through an approval asked again while the user waits", () => + Effect.gen(function* () { + const opened = (events: ReadonlyArray) => + events.flatMap((event) => (event.type === "request.opened" ? [event] : [])); + // Quiet limits far shorter than the wait: a request the machine lost + // track of would end the turn under the open card. + const agy = yield* startAgy( + "wake-permission-reask", + (descriptor) => ({ + ...descriptor, + turnMachine: { + ...descriptor.turnMachine!, + silentLimit: Duration.millis(500), + replyQuietLimit: Duration.millis(500), + }, + }), + "approval-required", + ); + const { turnId } = yield* agy.adapter.sendTurn({ + threadId: agy.threadId, + input: "build it", + attachments: [], + }); + yield* agy.waitFor((events) => opened(events).length === 2); + // Past the reply's quiet limit and the settle after it (2 seconds). + yield* Effect.sleep("3000 millis"); + expect(completedTurns(agy.events)).toHaveLength(0); + const reasked = opened(agy.events)[1]!; + yield* agy.adapter.respondToRequest( + agy.threadId, + ApprovalRequestId.make(String(reasked.requestId)), + "accept", + ); + yield* agy.waitFor((events) => completedTurns(events).length === 1); + // One turn, ended once the reply after the answer was done. + expect(completedTurns(agy.events).map((event) => event.turnId)).toEqual([turnId]); + expect(replyTo(agy.events, turnId)).toContain("Done after asking."); + }).pipe(Effect.scoped, Effect.provide(testServices)), + ); + + it.live("queues a message sent mid-turn, steering being off for Antigravity", () => + Effect.gen(function* () { + const agy = yield* startAgy("background"); + expect(agy.adapter.steerTurn).toBeUndefined(); + expect(agy.adapter.capabilities.activeTurnSteering).toBeUndefined(); + const first = yield* agy.adapter.sendTurn({ + threadId: agy.threadId, + input: "build it", + attachments: [], + }); + // Sent while the first prompt runs: it waits for that turn to end. + const second = yield* agy.adapter.sendTurn({ + threadId: agy.threadId, + input: "and then lint", + attachments: [], + }); + yield* agy.waitFor((events) => completedTurns(events).length === 2); + expect(completedTurns(agy.events).map((event) => event.turnId)).toEqual([ + first.turnId, + second.turnId, + ]); + const prompts = (yield* agy.frames()).filter((frame) => frame.method === "session/prompt"); + expect(prompts).toHaveLength(2); + }).pipe(Effect.scoped, Effect.provide(testServices)), + ); +}); + +describe("Antigravity turn reading", () => { + const tool = (fields: Partial): AcpToolCallState => ({ + toolCallId: "call", + data: {}, + ...fields, + }); + + it("holds nothing for a real call_mcp_tool call, as normalized before the turn sees it", () => { + const update = { + title: "MCP Tool list_issues", + kind: "execute", + rawInput: { ServerName: "github", ToolName: "list_issues", Arguments: { repo: "x/y" } }, + }; + const call = tool({ + toolCallId: "call_mcp", + kind: "execute", + title: update.title, + data: update, + }); + expect(antigravityWorkAfterPrompt(normalizeAntigravityToolCall(call, update))).toBeUndefined(); + // A later update that shows a command makes it one again: it holds the turn. + const shown = { kind: "execute", rawInput: { CommandLine: "rm -rf build" } }; + const command = normalizeAntigravityToolCall(normalizeAntigravityToolCall(call, update), shown); + expect(antigravityWorkAfterPrompt(command)).toEqual({ + kind: "command", + }); + }); + + it("tells the work that outlives a prompt from what ends with it", () => { + expect( + antigravityWorkAfterPrompt( + tool({ kind: "execute", data: { rawInput: { CommandLine: "npm test" } } }), + ), + ).toEqual({ kind: "command" }); + // A daemon (a dev server) may never end. + expect( + antigravityWorkAfterPrompt( + tool({ + kind: "execute", + data: { rawInput: { CommandLine: "npm run dev", IsDaemon: true } }, + }), + ), + ).toBeUndefined(); + expect(antigravityWorkAfterPrompt(tool({ kind: "other", title: "Running schedule" }))).toEqual({ + kind: "timer", + }); + expect( + antigravityWorkAfterPrompt( + tool({ + kind: "other", + title: "Running invoke_subagent", + data: { rawInput: { Role: "Artist", Prompt: "Paint" } }, + }), + ), + ).toEqual({ kind: "subagents", count: 1 }); + // agy 1.5 titles a launch it ran without asking "Run invoke_subagent". + expect( + antigravityWorkAfterPrompt( + tool({ + kind: "other", + title: "Run invoke_subagent", + data: { rawInput: { Role: "Artist", Prompt: "Paint" } }, + }), + ), + ).toEqual({ kind: "subagents", count: 1 }); + // A batch launch counts each subagent. + expect( + antigravityWorkAfterPrompt( + tool({ + kind: "other", + title: "Running invoke_subagent", + data: { + rawInput: { + Subagents: [ + { Role: "Artist", Prompt: "Paint" }, + { Role: "Critic", Prompt: "Judge" }, + ], + }, + }, + }), + ), + ).toEqual({ kind: "subagents", count: 2 }); + expect(antigravityWorkAfterPrompt(tool({ kind: "read", title: "Read file" }))).toBeUndefined(); + }); + + it("reads Google's error renderings into retryable failures and a quota reset", () => { + const nowMs = Date.UTC(2026, 10, 23, 12); + expect( + antigravityFailure({ + errorText: "UNAVAILABLE (code 503): The service is currently unavailable.", + nowMs, + }), + ).toEqual({ + errorMessage: "Antigravity: The service is currently unavailable. (503 UNAVAILABLE)", + failureCategory: "overloaded", + }); + // A plain rate limit fails the turn without a usage-limit notice. + expect( + antigravityFailure({ + errorText: + "Error 429, Message: Resource has been exhausted (e.g. check quota)., Status: RESOURCE_EXHAUSTED, Details: [map[reason:RATE_LIMIT_EXCEEDED]]", + nowMs, + }), + ).toMatchObject({ failureCategory: "rate_limit" }); + // A quota with only a delay resets that long from now. + expect( + antigravityFailure({ + errorText: "Details: [map[metadata:map[quotaResetDelay:1h30m0s] reason:QUOTA_EXHAUSTED]]", + nowMs, + })?.usageLimit, + ).toEqual({ resetsAt: "2026-11-23T13:30:00.000Z" }); + // `refusal` is the stop reason an exhausted quota gets, with no text. + expect( + antigravityFailure({ errorText: undefined, stopReason: "refusal", nowMs }), + ).toMatchObject({ failureCategory: "rate_limit", usageLimit: {} }); + expect(antigravityFailure({ errorText: undefined, stopReason: "end_turn", nowMs })).toBe( + undefined, + ); + // A 404 before the model answered: a model the account can't use. + expect( + antigravityFailure({ + errorText: + "Error 404, Message: Requested entity was not found., Status: NOT_FOUND, Details: []", + reachedModel: false, + nowMs, + })?.failureCategory, + ).toBe("model_unavailable"); + }); + + it.effect( + "gives a quota with no reset time the one the plan meter knows for the turn's model", + () => + Effect.gen(function* () { + const profileDir = yield* Effect.promise(() => + mkdtemp(path.join(os.tmpdir(), "threadlines-agy-turn-")), + ); + const asked: Array = []; + const behavior = antigravityTurnBehavior(profileDir, (model) => + Effect.sync(() => { + asked.push(model); + return { window: "weekly" as const, resetsAt: "2026-11-24T00:00:00.000Z" }; + }), + ); + const { check } = yield* behavior.turnMachine!.outcome!.watch( + "session-1", + "claude-sonnet-agent", + ); + const quota = { + _tag: "AcpRequestError", + errorMessage: "Details: [map[reason:QUOTA_EXHAUSTED]]", + }; + expect(yield* check({ error: quota })).toMatchObject({ + failureCategory: "rate_limit", + usageLimit: { window: "weekly", resetsAt: "2026-11-24T00:00:00.000Z" }, + }); + expect(asked).toEqual(["claude-sonnet-agent"]); + + // A reset time the agent gave wins, and the meter isn't asked. + const timed = { + _tag: "AcpRequestError", + errorMessage: + "Details: [map[metadata:map[quotaResetDelay:1h0m0s] reason:QUOTA_EXHAUSTED]]", + }; + expect((yield* check({ error: timed }))?.usageLimit?.window).toBeUndefined(); + expect(asked).toHaveLength(1); + }), + ); + + it("keeps a result that only wrote to the cache", () => { + expect( + antigravityTurnUsageTotals({ + inputTokens: 0, + outputTokens: 0, + cachedWriteTokens: 1_200, + totalTokens: 1_200, + }), + ).toMatchObject({ cacheCreationTokens: 1_200 }); + }); + + it("counts cached reads as input and thinking inside output", () => { + expect( + antigravityTurnUsageTotals({ + inputTokens: 1_000, + cachedReadTokens: 4_000, + outputTokens: 50, + thoughtTokens: 80, + totalTokens: 5_050, + }), + ).toEqual({ + uncachedInputTokens: 1_000, + cachedInputTokens: 4_000, + cacheCreationTokens: 0, + outputTokens: 50, + reasoningTokens: 50, + }); + }); +}); + +describe("Antigravity tool rows and attachments", () => { + const toolItem = (events: ReadonlyArray, id: string) => + events.findLast((event) => event.type === "item.completed" && String(event.itemId) === id) as + | Extract + | undefined; + + it.live.each(["approval-required", "full-access"] as const)( + "asks %s for a call_mcp_tool call as a command that names the server, tool and arguments", + (runtimeMode) => + Effect.gen(function* () { + const agy = yield* startAgy("mcp-permission", undefined, runtimeMode); + yield* agy.adapter.sendTurn({ threadId: agy.threadId, input: "go", attachments: [] }); + if (runtimeMode === "approval-required") { + // Supervised asks for both, as it did before. + for (let asked = 1; asked <= 2; asked += 1) { + yield* agy.waitFor( + (events) => + events.filter((event) => event.type === "request.opened").length === asked, + ); + const request = agy.events.filter((event) => event.type === "request.opened")[ + asked - 1 + ] as Extract; + yield* agy.adapter.respondToRequest( + agy.threadId, + ApprovalRequestId.make(String(request.requestId)), + "accept", + ); + } + const [mcp, spoof] = agy.events.filter( + (event) => event.type === "request.opened", + ) as ReadonlyArray>; + // The same kind of request as before; what runs is in its words. + expect(mcp?.payload).toMatchObject({ + requestType: "exec_command_approval", + detail: 'MCP tool github · list_issues {"repo":"x/y"}', + }); + // A command naming an MCP tool shows the command it runs. + expect(spoof?.payload).toMatchObject({ + requestType: "exec_command_approval", + detail: "rm -rf build", + }); + } + yield* agy.waitFor((events) => completedTurns(events).length === 1); + // Full access approves both once, as before; supervised passes on the answers. + const answers = (yield* agy.frames()).flatMap((frame) => + frame.result !== undefined && JSON.stringify(frame.result).includes("optionId") + ? [JSON.stringify(frame.result)] + : [], + ); + expect(answers).toEqual([ + JSON.stringify({ outcome: { outcome: "selected", optionId: "allow" } }), + JSON.stringify({ outcome: { outcome: "selected", optionId: "allow" } }), + ]); + }).pipe(Effect.scoped, Effect.provide(testServices)), + ); + + const opened = (events: ReadonlyArray) => + events.filter((event) => event.type === "request.opened") as ReadonlyArray< + Extract + >; + const answers = (frames: ReadonlyArray>) => + frames.flatMap((frame) => + frame.result !== undefined && JSON.stringify(frame.result).includes("outcome") + ? [frame.result] + : [], + ); + + it.live("asks about a call named by its id alone with what the session knows of it", () => + Effect.gen(function* () { + const agy = yield* startAgy("permission-partial", undefined, "approval-required"); + yield* agy.adapter.sendTurn({ threadId: agy.threadId, input: "go", attachments: [] }); + yield* agy.waitFor((events) => opened(events).length === 1); + expect(opened(agy.events)[0]?.payload).toMatchObject({ + requestType: "exec_command_approval", + detail: "rm -rf build", + }); + yield* agy.adapter.respondToRequest( + agy.threadId, + ApprovalRequestId.make(String(opened(agy.events)[0]!.requestId)), + "decline", + ); + yield* agy.waitFor((events) => completedTurns(events).length === 1); + }).pipe(Effect.scoped, Effect.provide(testServices)), + ); + + it.live("withdraws an open approval when an update shows it is for something else", () => + Effect.gen(function* () { + const agy = yield* startAgy("permission-reask", undefined, "approval-required"); + yield* agy.adapter.sendTurn({ threadId: agy.threadId, input: "go", attachments: [] }); + yield* agy.waitFor((events) => opened(events).length === 2); + const [asked, reasked] = opened(agy.events); + expect(asked?.payload.detail).toBe("MCP tool github · list_issues {}"); + expect(reasked?.payload).toMatchObject({ + requestType: "exec_command_approval", + detail: "rm -rf build", + }); + // The first card was closed unanswered, and can't be answered now. + expect( + agy.events.find( + (event) => event.type === "request.resolved" && event.requestId === asked?.requestId, + ), + ).toMatchObject({ payload: { requestType: "exec_command_approval" } }); + const stale = yield* Effect.flip( + agy.adapter.respondToRequest( + agy.threadId, + ApprovalRequestId.make(String(asked!.requestId)), + "accept", + ), + ); + expect(stale.message).toContain("Unknown pending approval request"); + yield* agy.adapter.respondToRequest( + agy.threadId, + ApprovalRequestId.make(String(reasked!.requestId)), + "decline", + ); + yield* agy.waitFor((events) => completedTurns(events).length === 1); + expect(answers(yield* agy.frames())).toEqual([ + { outcome: { outcome: "selected", optionId: "deny" } }, + ]); + }).pipe(Effect.scoped, Effect.provide(testServices)), + ); + + it.live("asks again when only an open approval's edit text changes", () => + Effect.gen(function* () { + const agy = yield* startAgy("permission-edit-changed", undefined, "approval-required"); + yield* agy.adapter.sendTurn({ threadId: agy.threadId, input: "go", attachments: [] }); + yield* agy.waitFor((events) => opened(events).length === 2); + const [asked, reasked] = opened(agy.events); + // Same title and path; the old card is closed and can't approve the new edit. + expect(reasked?.payload.detail).toBe(asked?.payload.detail); + expect( + agy.events.some( + (event) => event.type === "request.resolved" && event.requestId === asked?.requestId, + ), + ).toBe(true); + const stale = yield* Effect.flip( + agy.adapter.respondToRequest( + agy.threadId, + ApprovalRequestId.make(String(asked!.requestId)), + "accept", + ), + ); + expect(stale.message).toContain("Unknown pending approval request"); + yield* agy.adapter.respondToRequest( + agy.threadId, + ApprovalRequestId.make(String(reasked!.requestId)), + "decline", + ); + yield* agy.waitFor((events) => completedTurns(events).length === 1); + expect(answers(yield* agy.frames())).toEqual([ + { outcome: { outcome: "selected", optionId: "deny" } }, + ]); + }).pipe(Effect.scoped, Effect.provide(testServices)), + ); + + it.live("asks before writing another session's plan or a look-alike name", () => + Effect.gen(function* () { + const agy = yield* startAgy("plan-file-foreign", undefined, "approval-required"); + yield* agy.adapter.sendTurn({ threadId: agy.threadId, input: "plan", attachments: [] }); + for (let asked = 1; asked <= 2; asked += 1) { + yield* agy.waitFor((events) => opened(events).length === asked); + yield* agy.adapter.respondToRequest( + agy.threadId, + ApprovalRequestId.make(String(opened(agy.events)[asked - 1]!.requestId)), + "decline", + ); + } + yield* agy.waitFor((events) => completedTurns(events).length === 1); + // Both were asked about; only this session's own plan went through unasked. + expect(opened(agy.events)).toHaveLength(2); + expect(answers(yield* agy.frames())).toEqual([ + { outcome: { outcome: "selected", optionId: "deny" } }, + { outcome: { outcome: "selected", optionId: "deny" } }, + { outcome: { outcome: "selected", optionId: "allow" } }, + ]); + }).pipe(Effect.scoped, Effect.provide(testServices)), + ); + + it.live("approves only an edit of the plan file itself without asking", () => + Effect.gen(function* () { + const agy = yield* startAgy("plan-file-permission", undefined, "approval-required"); + yield* agy.adapter.sendTurn({ threadId: agy.threadId, input: "plan", attachments: [] }); + // The command naming the plan file is asked about. + yield* agy.waitFor((events) => opened(events).length === 1); + expect(opened(agy.events)[0]?.payload.requestType).toBe("exec_command_approval"); + yield* agy.adapter.respondToRequest( + agy.threadId, + ApprovalRequestId.make(String(opened(agy.events)[0]!.requestId)), + "decline", + ); + yield* agy.waitFor((events) => completedTurns(events).length === 1); + // The plan edit was allowed with no card of its own. + expect(opened(agy.events)).toHaveLength(1); + expect(answers(yield* agy.frames())).toEqual([ + { outcome: { outcome: "selected", optionId: "deny" } }, + { outcome: { outcome: "selected", optionId: "allow" } }, + ]); + }).pipe(Effect.scoped, Effect.provide(testServices)), + ); + + it.live("classifies a call by what the agent sent, not by the bounded copy", () => + Effect.gen(function* () { + const agy = yield* startAgy("mcp-lossy"); + yield* agy.adapter.sendTurn({ threadId: agy.threadId, input: "go", attachments: [] }); + yield* agy.waitFor((events) => completedTurns(events).length === 1); + // Bounding drops the trailing `Cwd`; the call still isn't the wrapper. + expect(toolItem(agy.events, "call_lossy")?.payload.itemType).not.toBe("mcp_tool_call"); + }).pipe(Effect.scoped, Effect.provide(testServices)), + ); + + it.live("stops showing a call as MCP once a later update names a file", () => + Effect.gen(function* () { + const agy = yield* startAgy("mcp-then-location"); + yield* agy.adapter.sendTurn({ threadId: agy.threadId, input: "go", attachments: [] }); + yield* agy.waitFor((events) => completedTurns(events).length === 1); + const rows = agy.events.flatMap((event) => + (event.type === "item.updated" || event.type === "item.completed") && + String(event.itemId) === "call_wrapped" + ? [event.payload] + : [], + ); + expect(rows[0]).toMatchObject({ itemType: "mcp_tool_call", title: "list_issues" }); + // The later, still-running update is shown at once, with no MCP label. + expect(rows).toHaveLength(3); + for (const row of rows.slice(1)) { + expect(row?.itemType).toBe("command_execution"); + expect(row?.title).not.toBe("list_issues"); + expect(row?.detail ?? "").not.toContain("MCP tool"); + } + }).pipe(Effect.scoped, Effect.provide(testServices)), + ); + + it.live("shows call_mcp_tool as the MCP tool, keeps a command's start, drops images", () => + Effect.gen(function* () { + const agy = yield* startAgy("tools"); + yield* agy.adapter.sendTurn({ threadId: agy.threadId, input: "go", attachments: [] }); + yield* agy.waitFor((events) => completedTurns(events).length === 1); + + expect(toolItem(agy.events, "call_mcp")?.payload).toMatchObject({ + itemType: "mcp_tool_call", + title: "list_issues", + data: { server: "github", tool: "list_issues", arguments: { repo: "x/y" } }, + }); + expect(toolItem(agy.events, "call_mcp")?.payload.data).not.toHaveProperty("item"); + + const command = toolItem(agy.events, "call_long")?.payload.data as { + command: string; + item: { command: string; aggregatedOutput: string }; + }; + expect(command.command.startsWith("echo start")).toBe(true); + expect(command.command.endsWith("[Command truncated]")).toBe(true); + expect(command.command.length).toBeLessThanOrEqual(8_000 + "\n\n[Command truncated]".length); + expect(command.item.aggregatedOutput.endsWith("tail")).toBe(true); + expect(command.item.aggregatedOutput.length).toBeLessThan(8_100); + + const shot = toolItem(agy.events, "call_shot"); + expect(JSON.stringify(shot)).not.toContain("aGVsbG8="); + expect(shot?.payload.data).toMatchObject({ + content: [{ type: "content", content: { type: "text", text: "Screenshot taken." } }], + }); + }).pipe(Effect.scoped, Effect.provide(testServices)), + ); + + it.live( + "sends images and audio inline, PDFs as links, text files as text, the rest as paths", + () => + Effect.gen(function* () { + const config = yield* ServerConfig; + const attachments: ReadonlyArray = [ + { type: "image", id: "img-1", name: "shot.png", mimeType: "image/png", sizeBytes: 4 }, + { + type: "file", + kind: "pdf", + id: "pdf-1", + name: "spec.pdf", + mimeType: "application/pdf", + sizeBytes: 9, + }, + { + type: "file", + kind: "text", + id: "txt-1", + name: "notes.txt", + mimeType: "text/plain", + sizeBytes: 5, + }, + { + type: "file", + kind: "other", + id: "u16-1", + name: "log.txt", + mimeType: "text/plain; charset=utf-16", + sizeBytes: 8, + }, + { + type: "file", + kind: "other", + id: "aud-1", + name: "memo.mp3", + mimeType: "audio/mpeg", + sizeBytes: 3, + }, + { + type: "file", + kind: "other", + id: "xls-1", + name: "budget.xlsx", + mimeType: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", + sizeBytes: 2, + }, + ]; + const bytes: Record = { + "img-1": Uint8Array.from([0x89, 0x50, 0x4e, 0x47]), + "pdf-1": new TextEncoder().encode("%PDF-1.7\n"), + "txt-1": new TextEncoder().encode("hello"), + // "hi!" in UTF-16LE with its byte order mark. + "u16-1": Uint8Array.from([0xff, 0xfe, 0x68, 0x00, 0x69, 0x00, 0x21, 0x00]), + "aud-1": Uint8Array.from([1, 2, 3]), + "xls-1": Uint8Array.from([0x50, 0x4b]), + }; + for (const attachment of attachments) { + const file = resolveAttachmentPath({ + attachmentsDir: config.attachmentsDir, + attachment, + })!; + yield* Effect.promise(async () => { + await mkdir(path.dirname(file), { recursive: true }); + await writeFile(file, bytes[attachment.id]!); + }); + } + const agy = yield* startAgy("simple"); + yield* agy.adapter.sendTurn({ threadId: agy.threadId, input: "look", attachments }); + yield* agy.waitFor((events) => completedTurns(events).length === 1); + + const prompt = (yield* agy.frames()).find((frame) => frame.method === "session/prompt") + ?.params as { prompt: ReadonlyArray> }; + const blocks = prompt.prompt; + expect(blocks.map((block) => block.type)).toEqual([ + "text", + "image", + "resource_link", + "resource", + "resource", + "audio", + "text", + ]); + expect(blocks[1]).toMatchObject({ mimeType: "image/png", data: "iVBORw==" }); + expect(blocks[2]).toMatchObject({ name: "spec.pdf", mimeType: "application/pdf" }); + expect(String(blocks[2]!.uri).startsWith("file://")).toBe(true); + expect(blocks[3]).toMatchObject({ resource: { mimeType: "text/plain", text: "hello" } }); + // The charset parameter is dropped; the byte order mark picks UTF-16. + expect(blocks[4]).toMatchObject({ resource: { mimeType: "text/plain", text: "hi!" } }); + expect(blocks[5]).toMatchObject({ mimeType: "audio/mpeg", data: "AQID" }); + expect(blocks[6]).toMatchObject({ type: "text" }); + expect(String(blocks[6]!.text)).toContain('Attached file "budget.xlsx"'); + }).pipe(Effect.scoped, Effect.provide(testServices)), + ); +}); diff --git a/apps/server/src/provider/antigravity/AntigravityTurns.ts b/apps/server/src/provider/antigravity/AntigravityTurns.ts new file mode 100644 index 000000000..95aa30092 --- /dev/null +++ b/apps/server/src/provider/antigravity/AntigravityTurns.ts @@ -0,0 +1,323 @@ +/** + * How an Antigravity turn runs on `agy acp` 1.5, for the generic ACP core: + * the work that outlives a prompt, steering with a second prompt, the + * failures a normal-looking end hides, and the turn's tokens. + * + * What `agy acp` does, from Google's changelog (google-antigravity/antigravity-cli): + * - 1.5.0 takes a prompt sent while one runs as a steer: it answers the + * running prompt and carries the turn on under the new one. + * - 1.5.8 sends `usage_update` after each model call. + * - 1.5.9 fails a turn with its real error (model, quota) instead of a + * generic one. + * - 1.5.10 sends what the agent does after a prompt ended (a background + * command or subagent finished and woke it) at once, and `session/cancel` + * stops those commands and subagents. + * Wire shapes and the upstream error text follow T3 Code's Antigravity + * adapter (AntigravityProtocol.ts, AntigravityTurnOutcome.ts). + * + * @module provider/antigravity/AntigravityTurns + */ +import type { RuntimeUsageLimit, UsageTokenTotals } from "@threadlines/contracts"; +import * as Clock from "effect/Clock"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import type * as EffectAcpSchema from "effect-acp/schema"; + +import { httpStatusFailureCategory } from "../providerFailureCategory.ts"; +import type { + AcpPromptFailure, + AcpPromptOutcome, + AcpPromptOutcomeWatch, + AcpProviderDescriptor, + AcpProviderSettings, + AcpWorkAfterPrompt, +} from "../acp/AcpProviderDescriptor.ts"; +import type { AcpToolCallState } from "../acp/AcpRuntimeModel.ts"; +import { antigravityLogPosition, antigravityTurnSteps } from "./AntigravitySessionLog.ts"; +import { antigravityChildLaunches } from "./AntigravityChildRecords.ts"; +import { isAntigravitySubagentLaunch } from "./AntigravitySubagents.ts"; + +/** `schedule` stays in progress until its wake fires; the agent then replies by itself. */ +const SCHEDULE_TITLES = new Set(["Run schedule", "Running schedule"]); +/** + * A command that has said nothing this long no longer holds its turn: the + * agent sometimes loses a command's end or its wake (T3 Code found the same + * and settled on 30 minutes, which still leaves long builds room). + */ +export const ANTIGRAVITY_SILENT_WORK_LIMIT = Duration.minutes(30); +/** + * Whether a message sent mid-turn steers the running turn (a second + * `session/prompt`, 1.5.0+). Off, it waits for the turn to end. + */ +// Off until this is fixed: a steer is recorded as an accepted follow-up before the sender writes it, so a process exit then shows one the agent never got. +export const ANTIGRAVITY_STEERS = false; + +const isRecord = (value: unknown): value is Record => + typeof value === "object" && value !== null && !Array.isArray(value); + +/** + * What a tool call goes on with after the prompt answers: a command the + * agent awaits (a daemon such as a dev server may never end, so it doesn't + * hold the turn), a scheduled wake-up, or a subagent it launched. + */ +export function antigravityWorkAfterPrompt( + toolCall: AcpToolCallState, +): AcpWorkAfterPrompt | undefined { + if (toolCall.title !== undefined && SCHEDULE_TITLES.has(toolCall.title)) { + return { kind: "timer" }; + } + const input = toolCall.data.rawInput; + if (toolCall.kind === "execute") { + return isRecord(input) && input.IsDaemon === true ? undefined : { kind: "command" }; + } + // The same launches the subagent view shows (auto-approved titles too), + // a batch counting each subagent in it. + const count = isAntigravitySubagentLaunch(toolCall) + ? (antigravityChildLaunches(input)?.length ?? 0) + : 0; + if (count > 0) return { kind: "subagents", count }; + return undefined; +} + +/** + * A turn's tokens from its `session/prompt` answer. Antigravity 1.5 leaves + * cached reads out of `inputTokens` and already counts thinking inside + * `outputTokens` (T3 Code 602e5b32f5), unlike the fx reading the generic + * conversion makes. + */ +export function antigravityTurnUsageTotals( + usage: EffectAcpSchema.Usage | null | undefined, +): UsageTokenTotals | null { + if (!usage) return null; + const count = (value: number | null | undefined) => + typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.trunc(value) : 0; + const outputTokens = count(usage.outputTokens); + const totals: UsageTokenTotals = { + uncachedInputTokens: count(usage.inputTokens), + cachedInputTokens: count(usage.cachedReadTokens), + cacheCreationTokens: count(usage.cachedWriteTokens), + outputTokens, + reasoningTokens: Math.min(outputTokens, count(usage.thoughtTokens)), + }; + return totals.uncachedInputTokens + + totals.cachedInputTokens + + totals.cacheCreationTokens + + totals.outputTokens > + 0 + ? totals + : null; +} + +// ── Failures ───────────────────────────────────────────────────────── + +/** + * The Go harness's rendering of a Google API error. Status is a gRPC code or + * an HTTP status line ("502 Bad Gateway"). A message stops at the next + * error, so the match stays linear. + */ +const API_ERROR = + /Error (\d{3}), Message: ((?:(?!, Status: |Error \d{3}, Message: ).)+), Status: ([A-Z_]+|\d{3}[^,\n]*)/su; +/** 1.5 with a Google account: "STATUS (code NNN): message". */ +const STATUS_ERROR = /(? = { + ns: 1e-6, + us: 1e-3, + µs: 1e-3, + μs: 1e-3, + ms: 1, + s: 1_000, + m: 60_000, + h: 3_600_000, +}; + +const QUOTA_MESSAGE = "You've reached your Antigravity quota for now."; +const LOST_SESSION_MESSAGE = + "Antigravity's saved conversation can no longer be sent to the model. The next message starts a new Antigravity session with this thread's history."; +const UNKNOWN_ERROR_MESSAGE = "Antigravity stopped this turn because of an error."; + +/** When an exhausted quota resets, as the error says, in ISO time. */ +function quotaResetAt(text: string, nowMs: number): string | undefined { + const stamp = RESET_TIMESTAMP.exec(text)?.[1]; + if (stamp !== undefined) { + const ms = Date.parse(stamp); + if (Number.isFinite(ms)) return new Date(ms).toISOString(); + } + const delay = RESET_DELAY.exec(text)?.[1]; + if (delay === undefined) return undefined; + let delayMs = 0; + for (const [, amount, unit] of delay.matchAll(GO_DURATION_PART)) { + delayMs += Number(amount) * (GO_DURATION_UNIT_MS[unit!] ?? 0); + } + return delayMs > 0 ? new Date(nowMs + delayMs).toISOString() : undefined; +} + +/** HTTP status, message and status name, from either rendering. */ +function parseApiError( + text: string, +): { readonly httpStatus: number; readonly message: string; readonly status: string } | undefined { + const api = API_ERROR.exec(text); + if (api !== null) { + return { httpStatus: Number(api[1]), message: api[2]!.trim(), status: api[3]!.trim() }; + } + const status = STATUS_ERROR.exec(text); + if (status !== null) { + return { httpStatus: Number(status[2]), message: status[3]!.trim(), status: status[1]! }; + } + return undefined; +} + +/** + * What an Antigravity failure was, from the error text the agent gave + * (its JSON-RPC error, or the error step in its log). `refusal` is the stop + * reason the agent gives an exhausted quota. `reachedModel` tells a 404 for + * a model the account can't use (before any reply) from a passing one. + */ +export function antigravityFailure(input: { + readonly errorText: string | undefined; + readonly stopReason?: string | undefined; + readonly reachedModel?: boolean; + readonly nowMs: number; +}): AcpPromptFailure | undefined { + const text = input.errorText ?? ""; + if (input.errorText === undefined && input.stopReason !== "refusal") return undefined; + if (input.stopReason === "refusal" || QUOTA_EXHAUSTED.test(text)) { + const resetsAt = quotaResetAt(text, input.nowMs); + return { + errorMessage: QUOTA_MESSAGE, + failureCategory: "rate_limit", + usageLimit: resetsAt !== undefined ? { resetsAt } : {}, + }; + } + if (LOST_THINKING_SIGNATURE.test(text)) { + return { errorMessage: LOST_SESSION_MESSAGE, sessionLost: true }; + } + const api = parseApiError(text); + if (api === undefined) return { errorMessage: UNKNOWN_ERROR_MESSAGE }; + const rateLimited = api.httpStatus === 429 || api.status === "RESOURCE_EXHAUSTED"; + const resetsAt = rateLimited ? quotaResetAt(text, input.nowMs) : undefined; + const failureCategory = rateLimited + ? "rate_limit" + : api.httpStatus === 404 + ? input.reachedModel === true + ? "server_error" + : "model_unavailable" + : httpStatusFailureCategory(api.httpStatus); + return { + errorMessage: `Antigravity: ${api.message} (${api.status.startsWith(String(api.httpStatus)) ? api.status : `${api.httpStatus} ${api.status}`})`, + ...(failureCategory !== undefined ? { failureCategory } : {}), + ...(resetsAt !== undefined ? { usageLimit: { resetsAt } } : {}), + }; +} + +/** The error text an ACP error carries: its message and any data the agent attached. */ +function acpErrorText(error: unknown): string | undefined { + if (!isRecord(error) || error._tag !== "AcpRequestError") return undefined; + const message = typeof error.errorMessage === "string" ? error.errorMessage : ""; + const data = error.data; + const dataText = + data === undefined ? "" : typeof data === "string" ? data : (JSON.stringify(data) ?? ""); + const text = `${message}\n${dataText}`.trim(); + return text.length > 0 ? text : undefined; +} + +/** + * The descriptor hooks for an Antigravity turn, with the instance's profile + * (where the CLI keeps its session logs). `readUsageLimit` gives a quota + * failure the agent gave no reset time the one the plan meter knows for the + * turn's model. + */ +export function antigravityTurnBehavior( + profileDir: string, + readUsageLimit?: (model: string) => Effect.Effect, +): Pick, "turnMachine" | "usageLedger" | "turnUsageTotals"> { + return { + // Turns outlive their prompt (1.5.10 sends what the agent does after a + // prompt ends at once) and a second prompt steers (1.5.0). Subagent + // holds follow the CLI's records (the descriptor's `subagents`). + turnMachine: { + workAfterPrompt: antigravityWorkAfterPrompt, + steer: ANTIGRAVITY_STEERS, + silentLimit: ANTIGRAVITY_SILENT_WORK_LIMIT, + outcome: antigravityPromptOutcome(profileDir, readUsageLimit), + }, + usageLedger: { provider: "antigravity" }, + turnUsageTotals: antigravityTurnUsageTotals, + }; +} + +/** + * Reads how an Antigravity prompt really ended: the JSON-RPC error it failed + * with (1.5.9+), or, for a normal end, an error step in the CLI's session log. + * + * The log names no prompt, so a step counts for the newest prompt if it is + * the log's last step and was written after that prompt went out. That + * never hides the newest prompt's own failure. What it costs: an older + * prompt's error written after a steer went out, with nothing after it, + * fails the turn although the steer was answered (the CLI writes the + * steer's reply after it, so this needs a steer that wrote no step). When + * the log can't be read the prompt's own answer stands: the turn completes + * and the agent's own words about the error stay in its reply. + */ +function antigravityPromptOutcome( + profileDir: string, + readUsageLimit?: (model: string) => Effect.Effect, +): AcpPromptOutcome { + return { + watch: (sessionId, model) => + Effect.gen(function* () { + const before = yield* antigravityLogPosition(profileDir, sessionId); + const withMeterReset = (failure: AcpPromptFailure | undefined) => + failure?.usageLimit !== undefined && + failure.usageLimit.resetsAt === undefined && + readUsageLimit !== undefined && + model !== undefined + ? readUsageLimit(model).pipe( + Effect.map((limit) => (limit ? { ...failure, usageLimit: limit } : failure)), + ) + : Effect.succeed(failure); + const check: AcpPromptOutcomeWatch["check"] = (answer) => + Effect.gen(function* () { + const nowMs = yield* Clock.currentTimeMillis; + // 1.5.9+ fails the prompt with the real error. + // Words it doesn't recognize keep the core's own reading. + if ("error" in answer) { + const errorText = acpErrorText(answer.error); + const recognized = + errorText !== undefined && + (parseApiError(errorText) !== undefined || + QUOTA_EXHAUSTED.test(errorText) || + LOST_THINKING_SIGNATURE.test(errorText)); + return recognized + ? yield* withMeterReset(antigravityFailure({ errorText, nowMs })) + : undefined; + } + // A normal end can hide an upstream error that only the + // agent's own log records. + const stopReason = answer.response.stopReason; + const steps = + before === undefined + ? undefined + : yield* antigravityTurnSteps(profileDir, sessionId, before); + return yield* withMeterReset( + antigravityFailure({ + errorText: steps?.errorText, + stopReason, + ...(steps !== undefined ? { reachedModel: steps.reachedModel } : {}), + nowMs, + }), + ); + }); + return { check }; + }), + }; +} diff --git a/apps/server/src/provider/antigravity/AntigravityUsage.test.ts b/apps/server/src/provider/antigravity/AntigravityUsage.test.ts new file mode 100644 index 000000000..00830a784 --- /dev/null +++ b/apps/server/src/provider/antigravity/AntigravityUsage.test.ts @@ -0,0 +1,746 @@ +import * as fs from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; + +import type { AntigravityAuthMethod, ServerProvider } from "@threadlines/contracts"; +import { assert, describe, it } from "@effect/vitest"; +import * as Deferred from "effect/Deferred"; +import * as Effect from "effect/Effect"; +import * as TestClock from "effect/testing/TestClock"; + +import { antigravityTokenPath } from "./AntigravityProfile.ts"; +import { usageLimitForModel, usageScopeHoldsModel } from "@threadlines/shared/usageLimits"; +import type * as Duration from "effect/Duration"; + +import { + ANTIGRAVITY_USAGE_EXPIRED_DETAIL, + ANTIGRAVITY_USAGE_FAILED_DETAIL, + ANTIGRAVITY_USAGE_USER_AGENT, + makeAntigravityUsageReader, + withAntigravityUsage, +} from "./AntigravityUsage.ts"; + +const ACCESS_TOKEN = "ya29.secret-access-token"; +const REFRESH_TOKEN = "1//secret-refresh-token"; + +// Shapes from T3 Code's fixtures (antigravityUsageLimits.test.ts and its open pull requests). +const SUMMARY = { + groups: [ + { + displayName: "Gemini Models", + buckets: [ + { + bucketId: "gemini-weekly", + window: "weekly", + remainingFraction: 0.96, + resetTime: "2026-10-12T19:41:43Z", + }, + { + bucketId: "gemini-5h", + window: "5h", + remainingFraction: 0.91, + resetTime: "2026-10-09T16:06:01Z", + }, + ], + }, + { + displayName: "Claude and GPT models", + buckets: [ + { + bucketId: "3p-weekly", + window: "weekly", + remainingFraction: 0, + resetTime: "2026-10-10T15:28:22Z", + }, + { bucketId: "3p-5h", window: "5h", remainingFraction: 0.44 }, + ], + }, + ], +}; + +const SUMMARY_WITHOUT_GEMINI = { groups: [SUMMARY.groups[1]!] }; + +const MODELS = { + models: { + "gemini-4-hydrogen-sonar": { + modelProvider: "MODEL_PROVIDER_GOOGLE", + quotaInfo: { remainingFraction: 0.9471137, resetTime: "2026-11-17T15:36:00Z" }, + }, + "gemini-3.1-pro-high": { + modelProvider: "MODEL_PROVIDER_GOOGLE", + quotaInfo: { remainingFraction: 0.6, resetTime: "2026-11-17T12:00:00Z" }, + }, + chat_20706: { isInternal: true, quotaInfo: { remainingFraction: 0 } }, + "claude-opus-5-5-high": { quotaInfo: { remainingFraction: 0.2 } }, + }, +}; + +/** An Enterprise answer: one group of per-model buckets with no window length. */ +const ENTERPRISE_SUMMARY = { + groups: [ + { + displayName: "All Models", + buckets: [ + { bucketId: "gemini-3.1-pro-high", remainingFraction: 0.5 }, + { bucketId: "gemini-3.1-pro-low", remainingFraction: 0.75 }, + { + bucketId: "gemini-4-argon-high", + remainingFraction: 0.1, + resetTime: "2026-11-24T00:00:00Z", + }, + { bucketId: "claude-opus-5-5-high", remainingFraction: 1 }, + { bucketId: "claude-sonnet-5-5", remainingFraction: 0.3 }, + { bucketId: "gpt-6-2-high", remainingFraction: 0.9, disabled: true }, + { bucketId: "gpt-6-1", remainingFraction: 0.95 }, + ], + }, + ], +}; + +interface Answer { + readonly status?: number; + readonly body?: unknown; + readonly headers?: Record; +} + +type Route = (url: URL) => Answer | "hang"; + +interface Sent { + readonly url: string; + readonly method: string; + readonly headers: Record; + readonly body: string | undefined; +} + +/** A stand-in for Google: answers per host and operation, and records what was asked. */ +function stubFetch(route: Route) { + const sent: Array = []; + const aborted: Array = []; + const fetch = (rawUrl: string, init: RequestInit) => { + const url = new URL(rawUrl); + sent.push({ + url: rawUrl, + method: init.method ?? "GET", + headers: Object.fromEntries(new Headers(init.headers)), + body: typeof init.body === "string" ? init.body : undefined, + }); + const answer = route(url); + if (answer === "hang") { + return new Promise((_resolve, reject) => { + init.signal?.addEventListener("abort", () => { + aborted.push(rawUrl); + reject(new Error("aborted")); + }); + }); + } + return Promise.resolve( + new Response(answer.body === undefined ? null : JSON.stringify(answer.body), { + status: answer.status ?? 200, + ...(answer.headers ? { headers: answer.headers } : {}), + }), + ); + }; + return { fetch, sent, aborted }; +} + +const googleRoute = + (answers: { + summary?: Answer | ((host: string) => Answer); + models?: Answer | ((host: string) => Answer); + userinfo?: Answer; + }): Route => + (url) => { + const pick = (answer: Answer | ((host: string) => Answer) | undefined) => + typeof answer === "function" ? answer(url.host) : (answer ?? { status: 404 }); + if (url.pathname.endsWith(":retrieveUserQuotaSummary")) return pick(answers.summary); + if (url.pathname.endsWith(":fetchAvailableModels")) return pick(answers.models); + if (url.pathname === "/oauth2/v2/userinfo") return answers.userinfo ?? { status: 403 }; + return { status: 404 }; + }; + +const makeProfile = Effect.promise(() => fs.mkdtemp(join(tmpdir(), "threadlines-agy-usage-"))); + +const writeToken = ( + profileDir: string, + overrides: { expiry?: string; refresh?: string; email?: string | null } = {}, +) => + Effect.promise(async () => { + const path = antigravityTokenPath(profileDir); + await fs.mkdir(dirname(path), { recursive: true }); + await fs.writeFile( + path, + JSON.stringify({ + token: { + access_token: ACCESS_TOKEN, + token_type: "Bearer", + refresh_token: overrides.refresh ?? REFRESH_TOKEN, + expiry: overrides.expiry ?? "2099-01-01T00:00:00Z", + }, + auth_method: "consumer", + ...(overrides.email === null + ? {} + : { id_token_email: overrides.email ?? "someone@example.com" }), + }), + ); + }); + +const signedInSnapshot = (method: AntigravityAuthMethod) => + ({ + enabled: true, + auth: { status: "authenticated", type: method, label: "Google account" }, + }) as unknown as ServerProvider; + +/** + * A reader on a fresh profile with a stub Google. `published` resolves with + * the snapshot the first finished read writes. + */ +const setup = (input: { + route: Route; + method?: AntigravityAuthMethod; + token?: Parameters[1] | false; + timeouts?: { request: Duration.Input; read: Duration.Input }; + models?: ServerProvider["models"]; +}) => + Effect.gen(function* () { + const profileDir = yield* makeProfile; + if (input.token !== false) yield* writeToken(profileDir, input.token); + const google = stubFetch(input.route); + const method = input.method ?? "oauth-personal"; + const reader = yield* makeAntigravityUsageReader({ + profileDir, + method, + fingerprint: "fingerprint-a", + fetch: google.fetch, + ...(input.timeouts ? { timeouts: input.timeouts } : {}), + }); + let snapshot = { ...signedInSnapshot(method), models: input.models ?? [] }; + let published = yield* Deferred.make(); + reader.attach({ + getSnapshot: Effect.sync(() => snapshot), + patchSnapshot: (update) => + Effect.gen(function* () { + const next = update(snapshot); + if (next) snapshot = next; + yield* Deferred.succeed(published, snapshot); + }), + }); + /** Runs a status check and waits for the read it starts to publish. */ + const readOnce = Effect.gen(function* () { + published = yield* Deferred.make(); + yield* reader.status; + return yield* Deferred.await(published); + }); + return { + profileDir, + reader, + google, + readOnce, + current: Effect.sync(() => snapshot), + setSnapshot: (next: ServerProvider) => Effect.sync(() => void (snapshot = next)), + }; + }); + +const windowsOf = (snapshot: ServerProvider) => + snapshot.accountUsage?.limits[0]?.scoped?.map((window) => ({ + label: window.scopeLabel, + minutes: window.windowDurationMins, + used: window.usedPercent, + })); + +describe("Antigravity plan limits", () => { + it.effect("reads each family's 5-hour and weekly limits, with the email from the sign-in", () => + Effect.gen(function* () { + const { readOnce, google } = yield* setup({ + route: googleRoute({ summary: { body: SUMMARY } }), + }); + const snapshot = yield* readOnce; + + assert.deepEqual(windowsOf(snapshot), [ + { label: "Gemini", minutes: 300, used: 9 }, + { label: "Gemini", minutes: 10080, used: 4 }, + { label: "Claude & GPT", minutes: 300, used: 56 }, + { label: "Claude & GPT", minutes: 10080, used: 100 }, + ]); + const scoped = snapshot.accountUsage!.limits[0]!.scoped!; + assert.deepEqual(scoped[0]!.scopeModels, ["Gemini"]); + assert.deepEqual(scoped[2]!.scopeModels, ["Claude", "GPT"]); + assert.equal(scoped[3]!.resetsAt, Date.parse("2026-10-10T15:28:22Z")); + // What clients built before Antigravity accept: an unknown source fails + // their whole config, so the reading names itself in `limitName`. + assert.include( + ["codex-rate-limits", "claude-oauth-usage", "muse-subscription-usage", "grok-billing"], + snapshot.accountUsage!.source, + ); + assert.equal(snapshot.accountUsage!.limits[0]!.limitName, "Antigravity usage"); + assert.equal(snapshot.auth.email, "someone@example.com"); + assert.equal(snapshot.auth.capabilities?.usage, undefined); + + // Both hosts, our own name, the token only as a Bearer header, nowhere else. + assert.deepEqual(google.sent.map((request) => new URL(request.url).host).toSorted(), [ + "cloudcode-pa.googleapis.com", + "daily-cloudcode-pa.googleapis.com", + ]); + for (const request of google.sent) { + assert.equal(request.method, "POST"); + assert.equal(request.body, "{}"); + assert.equal(request.headers["user-agent"], ANTIGRAVITY_USAGE_USER_AGENT); + assert.match(request.headers["user-agent"]!, /^Threadlines\/\d/); + assert.equal(request.headers.authorization, `Bearer ${ACCESS_TOKEN}`); + } + assert.notInclude(JSON.stringify(snapshot), ACCESS_TOKEN); + assert.notInclude(JSON.stringify(snapshot), REFRESH_TOKEN); + }), + ); + + it.effect("fills Gemini in from the per-model quotas when the summary leaves it out", () => + Effect.gen(function* () { + const { readOnce } = yield* setup({ + route: googleRoute({ + summary: { body: SUMMARY_WITHOUT_GEMINI }, + models: { body: MODELS }, + }), + }); + const snapshot = yield* readOnce; + // Each Gemini model keeps its own quota; Claude stays the summary's shared pool. + assert.deepEqual(windowsOf(snapshot), [ + { label: "Gemini 3.1 Pro", minutes: undefined, used: 40 }, + { label: "Gemini 4 Hydrogen Sonar", minutes: undefined, used: 5 }, + { label: "Claude & GPT", minutes: 300, used: 56 }, + { label: "Claude & GPT", minutes: 10080, used: 100 }, + ]); + }), + ); + + it.effect("falls back to per-model quotas without making up a window length", () => + Effect.gen(function* () { + const { readOnce } = yield* setup({ + route: googleRoute({ summary: { status: 404 }, models: { body: MODELS } }), + }); + assert.deepEqual(windowsOf(yield* readOnce), [ + { label: "Gemini 3.1 Pro", minutes: undefined, used: 40 }, + { label: "Gemini 4 Hydrogen Sonar", minutes: undefined, used: 5 }, + { label: "Claude Opus 5.5", minutes: undefined, used: 80 }, + ]); + }), + ); + + it.effect("gives each model of an Enterprise answer its own row, its levels folded", () => + Effect.gen(function* () { + const { readOnce } = yield* setup({ + method: "oauth-business", + route: googleRoute({ + // The host an Enterprise account is metered on wins where both answer. + summary: (host) => + host === "cloudcode-pa.googleapis.com" + ? { body: ENTERPRISE_SUMMARY } + : { body: { buckets: [{ bucketId: "claude-opus-5-5-high", remainingFraction: 0 }] } }, + }), + }); + const snapshot = yield* readOnce; + // Opus unused stays unused beside a Sonnet that is 70% through its quota. + assert.deepEqual(windowsOf(snapshot), [ + { label: "Gemini 3.1 Pro", minutes: undefined, used: 50 }, + { label: "Gemini 4 Argon", minutes: undefined, used: 90 }, + { label: "Claude Opus 5.5", minutes: undefined, used: 0 }, + { label: "Claude Sonnet 5.5", minutes: undefined, used: 70 }, + { label: "GPT 6.1", minutes: undefined, used: 5 }, + ]); + const scoped = snapshot.accountUsage!.limits[0]!.scoped!; + assert.equal(scoped[1]!.resetsAt, Date.parse("2026-11-24T00:00:00Z")); + assert.deepEqual(scoped[2]!.scopeModels, ["Claude Opus 5.5"]); + const limits = snapshot.accountUsage!; + assert.isTrue( + usageScopeHoldsModel( + { name: scoped[3]!.scopeLabel, models: scoped[3]!.scopeModels }, + "Claude Sonnet 5.5", + ), + ); + assert.isFalse( + usageScopeHoldsModel( + { name: scoped[3]!.scopeLabel, models: scoped[3]!.scopeModels }, + "Claude Opus 5.5", + ), + ); + assert.equal(usageLimitForModel(limits, "Claude Opus 5.5", Date.now()), undefined); + }), + ); + + it.effect("labels Gemini 4 pools apart and leaves them out of the default Gemini pool", () => + Effect.gen(function* () { + const { readOnce } = yield* setup({ + route: googleRoute({ + summary: { + body: { + groups: [ + ...SUMMARY.groups, + { + displayName: "Gemini 4 Argon", + buckets: [ + { + bucketId: "gemini-argon-wtu-weekly", + window: "weekly", + remainingFraction: 0.6, + }, + ], + }, + { + displayName: " ", + buckets: [{ bucketId: "gemini-neon-5h", window: "5h", remainingFraction: 0.8 }], + }, + ], + }, + }, + }), + }); + const scoped = (yield* readOnce).accountUsage!.limits[0]!.scoped!; + assert.deepEqual( + scoped.map((window) => window.scopeLabel), + ["Gemini", "Gemini", "Gemini 4 Argon", "Gemini Neon", "Claude & GPT", "Claude & GPT"], + ); + assert.deepEqual(scoped[0]!.scopeExcludes, ["Argon", "Neon"]); + assert.deepEqual(scoped[2]!.scopeModels, ["Argon"]); + }), + ); + + it.effect("leaves out the reset of a pool nobody has touched", () => + Effect.gen(function* () { + yield* TestClock.setTime(Date.parse("2026-10-21T10:16:04Z")); + const { readOnce } = yield* setup({ + route: googleRoute({ + summary: { + body: { + buckets: [ + { + bucketId: "3p-5h", + window: "5h", + remainingFraction: 1, + resetTime: "2026-10-21T15:16:05Z", + }, + { + bucketId: "gemini-5h", + window: "5h", + remainingFraction: 0.848104, + resetTime: "2026-10-21T13:29:53Z", + description: "You have used some of your 5-hour limit.", + }, + ], + }, + }, + }), + }); + const scoped = (yield* readOnce).accountUsage!.limits[0]!.scoped!; + assert.equal( + scoped.find((window) => window.scopeLabel === "Claude & GPT")!.resetsAt, + undefined, + ); + assert.equal( + scoped.find((window) => window.scopeLabel === "Gemini")!.resetsAt, + Date.parse("2026-10-21T13:29:53Z"), + ); + }), + ); + + it.effect("asks for the email when the sign-in doesn't carry it", () => + Effect.gen(function* () { + const { readOnce, google } = yield* setup({ + token: { email: null }, + route: googleRoute({ + summary: { body: SUMMARY }, + userinfo: { body: { id: "1", email: "other@example.com" } }, + }), + }); + assert.equal((yield* readOnce).auth.email, "other@example.com"); + const userinfo = google.sent.find((request) => request.url.includes("userinfo"))!; + assert.equal(userinfo.method, "GET"); + assert.equal(new URL(userinfo.url).host, "www.googleapis.com"); + }), + ); + + it.effect( + "with an expired sign-in, keeps the last numbers and asks for a chat, without a request", + () => + Effect.gen(function* () { + yield* TestClock.setTime(Date.parse("2026-10-09T12:00:00Z")); + const { readOnce, reader, google, profileDir } = yield* setup({ + route: googleRoute({ summary: { body: SUMMARY } }), + }); + const first = yield* readOnce; + const asked = google.sent.length; + + yield* writeToken(profileDir, { expiry: "2000-01-01T00:00:00Z" }); + const status = yield* reader.status; + assert.equal(google.sent.length, asked); + assert.deepEqual(status.accountUsage, first.accountUsage); + assert.deepEqual(status.usage, { + status: "unavailable", + detail: ANTIGRAVITY_USAGE_EXPIRED_DETAIL, + }); + + // A fresh reader (a restart) with an expired sign-in asks nothing either. + const cold = yield* setup({ + token: { expiry: "2026-10-09T12:00:30Z" }, + route: googleRoute({ summary: { body: SUMMARY } }), + }); + const coldStatus = yield* cold.reader.status; + assert.equal(coldStatus.accountUsage, undefined); + assert.equal(coldStatus.usage?.detail, ANTIGRAVITY_USAGE_EXPIRED_DETAIL); + assert.deepEqual(cold.google.sent, []); + }), + ); + + it.effect("when Google refuses, says it couldn't read and keeps the last good numbers", () => + Effect.gen(function* () { + let refuse = false; + const { readOnce, google } = yield* setup({ + route: (url) => + refuse + ? { status: 403, body: { error: { message: "unknown client" } } } + : googleRoute({ summary: { body: SUMMARY } })(url), + }); + const first = yield* readOnce; + + refuse = true; + yield* TestClock.adjust("3 minutes"); + const second = yield* readOnce; + assert.deepEqual(second.accountUsage, first.accountUsage); + assert.deepEqual(second.auth.capabilities?.usage, { + status: "unavailable", + reason: "unreachable", + detail: ANTIGRAVITY_USAGE_FAILED_DETAIL, + }); + // The summary had nothing, so the per-model quotas were asked too. + assert.isTrue(google.sent.some((request) => request.url.endsWith(":fetchAvailableModels"))); + + refuse = false; + yield* TestClock.adjust("3 minutes"); + assert.equal((yield* readOnce).auth.capabilities?.usage, undefined); + }), + ); + + it.effect("treats a redirect as a failed read and never follows it", () => + Effect.gen(function* () { + const { readOnce, google } = yield* setup({ + route: (url) => + url.host === "cloudcode-pa.googleapis.com" || + url.host === "daily-cloudcode-pa.googleapis.com" + ? { status: 302, headers: { location: "https://collector.example/steal" } } + : { status: 404 }, + }); + const snapshot = yield* readOnce; + assert.equal(snapshot.accountUsage, undefined); + assert.equal(snapshot.auth.capabilities?.usage?.detail, ANTIGRAVITY_USAGE_FAILED_DETAIL); + assert.isFalse(google.sent.some((request) => request.url.includes("collector.example"))); + }), + ); + + it.effect( + "reads nothing for a sign-in that isn't Google's, even with a Google token on disk", + () => + Effect.gen(function* () { + for (const method of ["gemini-api-key", "agent-platform"] as const) { + const { reader, google } = yield* setup({ + method, + route: googleRoute({ summary: { body: SUMMARY } }), + }); + assert.deepEqual(yield* reader.status, {}); + assert.equal(yield* reader.usageLimitFor("Gemini 3.1 Pro"), undefined); + assert.deepEqual(google.sent, []); + } + }), + ); + + it.effect("never shows one Google account's numbers for another", () => + Effect.gen(function* () { + const { readOnce, reader, profileDir } = yield* setup({ + route: googleRoute({ summary: { body: SUMMARY } }), + }); + yield* readOnce; + yield* writeToken(profileDir, { refresh: "1//another-account", email: "b@example.com" }); + const status = yield* reader.status; + assert.equal(status.accountUsage, undefined); + assert.equal(status.email, "b@example.com"); + + // Signed out: nothing at all. + yield* Effect.promise(() => fs.rm(antigravityTokenPath(profileDir))); + assert.deepEqual(yield* reader.status, {}); + }), + ); + + it.effect("signing in or out cancels a read in flight, and it never lands", () => + Effect.gen(function* () { + const { reader, google } = yield* setup({ route: () => "hang" }); + yield* reader.status; + yield* Effect.yieldNow; + assert.isAbove(google.sent.length, 0); + yield* reader.reset; + assert.sameMembers( + google.aborted, + google.sent.map((request) => request.url), + ); + assert.equal((yield* reader.status).accountUsage, undefined); + }), + ); + + it.effect("names the limit a stopped model waits on, from the last reading", () => + Effect.gen(function* () { + yield* TestClock.setTime(Date.parse("2026-10-09T12:00:00Z")); + const { readOnce, reader } = yield* setup({ + route: googleRoute({ summary: { body: SUMMARY } }), + }); + yield* readOnce; + assert.deepEqual(yield* reader.usageLimitFor("Claude Sonnet 5.5"), { + window: "weekly", + resetsAt: "2026-10-10T15:28:22.000Z", + }); + assert.equal(yield* reader.usageLimitFor("Gemini 3.1 Pro"), undefined); + }), + ); + + it.effect("drops another account's numbers and email, even when it has no email itself", () => + Effect.gen(function* () { + yield* TestClock.setTime(Date.parse("2026-10-09T12:00:00Z")); + const { readOnce, reader, profileDir, current } = yield* setup({ + route: googleRoute({ summary: { body: SUMMARY } }), + }); + const signedInAsA = yield* readOnce; + assert.equal(signedInAsA.auth.email, "someone@example.com"); + + // Account B: no email in its sign-in, and expired, so nothing is read for it. + yield* writeToken(profileDir, { + refresh: "1//account-b", + email: null, + expiry: "2026-10-09T11:00:00Z", + }); + const status = yield* reader.status; + assert.isDefined(status.accountId); + assert.notEqual(status.accountId, signedInAsA.auth.accountId); + assert.equal(status.accountUsage, undefined); + // Folded onto the row still showing A, B's status takes A's numbers and email off it. + const row = withAntigravityUsage(yield* current, status); + assert.equal(row.accountUsage, undefined); + assert.equal(row.auth.email, undefined); + assert.equal(row.auth.accountId, status.accountId); + // The same account keeps its last numbers. + const again = withAntigravityUsage(signedInAsA, { + accountId: signedInAsA.auth.accountId!, + }); + assert.deepEqual(again.accountUsage, signedInAsA.accountUsage); + }), + ); + + it.effect("a read that times out never lands on another account's row", () => + Effect.gen(function* () { + const { reader, profileDir, current, google } = yield* setup({ + route: () => "hang", + timeouts: { request: "1 hour", read: "30 seconds" }, + }); + yield* reader.status; + yield* Effect.yieldNow; + assert.isAbove(google.sent.length, 0); + yield* writeToken(profileDir, { refresh: "1//account-b", email: "b@example.com" }); + yield* TestClock.adjust("31 seconds"); + // The landing reads the token file: give that real time to finish. + yield* Effect.promise(() => new Promise((done) => setTimeout(done, 200))); + const row = yield* current; + assert.equal(row.auth.email, undefined); + assert.equal(row.auth.accountId, undefined); + }), + ); + + it.effect("keeps the rows a failed host would have given, with their age", () => + Effect.gen(function* () { + let prodDown = false; + const { readOnce } = yield* setup({ + route: googleRoute({ + // The daily host has Gemini, the production host Claude & GPT. + summary: (host) => + host === "daily-cloudcode-pa.googleapis.com" + ? { body: { groups: [SUMMARY.groups[0]!] } } + : prodDown + ? { status: 503 } + : { body: SUMMARY_WITHOUT_GEMINI }, + }), + }); + const first = yield* readOnce; + const shared = first.accountUsage!.limits[0]!.scoped!.filter( + (window) => window.scopeLabel === "Claude & GPT", + ); + assert.lengthOf(shared, 2); + + prodDown = true; + yield* TestClock.adjust("3 minutes"); + const second = yield* readOnce; + const scoped = second.accountUsage!.limits[0]!.scoped!; + assert.deepEqual( + scoped.filter((window) => window.scopeLabel === "Claude & GPT"), + shared, + ); + // Gemini is fresh; the kept rows carry the earlier time. + assert.isAbove( + Date.parse(scoped.find((window) => window.scopeLabel === "Gemini")!.checkedAt!), + Date.parse(shared[0]!.checkedAt!), + ); + assert.equal(second.auth.capabilities?.usage?.detail, ANTIGRAVITY_USAGE_FAILED_DETAIL); + }), + ); + + it.effect("keeps Gemini when the per-model quotas that filled it in don't answer", () => + Effect.gen(function* () { + let modelsDown = false; + const { readOnce } = yield* setup({ + route: googleRoute({ + summary: { body: SUMMARY_WITHOUT_GEMINI }, + models: () => (modelsDown ? { status: 503 } : { body: MODELS }), + }), + }); + yield* readOnce; + modelsDown = true; + yield* TestClock.adjust("3 minutes"); + const labels = windowsOf(yield* readOnce)!.map((window) => window.label); + assert.includeMembers(labels, ["Gemini 3.1 Pro", "Claude & GPT"]); + }), + ); + + it.effect("never rounds a quota with something left up to spent", () => + Effect.gen(function* () { + const { readOnce } = yield* setup({ + route: googleRoute({ + summary: { + body: { + buckets: [ + { bucketId: "gemini-5h", window: "5h", remainingFraction: 0.004 }, + { bucketId: "gemini-weekly", window: "weekly", remainingFraction: 0 }, + ], + }, + }, + }), + }); + const [fiveHour, weekly] = (yield* readOnce).accountUsage!.limits[0]!.scoped!; + assert.deepInclude(fiveHour, { usedPercent: 99, remainingPercent: 1 }); + assert.deepInclude(weekly, { usedPercent: 100, remainingPercent: 0 }); + }), + ); + + it.effect("finds a picker model's limit by its slug, for Continue at reset", () => + Effect.gen(function* () { + yield* TestClock.setTime(Date.parse("2026-10-09T12:00:00Z")); + const { readOnce, reader } = yield* setup({ + route: googleRoute({ summary: { body: SUMMARY } }), + models: [ + { + // Agent ids don't name the model's family. + slug: "model-placeholder-m26", + name: "Claude Sonnet 5.5", + isCustom: false, + capabilities: { optionDescriptors: [] }, + }, + ] as unknown as ServerProvider["models"], + }); + yield* readOnce; + assert.deepEqual(yield* reader.usageLimitFor("model-placeholder-m26"), { + window: "weekly", + resetsAt: "2026-10-10T15:28:22.000Z", + }); + }), + ); +}); diff --git a/apps/server/src/provider/antigravity/AntigravityUsage.ts b/apps/server/src/provider/antigravity/AntigravityUsage.ts new file mode 100644 index 000000000..fc50992b2 --- /dev/null +++ b/apps/server/src/provider/antigravity/AntigravityUsage.ts @@ -0,0 +1,909 @@ +/** + * AntigravityUsage — how much of the user's Google plan an Antigravity + * instance has used, and the signed-in Google account's email. + * + * THIS READS AN UNPUBLISHED GOOGLE API. `v1internal:retrieveUserQuotaSummary` + * and `v1internal:fetchAvailableModels` on Google's Cloud Code hosts are what + * Google's own Antigravity apps call; Google documents neither and can change + * or close them at any time. Everything that knows about them is in this + * module, so it comes out in one piece: delete this file and the lines in + * `Drivers/AntigravityDriver.ts` and `acp/AntigravityAcpSupport.ts` that name + * it. The answer shapes follow T3 Code (MIT, `antigravityUsageLimits.ts` and + * its open pull requests); the code is our own. + * + * Rules it keeps: + * - It reads only for a Google sign-in (Google account or Gemini + * Enterprise). An instance switched to an API key or Vertex AI keeps its + * earlier Google token on disk on purpose, and that token says nothing + * about what the instance now bills. + * - The token is the CLI's own file in the instance's profile + * (`antigravityTokenPath`), read and never written, renewed or removed. + * Google's token endpoint is never called and the OS keyring never read. + * An expired token keeps the last numbers, with a line saying a chat + * refreshes them: the agent renews its own sign-in when it runs. + * - Readings are kept per sign-in fingerprint and Google account, so one + * account never shows another's numbers or email. + * - Requests go only to the two Cloud Code hosts and Google's userinfo + * endpoint, through a fetch that refuses every other host and every + * redirect, under Threadlines' own User-Agent. The token is never logged: + * errors are dropped for fixed words. + * - It fails soft. A status check never waits for Google: it gets the last + * reading and starts a read in the background. One read at a time, 10 + * seconds per request and 30 in all; a failed read keeps the last good + * numbers. Signing in or out cancels a read in flight. + * + * @module provider/antigravity/AntigravityUsage + */ +import { createHash } from "node:crypto"; +import * as fs from "node:fs/promises"; + +import type { + AntigravityAuthMethod, + RuntimeUsageLimit, + ServerProviderAccountUsage, + ServerProviderAuth, + ServerProviderAuthCapability, + ServerProviderScopedUsageWindow, +} from "@threadlines/contracts"; +import { usageLimitForModel } from "@threadlines/shared/usageLimits"; +import * as Clock from "effect/Clock"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as FiberHandle from "effect/FiberHandle"; +import * as Schema from "effect/Schema"; +import type * as Scope from "effect/Scope"; + +import type { ServerProviderShape } from "../Services/ServerProvider.ts"; + +import { THREADLINES_ACP_CLIENT_INFO } from "../acp/acpClientInfo.ts"; +import { makeHttpsFetch } from "../managedRuntime/HttpsFetch.ts"; +import type { DownloadFetch } from "../managedRuntime/VerifiedDownload.ts"; +import { antigravityTokenPath } from "./AntigravityProfile.ts"; + +// ── Google's hosts ─────────────────────────────────────────────────── + +const DAILY_HOST = "daily-cloudcode-pa.googleapis.com"; +const PROD_HOST = "cloudcode-pa.googleapis.com"; +const USERINFO_HOST = "www.googleapis.com"; +const USERINFO_URL = `https://${USERINFO_HOST}/oauth2/v2/userinfo`; + +/** Every host a read may contact. */ +export const ANTIGRAVITY_USAGE_HOSTS = [DAILY_HOST, PROD_HOST, USERINFO_HOST] as const; + +type GoogleMethod = Extract; + +/** + * Both hosts are asked: their answers differ by account. Where both name a + * bucket, the host the account is metered on wins (T3 Code: personal + * accounts on the daily host, Enterprise on the production one). + */ +const HOSTS_BY_METHOD: Record = { + "oauth-personal": [DAILY_HOST, PROD_HOST], + "oauth-business": [PROD_HOST, DAILY_HOST], +}; + +const isGoogleMethod = (method: AntigravityAuthMethod): method is GoogleMethod => + method === "oauth-personal" || method === "oauth-business"; + +/** What a usage surface calls the reading. */ +export const ANTIGRAVITY_USAGE_LABEL = "Antigravity usage"; + +/** Threadlines under its own name; never another app's client string. */ +export const ANTIGRAVITY_USAGE_USER_AGENT = `Threadlines/${THREADLINES_ACP_CLIENT_INFO.version}`; + +const REQUEST_TIMEOUT = Duration.seconds(10); +const READ_TIMEOUT = Duration.seconds(30); +/** Status checks come every five minutes and on demand; reads come no closer than this. */ +const MIN_READ_INTERVAL_MS = 2 * 60_000; +/** A token this close to expiry counts as expired: a read would race it. */ +const EXPIRY_MARGIN_MS = 60_000; +/** Answers are a few kilobytes; anything near this is not one. */ +const MAX_ANSWER_CHARS = 2_000_000; + +// ── The CLI's token file ───────────────────────────────────────────── + +const TokenFile = Schema.Struct({ + token: Schema.Struct({ + access_token: Schema.NonEmptyString, + refresh_token: Schema.optional(Schema.String), + expiry: Schema.optional(Schema.String), + }), + id_token_email: Schema.optional(Schema.String), +}); +const decodeTokenFile = Schema.decodeUnknownOption(Schema.fromJsonString(TokenFile)); + +interface SavedToken { + readonly accessToken: string; + /** Undefined when the file doesn't say: then it counts as expired. */ + readonly expiresAtMs: number | undefined; + readonly email: string | undefined; + /** Names the Google sign-in without holding it. */ + readonly accountKey: string; +} + +const sha256 = (text: string) => createHash("sha256").update(text).digest("hex").slice(0, 32); + +const cleanEmail = (value: string | undefined) => { + const email = value?.trim(); + return email && email.includes("@") && email.length <= 320 ? email : undefined; +}; + +const readSavedToken = (profileDir: string) => + Effect.promise(async (): Promise => { + const raw = await fs.readFile(antigravityTokenPath(profileDir), "utf8").catch(() => undefined); + if (raw === undefined) return undefined; + const decoded = decodeTokenFile(raw); + if (decoded._tag === "None") return undefined; + const { token, id_token_email } = decoded.value; + const expiresAtMs = token.expiry ? Date.parse(token.expiry) : Number.NaN; + const email = cleanEmail(id_token_email); + return { + accessToken: token.access_token, + expiresAtMs: Number.isFinite(expiresAtMs) ? expiresAtMs : undefined, + email, + // The refresh token outlives renewals; the access token is the last resort. + accountKey: sha256( + `antigravity-account/1\0${token.refresh_token || email || token.access_token}`, + ), + }; + }); + +// ── Google's answers ───────────────────────────────────────────────── + +const Quota = Schema.Struct({ + remainingFraction: Schema.optional(Schema.Number), + resetTime: Schema.optional(Schema.String), +}); +const Bucket = Schema.Struct({ + ...Quota.fields, + bucketId: Schema.NonEmptyString, + window: Schema.optional(Schema.String), + displayName: Schema.optional(Schema.String), + description: Schema.optional(Schema.String), + disabled: Schema.optional(Schema.Boolean), +}); +const Summary = Schema.Struct({ + groups: Schema.optional( + Schema.Array( + Schema.Struct({ + displayName: Schema.optional(Schema.String), + buckets: Schema.optional(Schema.Array(Bucket)), + }), + ), + ), + buckets: Schema.optional(Schema.Array(Bucket)), +}); +const Models = Schema.Struct({ + models: Schema.Record( + Schema.String, + Schema.Struct({ + modelProvider: Schema.optional(Schema.String), + displayName: Schema.optional(Schema.String), + isInternal: Schema.optional(Schema.Boolean), + quotaInfo: Schema.optional(Quota), + weeklyQuotaInfo: Schema.optional(Quota), + }), + ), +}); +const UserInfo = Schema.Struct({ email: Schema.optional(Schema.String) }); + +const decodeSummary = Schema.decodeUnknownOption(Summary); +const decodeModels = Schema.decodeUnknownOption(Models); +const decodeUserInfo = Schema.decodeUnknownOption(UserInfo); + +type Period = "5h" | "weekly" | "quota"; +const PERIOD_MINUTES: Record = { + "5h": 5 * 60, + weekly: 7 * 24 * 60, + quota: undefined, +}; + +/** A group of models one quota covers: a pool, or one model's own quota. */ +interface Family { + readonly key: string; + readonly label: string; + /** Names a model holds to be in the family; undefined: the label. */ + readonly models?: ReadonlyArray; + /** A Gemini family, which the summary sometimes leaves out. */ + readonly gemini: boolean; + /** One model's own quota (Enterprise answers, per-model quotas), not a pool. */ + readonly perModel?: boolean; +} + +const GEMINI: Family = { key: "gemini", label: "Gemini", models: ["Gemini"], gemini: true }; +const SHARED_3P: Family = { + key: "3p", + label: "Claude & GPT", + models: ["Claude", "GPT"], + gemini: false, +}; + +const capitalize = (word: string) => word.charAt(0).toUpperCase() + word.slice(1); + +/** A Gemini 4 pool of its own (`gemini-argon-wtu-weekly`). */ +function geminiSubfamily(sub: string, groupName: string | undefined): Family { + const named = groupName?.trim(); + return { + key: `gemini-${sub}`, + label: + named && named.toLowerCase().split(/\s+/).includes(sub) ? named : `Gemini ${capitalize(sub)}`, + models: [capitalize(sub)], + gemini: true, + }; +} + +/** A thinking level a per-model quota is named with: one model's levels share its row. */ +const EFFORT_SUFFIX = /-(?:extra-high|xhigh|high|medium|low|minimal)$/u; +const EFFORT_NAME = /\s*\((?:extra high|xhigh|high|medium|low|minimal)\)$/iu; + +/** + * One model's own quota, named as the picker names the model: the display + * name Google gives ("Claude Opus 5.5 (High)" without its level), else one + * made from the id ("claude-opus-5-5-high" is "Claude Opus 5.5"). + */ +function perModelFamily(modelId: string, displayName: string | undefined): Family | undefined { + const id = modelId.toLowerCase().replace(EFFORT_SUFFIX, ""); + if (!/^(gemini|claude|gpt)-/.test(id)) return undefined; + const label = + displayName?.trim().replace(EFFORT_NAME, "") || + id + .replace(/(\d)-(?=\d)/g, "$1.") + .split("-") + .map((word) => (word === "gpt" ? "GPT" : capitalize(word))) + .join(" "); + return { + key: `model:${id}`, + label, + models: [label], + gemini: id.startsWith("gemini-"), + perModel: true, + }; +} + +interface QuotaWindow { + readonly family: Family; + readonly period: Period; + /** 0 to 100, unrounded. */ + readonly usedPercent: number; + readonly resetsAtMs: number | undefined; + /** When it was read, for a window kept from an earlier read. */ + readonly checkedAt?: string; +} + +const windowKey = (window: Pick) => + `${window.family.key}:${window.period}`; + +function usedPercentOf(quota: typeof Quota.Type): number | undefined { + const fraction = quota.remainingFraction; + if (fraction === undefined || !Number.isFinite(fraction)) return undefined; + return (1 - Math.max(0, Math.min(1, fraction))) * 100; +} + +const parseTime = (value: string | undefined) => { + const ms = value ? Date.parse(value) : Number.NaN; + return Number.isFinite(ms) ? ms : undefined; +}; + +/** + * Keeps the fuller of two readings of one window; on a tie, the one with a + * reset time, then the earlier reset. A model's row is as tight as its + * tightest thinking level. + */ +function fold(into: Map, window: QuotaWindow) { + const key = windowKey(window); + const previous = into.get(key); + if ( + previous === undefined || + window.usedPercent > previous.usedPercent || + (window.usedPercent === previous.usedPercent && + window.resetsAtMs !== undefined && + (previous.resetsAtMs === undefined || window.resetsAtMs < previous.resetsAtMs)) + ) { + into.set(key, window); + } +} + +/** + * The windows in one `retrieveUserQuotaSummary` answer, requested at + * `requestedAtMs`. Pools (`5h`, `weekly`) keep their own rows; an Enterprise + * answer's per-model buckets get one row per model, its thinking levels + * folded together. + */ +export function antigravitySummaryWindows( + answer: unknown, + requestedAtMs: number, +): ReadonlyArray { + const decoded = decodeSummary(answer); + if (decoded._tag === "None") return []; + const summary = decoded.value; + const groups = summary.groups?.some((group) => group.buckets?.length) + ? summary.groups + : [{ displayName: undefined, buckets: summary.buckets }]; + const windows = new Map(); + for (const group of groups ?? []) { + for (const bucket of group.buckets ?? []) { + if (bucket.disabled) continue; + const usedPercent = usedPercentOf(bucket); + if (usedPercent === undefined) continue; + const pooled = bucket.window === "5h" || bucket.window === "weekly"; + const period: Period = pooled ? (bucket.window as Period) : "quota"; + const id = bucket.bucketId; + const sub = /^gemini-([a-z]+)-/.exec(id)?.[1]; + const family: Family = + (id.startsWith("3p-") + ? SHARED_3P + : /^gemini-(5h|weekly|quota)$/.test(id) + ? GEMINI + : pooled && sub !== undefined + ? geminiSubfamily(sub, group.displayName) + : !pooled + ? perModelFamily(id, bucket.displayName) + : undefined) ?? + ({ + key: `other-${id}`, + label: group.displayName?.trim() || bucket.displayName?.trim() || id, + gemini: false, + } satisfies Family); + // A pool nobody has touched reports a reset one full window from now, + // which is not a real reset time. + const minutes = PERIOD_MINUTES[period]; + const resetsAtMs = parseTime(bucket.resetTime); + const untouched = + bucket.remainingFraction === 1 && + bucket.description === undefined && + minutes !== undefined && + resetsAtMs !== undefined && + Math.abs(resetsAtMs - requestedAtMs - minutes * 60_000) <= 60_000; + fold(windows, { + family, + period, + usedPercent, + resetsAtMs: untouched ? undefined : resetsAtMs, + }); + } + } + return [...windows.values()]; +} + +/** + * The windows in a `fetchAvailableModels` answer: each model's own quota. + * Older accounts report quotas this way only, without a window length, so + * none is made up. + */ +export function antigravityModelWindows(answer: unknown): ReadonlyArray { + const decoded = decodeModels(answer); + if (decoded._tag === "None") return []; + const windows = new Map(); + for (const [modelId, model] of Object.entries(decoded.value.models)) { + if (model.isInternal) continue; + const family = perModelFamily(modelId, model.displayName); + if (!family) continue; + for (const [period, quota] of [ + ["quota", model.quotaInfo], + ["weekly", model.weeklyQuotaInfo], + ] as const) { + const usedPercent = quota ? usedPercentOf(quota) : undefined; + if (usedPercent === undefined) continue; + fold(windows, { family, period, usedPercent, resetsAtMs: parseTime(quota?.resetTime) }); + } + } + return [...windows.values()]; +} + +/** Merges answers in host order: the first host's reading of a window wins. */ +function mergeHosts(answers: ReadonlyArray>) { + const merged = new Map(); + for (const windows of answers) { + for (const window of windows) { + if (!merged.has(windowKey(window))) merged.set(windowKey(window), window); + } + } + return [...merged.values()]; +} + +const FAMILY_ORDER = (family: Family) => + family.key === "gemini" ? 0 : family.gemini ? 1 : family === SHARED_3P || family.perModel ? 2 : 3; +const PERIOD_ORDER: Record = { "5h": 0, weekly: 1, quota: 2 }; + +/** Words as `usageScopeHoldsModel` (@threadlines/shared/usageLimits) reads them. */ +const familyWords = (name: string) => + name + .toLowerCase() + .split(/[^\p{L}\p{N}.]+/u) + .filter(Boolean); +const holdsWords = (model: ReadonlyArray, words: ReadonlyArray) => + words.length > 0 && + model.some((_, start) => words.every((word, offset) => model[start + offset] === word)); + +/** + * A used share as the snapshot carries it, in whole percent. Only an empty + * quota is 100: rounding 99.6 up would say "limit reached" with quota left. + */ +function wholePercentUsed(usedPercent: number): number { + return usedPercent >= 100 ? 100 : Math.min(99, Math.round(usedPercent)); +} + +/** + * A reading as the snapshot carries it: every window is one family's or + * model's own (`scoped`), since a spent one never stops the others. A row + * leaves out the models that have a row of their own: the default Gemini pool + * leaves out the Gemini 4 pools, and "Claude Opus 5" leaves out "Claude Opus + * 5.5". + */ +export function antigravityAccountUsage( + windows: ReadonlyArray, + checkedAt: string, +): ServerProviderAccountUsage { + const families = [ + ...new Map(windows.map((window) => [window.family.key, window.family])).values(), + ]; + const excludesOf = (family: Family): ReadonlyArray => { + if (family.key === "gemini") { + return [ + ...new Set( + families + .filter((other) => other.gemini && !other.perModel && other.key !== "gemini") + .flatMap((other) => other.models ?? []), + ), + ]; + } + if (!family.perModel) return []; + const words = familyWords(family.label); + return families + .filter( + (other) => + other.perModel && + other.key !== family.key && + familyWords(other.label).length > words.length && + holdsWords(familyWords(other.label), words), + ) + .map((other) => other.label); + }; + const scoped = [...windows] + .sort( + (a, b) => + FAMILY_ORDER(a.family) - FAMILY_ORDER(b.family) || + a.family.label.localeCompare(b.family.label) || + PERIOD_ORDER[a.period] - PERIOD_ORDER[b.period], + ) + .map((window): ServerProviderScopedUsageWindow => { + const usedPercent = wholePercentUsed(window.usedPercent); + const minutes = PERIOD_MINUTES[window.period]; + const excludes = excludesOf(window.family); + return { + scopeLabel: window.family.label, + ...(window.family.models ? { scopeModels: window.family.models } : {}), + ...(excludes.length > 0 ? { scopeExcludes: excludes } : {}), + usedPercent, + remainingPercent: 100 - usedPercent, + ...(window.resetsAtMs !== undefined ? { resetsAt: window.resetsAtMs } : {}), + ...(minutes !== undefined ? { windowDurationMins: minutes } : {}), + checkedAt: window.checkedAt ?? checkedAt, + }; + }); + return { + // Older clients reject a source they don't know, and with it the whole + // config, so the reading goes under an existing one and names itself + // in `limitName` (see `ServerProviderAccountUsage.source`). + source: "grok-billing", + checkedAt, + primaryLimitId: "antigravity", + limits: [{ limitId: "antigravity", limitName: ANTIGRAVITY_USAGE_LABEL, scoped }], + }; +} + +// ── Requests ───────────────────────────────────────────────────────── + +/** Why a request failed, in words that never carry the token. */ +class UsageRequestError extends Schema.TaggedError()( + "AntigravityUsageRequestError", + { reason: Schema.String }, +) {} + +interface Timeouts { + readonly request: Duration.Input; + readonly read: Duration.Input; +} + +const requestJson = ( + fetch: DownloadFetch, + url: string, + init: { method: "GET" | "POST"; accessToken: string; body?: string }, + timeout: Duration.Input, +) => + Effect.tryPromise({ + try: async (signal) => { + const response = await fetch(url, { + method: init.method, + headers: { + Authorization: `Bearer ${init.accessToken}`, + "User-Agent": ANTIGRAVITY_USAGE_USER_AGENT, + Accept: "application/json", + ...(init.body !== undefined ? { "Content-Type": "application/json" } : {}), + }, + ...(init.body !== undefined ? { body: init.body } : {}), + redirect: "manual", + signal, + }); + if (!response.ok) { + await response.body?.cancel().catch(() => undefined); + throw new Error(`status ${response.status}`); + } + const text = await response.text(); + if (text.length > MAX_ANSWER_CHARS) throw new Error("answer too large"); + return JSON.parse(text) as unknown; + }, + // The cause can quote the request; only the host is kept. + catch: () => new UsageRequestError({ reason: `${new URL(url).host} did not answer` }), + }).pipe( + Effect.timeoutOrElse({ + duration: timeout, + orElse: () => + Effect.fail(new UsageRequestError({ reason: `${new URL(url).host} timed out` })), + }), + ); + +/** What a read got: its windows, and whether every request it made was answered. */ +interface QuotaRead { + readonly windows: ReadonlyArray; + readonly complete: boolean; +} + +/** One operation on every host, in the method's host order; a host that fails adds nothing. */ +const askHosts = ( + fetch: DownloadFetch, + method: GoogleMethod, + accessToken: string, + operation: "retrieveUserQuotaSummary" | "fetchAvailableModels", + parse: (answer: unknown, requestedAtMs: number) => ReadonlyArray, + timeout: Duration.Input, +) => + Effect.forEach( + HOSTS_BY_METHOD[method], + (host) => + Effect.gen(function* () { + const requestedAtMs = yield* Clock.currentTimeMillis; + const answer = yield* requestJson( + fetch, + `https://${host}/v1internal:${operation}`, + { method: "POST", accessToken, body: "{}" }, + timeout, + ); + return { answered: true, windows: parse(answer, requestedAtMs) }; + }).pipe(Effect.orElseSucceed(() => ({ answered: false, windows: [] as const }))), + { concurrency: "unbounded" }, + ).pipe( + Effect.map((answers): QuotaRead => ({ + complete: answers.every((answer) => answer.answered), + windows: mergeHosts(answers.map((answer) => answer.windows)), + })), + ); + +/** + * One full read. The summary comes first; when it has no Gemini row (Google + * leaves it out for some clients) the per-model quotas fill in Gemini, and + * when it has nothing they stand in for all of it. + */ +const readQuotaWindows = ( + fetch: DownloadFetch, + method: GoogleMethod, + accessToken: string, + timeout: Duration.Input, +) => + Effect.gen(function* () { + const summary = yield* askHosts( + fetch, + method, + accessToken, + "retrieveUserQuotaSummary", + antigravitySummaryWindows, + timeout, + ); + if (summary.windows.some((window) => window.family.gemini)) return summary; + const models = yield* askHosts( + fetch, + method, + accessToken, + "fetchAvailableModels", + antigravityModelWindows, + timeout, + ); + if (summary.windows.length === 0) { + return { windows: models.windows, complete: summary.complete && models.complete }; + } + return { + windows: [...summary.windows, ...models.windows.filter((window) => window.family.gemini)], + complete: summary.complete && models.complete, + } satisfies QuotaRead; + }); + +const readEmail = (fetch: DownloadFetch, accessToken: string, timeout: Duration.Input) => + requestJson(fetch, USERINFO_URL, { method: "GET", accessToken }, timeout).pipe( + Effect.map((answer) => { + const decoded = decodeUserInfo(answer); + return decoded._tag === "Some" ? cleanEmail(decoded.value.email) : undefined; + }), + Effect.orElseSucceed(() => undefined), + ); + +/** + * A read on top of the last one for the same account. Where a host or the + * per-model fallback didn't answer, the rows it would have given are kept + * from before, with the time they were read, so a partial outage doesn't + * drop them. Where every request was answered, the read stands as it is. + */ +function mergeRead( + previous: ReadonlyArray | undefined, + read: QuotaRead, + checkedAt: string, +): ReadonlyArray { + const fresh = read.windows.map((window) => ({ ...window, checkedAt })); + if (read.complete || previous === undefined) return fresh; + const got = new Set(fresh.map(windowKey)); + return [...fresh, ...previous.filter((window) => !got.has(windowKey(window)))]; +} + +// ── The reader ─────────────────────────────────────────────────────── + +export const ANTIGRAVITY_USAGE_EXPIRED_DETAIL = + "Start a chat to refresh these limits. Antigravity renews its Google sign-in only while it runs."; +export const ANTIGRAVITY_USAGE_FAILED_DETAIL = + "Couldn't read Antigravity limits. Trying again soon."; + +/** What a status check shows of the plan: the reading, the email, and what to say about either. */ +export interface AntigravityUsageStatus { + /** Names the Google account the rest belongs to (`ServerProviderAuth.accountId`). */ + readonly accountId?: string; + readonly accountUsage?: ServerProviderAccountUsage; + readonly email?: string; + /** Set when there is something to say: an expired token, or a failed read. */ + readonly usage?: ServerProviderAuthCapability; +} + +/** The instance's snapshot, as the reader uses it once it exists. */ +export type AntigravityUsageSnapshot = Pick; + +export interface AntigravityUsageReader { + /** + * The last reading for the sign-in on disk, never waiting on Google: it + * reads only the token file, and starts a read in the background when one + * is due. Empty for a method that isn't a Google sign-in, or when signed out. + */ + readonly status: Effect.Effect; + /** Cancels a read in flight and forgets every reading: for sign-in and sign-out. */ + readonly reset: Effect.Effect; + /** The instance's snapshot, once it exists: finished reads publish to it. */ + readonly attach: (snapshot: AntigravityUsageSnapshot) => void; + /** + * The limit the last reading says `model` (a picker slug, or a model's + * name) is stopped on, for Continue at reset when the agent gave no time. + */ + readonly usageLimitFor: (model: string) => Effect.Effect; +} + +export interface AntigravityUsageReaderInput { + readonly profileDir: string; + readonly method: AntigravityAuthMethod; + /** `antigravityCredentialFingerprint` of the instance's sign-in. */ + readonly fingerprint: string; + /** Test seam; by default a fetch held to `ANTIGRAVITY_USAGE_HOSTS` with no redirects. */ + readonly fetch?: DownloadFetch; + /** Test seam; by default 10 seconds per request and 30 per read. */ + readonly timeouts?: Timeouts; +} + +interface Reading { + readonly key: string; + readonly windows: ReadonlyArray; + readonly accountUsage: ServerProviderAccountUsage; +} + +export const makeAntigravityUsageReader = ( + input: AntigravityUsageReaderInput, +): Effect.Effect => + Effect.gen(function* () { + const fetch = + input.fetch ?? makeHttpsFetch({ allowedHosts: ANTIGRAVITY_USAGE_HOSTS, maxRedirects: 0 }); + const timeouts = input.timeouts ?? { request: REQUEST_TIMEOUT, read: READ_TIMEOUT }; + const inFlight = yield* FiberHandle.make(); + let reading: Reading | undefined; + let emails = new Map(); + /** The key, time and outcome of the last read started. */ + let lastAttempt: { key: string; atMs: number; failed: boolean } | undefined; + /** Bumped by `reset`: a read started before it doesn't land. */ + let generation = 0; + let snapshot: AntigravityUsageSnapshot | undefined; + + const keyOf = (token: SavedToken) => `${input.fingerprint}:${token.accountKey}`; + + const statusFor = (token: SavedToken, key: string, nowMs: number): AntigravityUsageStatus => { + const kept = reading?.key === key ? reading.accountUsage : undefined; + const email = token.email ?? emails.get(key); + const expired = + token.expiresAtMs === undefined || token.expiresAtMs <= nowMs + EXPIRY_MARGIN_MS; + const usage: ServerProviderAuthCapability | undefined = expired + ? { status: "unavailable", detail: ANTIGRAVITY_USAGE_EXPIRED_DETAIL } + : lastAttempt?.key === key && lastAttempt.failed + ? { + status: "unavailable", + reason: "unreachable", + detail: ANTIGRAVITY_USAGE_FAILED_DETAIL, + } + : undefined; + return { + accountId: accountIdOf(key), + ...(kept ? { accountUsage: kept } : {}), + ...(email ? { email } : {}), + ...(usage ? { usage } : {}), + }; + }; + + const publishStatus = (status: AntigravityUsageStatus) => + snapshot + ? snapshot.patchSnapshot((current) => { + if ( + !current.enabled || + current.auth.status !== "authenticated" || + current.auth.type !== input.method + ) { + return null; + } + return withAntigravityUsage(current, status); + }) + : Effect.void; + + /** + * Where every read ends, done or timed out: only while the sign-in it read + * for is still the one on disk, so one account's numbers and email never + * land on another's. + */ + const land = (key: string, started: number, read: QuotaRead, email: string | undefined) => + Effect.gen(function* () { + const current = yield* readSavedToken(input.profileDir); + if (generation !== started || current === undefined || keyOf(current) !== key) return; + const nowMs = yield* Clock.currentTimeMillis; + if (read.windows.length > 0) { + const windows = mergeRead( + reading?.key === key ? reading.windows : undefined, + read, + new Date(nowMs).toISOString(), + ); + reading = { + key, + windows, + accountUsage: antigravityAccountUsage(windows, new Date(nowMs).toISOString()), + }; + } + if (email) emails.set(key, email); + lastAttempt = { + key, + atMs: lastAttempt?.atMs ?? nowMs, + failed: read.windows.length === 0 || !read.complete, + }; + yield* publishStatus(statusFor(current, key, nowMs)); + }); + + const read = (token: SavedToken, key: string, method: GoogleMethod) => + Effect.gen(function* () { + const started = generation; + return yield* Effect.gen(function* () { + const [windows, email] = yield* Effect.all( + [ + readQuotaWindows(fetch, method, token.accessToken, timeouts.request), + token.email !== undefined || emails.has(key) + ? Effect.succeed(token.email ?? emails.get(key)) + : readEmail(fetch, token.accessToken, timeouts.request), + ], + { concurrency: "unbounded" }, + ); + yield* land(key, started, windows, email); + }).pipe( + Effect.timeoutOrElse({ + duration: timeouts.read, + orElse: () => land(key, started, { windows: [], complete: false }, undefined), + }), + ); + }).pipe( + // Nothing a read does may fail the instance. + Effect.catchCause(() => Effect.void), + ); + + const status = Effect.gen(function* () { + if (!isGoogleMethod(input.method)) return {}; + const token = yield* readSavedToken(input.profileDir); + if (token === undefined) { + // Signed out: whatever is kept belongs to a sign-in that's gone. + reading = undefined; + return {}; + } + const key = keyOf(token); + if (reading !== undefined && reading.key !== key) reading = undefined; + const nowMs = yield* Clock.currentTimeMillis; + const expired = + token.expiresAtMs === undefined || token.expiresAtMs <= nowMs + EXPIRY_MARGIN_MS; + const due = + lastAttempt === undefined || + lastAttempt.key !== key || + nowMs - lastAttempt.atMs >= MIN_READ_INTERVAL_MS; + if (!expired && due) { + lastAttempt = { + key, + atMs: nowMs, + failed: lastAttempt?.key === key ? lastAttempt.failed : false, + }; + yield* FiberHandle.run(inFlight, read(token, key, input.method), { onlyIfMissing: true }); + } + return statusFor(token, key, nowMs); + }).pipe(Effect.catchCause(() => Effect.succeed({}))); + + /** A picker slug's model name, from the instance's model list; a name passes through. */ + const modelName = (model: string) => + snapshot + ? snapshot.getSnapshot.pipe( + Effect.map( + (current) => + current.models.find((candidate) => candidate.slug === model)?.name ?? model, + ), + ) + : Effect.succeed(model); + + return { + status, + reset: Effect.gen(function* () { + generation += 1; + yield* FiberHandle.clear(inFlight); + reading = undefined; + emails = new Map(); + lastAttempt = undefined; + }), + attach: (next) => { + snapshot = next; + }, + usageLimitFor: (model) => + Effect.gen(function* () { + if (!isGoogleMethod(input.method)) return undefined; + const token = yield* readSavedToken(input.profileDir); + if (token === undefined || reading?.key !== keyOf(token)) return undefined; + return usageLimitForModel( + reading.accountUsage, + yield* modelName(model), + yield* Clock.currentTimeMillis, + ); + }).pipe(Effect.catchCause(() => Effect.succeed(undefined))), + } satisfies AntigravityUsageReader; + }); + +/** An opaque name for one Google account on one instance's sign-in; never the token's hash itself. */ +const accountIdOf = (key: string) => + createHash("sha256").update(`antigravity-account-id/1\0${key}`).digest("hex").slice(0, 16); + +/** + * A snapshot (or status) with a usage status folded in: the reading, the + * email, the line about them, and the account they belong to. A status + * without a reading keeps the one already there, the last good one, but only + * for the same account: another account's numbers and email are dropped. + */ +export function withAntigravityUsage< + T extends { + readonly auth: ServerProviderAuth; + readonly accountUsage?: ServerProviderAccountUsage | undefined; + }, +>(target: T, status: AntigravityUsageStatus): T { + const { capabilities, email: previousEmail, accountId: previousAccountId, ...auth } = target.auth; + const { usage: _previous, ...others } = capabilities ?? {}; + const nextCapabilities = { ...others, ...(status.usage ? { usage: status.usage } : {}) }; + const sameAccount = previousAccountId === undefined || previousAccountId === status.accountId; + const { accountUsage: previousUsage, ...rest } = target; + const email = status.email ?? (sameAccount ? previousEmail : undefined); + const accountUsage = status.accountUsage ?? (sameAccount ? previousUsage : undefined); + return { + ...rest, + auth: { + ...auth, + ...(status.accountId ? { accountId: status.accountId } : {}), + ...(email ? { email } : {}), + ...(Object.keys(nextCapabilities).length > 0 ? { capabilities: nextCapabilities } : {}), + }, + ...(accountUsage ? { accountUsage } : {}), + } as T; +} diff --git a/apps/server/src/provider/antigravity/AntigravityUserConfig.test.ts b/apps/server/src/provider/antigravity/AntigravityUserConfig.test.ts new file mode 100644 index 000000000..94bb63b9f --- /dev/null +++ b/apps/server/src/provider/antigravity/AntigravityUserConfig.test.ts @@ -0,0 +1,435 @@ +// @effect-diagnostics nodeBuiltinImport:off - builds a fake home and profile on disk +import { execFileSync } from "node:child_process"; +import { createHash } from "node:crypto"; +import * as NodeFS from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; + +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { afterEach, describe, expect, it } from "@effect/vitest"; +import { AntigravitySettings } from "@threadlines/contracts"; +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; +import { HttpClient } from "effect/http"; +import { ChildProcessSpawner } from "effect/process"; + +import { checkAcpProviderStatus } from "../acp/AcpProvider.ts"; +import { makeAntigravityDescriptor } from "../acp/AntigravityAcpSupport.ts"; +import { antigravityInstancePaths } from "./AntigravityProfile.ts"; +import { antigravitySignInConfig } from "./AntigravitySignInMethod.ts"; +import { + antigravitySharedConfigRecordPath, + ANTIGRAVITY_SHARED_DIRS, + ANTIGRAVITY_SHARED_FILES, + antigravityUserHome, + shareAntigravityUserConfigNow, +} from "./AntigravityUserConfig.ts"; + +const decodeAntigravitySettings = Schema.decodeSync(AntigravitySettings); +const roots: Array = []; + +afterEach(async () => { + await Promise.all(roots.splice(0).map((root) => NodeFS.rm(root, { recursive: true }))); +}); + +async function makeSetup() { + const root = await NodeFS.realpath(await NodeFS.mkdtemp(path.join(os.tmpdir(), "agy-share-"))); + roots.push(root); + const userHome = path.join(root, "home"); + const gemini = path.join(userHome, ".gemini"); + const profileDir = path.join(root, "profile"); + await NodeFS.mkdir(profileDir, { recursive: true }); + const write = async (rel: string, content: string) => { + const file = path.join(gemini, ...rel.split("/")); + await NodeFS.mkdir(path.dirname(file), { recursive: true }); + await NodeFS.writeFile(file, content); + return file; + }; + return { root, userHome, gemini, profileDir, write }; +} + +const inProfile = (profileDir: string, rel: string) => path.join(profileDir, ...rel.split("/")); +const linkOf = (file: string) => NodeFS.readlink(file).catch(() => undefined); +const exists = (file: string) => + NodeFS.lstat(file).then( + () => true, + () => false, + ); + +/** Everything in the profile except the record Threadlines keeps. */ +async function profileEntries(profileDir: string): Promise> { + const found: Array = []; + const walk = async (dir: string) => { + for (const entry of await NodeFS.readdir(dir, { withFileTypes: true })) { + const rel = path.relative(profileDir, path.join(dir, entry.name)).split(path.sep).join("/"); + if (rel === "threadlines-shared-config.json") continue; + found.push(rel); + if (entry.isDirectory()) await walk(path.join(dir, entry.name)); + } + }; + await walk(profileDir); + return found.toSorted(); +} + +describe("shareAntigravityUserConfigNow on macOS and Linux", () => { + it("links the rules and skills that exist, and nothing else from ~/.gemini", async () => { + const setup = await makeSetup(); + for (const rel of ANTIGRAVITY_SHARED_FILES) await setup.write(rel, `rule ${rel}`); + for (const rel of ANTIGRAVITY_SHARED_DIRS) await setup.write(`${rel}/one/SKILL.md`, "x"); + // Never shared: sign-in, hooks, MCP, plugins, settings. + for (const rel of [ + "antigravity-cli/antigravity-oauth-token", + "config/hooks.json", + "config/mcp_config.json", + "config/plugins/p/plugin.json", + "config/config.json", + "antigravity-cli/settings.json", + ]) { + await setup.write(rel, "secret"); + } + + const problems = await shareAntigravityUserConfigNow({ ...setup, platform: "darwin" }); + + expect(problems).toEqual([]); + for (const rel of [...ANTIGRAVITY_SHARED_FILES, ...ANTIGRAVITY_SHARED_DIRS]) { + expect(await linkOf(inProfile(setup.profileDir, rel))).toBe(path.join(setup.gemini, rel)); + } + expect(await profileEntries(setup.profileDir)).toEqual( + [ + "antigravity-cli", + "config", + ...ANTIGRAVITY_SHARED_FILES, + ...ANTIGRAVITY_SHARED_DIRS, + ].toSorted(), + ); + }); + + it("does nothing without ~/.gemini, and picks up a source that appears later", async () => { + const setup = await makeSetup(); + expect(await shareAntigravityUserConfigNow({ ...setup, platform: "linux" })).toEqual([]); + expect(await profileEntries(setup.profileDir)).toEqual([]); + + // The agent creates an empty skills folder of its own meanwhile. + await NodeFS.mkdir(inProfile(setup.profileDir, "config/skills"), { recursive: true }); + await setup.write("GEMINI.md", "rule"); + await setup.write("config/skills/review/SKILL.md", "x"); + await shareAntigravityUserConfigNow({ ...setup, platform: "linux" }); + + expect(await linkOf(inProfile(setup.profileDir, "GEMINI.md"))).toBe( + path.join(setup.gemini, "GEMINI.md"), + ); + expect(await linkOf(inProfile(setup.profileDir, "config/skills"))).toBe( + path.join(setup.gemini, "config/skills"), + ); + }); + + it("removes its own link once the source is gone, so the agent can make the folder", async () => { + const setup = await makeSetup(); + await setup.write("antigravity-cli/skills/a/SKILL.md", "x"); + await shareAntigravityUserConfigNow({ ...setup, platform: "linux" }); + await NodeFS.rm(path.join(setup.gemini, "antigravity-cli"), { recursive: true }); + + await shareAntigravityUserConfigNow({ ...setup, platform: "linux" }); + + expect(await exists(inProfile(setup.profileDir, "antigravity-cli/skills"))).toBe(false); + }); + + it("replaces a link it made for an old home, and leaves what it didn't make", async () => { + const setup = await makeSetup(); + const oldHome = path.join(setup.root, "old-home"); + await NodeFS.mkdir(path.join(oldHome, ".gemini"), { recursive: true }); + await NodeFS.writeFile(path.join(oldHome, ".gemini", "AGENTS.md"), "old"); + await shareAntigravityUserConfigNow({ ...setup, userHome: oldHome, platform: "linux" }); + expect(await linkOf(inProfile(setup.profileDir, "AGENTS.md"))).toBe( + path.join(oldHome, ".gemini", "AGENTS.md"), + ); + + await setup.write("AGENTS.md", "new"); + await setup.write("GEMINI.md", "rule"); + await setup.write("config/rules/always.md", "rule"); + await setup.write("config/skills/a/SKILL.md", "x"); + // Not Threadlines': a link someone else made, a file the agent wrote, + // and a skills folder with the agent's own skill in it. + const elsewhere = path.join(setup.root, "elsewhere.md"); + await NodeFS.writeFile(elsewhere, "theirs"); + await NodeFS.symlink(elsewhere, inProfile(setup.profileDir, "GEMINI.md")); + await NodeFS.mkdir(inProfile(setup.profileDir, "config"), { recursive: true }); + await NodeFS.writeFile(inProfile(setup.profileDir, "config/rules"), "agent's file"); + await NodeFS.mkdir(inProfile(setup.profileDir, "config/skills/own"), { recursive: true }); + + await shareAntigravityUserConfigNow({ ...setup, platform: "linux" }); + + expect(await linkOf(inProfile(setup.profileDir, "AGENTS.md"))).toBe( + path.join(setup.gemini, "AGENTS.md"), + ); + expect(await linkOf(inProfile(setup.profileDir, "GEMINI.md"))).toBe(elsewhere); + expect(await NodeFS.readFile(inProfile(setup.profileDir, "config/rules"), "utf8")).toBe( + "agent's file", + ); + expect(await exists(inProfile(setup.profileDir, "config/skills/own"))).toBe(true); + }); +}); + +describe("shareAntigravityUserConfigNow on Windows", () => { + it("copies rule files, refreshes them, and never overwrites one the agent changed", async () => { + const setup = await makeSetup(); + await setup.write("AGENTS.md", "first"); + await setup.write("config/GEMINI.md", "rule"); + await setup.write("config/skills/a/SKILL.md", "x"); + + await shareAntigravityUserConfigNow({ ...setup, platform: "win32" }); + + const agents = inProfile(setup.profileDir, "AGENTS.md"); + const gemini = inProfile(setup.profileDir, "config/GEMINI.md"); + expect(await linkOf(agents)).toBeUndefined(); + expect(await NodeFS.readFile(agents, "utf8")).toBe("first"); + // Folders become junctions, which need no privileges (a plain link off Windows). + expect(await linkOf(inProfile(setup.profileDir, "config/skills"))).toBe( + path.join(setup.gemini, "config/skills"), + ); + + await setup.write("AGENTS.md", "second"); + await NodeFS.writeFile(gemini, "edited in the profile"); + await shareAntigravityUserConfigNow({ ...setup, platform: "win32" }); + expect(await NodeFS.readFile(agents, "utf8")).toBe("second"); + expect(await NodeFS.readFile(gemini, "utf8")).toBe("edited in the profile"); + + await NodeFS.rm(path.join(setup.gemini, "AGENTS.md")); + await NodeFS.rm(path.join(setup.gemini, "config/GEMINI.md")); + await shareAntigravityUserConfigNow({ ...setup, platform: "win32" }); + expect(await exists(agents)).toBe(false); + expect(await NodeFS.readFile(gemini, "utf8")).toBe("edited in the profile"); + }); + + it("leaves a rule file that was in the profile before Threadlines copied anything", async () => { + const setup = await makeSetup(); + await setup.write("AGENTS.md", "user's"); + await NodeFS.writeFile(inProfile(setup.profileDir, "AGENTS.md"), "agent's"); + + await shareAntigravityUserConfigNow({ ...setup, platform: "win32" }); + + expect(await NodeFS.readFile(inProfile(setup.profileDir, "AGENTS.md"), "utf8")).toBe("agent's"); + }); +}); + +describe("shareAntigravityUserConfigNow keeps to the profile and the allowlist", () => { + it("never writes through a profile folder that links to the user's real config", async () => { + const setup = await makeSetup(); + // The agent (or anyone) made the profile's config a link to the real one. + const realConfig = path.join(setup.gemini, "config"); + await NodeFS.mkdir(path.join(realConfig, "skills"), { recursive: true }); + await setup.write("config/GEMINI.md", "the user's own"); + await NodeFS.symlink(realConfig, inProfile(setup.profileDir, "config")); + + const problems = await shareAntigravityUserConfigNow({ ...setup, platform: "linux" }); + + // The real, empty skills folder is still a real folder, not a link to itself. + const skills = await NodeFS.lstat(path.join(realConfig, "skills")); + expect(skills.isDirectory()).toBe(true); + expect(await NodeFS.readFile(path.join(realConfig, "GEMINI.md"), "utf8")).toBe( + "the user's own", + ); + expect(problems.map((problem) => path.relative(setup.profileDir, problem.path))).toEqual( + expect.arrayContaining([path.join("config", "skills"), path.join("config", "GEMINI.md")]), + ); + }); + + it("brings in linked sources from elsewhere, but never a keep-out file or Threadlines data", async () => { + const setup = await makeSetup(); + const dotfiles = path.join(setup.root, "dotfiles"); + const threadlinesDir = path.join(setup.root, "threadlines"); + await NodeFS.mkdir(path.join(threadlinesDir, "secrets"), { recursive: true }); + await NodeFS.mkdir(dotfiles, { recursive: true }); + await NodeFS.writeFile(path.join(dotfiles, "AGENTS.md"), "from dotfiles"); + await NodeFS.writeFile(path.join(dotfiles, "mcp_config.json"), "{}"); + const token = await setup.write("antigravity-cli/antigravity-oauth-token", "TOKEN"); + await NodeFS.mkdir(path.join(setup.gemini, "config"), { recursive: true }); + const link = (target: string, rel: string) => + NodeFS.symlink(target, path.join(setup.gemini, ...rel.split("/"))); + await link(path.join(dotfiles, "AGENTS.md"), "AGENTS.md"); + await link(token, "GEMINI.md"); + await link(path.join(dotfiles, "mcp_config.json"), "config/rules.json"); + await link(path.join(threadlinesDir, "secrets"), "config/rules"); + await link(path.join(setup.gemini, "AGENTS.md"), "config/AGENTS.md"); + // Elsewhere in ~/.gemini, under any name: the CLI's own settings. + await link(await setup.write("antigravity-cli/settings.json", "{}"), "config/skills.json"); + + for (const platform of ["linux", "win32"] as const) { + const profileDir = path.join(setup.root, `profile-${platform}`); + await shareAntigravityUserConfigNow({ ...setup, profileDir, platform, threadlinesDir }); + const read = (rel: string) => + NodeFS.readFile(inProfile(profileDir, rel), "utf8").catch(() => undefined); + expect(await read("AGENTS.md")).toBe("from dotfiles"); + // A shared entry linked to another shared entry is fine. + expect(await read("config/AGENTS.md")).toBe("from dotfiles"); + expect(await exists(inProfile(profileDir, "GEMINI.md"))).toBe(false); + expect(await exists(inProfile(profileDir, "config/rules.json"))).toBe(false); + expect(await exists(inProfile(profileDir, "config/rules"))).toBe(false); + expect(await exists(inProfile(profileDir, "config/skills.json"))).toBe(false); + } + }); + + it.skipIf(process.platform === "win32")( + "doesn't hang on a FIFO where the record or a source should be", + async () => { + const setup = await makeSetup(); + execFileSync("mkfifo", [antigravitySharedConfigRecordPath(setup.profileDir)]); + await NodeFS.mkdir(setup.gemini, { recursive: true }); + execFileSync("mkfifo", [path.join(setup.gemini, "AGENTS.md")]); + await setup.write("GEMINI.md", "rule"); + + for (const platform of ["linux", "win32"] as const) { + await shareAntigravityUserConfigNow({ ...setup, platform }); + } + + expect(await NodeFS.readFile(inProfile(setup.profileDir, "GEMINI.md"), "utf8")).toBe("rule"); + expect(await exists(inProfile(setup.profileDir, "AGENTS.md"))).toBe(false); + }, + 5_000, + ); +}); + +describe("shareAntigravityUserConfigNow only removes what it made", () => { + it("uses a matching link it didn't make, and leaves it when the source goes", async () => { + const setup = await makeSetup(); + const source = await setup.write("GEMINI.md", "rule"); + const skills = path.join(setup.gemini, "config", "skills"); + await NodeFS.mkdir(path.join(setup.profileDir, "config"), { recursive: true }); + // Someone else's links, one of them already dangling. + await NodeFS.symlink(source, inProfile(setup.profileDir, "GEMINI.md")); + await NodeFS.symlink(skills, inProfile(setup.profileDir, "config/skills")); + + await shareAntigravityUserConfigNow({ ...setup, platform: "linux" }); + expect(await linkOf(inProfile(setup.profileDir, "config/skills"))).toBe(skills); + await NodeFS.rm(source); + await shareAntigravityUserConfigNow({ ...setup, platform: "linux" }); + + expect(await linkOf(inProfile(setup.profileDir, "GEMINI.md"))).toBe(source); + expect(await linkOf(inProfile(setup.profileDir, "config/skills"))).toBe(skills); + }); + + it("keeps its record out of the profile, so a record written there authorizes nothing", async () => { + const setup = await makeSetup(); + await setup.write("AGENTS.md", "the user's rule"); + const agentRule = "the agent's own rule"; + await NodeFS.writeFile(inProfile(setup.profileDir, "AGENTS.md"), agentRule); + const digest = createHash("sha256").update(agentRule).digest("hex"); + // What the record looked like when it lived in the profile. + await NodeFS.writeFile( + path.join(setup.profileDir, "threadlines-shared-config.json"), + JSON.stringify({ links: {}, copies: { "AGENTS.md": digest } }), + ); + + await shareAntigravityUserConfigNow({ ...setup, platform: "win32" }); + + expect(await NodeFS.readFile(inProfile(setup.profileDir, "AGENTS.md"), "utf8")).toBe(agentRule); + }); + + it("still knows a copy as its own after a refresh cut short before the record caught up", async () => { + const setup = await makeSetup(); + await setup.write("AGENTS.md", "v1"); + await shareAntigravityUserConfigNow({ ...setup, platform: "win32" }); + // A refresh to v2 that stopped after the copy landed: the record then + // names both versions (it is written before the copy moves). + await NodeFS.writeFile(inProfile(setup.profileDir, "AGENTS.md"), "v2"); + const sha = (text: string) => createHash("sha256").update(text).digest("hex"); + await NodeFS.writeFile( + antigravitySharedConfigRecordPath(setup.profileDir), + JSON.stringify({ links: {}, copies: { "AGENTS.md": [sha("v1"), sha("v2")] } }), + ); + await setup.write("AGENTS.md", "v3"); + + await shareAntigravityUserConfigNow({ ...setup, platform: "win32" }); + + expect(await NodeFS.readFile(inProfile(setup.profileDir, "AGENTS.md"), "utf8")).toBe("v3"); + }); + + it("lets starts that overlap take turns", async () => { + const setup = await makeSetup(); + for (const rel of ANTIGRAVITY_SHARED_FILES) await setup.write(rel, `rule ${rel}`); + const runs = await Promise.all( + Array.from({ length: 8 }, () => + shareAntigravityUserConfigNow({ ...setup, platform: "win32" }), + ), + ); + expect(runs.flat()).toEqual([]); + for (const rel of ANTIGRAVITY_SHARED_FILES) { + expect(await NodeFS.readFile(inProfile(setup.profileDir, rel), "utf8")).toBe(`rule ${rel}`); + } + // Every copy is still known as Threadlines', so it goes with its source. + await NodeFS.rm(setup.gemini, { recursive: true }); + await shareAntigravityUserConfigNow({ ...setup, platform: "win32" }); + for (const rel of ANTIGRAVITY_SHARED_FILES) { + expect(await exists(inProfile(setup.profileDir, rel))).toBe(false); + } + }); +}); + +describe("antigravityUserHome", () => { + it("reads the home the agent will expand ~ to", () => { + expect(antigravityUserHome("darwin", { HOME: "/Users/a" }, "/fallback")).toBe("/Users/a"); + expect(antigravityUserHome("linux", {}, "/fallback")).toBe("/fallback"); + expect(antigravityUserHome("win32", { USERPROFILE: "C:\\Users\\a", HOME: "/x" }, "C:\\f")).toBe( + "C:\\Users\\a", + ); + expect(antigravityUserHome("win32", { HOMEDRIVE: "D:", HOMEPATH: "\\u" }, "C:\\f")).toBe( + "D:\\u", + ); + }); +}); + +describe("an Antigravity instance and the user's own setup", () => { + it("brings the user's rules in at launch and lists their skills in the status", async () => { + const setup = await makeSetup(); + await setup.write("GEMINI.md", "rule"); + const skill = await setup.write( + "config/skills/review/SKILL.md", + "---\nname: review\ndescription: Review changes.\n---\n", + ); + const agy = path.join(setup.root, "agy"); + await NodeFS.writeFile(agy, "#!/bin/sh\n", { mode: 0o755 }); + const settings = { + ...decodeAntigravitySettings({}), + enabled: true, + binaryPath: agy, + }; + const paths = antigravityInstancePaths(path.join(setup.root, "state"), "antigravity-test"); + const descriptor = makeAntigravityDescriptor({ + paths, + runtime: undefined, + releases: undefined, + signIn: antigravitySignInConfig(settings, undefined), + skillsCwd: path.join(setup.root, "project"), + }); + const environment = { HOME: setup.userHome, USERPROFILE: setup.userHome }; + + const status = await Effect.runPromise( + Effect.gen(function* () { + // Builds the launch without starting anything. + const launch = descriptor.spawn(settings, setup.root, environment); + if (Effect.isEffect(launch)) yield* Effect.scoped(launch); + return yield* checkAcpProviderStatus(descriptor, settings, environment); + }).pipe( + Effect.provideService( + ChildProcessSpawner.ChildProcessSpawner, + ChildProcessSpawner.make(() => Effect.die("The status check must not start the agent")), + ), + Effect.provideService( + HttpClient.HttpClient, + HttpClient.make(() => Effect.die("The status check must not reach the network")), + ), + Effect.provide(NodeServices.layer), + ), + ); + + const rules = path.join(paths.profileDir, "GEMINI.md"); + if (process.platform === "win32") { + expect(await NodeFS.readFile(rules, "utf8")).toBe("rule"); + } else { + expect(await linkOf(rules)).toBe(path.join(setup.gemini, "GEMINI.md")); + } + expect(status.skills).toEqual([ + { name: "review", description: "Review changes.", path: skill, scope: "user", enabled: true }, + ]); + }); +}); diff --git a/apps/server/src/provider/antigravity/AntigravityUserConfig.ts b/apps/server/src/provider/antigravity/AntigravityUserConfig.ts new file mode 100644 index 000000000..5c4653a3b --- /dev/null +++ b/apps/server/src/provider/antigravity/AntigravityUserConfig.ts @@ -0,0 +1,542 @@ +/** + * AntigravityUserConfig — brings the user's own global rules and skills from + * `~/.gemini` into each instance's private profile. + * + * An instance runs with its own `GEMINI_HOME` (`AntigravityProfile`) so its + * sign-in stays separate, and the agent reads global rules and skills from + * there. This module links the rule files and skill folders listed below + * into the profile on macOS and Linux. On Windows it uses junctions for the + * folders (they need no privileges) and copies the files, refreshing each + * copy when its source changes. Runs before every agent start and every + * status check, so a source that appears later is picked up then, and one + * that goes away takes Threadlines' link or copy with it. + * + * What it will not do: + * + * - Bring in anything on the keep-out list, even through a link: sign-in + * and token files, hooks, MCP config, plugins, agents config, the rest of + * `~/.gemini`, and Threadlines' own data folder. + * - Touch anything it didn't make. A record beside the profile (outside the + * agent's home) names each link and copy Threadlines made; only those are + * replaced or removed. A matching link someone else made is used as it is + * and never removed. The one exception is an empty folder the agent left + * where a link was missing, which holds nothing to lose. + * - Work through a link inside the profile: a profile folder that is a link + * (to the user's real `~/.gemini/config`, say) would turn a profile write + * into a write to the user's own files, so that entry is skipped. + * - Hold up a chat: the whole step has a time bound, and file reads never + * block on a FIFO. + * + * Writes go in a crash-safe order: the record claims a link or copy before + * it is made, a new copy is linked into place without overwriting, and a + * replaced or removed one is first moved aside and checked. + * + * @module provider/antigravity/AntigravityUserConfig + */ +import { createHash, randomBytes } from "node:crypto"; +import * as fs from "node:fs/promises"; +import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path"; + +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; + +import { readRegularFile } from "./AntigravityFileReads.ts"; + +/** + * Folders Google's CLI reads global skills and rules from, relative to + * `GEMINI_HOME`. The CLI looks in `antigravity-cli/skills` even when its app + * data dir is `antigravity-acp` (T3 Code links the same two skill folders; + * the CLI creates both itself when they are missing). `config/rules` holds + * always-on rule files (CLI changelog: global customization in + * `~/.gemini/config` includes the `rules/` folder). + */ +export const ANTIGRAVITY_SHARED_DIRS = [ + "config/skills", + "antigravity-cli/skills", + "config/rules", +] as const; + +/** Global rule files and the skill and rule manifests, relative to `GEMINI_HOME`. */ +export const ANTIGRAVITY_SHARED_FILES = [ + "AGENTS.md", + "GEMINI.md", + "config/AGENTS.md", + "config/GEMINI.md", + "config/skills.json", + "config/rules.json", +] as const; + +/** + * File names never brought in, wherever a shared source's link leads: + * sign-in and token files, hooks, MCP config, plugins and agents config. + */ +const KEEP_OUT_NAMES = new Set([ + "antigravity-oauth-token", + "acp_token.json", + "oauth_creds.json", + "google_accounts.json", + "application_default_credentials.json", + "credentials.db", + "access_tokens.db", + "hooks.json", + "mcp_config.json", + "plugins.json", + "plugins", + "agents.json", +]); + +/** Copies above this size are skipped: the CLI cuts a rule file off far below it. */ +const MAX_COPY_BYTES = 1_000_000; +const MAX_RECORD_BYTES = 64 * 1024; +/** No chat waits longer than this for the user's rules and skills. */ +const SHARE_TIME_LIMIT = Duration.seconds(10); + +/** What Threadlines put in the profile, so it never touches what it didn't. */ +interface SharedConfigRecord { + /** Link path (relative to the profile) to the target it was made for. */ + links: Record; + /** + * Copy path (relative to the profile) to the sha256 of each content that + * is Threadlines': two while a refresh is in flight, so a crash between + * the copy landing and the record catching up leaves it still ours. + */ + copies: Record>; +} + +/** Beside the profile, so the record is outside the folder the agent keeps as its home. */ +export const antigravitySharedConfigRecordPath = (profileDir: string) => + `${profileDir}.shared-config.json`; + +function parseRecord(raw: unknown): SharedConfigRecord { + const record: SharedConfigRecord = { links: {}, copies: {} }; + if (typeof raw !== "object" || raw === null) return record; + const { links, copies } = raw as { links?: unknown; copies?: unknown }; + if (typeof links === "object" && links !== null) { + for (const [rel, target] of Object.entries(links)) { + if (typeof target === "string") record.links[rel] = target; + } + } + if (typeof copies === "object" && copies !== null) { + for (const [rel, digests] of Object.entries(copies)) { + if (Array.isArray(digests)) { + record.copies[rel] = digests.filter((digest) => typeof digest === "string"); + } + } + } + return record; +} + +async function readRecord(profileDir: string): Promise { + const raw = await readRegularFile(antigravitySharedConfigRecordPath(profileDir), { + maxBytes: MAX_RECORD_BYTES, + followLink: false, + }); + try { + return parseRecord(raw === undefined ? undefined : JSON.parse(raw.toString("utf8"))); + } catch { + return { links: {}, copies: {} }; + } +} + +async function writeRecord(profileDir: string, record: SharedConfigRecord): Promise { + const target = antigravitySharedConfigRecordPath(profileDir); + const temp = `${target}.${randomBytes(4).toString("hex")}.tmp`; + await fs.writeFile(temp, JSON.stringify(record), { mode: 0o600, flag: "wx" }); + await fs.rename(temp, target); +} + +/** + * The home folder the agent will treat as `~`, which is where its global + * config lives: Python's `os.path.expanduser`, so `USERPROFILE` (then + * `HOMEDRIVE` + `HOMEPATH`) on Windows and `HOME` elsewhere. + */ +export function antigravityUserHome( + platform: NodeJS.Platform, + environment: NodeJS.ProcessEnv, + fallback: string, +): string { + if (platform === "win32") { + if (environment.USERPROFILE) return environment.USERPROFILE; + if (environment.HOMEDRIVE && environment.HOMEPATH) { + return `${environment.HOMEDRIVE}${environment.HOMEPATH}`; + } + return fallback; + } + return environment.HOME || fallback; +} + +/** The user's own `~/.gemini`. */ +export const antigravityUserGeminiDir = (userHome: string) => join(userHome, ".gemini"); + +type EntryKind = "dir" | "file"; + +const isInside = (root: string, path: string) => { + const rel = relative(root, path); + return rel === "" || (!isAbsolute(rel) && rel !== ".." && !rel.startsWith(`..${sep}`)); +}; + +const realpathOf = (path: string) => fs.realpath(path).catch(() => undefined); +const codeOf = (error: unknown) => (error as NodeJS.ErrnoException).code; + +/** Where Threadlines may and may not take a shared source from. */ +interface SourceRules { + /** The user's real `~/.gemini`, if it exists. */ + readonly realGemini: string | undefined; + /** Folders a source may never lead into: Threadlines' data and the profile. */ + readonly forbidden: ReadonlyArray; +} + +/** + * Whether the source of a shared entry exists as `kind` and may be brought + * in. A source can be a link (people keep these in a dotfiles repo); what + * counts is where it leads. Inside `~/.gemini` it may only lead to one of + * the shared entries, so a `GEMINI.md` linked to the sign-in token is not a + * rule; anywhere else it must not be a keep-out file or Threadlines' data. + */ +async function sourceAllowed(source: string, kind: EntryKind, rules: SourceRules) { + const real = await realpathOf(source); + if (real === undefined) return false; + const stat = await fs.stat(real).catch(() => undefined); + if (kind === "dir" ? !stat?.isDirectory() : !stat?.isFile()) return false; + if (KEEP_OUT_NAMES.has(basename(real).toLowerCase())) return false; + if (rules.forbidden.some((root) => isInside(root, real))) return false; + const { realGemini } = rules; + if (realGemini !== undefined && isInside(realGemini, real)) { + return [...ANTIGRAVITY_SHARED_DIRS, ...ANTIGRAVITY_SHARED_FILES].some((rel) => + isInside(join(realGemini, ...rel.split("/")), real), + ); + } + return true; +} + +/** + * Whether every folder between the profile and an entry is a real folder + * inside the profile (or missing, when `create` is off); false when one is a + * link or anything else, so nothing is read or written through it. With + * `create`, missing folders are made, one level at a time. + */ +async function realParentInProfile(input: { + readonly profileDir: string; + readonly realProfile: string; + readonly rel: string; + readonly create: boolean; +}): Promise { + const parts = input.rel.split("/").slice(0, -1); + let dir = input.profileDir; + for (const part of parts) { + dir = join(dir, part); + const stat = await fs.lstat(dir).catch(() => undefined); + if (stat === undefined) { + if (!input.create) return true; + // Not recursive: mkdir -p would walk through a link made meanwhile. + await fs.mkdir(dir, { mode: 0o700 }).catch((error: unknown) => { + if (codeOf(error) !== "EEXIST") throw error; + }); + continue; + } + if (!stat.isDirectory()) return false; + } + return (await realpathOf(dir)) === join(input.realProfile, ...parts); +} + +/** Where an existing link points, as an absolute path; Windows' `\\?\` prefix dropped. */ +const linkTarget = async (link: string) => { + const raw = await fs.readlink(link); + return resolve(dirname(link), raw.replace(/^\\\\\?\\/u, "")); +}; + +const asidePath = (path: string) => `${path}.threadlines-${randomBytes(4).toString("hex")}`; + +/** + * Puts back something moved aside that turned out not to be Threadlines', + * without replacing whatever took its place meanwhile. If its name is taken + * it stays under the aside name, and that is reported. + */ +async function putBack(aside: string, path: string): Promise { + const stat = await fs.lstat(aside); + if (stat.isSymbolicLink()) { + await fs.symlink(await fs.readlink(aside), path); + await fs.unlink(aside); + } else if (stat.isDirectory()) { + await fs.rename(aside, path); + } else { + await fs.link(aside, path); + await fs.unlink(aside); + } +} + +/** + * Removes `path` only if it still is what `isOurs` recognizes, judged after + * it is moved aside, so a file the agent writes at the same moment is never + * deleted in its place. + */ +async function removeIfOurs( + path: string, + isOurs: (aside: string) => Promise, +): Promise { + const aside = asidePath(path); + try { + await fs.rename(path, aside); + } catch (error) { + if (codeOf(error) === "ENOENT") return true; + throw error; + } + if (await isOurs(aside)) { + await fs.unlink(aside); + return true; + } + await putBack(aside, path).catch((error: unknown) => { + throw new Error(`Left ${aside} beside ${path}: ${String(error)}`, { cause: error }); + }); + return false; +} + +interface EntryContext { + readonly rel: string; + readonly path: string; + readonly source: string; + readonly kind: EntryKind; + readonly allowed: boolean; + readonly platform: NodeJS.Platform; + readonly record: SharedConfigRecord; + /** Saves the record before a link or copy is made, so a crash leaves it claimed. */ + readonly claim: () => Promise; + /** Makes the entry's folders, still refusing any that is a link; false when refused. */ + readonly makeParent: () => Promise; +} + +/** Links one shared folder or file; updates the record with what is Threadlines'. */ +async function shareByLink(entry: EntryContext): Promise { + const { path, source, record, rel } = entry; + const recorded = record.links[rel]; + const stat = await fs.lstat(path).catch(() => undefined); + if (stat?.isSymbolicLink()) { + const current = await linkTarget(path); + if (current === source && entry.allowed) return; + // A link Threadlines didn't make is used as it is, and never removed. + if (recorded === undefined || current !== recorded) { + delete record.links[rel]; + return; + } + const removed = await removeIfOurs(path, async (aside) => { + const asideStat = await fs.lstat(aside).catch(() => undefined); + return asideStat?.isSymbolicLink() === true && (await linkTarget(aside)) === recorded; + }); + if (!removed) { + delete record.links[rel]; + return; + } + } else if (stat?.isDirectory()) { + delete record.links[rel]; + if (!entry.allowed || entry.kind !== "dir") return; + // The agent leaves an empty folder where a link was missing. rmdir + // refuses one with anything in it, so nothing the agent wrote is lost. + const removed = await fs.rmdir(path).then( + () => true, + () => false, + ); + if (!removed) return; + } else if (stat) { + // A real file the agent or the user put there. + delete record.links[rel]; + return; + } + delete record.links[rel]; + if (!entry.allowed) return; + if (!(await entry.makeParent())) return; + record.links[rel] = source; + await entry.claim(); + const type = + entry.kind === "file" ? "file" : entry.platform === "win32" ? "junction" : ("dir" as const); + try { + // Fails on an existing entry instead of replacing it. + await fs.symlink(source, path, type); + } catch (error) { + if (codeOf(error) === "EEXIST" && (await linkTarget(path).catch(() => undefined)) === source) { + return; + } + delete record.links[rel]; + throw error; + } +} + +const sha256 = (content: Buffer) => createHash("sha256").update(content).digest("hex"); + +const readCopy = (path: string) => + readRegularFile(path, { maxBytes: MAX_COPY_BYTES, followLink: false }); + +/** + * Copies one shared file (Windows, where a file link needs elevation) and + * updates the record. A copy the record doesn't recognize is the agent's or + * the user's own and is left alone for good. + */ +async function shareByCopy(entry: EntryContext): Promise { + const { path, record, rel } = entry; + const ours = record.copies[rel] ?? []; + const stat = await fs.lstat(path).catch(() => undefined); + const current = stat ? await readCopy(path) : undefined; + const currentHash = current === undefined ? undefined : sha256(current); + if (stat && (currentHash === undefined || !ours.includes(currentHash))) { + delete record.copies[rel]; + return; + } + const isOurs = async (aside: string) => { + const content = await readCopy(aside); + return content !== undefined && ours.includes(sha256(content)); + }; + const source = entry.allowed + ? await readRegularFile(entry.source, { maxBytes: MAX_COPY_BYTES, followLink: true }) + : undefined; + if (source === undefined) { + if (stat) await removeIfOurs(path, isOurs); + delete record.copies[rel]; + return; + } + const hash = sha256(source); + if (currentHash === hash) { + record.copies[rel] = [hash]; + return; + } + if (!(await entry.makeParent())) return; + record.copies[rel] = currentHash === undefined ? [hash] : [currentHash, hash]; + await entry.claim(); + const temp = asidePath(path); + await fs.writeFile(temp, source, { mode: 0o600, flag: "wx" }); + try { + if (stat && !(await removeIfOurs(path, isOurs))) { + delete record.copies[rel]; + return; + } + try { + // Fails on an existing entry, so a file the agent just made stays. + await fs.link(temp, path); + } catch (error) { + if (codeOf(error) !== "EEXIST") throw error; + delete record.copies[rel]; + return; + } + record.copies[rel] = [hash]; + } finally { + await fs.rm(temp, { force: true }); + } +} + +export interface ShareAntigravityUserConfigInput { + readonly profileDir: string; + readonly userHome: string; + readonly platform: NodeJS.Platform; + /** Threadlines' own data folder, which a shared source may never lead into. */ + readonly threadlinesDir?: string; +} + +/** Brings the user's shared rules and skills into the profile; returns what failed. */ +async function shareOnce( + input: ShareAntigravityUserConfigInput, +): Promise> { + await fs.mkdir(input.profileDir, { recursive: true, mode: 0o700 }); + const realProfile = await fs.realpath(input.profileDir); + const userGemini = antigravityUserGeminiDir(input.userHome); + const threadlinesDir = input.threadlinesDir ? await realpathOf(input.threadlinesDir) : undefined; + const rules: SourceRules = { + realGemini: await realpathOf(userGemini), + forbidden: [realProfile, ...(threadlinesDir ? [threadlinesDir] : [])], + }; + const before = await readRecord(input.profileDir); + const record: SharedConfigRecord = { + links: { ...before.links }, + copies: { ...before.copies }, + }; + let saved = JSON.stringify(record); + const save = async () => { + const next = JSON.stringify(record); + if (next === saved) return; + await writeRecord(input.profileDir, record); + saved = next; + }; + const problems: Array<{ path: string; error: string }> = []; + const entries = [ + ...ANTIGRAVITY_SHARED_DIRS.map((rel) => ({ rel, kind: "dir" as const })), + ...ANTIGRAVITY_SHARED_FILES.map((rel) => ({ rel, kind: "file" as const })), + ]; + for (const { rel, kind } of entries) { + const path = join(input.profileDir, ...rel.split("/")); + try { + const parent = { profileDir: input.profileDir, realProfile, rel }; + if (!(await realParentInProfile({ ...parent, create: false }))) { + problems.push({ path, error: "A folder on the way is a link; left alone." }); + continue; + } + const source = join(userGemini, ...rel.split("/")); + const entry: EntryContext = { + rel, + path, + source, + kind, + allowed: await sourceAllowed(source, kind, rules), + platform: input.platform, + record, + claim: save, + makeParent: () => realParentInProfile({ ...parent, create: true }), + }; + if (kind === "file" && input.platform === "win32") await shareByCopy(entry); + else await shareByLink(entry); + } catch (error) { + problems.push({ path, error: String(error) }); + } + } + await save().catch((error: unknown) => + problems.push({ + path: antigravitySharedConfigRecordPath(input.profileDir), + error: String(error), + }), + ); + return problems; +} + +/** The run in progress for each profile: two starts never share at once. */ +const running = new Map>(); + +/** `shareOnce`, one at a time per profile; a run stuck past the time bound no longer holds the next. */ +export function shareAntigravityUserConfigNow( + input: ShareAntigravityUserConfigInput, +): Promise> { + const key = resolve(input.profileDir); + const previous = running.get(key) ?? Promise.resolve(); + const waited = Promise.race([ + previous.catch(() => undefined), + new Promise((done) => setTimeout(done, Duration.toMillis(SHARE_TIME_LIMIT)).unref()), + ]); + const run = waited.then(() => shareOnce(input)); + const settled = run.catch(() => undefined); + running.set(key, settled); + void settled.then(() => { + if (running.get(key) === settled) running.delete(key); + }); + return run; +} + +/** + * `shareAntigravityUserConfigNow` as an effect that never fails and never + * waits past its time bound: a rule or skill that can't be brought in is + * logged, and the agent starts without it. + */ +export const shareAntigravityUserConfig = (input: ShareAntigravityUserConfigInput) => + Effect.promise(() => + shareAntigravityUserConfigNow(input).catch((error: unknown) => [ + { path: input.profileDir, error: String(error) }, + ]), + ).pipe( + Effect.timeoutOption(SHARE_TIME_LIMIT), + Effect.flatMap((result) => + Option.isNone(result) + ? Effect.logWarning("Sharing the user's Antigravity rules and skills took too long.", { + profileDir: input.profileDir, + }) + : result.value.length === 0 + ? Effect.void + : Effect.logWarning("Some of the user's Antigravity rules or skills are not shared.", { + problems: result.value, + }), + ), + ); diff --git a/apps/server/src/provider/managedRuntime/HttpsFetch.test.ts b/apps/server/src/provider/managedRuntime/HttpsFetch.test.ts index 7f6cfb9e0..a5682dd8d 100644 --- a/apps/server/src/provider/managedRuntime/HttpsFetch.test.ts +++ b/apps/server/src/provider/managedRuntime/HttpsFetch.test.ts @@ -297,4 +297,28 @@ describe("makeHttpsFetch", () => { ); expect(seen).toEqual(["/file", "/elsewhere"]); }); + + it("sends a POST's body and headers, and never follows its redirect", async () => { + const seen: Array = []; + const origin = await serve((request, response) => { + let body = ""; + request.on("data", (chunk: Buffer) => (body += chunk.toString())); + request.on("end", () => { + seen.push( + `${request.method} ${request.url} ${request.headers.authorization} ${request.headers["content-length"]} ${body}`, + ); + if (request.url === "/moved") { + response.writeHead(307, { location: "/answer" }).end(); + } else { + response.writeHead(200).end('{"ok":true}'); + } + }); + }); + const fetch = makeHttpsFetch({ allowHttp: true, proxyEnv: {} }); + const init = { method: "POST", headers: { authorization: "Bearer t" }, body: "{}" }; + + expect(await (await fetch(`${origin}/answer`, init)).json()).toEqual({ ok: true }); + await expect(fetch(`${origin}/moved`, init)).rejects.toThrow(/redirect of a request/u); + expect(seen).toEqual(["POST /answer Bearer t 2 {}", "POST /moved Bearer t 2 {}"]); + }); }); diff --git a/apps/server/src/provider/managedRuntime/HttpsFetch.ts b/apps/server/src/provider/managedRuntime/HttpsFetch.ts index f90cffae9..38cf8e7e2 100644 --- a/apps/server/src/provider/managedRuntime/HttpsFetch.ts +++ b/apps/server/src/provider/managedRuntime/HttpsFetch.ts @@ -1,6 +1,7 @@ -// @effect-diagnostics nodeBuiltinImport:off - one GET over node:https +// @effect-diagnostics nodeBuiltinImport:off - one request over node:https /** - * HttpsFetch — the `fetch` behind downloads of programs Threadlines installs. + * HttpsFetch — the `fetch` behind downloads of programs Threadlines installs, + * and behind requests that carry a sign-in to a fixed set of hosts. * * It differs from the global `fetch` where a download needs it to: * - it goes through the proxy the environment names (`HTTPS_PROXY`, @@ -8,7 +9,7 @@ * does when the whole server was started for it. Extra certificate * authorities (`NODE_EXTRA_CA_CERTS`) apply to both; * - it follows redirects itself, so every hop is https and there are at - * most five; + * most five; a request with a body (a POST) never follows one; * - it can be held to the public internet (`publicAddressesOnly`) and to * named hosts (`allowedHosts`), on every hop, for addresses that come * from a list Threadlines doesn't write. @@ -154,7 +155,10 @@ function toResponse(message: http.IncomingMessage): Response { return new Response(Readable.toWeb(message) as ReadableStream, { status, headers }); } -/** Builds a `fetch` for GETs. Rejects for anything but https, and for a URL that carries credentials. */ +/** + * Builds a `fetch` for GETs and text-body requests. Rejects for anything but + * https, and for a URL that carries credentials. + */ export function makeHttpsFetch(options: HttpsFetchOptions = {}): DownloadFetch { const proxyEnv = options.proxyEnv ?? process.env; const httpsAgent = new https.Agent({ proxyEnv }); @@ -165,17 +169,22 @@ export function makeHttpsFetch(options: HttpsFetchOptions = {}): DownloadFetch { const lookup = options.publicAddressesOnly ? publicAddressLookup() : undefined; const maxRedirects = options.maxRedirects ?? MAX_REDIRECTS; - const get = (url: URL, init: RequestInit) => + const send = (url: URL, init: RequestInit, body: string | undefined) => new Promise((resolve, reject) => { + const headers = new Headers(init.headers); + if (body !== undefined && !headers.has("content-length")) { + headers.set("content-length", String(Buffer.byteLength(body))); + } const requestOptions = { - headers: Object.fromEntries(new Headers(init.headers)), + method: init.method ?? "GET", + headers: Object.fromEntries(headers), ...(init.signal ? { signal: init.signal } : {}), ...(lookup ? { lookup } : {}), }; const request = url.protocol === "https:" - ? https.get(url, { ...requestOptions, agent: httpsAgent }, resolve) - : http.get(url, { ...requestOptions, agent: httpAgent }, resolve); + ? https.request(url, { ...requestOptions, agent: httpsAgent }, resolve) + : http.request(url, { ...requestOptions, agent: httpAgent }, resolve); request.on("error", reject); // Neither of these is a response, and without them the promise would // never settle: a server that switches protocols, and a connection @@ -187,9 +196,14 @@ export function makeHttpsFetch(options: HttpsFetchOptions = {}): DownloadFetch { request.on("close", () => { reject(new Error(`The connection to ${url.host} closed before it answered.`)); }); + request.end(body); }); return async (rawUrl, init) => { + if (init.body !== undefined && init.body !== null && typeof init.body !== "string") { + throw new Error("Only a text body can be sent."); + } + const body = init.body ?? undefined; let url = new URL(rawUrl); for (let redirects = 0; ; redirects += 1) { if (url.protocol !== "https:" && !(options.allowHttp && url.protocol === "http:")) { @@ -208,12 +222,15 @@ export function makeHttpsFetch(options: HttpsFetchOptions = {}): DownloadFetch { `Refusing to download from ${url.host}: the address is an IP address, not a name.`, ); } - const message = await get(url, init); + const message = await send(url, init, body); const location = message.headers.location; if (!REDIRECT_STATUSES.has(message.statusCode ?? 0) || location === undefined) { return toResponse(message); } message.resume(); + if (body !== undefined) { + throw new Error(`Refusing to follow ${url.host}'s redirect of a request with a body.`); + } if (redirects >= maxRedirects) { throw new Error( maxRedirects === 0 diff --git a/apps/server/src/provider/managedRuntime/VerifiedDownload.ts b/apps/server/src/provider/managedRuntime/VerifiedDownload.ts index 6cf7f877a..da6376097 100644 --- a/apps/server/src/provider/managedRuntime/VerifiedDownload.ts +++ b/apps/server/src/provider/managedRuntime/VerifiedDownload.ts @@ -1,7 +1,9 @@ // @effect-diagnostics nodeBuiltinImport:off - streams the download to disk /** - * VerifiedDownload — fetches a pinned release archive to disk: the exact - * size and sha256 are known up front, and anything else is refused. + * VerifiedDownload — fetches a release archive to disk, refusing anything + * that isn't it: the hash (sha256 or sha512) is known up front, and so is + * the exact size, or for a source that lists none (Antigravity's update + * feed) a cap the download may not pass. * * @module provider/managedRuntime/VerifiedDownload */ @@ -14,27 +16,40 @@ import { ManagedRuntimeError, managedRuntimeError } from "./ManagedRuntimeStore. /** The part of `fetch` a download uses; tests pass a stub. */ export type DownloadFetch = (url: string, init: RequestInit) => Promise; -export interface VerifiedDownloadInput { - readonly fetch: DownloadFetch; - /** The program's name as users know it, for messages. */ - readonly label: string; - readonly url: string; - /** Lowercase or uppercase hex. */ - readonly sha256: string; - readonly bytes: number; - /** Must not exist yet. */ - readonly destination: string; - readonly signal: AbortSignal; - readonly onReceived: (receivedBytes: number) => void; -} +/** The download's hash, in lowercase or uppercase hex. */ +export type VerifiedDownloadDigest = + | { readonly sha256: string; readonly sha512?: never } + | { readonly sha512: string; readonly sha256?: never }; + +/** The exact size, or only a cap when the source lists none. */ +export type VerifiedDownloadSize = + | { readonly bytes: number; readonly maxBytes?: never } + | { readonly maxBytes: number; readonly bytes?: never }; + +export type VerifiedDownloadInput = VerifiedDownloadDigest & + VerifiedDownloadSize & { + readonly fetch: DownloadFetch; + /** The program's name as users know it, for messages. */ + readonly label: string; + readonly url: string; + /** Must not exist yet. */ + readonly destination: string; + readonly signal: AbortSignal; + readonly onReceived: (receivedBytes: number) => void; + }; /** * Streams `url` to `destination`, hashing as it goes and stopping as soon as - * it runs past the expected size. Throws a `ManagedRuntimeError`: `download` - * when the transfer fails, `checksum` when what arrived isn't the release. + * it runs past the expected size or the cap. Resolves to the number of bytes + * written. Throws a `ManagedRuntimeError`: `download` when the transfer + * fails, `checksum` when what arrived isn't the release. */ -export async function downloadVerified(input: VerifiedDownloadInput): Promise { +export async function downloadVerified(input: VerifiedDownloadInput): Promise { const { label } = input; + const algorithm = input.sha512 !== undefined ? "sha512" : "sha256"; + const expectedDigest = (input.sha512 ?? input.sha256).toLowerCase(); + const exactBytes = input.bytes; + const limit = input.bytes ?? input.maxBytes; const unreachable = `Couldn't download ${label}. Check your internet connection and try again.`; const mismatch = (detail: string) => managedRuntimeError( @@ -63,16 +78,23 @@ export async function downloadVerified(input: VerifiedDownloadInput): Promise limit) ) { await response.body.cancel().catch(() => undefined); - throw mismatch(`server declared ${declaredLength} bytes, expected ${input.bytes}`); + throw mismatch( + exactBytes !== undefined + ? `server declared ${declaredLength} bytes, expected ${exactBytes}` + : `server declared ${declaredLength} bytes, more than the ${limit} allowed`, + ); } - const hash = createHash("sha256"); + const hash = createHash(algorithm); let received = 0; await pipeline( response.body, @@ -80,8 +102,8 @@ export async function downloadVerified(input: VerifiedDownloadInput): Promise input.bytes) { - throw mismatch(`received more than ${input.bytes} bytes`); + if (received > limit) { + throw mismatch(`received more than ${limit} bytes`); } hash.update(chunk); input.onReceived(received); @@ -96,7 +118,8 @@ export async function downloadVerified(input: VerifiedDownloadInput): Promise { + it.effect("never writes running sessions' command lists to disk", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-provider-cache-live-" }); + const filePath = yield* resolveProviderStatusCachePath({ + cacheDir: tempDir, + instanceId: defaultInstanceIdForDriver(CODEX_DRIVER), + }); + yield* writeProviderStatusCache({ + filePath, + provider: makeProvider(CODEX_DRIVER, { + sessionCommands: [{ sessions: ["thread-1"], commands: [{ name: "goal" }] }], + }), + }); + assert.notInclude(yield* fs.readFileString(filePath), "sessionCommands"); + }), + ); + it.effect( "replaces the cache after a temporary Windows file lock without removing the old file", () => diff --git a/apps/server/src/provider/providerStatusCache.ts b/apps/server/src/provider/providerStatusCache.ts index ec8daac66..820dd4ac6 100644 --- a/apps/server/src/provider/providerStatusCache.ts +++ b/apps/server/src/provider/providerStatusCache.ts @@ -158,7 +158,12 @@ export const writeProviderStatusCache = (input: { readonly filePath: string; readonly provider: ServerProvider; }) => { - const { updateState: _updateState, ...cacheableProvider } = input.provider; + // Live session state never goes to disk: the sessions are gone after a restart. + const { + updateState: _updateState, + sessionCommands: _sessionCommands, + ...cacheableProvider + } = input.provider; return writeFileStringAtomically({ filePath: input.filePath, contents: `${JSON.stringify(cacheableProvider, null, 2)}\n`, diff --git a/apps/server/src/usage/usageAggregation.ts b/apps/server/src/usage/usageAggregation.ts index b476bc506..82fb1d1ea 100644 --- a/apps/server/src/usage/usageAggregation.ts +++ b/apps/server/src/usage/usageAggregation.ts @@ -177,7 +177,12 @@ export class UsageAggregator { bucket.totals = addTotals(bucket.totals, record.totals); bucket.costUsd += priced.costUsd; - bucket.cacheSavingsUsd += cacheSavingsUsd(this.#options.rates, record.model, record.totals); + bucket.cacheSavingsUsd += cacheSavingsUsd( + this.#options.rates, + record.model, + record.totals, + record.timestampMs, + ); bucket.records += 1; if (priced.costSource === "unpriced") bucket.unpricedRecords += 1; if (priced.costSource === "providerReported") bucket.providerReportedRecords += 1; diff --git a/apps/server/src/usage/usageLedger.ts b/apps/server/src/usage/usageLedger.ts index 2910ef28e..94b7541a5 100644 --- a/apps/server/src/usage/usageLedger.ts +++ b/apps/server/src/usage/usageLedger.ts @@ -5,7 +5,8 @@ * * Agents on the generic ACP driver report a turn's tokens in the * `session/prompt` result and a running session cost in `usage_update`, and - * some keep no record of either (fx stopped in 0.0.14). The ACP core appends + * some keep no record of either (fx stopped in 0.0.14; Antigravity keeps its + * in a private format). The ACP core appends * one line per turn to `/usage-ledger//.jsonl`, and * the usage scan reads those folders like any provider's transcripts. Only * chats run in Threadlines are in it. @@ -21,7 +22,10 @@ import * as FileSystem from "effect/FileSystem"; import { totalTokens, type UsageRecord } from "./usageTranscripts.ts"; /** The providers whose usage comes from the ledger rather than their own files. */ -export const USAGE_LEDGER_PROVIDERS = ["fx"] as const satisfies readonly UsageProviderKind[]; +export const USAGE_LEDGER_PROVIDERS = [ + "fx", + "antigravity", +] as const satisfies readonly UsageProviderKind[]; export type UsageLedgerProvider = (typeof USAGE_LEDGER_PROVIDERS)[number]; export const isUsageLedgerProvider = ( diff --git a/apps/server/src/usage/usagePricing.test.ts b/apps/server/src/usage/usagePricing.test.ts index 76c16f41f..93ffe77ca 100644 --- a/apps/server/src/usage/usagePricing.test.ts +++ b/apps/server/src/usage/usagePricing.test.ts @@ -104,4 +104,40 @@ describe("priceUsage", () => { }); expect(lookupRate(table, "claude-fable-5-2")?.inputCostPerToken).toBe(1e-6); }); + + it("prices Gemini 4 at the rate of the day it ran, whatever level the agent names", () => { + const million = { + uncachedInputTokens: 1_000_000, + cachedInputTokens: 1_000_000, + cacheCreationTokens: 0, + outputTokens: 1_000_000, + reasoningTokens: 0, + }; + const price = (model: string, timestampMs: number) => + priceUsage(new Map(), { + model, + totals: million, + cacheCreation1hTokens: 0, + reportedCostUsd: null, + timestampMs, + }).costUsd; + // Argon doubles on December 1, 2026; Antigravity names its effort in the id. + expect(price("gemini-4-argon-high", Date.UTC(2026, 10, 30, 12))).toBeCloseTo(2 + 0.1 + 10, 9); + expect(price("gemini-4-argon", Date.UTC(2026, 11, 1, 12))).toBeCloseTo(4 + 0.2 + 20, 9); + expect(price("gemini-4-neon", Date.UTC(2026, 11, 1, 12))).toBeCloseTo(3 + 0.15 + 15, 9); + // A fetched table holds only today's rate: earlier days keep theirs. + const table = parseRateTable({ + "gemini-4-argon": { + input_cost_per_token: 4e-6, + output_cost_per_token: 2e-5, + cache_read_input_token_cost: 2e-7, + }, + }); + expect(lookupRate(table, "gemini-4-argon", Date.UTC(2026, 10, 30))?.inputCostPerToken).toBe( + 2e-6, + ); + expect(lookupRate(table, "gemini-4-argon", Date.UTC(2026, 11, 2))?.inputCostPerToken).toBe( + 4e-6, + ); + }); }); diff --git a/apps/server/src/usage/usagePricing.ts b/apps/server/src/usage/usagePricing.ts index b38910266..3f18ae4d0 100644 --- a/apps/server/src/usage/usagePricing.ts +++ b/apps/server/src/usage/usagePricing.ts @@ -124,6 +124,53 @@ const BUILT_IN_RATES: RateTable = new Map([ ], ]); +/** A Gemini rate: no cache-write charge (Gemini 4 caches implicitly). */ +const geminiRate = (input: number, output: number, cacheRead: number): ModelRate => ({ + inputCostPerToken: perMillion(input), + outputCostPerToken: perMillion(output), + cacheReadCostPerToken: perMillion(cacheRead), + cacheCreationCostPerToken: perMillion(input), + cacheCreation1hCostPerToken: perMillion(input), +}); + +/** Google's Gemini 4 rise of December 1, 2026, taken as midnight UTC. */ +const GEMINI_4_RISE_MS = Date.UTC(2026, 11, 1); + +/** + * Rates that change on a known day, newest last: each applies from its + * `fromMs` on. Gemini 4's Standard tier, from Google's price list + * (aistudio.google.com/docs/pricing, read 2026-11-23; no tier above 200k + * tokens was listed). Antigravity's Google plans don't bill per token, so + * these are the API equivalent, like every figure here. + */ +const BUILT_IN_DATED_RATES: ReadonlyMap< + string, + ReadonlyArray<{ readonly fromMs: number; readonly rate: ModelRate }> +> = new Map([ + [ + "gemini-4-carbon", + [ + { fromMs: 0, rate: geminiRate(2, 10, 0.1) }, + { fromMs: GEMINI_4_RISE_MS, rate: geminiRate(4, 20, 0.2) }, + ], + ], + [ + "gemini-4-argon", + [ + { fromMs: 0, rate: geminiRate(2, 10, 0.1) }, + { fromMs: GEMINI_4_RISE_MS, rate: geminiRate(4, 20, 0.2) }, + ], + ], + ["gemini-4-neon", [{ fromMs: 0, rate: geminiRate(3, 15, 0.15) }]], + ["gemini-4-hydrogen", [{ fromMs: 0, rate: geminiRate(1.5, 7.5, 0.075) }]], +]); + +/** + * The Gemini 4 family a model id names, for an agent that adds a reasoning + * level or a role to it (Antigravity's `gemini-4-argon-high`). + */ +const GEMINI_4_FAMILY = /^(gemini-4-(?:carbon|argon|neon|hydrogen))-[a-z0-9-]+$/u; + /** * Canonicalises a model name for lookup. * @@ -153,10 +200,41 @@ const UNPRICEABLE_MODELS = new Set([ "fable", ]); -export function lookupRate(table: RateTable, model: string): ModelRate | null { +/** + * The rate for `model` at `atMs` (the newest when absent): the fetched table's, + * then the built-in ones. A model id with a suffix the family doesn't + * publish is priced as its family. + */ +export function lookupRate(table: RateTable, model: string, atMs?: number): ModelRate | null { const normalized = normalizeModelName(model); if (normalized.length === 0 || UNPRICEABLE_MODELS.has(normalized)) return null; - return table.get(normalized) ?? BUILT_IN_RATES.get(normalized) ?? null; + const family = GEMINI_4_FAMILY.exec(normalized)?.[1]; + const names = family === undefined ? [normalized] : [normalized, family]; + // Before a known price change, the price history decides: the fetched + // table holds only the current rate. + for (const name of names) { + const earlier = earlierDatedRate(name, atMs); + if (earlier !== undefined) return earlier; + } + for (const name of names) { + const rate = table.get(name) ?? BUILT_IN_RATES.get(name) ?? datedRate(name, atMs); + if (rate !== undefined) return rate; + } + return null; +} + +/** The dated rate for a time before the model's last known change, else nothing. */ +function earlierDatedRate(name: string, atMs: number | undefined): ModelRate | undefined { + const lastChange = BUILT_IN_DATED_RATES.get(name)?.at(-1)?.fromMs; + if (atMs === undefined || lastChange === undefined || atMs >= lastChange) return undefined; + return datedRate(name, atMs); +} + +function datedRate(name: string, atMs: number | undefined): ModelRate | undefined { + const rates = BUILT_IN_DATED_RATES.get(name); + if (rates === undefined) return undefined; + if (atMs === undefined) return rates.at(-1)?.rate; + return rates.findLast((entry) => entry.fromMs <= atMs)?.rate ?? rates[0]?.rate; } export interface PricedUsage { @@ -171,6 +249,8 @@ export interface PriceableUsage { /** Portion of `totals.cacheCreationTokens` written with the 1-hour TTL. */ readonly cacheCreation1hTokens: number; readonly reportedCostUsd: number | null; + /** When it was used, for a rate that changed on a known day. */ + readonly timestampMs?: number; } /** @@ -184,7 +264,7 @@ export function priceUsage(table: RateTable, usage: PriceableUsage): PricedUsage return { costUsd: usage.reportedCostUsd, costSource: "providerReported" }; } - const rate = lookupRate(table, usage.model); + const rate = lookupRate(table, usage.model, usage.timestampMs); if (rate === null) return { costUsd: 0, costSource: "unpriced" }; const { totals } = usage; @@ -204,8 +284,13 @@ export function priceUsage(table: RateTable, usage: PriceableUsage): PricedUsage * What the cached input would have cost at full input rates, minus what it * actually cost. Drives the "cache savings" figure. */ -export function cacheSavingsUsd(table: RateTable, model: string, totals: UsageTokenTotals): number { - const rate = lookupRate(table, model); +export function cacheSavingsUsd( + table: RateTable, + model: string, + totals: UsageTokenTotals, + atMs?: number, +): number { + const rate = lookupRate(table, model, atMs); if (rate === null) return 0; return totals.cachedInputTokens * (rate.inputCostPerToken - rate.cacheReadCostPerToken); } diff --git a/apps/server/src/usage/usageTranscripts.ts b/apps/server/src/usage/usageTranscripts.ts index 548b9319a..04b61c8e6 100644 --- a/apps/server/src/usage/usageTranscripts.ts +++ b/apps/server/src/usage/usageTranscripts.ts @@ -90,6 +90,7 @@ export function mightCarryUsage(line: string, provider: UsageProviderKind): bool // A database, read by `usageOpenCode`, never a transcript. return false; case "fx": + case "antigravity": // Threadlines' own ledger: every line is a turn. return true; } diff --git a/apps/web/src/components/chat/AgentsPanel.tsx b/apps/web/src/components/chat/AgentsPanel.tsx index 993cf9b6b..76a222fb7 100644 --- a/apps/web/src/components/chat/AgentsPanel.tsx +++ b/apps/web/src/components/chat/AgentsPanel.tsx @@ -174,6 +174,9 @@ function trunkColor(providerLabel: string | null | undefined): string { if (provider !== undefined && /(^|\W)fx(\W|$)/u.test(provider)) { return "var(--provider-fx)"; } + if (provider?.includes("antigravity")) { + return "var(--provider-antigravity)"; + } return "var(--border)"; } diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index 08423f4bb..d891c6727 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -208,6 +208,11 @@ import { useRoomRecipientStore, } from "../../rooms"; import { getPickerModelName } from "./providerIconUtils"; +import { + composerProviderSlashList, + composerSlashAgent, + sessionSlashCommands, +} from "./composerAgentCommands"; import { awaitingInvite } from "@threadlines/shared/roomAgentRequests"; import { shownSettingsChange } from "@threadlines/shared/settingsChangeState"; import { activeParticipants, hasAgentRecords } from "@threadlines/shared/threadParticipants"; @@ -264,6 +269,17 @@ const CODEX_AGENT_PROVIDER = ProviderDriverKind.make("codex"); const CLAUDE_AGENT_PROVIDER = ProviderDriverKind.make("claudeAgent"); const EMPTY_PROJECT_ENTRIES: ProjectEntry[] = []; const EMPTY_PROVIDER_SKILLS: ServerProvider["skills"] = []; +/** The `/` commands Threadlines answers itself; an agent's own of the same name stays out of the list. */ +const THREADLINES_SLASH_COMMANDS: ReadonlySet = new Set([ + "model", + "plan", + "theme", + "default", +]); +const THREADLINES_SLASH_COMMANDS_WITH_GOAL: ReadonlySet = new Set([ + ...THREADLINES_SLASH_COMMANDS, + "goal", +]); /** A thread with no agents besides its own, while there is no thread yet. */ const NO_ROOM_THREAD = {}; const COMPOSER_FLOATING_LAYER_SELECTOR = [ @@ -275,17 +291,20 @@ const COMPOSER_FLOATING_LAYER_SELECTOR = [ ].join(","); /** Menu rows for provider skills, shared by the `$` trigger and the `/` menu's - * Skills section. Both insert the same `$skill-name` token on select. */ + * Skills section. Both insert the same `$skill-name` token on select, except + * for an agent that runs skills as `/skill-name` (`invocation: "slash"`). */ function buildComposerSkillItems( skills: ServerProvider["skills"], provider: ProviderDriverKind, + invocation?: "slash", ): Array> { return skills.map((skill) => ({ id: `skill:${provider}:${skill.name}`, type: "skill" as const, provider, skill, - label: formatProviderSkillDisplayName(skill), + ...(invocation ? { invocation } : {}), + label: invocation === "slash" ? `/${skill.name}` : formatProviderSkillDisplayName(skill), description: skill.shortDescription ?? skill.description ?? @@ -1314,14 +1333,55 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) // Commands this thread will act on: the built-ins plus whatever the selected // provider reports. The editor tints the leading token so typed-past-the-menu // commands still read as commands. + // The provider's part of the `/` list describes the agent the next message + // goes to: in a room, an added agent's own provider, its skills and, for an + // agent that lists its own commands per session (Antigravity), the list its + // running session put on that provider's status. + const slashRecipientId = addressingRoomAgent ? roomRecipientId : null; + const slashRecipientInstanceId = + slashRecipientId === null + ? undefined + : (activeThread?.participants ?? []).find((entry) => entry.id === slashRecipientId) + ?.modelSelection.instanceId; + const slashAgent = composerSlashAgent({ + threadId: activeThread?.id ?? null, + recipient: + slashRecipientId !== null && slashRecipientInstanceId !== undefined + ? { id: slashRecipientId, instanceId: slashRecipientInstanceId } + : null, + entries: providerInstanceEntries, + selected: { + status: selectedProviderStatus, + driverKind: selectedProvider, + label: selectedProviderDisplayName, + }, + }); + const slashProviderStatus = slashAgent.status; + const slashProvider = slashAgent.driverKind; + const slashProviderLabel = slashAgent.label; + const sessionCommands = sessionSlashCommands(slashProviderStatus, slashAgent.sessionKey); + const providerSlashList = useMemo( + () => + composerProviderSlashList({ + provider: slashProviderStatus, + sessionCommands, + threadlinesCommands: goalSupported + ? THREADLINES_SLASH_COMMANDS_WITH_GOAL + : THREADLINES_SLASH_COMMANDS, + }), + [goalSupported, sessionCommands, slashProviderStatus], + ); + // Codex's `$` skills belong to the thread's own Codex, not an added agent. + const slashListCodexSkills = slashAgent.addedAgent ? EMPTY_PROVIDER_SKILLS : composerSkills; const recognizedSlashCommands = useMemo( () => [ "plan", "default", ...(goalSupported ? ["goal"] : []), - ...(selectedProviderStatus?.slashCommands ?? []).map((command) => command.name), + ...providerSlashList.commands.map((command) => command.name), + ...providerSlashList.slashSkills.map((skill) => skill.name), ], - [goalSupported, selectedProviderStatus], + [goalSupported, providerSlashList], ); useEffect(() => { @@ -1469,13 +1529,13 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) description: "Switch this thread back to normal build mode", }, ] satisfies ReadonlyArray>; - const providerSlashCommandItems = (selectedProviderStatus?.slashCommands ?? []) + const providerSlashCommandItems = providerSlashList.commands // Claude lists its own /goal; the goal bar's stands in for it. .filter((command) => !(goalSupported && command.name === "goal")) .map((command) => ({ - id: `provider-slash-command:${selectedProvider}:${command.name}`, + id: `provider-slash-command:${slashProvider}:${command.name}`, type: "provider-slash-command" as const, - provider: selectedProvider, + provider: slashProvider, command, label: `/${command.name}`, description: command.description ?? command.input?.hint ?? "Run provider command", @@ -1488,10 +1548,17 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) // Skills are ranked in their own list and appended after the commands — // the two kinds score on different scales, so a shared ranker would // interleave them arbitrarily. - const skillItems = buildComposerSkillItems( - searchProviderSkills(composerSkills, query), - selectedProvider, - ); + const skillItems = [ + ...buildComposerSkillItems( + searchProviderSkills(slashListCodexSkills, query), + selectedProvider, + ), + ...buildComposerSkillItems( + searchProviderSkills(providerSlashList.slashSkills, query), + slashProvider, + "slash", + ), + ]; // The menu shows labeled sections even while filtering, so keyboard // order must match section order: built-ins, provider commands, plugin // skills, skills. Ranking is preserved within each section. @@ -1519,8 +1586,10 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) composerSkills, composerTrigger, goalSupported, + providerSlashList, selectedProvider, - selectedProviderStatus, + slashListCodexSkills, + slashProvider, threadGoal, workspaceEntries, ]); @@ -3038,7 +3107,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) return; } if (item.type === "skill") { - const replacement = `$${item.skill.name} `; + const replacement = + item.invocation === "slash" ? `/${item.skill.name} ` : `$${item.skill.name} `; const replacementRangeEnd = extendReplacementRangeForTrailingSpace( snapshot.value, trigger.rangeEnd, @@ -4098,7 +4168,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) resolvedTheme={resolvedTheme} isLoading={isComposerMenuLoading} triggerKind={composerTriggerKind} - providerGroupLabel={selectedProviderDisplayName} + providerGroupLabel={slashProviderLabel} emptyStateText={composerMenuEmptyState} activeItemId={activeComposerMenuItem?.id ?? null} onHighlightedItemChange={onComposerMenuItemHighlighted} diff --git a/apps/web/src/components/chat/ComposerCommandMenu.tsx b/apps/web/src/components/chat/ComposerCommandMenu.tsx index a8cc2e6ba..0a9e23601 100644 --- a/apps/web/src/components/chat/ComposerCommandMenu.tsx +++ b/apps/web/src/components/chat/ComposerCommandMenu.tsx @@ -53,6 +53,8 @@ export type ComposerCommandItem = type: "skill"; provider: ProviderDriverKind; skill: ServerProviderSkill; + /** Inserted as `/name` (Antigravity) rather than the `$name` token. */ + invocation?: "slash"; label: string; description: string; } diff --git a/apps/web/src/components/chat/composerAgentCommands.test.ts b/apps/web/src/components/chat/composerAgentCommands.test.ts new file mode 100644 index 000000000..85dd033cc --- /dev/null +++ b/apps/web/src/components/chat/composerAgentCommands.test.ts @@ -0,0 +1,138 @@ +import { + ProviderDriverKind, + ProviderInstanceId, + ThreadId, + ThreadParticipantId, + type ServerProvider, + type ServerProviderSkill, +} from "@threadlines/contracts"; +import { participantSessionKey } from "@threadlines/shared/threadParticipants"; +import { describe, expect, it } from "vite-plus/test"; + +import type { ProviderInstanceEntry } from "../../providerInstances"; +import { + composerProviderSlashList, + composerSlashAgent, + sessionSlashCommands, +} from "./composerAgentCommands"; + +const skill = (name: string, enabled = true): ServerProviderSkill => ({ + name, + path: `/skills/${name}/SKILL.md`, + enabled, +}); +const THREADLINES = new Set(["model", "plan", "theme", "default"]); + +describe("composerProviderSlashList", () => { + it("keeps a provider's own status commands when it doesn't run skills on /", () => { + const provider = { + slashCommands: [{ name: "compact" }, { name: "model" }], + skills: [skill("review")], + }; + expect( + composerProviderSlashList({ + provider, + sessionCommands: [{ name: "other" }], + threadlinesCommands: THREADLINES, + }), + ).toEqual({ commands: provider.slashCommands, slashSkills: [] }); + }); + + it("lists the status's skills, then the session's commands with the session's entry first", () => { + const provider = { + slashCommands: [], + skills: [ + skill("review"), + skill("compact"), + skill("off", false), + skill("two words"), + skill("a/b"), + ], + slashSkills: true, + }; + // Before a session has listed its own: the skills alone, only typeable ones. + expect( + composerProviderSlashList({ + provider, + sessionCommands: undefined, + threadlinesCommands: THREADLINES, + }), + ).toEqual({ commands: [], slashSkills: [skill("review"), skill("compact")] }); + + expect( + composerProviderSlashList({ + provider, + sessionCommands: [ + { name: "goal", input: { hint: "objective" } }, + { name: "compact", description: "Summarize the conversation" }, + { name: "model" }, + ], + threadlinesCommands: THREADLINES, + }), + ).toEqual({ + commands: [ + { name: "goal", input: { hint: "objective" } }, + { name: "compact", description: "Summarize the conversation" }, + ], + slashSkills: [skill("review")], + }); + }); + + it("finds the list of the session the next message goes to, a room agent's included", () => { + const thread = ThreadId.make("thread-1"); + const agent = ThreadParticipantId.make("7a0b1c2d-3e4f-4a5b-8c6d-7e8f9a0b1c2d"); + const provider = { + sessionCommands: [ + { sessions: [thread], commands: [{ name: "goal" }] }, + { sessions: [participantSessionKey(thread, agent)], commands: [{ name: "compact" }] }, + ], + }; + expect(sessionSlashCommands(provider, participantSessionKey(thread, null))).toEqual([ + { name: "goal" }, + ]); + expect(sessionSlashCommands(provider, participantSessionKey(thread, agent))).toEqual([ + { name: "compact" }, + ]); + expect(sessionSlashCommands(provider, "thread-2")).toBeUndefined(); + }); + + it("describes the agent the next message goes to: a room agent's own provider and session", () => { + const thread = ThreadId.make("thread-1"); + const agent = ThreadParticipantId.make("7a0b1c2d-3e4f-4a5b-8c6d-7e8f9a0b1c2d"); + const antigravity = { + instanceId: ProviderInstanceId.make("antigravity"), + driverKind: ProviderDriverKind.make("antigravity"), + displayName: "Antigravity", + snapshot: { slashSkills: true }, + } as unknown as ProviderInstanceEntry; + const claude = { + status: { slashCommands: [{ name: "compact" }] } as unknown as ServerProvider, + driverKind: ProviderDriverKind.make("claudeAgent"), + label: "Claude", + }; + // Claude's thread, Antigravity added and addressed: Antigravity's list. + expect( + composerSlashAgent({ + threadId: thread, + recipient: { id: agent, instanceId: antigravity.instanceId }, + entries: [antigravity], + selected: claude, + }), + ).toEqual({ + status: antigravity.snapshot, + driverKind: antigravity.driverKind, + label: "Antigravity", + sessionKey: participantSessionKey(thread, agent), + addedAgent: true, + }); + // The thread's own agent addressed: its own provider and session. + expect( + composerSlashAgent({ + threadId: thread, + recipient: null, + entries: [antigravity], + selected: claude, + }), + ).toEqual({ ...claude, sessionKey: thread, addedAgent: false }); + }); +}); diff --git a/apps/web/src/components/chat/composerAgentCommands.ts b/apps/web/src/components/chat/composerAgentCommands.ts new file mode 100644 index 000000000..ce7c1a3b2 --- /dev/null +++ b/apps/web/src/components/chat/composerAgentCommands.ts @@ -0,0 +1,112 @@ +import type { + ProviderDriverKind, + ServerProvider, + ServerProviderSkill, + ServerProviderSlashCommand, + ThreadId, + ThreadParticipantId, +} from "@threadlines/contracts"; +import { isSlashCommandName } from "@threadlines/shared/slashCommands"; +import { participantSessionKey } from "@threadlines/shared/threadParticipants"; + +import type { ProviderInstanceEntry } from "../../providerInstances"; + +export interface ComposerProviderSlashList { + /** The provider section of the `/` list. */ + readonly commands: ReadonlyArray; + /** Skills the agent runs on `/`, for the Skills section; none it lists as a command. */ + readonly slashSkills: ReadonlyArray; +} + +const NO_SKILLS: ReadonlyArray = []; + +export interface ComposerSlashAgent { + /** Its provider's status, whose commands and skills the list offers. */ + readonly status: ServerProvider | null; + readonly driverKind: ProviderDriverKind; + /** Heading of the provider section. */ + readonly label: string; + /** Its session's key, for the list that session reported. */ + readonly sessionKey: string | null; + /** An added room agent rather than the thread's own. */ + readonly addedAgent: boolean; +} + +/** + * The agent the `/` list describes: the one the next message goes to. In a + * room that is an added agent's own provider instance; otherwise the + * composer's selected provider. + */ +export function composerSlashAgent(input: { + readonly threadId: ThreadId | null; + /** The added room agent the message is addressed to, or null. */ + readonly recipient: { + readonly id: ThreadParticipantId; + readonly instanceId: ProviderInstanceEntry["instanceId"]; + } | null; + readonly entries: ReadonlyArray; + readonly selected: { + readonly status: ServerProvider | null; + readonly driverKind: ProviderDriverKind; + readonly label: string; + }; +}): ComposerSlashAgent { + const recipient = input.recipient; + const entry = + recipient === null + ? undefined + : input.entries.find((candidate) => candidate.instanceId === recipient.instanceId); + const keyOf = (participantId: ThreadParticipantId | null) => + input.threadId === null ? null : participantSessionKey(input.threadId, participantId); + return entry !== undefined && recipient !== null + ? { + status: entry.snapshot, + driverKind: entry.driverKind, + label: entry.displayName, + sessionKey: keyOf(recipient.id), + addedAgent: true, + } + : { ...input.selected, sessionKey: keyOf(null), addedAgent: false }; +} + +/** The list a running session put on its provider's status, by session key. */ +export function sessionSlashCommands( + provider: Pick | null, + sessionKey: string | null, +): ReadonlyArray | undefined { + if (sessionKey === null) return undefined; + return provider?.sessionCommands?.find((entry) => entry.sessions.includes(sessionKey))?.commands; +} + +/** + * What the composer's `/` list offers from the agent the next message goes + * to. A provider whose agent runs skills on `/` + * (`ServerProvider.slashSkills`, Antigravity) lists the commands that agent's + * running session put on the status, else the status's own, and the status's + * skills less any the commands already name, so the session's entry wins. + * Commands Threadlines answers itself (`/model`, `/plan`…) stay Threadlines'. + * Every other provider keeps its status's commands, as before. + */ +export function composerProviderSlashList(input: { + readonly provider: Pick | null; + /** The list the agent's running session reported, if any (`sessionSlashCommands`). */ + readonly sessionCommands: ReadonlyArray | undefined; + readonly threadlinesCommands: ReadonlySet; +}): ComposerProviderSlashList { + const provider = input.provider; + if (provider?.slashSkills !== true) { + return { commands: provider?.slashCommands ?? [], slashSkills: NO_SKILLS }; + } + const commands = (input.sessionCommands ?? provider.slashCommands).filter( + (command) => !input.threadlinesCommands.has(command.name), + ); + const named = new Set(commands.map((command) => command.name)); + const slashSkills = provider.skills.filter( + (skill) => + skill.enabled && + !named.has(skill.name) && + !input.threadlinesCommands.has(skill.name) && + isSlashCommandName(skill.name), + ); + return { commands, slashSkills }; +} diff --git a/apps/web/src/components/usage/UsageView.tsx b/apps/web/src/components/usage/UsageView.tsx index 823454909..6fc40597c 100644 --- a/apps/web/src/components/usage/UsageView.tsx +++ b/apps/web/src/components/usage/UsageView.tsx @@ -28,6 +28,7 @@ import { RelativeTimeLabel } from "../RelativeTimeLabel"; import { PageTitlebar } from "../PageTitlebar"; import { ClaudeAI, + AntigravityIcon, FxIcon, GrokIcon, MuseIcon, @@ -129,6 +130,7 @@ const USAGE_PROVIDER_ICONS: Record = { muse: MuseIcon, opencode: OpenCodeIcon, fx: FxIcon, + antigravity: AntigravityIcon, }; function shareDigits(share: number): number { diff --git a/apps/web/src/components/usage/usageView.logic.ts b/apps/web/src/components/usage/usageView.logic.ts index 79506493c..d88c2a45c 100644 --- a/apps/web/src/components/usage/usageView.logic.ts +++ b/apps/web/src/components/usage/usageView.logic.ts @@ -46,6 +46,7 @@ export const USAGE_PROVIDER_LABELS: Record = { muse: "Muse Code", opencode: "OpenCode", fx: "fx", + antigravity: "Antigravity", }; /** For the narrow columns where the product name would not fit. */ @@ -57,6 +58,7 @@ export const USAGE_PROVIDER_SHORT_LABELS: Record = { muse: "Muse", opencode: "OpenCode", fx: "fx", + antigravity: "Antigravity", }; /** @@ -75,6 +77,7 @@ export const USAGE_PROVIDER_COLORS: Record = { muse: "var(--provider-muse)", opencode: "var(--provider-opencode)", fx: "var(--provider-fx)", + antigravity: "var(--provider-antigravity)", }; /** Reading order for legends and rows: the same order every time. */ @@ -86,6 +89,7 @@ export const USAGE_PROVIDER_READING_ORDER: readonly UsageProviderKind[] = [ "muse", "opencode", "fx", + "antigravity", ]; /** @@ -1011,6 +1015,7 @@ const USAGE_PROVIDER_BY_DRIVER: ReadonlyMap { ), ).toBeNull(); }); + + it("says what Antigravity's server says about its limits, in its words", () => { + const antigravity = ProviderDriverKind.make("antigravity"); + const reading = (checkedAt: string): ServerProviderAccountUsage => ({ + source: "grok-billing", + checkedAt, + primaryLimitId: "antigravity", + limits: [ + { + limitId: "antigravity", + limitName: "Antigravity usage", + scoped: [ + { + scopeLabel: "Gemini", + scopeModels: ["Gemini"], + usedPercent: 12, + remainingPercent: 88, + windowDurationMins: 300, + checkedAt, + }, + ], + }, + ], + }); + const auth = ( + usage: NonNullable["usage"]>, + ): ServerProvider["auth"] => ({ + status: "authenticated", + type: "oauth-personal", + capabilities: { usage }, + }); + const expired = { status: "unavailable" as const, detail: "Start a chat to refresh." }; + const failed = { + status: "unavailable" as const, + reason: "unreachable" as const, + detail: "Couldn't read Antigravity limits.", + }; + + // An expired sign-in is said beside the kept numbers, which show their age. + const kept = deriveProviderAccountUsagePresentationForProvider( + { + driver: antigravity, + auth: auth(expired), + accountUsage: reading("2026-07-09T10:00:00.000Z"), + }, + nowMs, + ); + expect(kept?.label).toBe("Antigravity usage"); + expect(kept?.windows[0]?.detail).toBe("12% used · as of 2h ago"); + expect(kept?.notice).toEqual({ signIn: false, text: "Start a chat to refresh." }); + + // A failed read stays quiet while the numbers are recent, and says so with none. + expect( + deriveProviderAccountUsagePresentationForProvider( + { + driver: antigravity, + auth: auth(failed), + accountUsage: reading("2026-07-09T11:58:00.000Z"), + }, + nowMs, + )?.notice, + ).toBeUndefined(); + expect( + deriveProviderAccountUsagePresentationForProvider( + { driver: antigravity, auth: auth(failed) }, + nowMs, + ), + ).toEqual({ + label: "Antigravity usage", + windows: [], + reachedLimit: false, + notice: { signIn: false, text: "Couldn't read Antigravity limits." }, + }); + }); }); const makeUsage = (usedPercent: number): ServerProviderAccountUsage => ({ @@ -1175,6 +1249,50 @@ describe("a model's own usage limit", () => { expect(label(100)).toMatchObject({ text: "Limit · resets in 3d 16h", tone: "reached" }); }); + const antigravity = deriveProviderAccountUsagePresentation( + { + source: "grok-billing", + checkedAt: "2026-07-03T00:00:00.000Z", + primaryLimitId: "antigravity", + limits: [ + { + limitId: "antigravity", + limitName: "Antigravity usage", + scoped: [ + ["Gemini", ["Gemini"], 300, 20], + ["Gemini", ["Gemini"], 10_080, 35], + ["Gemini 4 Argon", ["Argon"], 10_080, 90], + ["Claude & GPT", ["Claude", "GPT"], 300, 60], + ].map(([scopeLabel, scopeModels, windowDurationMins, usedPercent]) => ({ + scopeLabel: scopeLabel as string, + scopeModels: scopeModels as string[], + ...(scopeLabel === "Gemini" ? { scopeExcludes: ["Argon"] } : {}), + usedPercent: usedPercent as number, + remainingPercent: 100 - (usedPercent as number), + windowDurationMins: windowDurationMins as number, + })), + }, + ], + }, + NOW, + ); + + it("gives each Antigravity model its own family's limit", () => { + expect(modelOwnUsageLimit(antigravity, "Gemini 3.1 Pro")?.usedPercent).toBe(35); + expect(modelOwnUsageLimit(antigravity, "Gemini 4 Argon")?.usedPercent).toBe(90); + expect(modelOwnUsageLimit(antigravity, "Claude Sonnet 5.5")?.label).toBe("Claude & GPT (5h)"); + expect(modelOwnUsageLimit(antigravity, "GPT-OSS 120B")?.usedPercent).toBe(60); + }); + + it("keeps the period on short labels two windows share", () => { + expect(compactUsageMeters(antigravity!, 10).map((line) => line.label)).toEqual([ + "Gemini (5h)", + "Gemini (weekly)", + "Gemini 4 Argon", + "Claude & GPT", + ]); + }); + it("leaves a model's own limit out of the account's near-limit mark", () => { // Fable's week is used up, the account's is not: only Fable's row says so. expect(isProviderUsageNearLimit(claude(40, 100), { modelLimits: false })).toBe(false); diff --git a/apps/web/src/lib/providerUsage.ts b/apps/web/src/lib/providerUsage.ts index 98bf04174..a98338aed 100644 --- a/apps/web/src/lib/providerUsage.ts +++ b/apps/web/src/lib/providerUsage.ts @@ -8,6 +8,7 @@ import type { ServerProviderUsageLimit, ServerProviderUsageWindow, } from "@threadlines/contracts"; +import { type UsageScope, usageScopeHoldsModel } from "@threadlines/shared/usageLimits"; /** * `warning` is the single "render attention affordances" signal for usage @@ -44,8 +45,7 @@ export interface ProviderAccountUsageWindowPresentation { * per-model weekly limits): the name the provider gives it ("Fable"), its * period ("Weekly"), and when it resets ("resets in 3d 16h"). */ - readonly scope?: { - readonly name: string; + readonly scope?: UsageScope & { readonly period: string | null; readonly resetDetail: string | null; }; @@ -362,6 +362,13 @@ export function compactUsageMeters( usage: Pick, limit: number = COMPACT_USAGE_METER_LIMIT, ): ReadonlyArray { + // A short label two windows share ("Gemini" for its 5h and weekly limits) + // keeps its period, so the lines stay apart. + const shortLabelCounts = new Map(); + for (const window of usage.windows) { + if (window.shortLabel === undefined) continue; + shortLabelCounts.set(window.shortLabel, (shortLabelCounts.get(window.shortLabel) ?? 0) + 1); + } const lines: ReadonlyArray = [ ...(usage.spendControl ? [ @@ -377,7 +384,10 @@ export function compactUsageMeters( : []), ...usage.windows.map((window) => ({ key: window.key, - label: window.shortLabel ?? window.label, + label: + window.shortLabel !== undefined && shortLabelCounts.get(window.shortLabel) === 1 + ? window.shortLabel + : window.label, detail: window.detail, usedPercent: window.usedPercent, warning: window.warning, @@ -527,7 +537,13 @@ function formatScopedUsageWindowPresentation( reachedLimit, warning: reachedLimit || severityWarning || usedPercent >= USAGE_WARNING_THRESHOLD_PERCENT, ...usagePaceFields(window, elapsedPercent), - scope: { name: window.scopeLabel, period: durationLabel || null, resetDetail }, + scope: { + name: window.scopeLabel, + ...(window.scopeModels ? { models: window.scopeModels } : {}), + ...(window.scopeExcludes ? { excludes: window.scopeExcludes } : {}), + period: durationLabel || null, + resetDetail, + }, }; } @@ -871,10 +887,42 @@ function deriveClaudeUsageNotice( } } +/** + * What another provider's server says about its own usage check, in its own + * words (Antigravity: "start a chat to refresh"). A failed read stays quiet + * while the kept numbers are recent; anything else is said either way. + */ +function deriveReportedUsageNotice( + provider: ProviderAccountUsagePresentationProvider, + hasNumbers: boolean, + hasStaleReading: boolean, +): ProviderAccountUsageNotice | undefined { + if (provider.driver === "claudeAgent" || provider.auth.status !== "authenticated") { + return undefined; + } + const usage = provider.auth.capabilities?.usage; + if (usage?.status !== "unavailable" || usage.detail === undefined) return undefined; + if (usage.reason === "unreachable" && hasNumbers && !hasStaleReading) return undefined; + return { signIn: false, text: usage.detail }; +} + +/** What a usage surface is titled when the provider has a notice and no reading. */ +function providerUsageLabel(provider: ProviderAccountUsagePresentationProvider): string { + switch (provider.driver) { + case "claudeAgent": + return PROVIDER_USAGE_SOURCE_LABELS["claude-oauth-usage"]; + case "antigravity": + return "Antigravity usage"; + default: + return "Plan usage"; + } +} + /** * The usage presentation for a provider as a whole, not just its usage - * payload: a Claude subscription whose usage check produced no numbers comes - * back with a `notice` (keeping the numbers it has, and any local token + * payload: a Claude subscription whose usage check produced no numbers, or a + * provider whose server explains its own (Antigravity), comes back with a + * `notice` (keeping the numbers it has, and any local token * history) instead of as nothing, so its surfaces can say what is wrong. A * notice with no windows means there is nothing to draw: an empty meter * would read as "0% used". @@ -888,16 +936,15 @@ export function deriveProviderAccountUsagePresentationForProvider( const hasNumbers = presentation !== null && (presentation.windows.length > 0 || presentation.spendControl !== undefined); - const notice = deriveClaudeUsageNotice( - provider, - hasNumbers, - hasStaleUsageReading(provider.accountUsage, nowMs), - ); + const hasStaleReading = hasStaleUsageReading(provider.accountUsage, nowMs); + const notice = + deriveClaudeUsageNotice(provider, hasNumbers, hasStaleReading) ?? + deriveReportedUsageNotice(provider, hasNumbers, hasStaleReading); if (!notice) return presentation; return presentation ? { ...presentation, notice } : { - label: PROVIDER_USAGE_SOURCE_LABELS["claude-oauth-usage"], + label: providerUsageLabel(provider), windows: [], reachedLimit: false, notice, @@ -955,26 +1002,20 @@ export function providerUsageNearLimitColor( return usageMeterColor(hottestPercent, true); } -const nameTokens = (name: string) => name.toLowerCase().split(/\s+/).filter(Boolean); - /** - * The limit a model has of its own, if the account reports one. Providers name - * such a limit, not the model's id ("Fable" for every Fable model), so it - * matches a model whose name holds the limit's name as whole words: "Fable" - * matches "Claude Fable 5.2", while "Opus 5" does not match "Opus 5.5". The - * fullest applies when several do. + * The limit a model has of its own, if the account reports one: a window + * whose scope holds the model's name (`usageScopeHoldsModel`). The fullest + * applies when several do. */ export function modelOwnUsageLimit( usage: Pick | null | undefined, modelName: string, ): ProviderAccountUsageWindowPresentation | null { if (!usage) return null; - const model = nameTokens(modelName); - const holds = (scope: ReadonlyArray) => - scope.length > 0 && - model.some((_, start) => scope.every((token, offset) => model[start + offset] === token)); return usage.windows.reduce((fullest, window) => { - if (window.scope === undefined || !holds(nameTokens(window.scope.name))) return fullest; + if (window.scope === undefined || !usageScopeHoldsModel(window.scope, modelName)) { + return fullest; + } return fullest === null || window.usedPercent > fullest.usedPercent ? window : fullest; }, null); } diff --git a/docs/providers/antigravity-cli-plan.md b/docs/providers/antigravity-cli-plan.md new file mode 100644 index 000000000..fd193cd85 --- /dev/null +++ b/docs/providers/antigravity-cli-plan.md @@ -0,0 +1,227 @@ +# Antigravity: move to Google's CLI and close the gap with T3 Code (plan, 2026-11-23) + +Goal, from Will: Antigravity in Threadlines should be at least as good as in T3 Code, better where +we see room, and should include what Google's own engineers have contributed to T3 Code. + +This file is the shared brief for everyone building it. Facts marked [v] were checked on +2026-11-23 against the named source. Facts marked [t3] come from reading T3 Code's source and are +how T3 does it, not proof of how the agent behaves. Nothing here was checked against a signed-in +session. + +## Sources + +- Google's CLI repo and changelog: https://github.com/google-antigravity/antigravity-cli + (`CHANGELOG.md` is the authority on what `agy acp` does in each version). +- Google's update feed, one manifest per build: + `https://antigravity-cli-auto-updater-974169037036.us-central1.run.app/manifests/_.json` + with `{version, url, sha512}`; `url` is under + `https://storage.googleapis.com/antigravity-public/antigravity-cli/-/` [v]. It served + 1.5.14 for `darwin_arm64`, `linux_amd64` and `windows_amd64` on 2026-11-23 [v]. +- T3 Code, MIT licensed: https://github.com/pingdotgg/t3code. A clone may be at + `/tmp/t3research/t3code`; clone it again if it is gone. Read it for wire shapes, edge cases and + test fixtures. Write our own code in our own structure: do not paste theirs. +- The two T3 pull requests from a Google engineer (patrick-toulme, the only author of 284 checked + whose profile says Google): #31158, merged, client identity; #40368, open, native swarm. + +## Decisions + +### 1. Run the CLI (`agy acp`), not the `agy_acp_server` package + +Google moved ACP into the Antigravity CLI in 1.5.0 and does its ACP work there [v, changelog]. +The registry package we install today is the old channel: it is at 1.5.2 while the CLI is at +1.5.14 [v]. What the CLI's ACP mode has, by version [v, changelog]: + +| Version | What it adds for an app like ours | +| ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| 1.5.0 | `agy acp`; modes `default`, `accept-edits`, `plan`; steering a running turn by sending another prompt; `session/resume`; `agy acp --login` | +| 1.5.1 | Every model on the account (Claude and GPT too) for every ACP client, not only allowlisted editors | +| 1.5.4 | `auto` mode; a second approval for the same tool call arrives as a new request | +| 1.5.8 | Context window usage updates | +| 1.5.9 | A failed turn reports its real error (model, quota) | +| 1.5.10 | Replies, tool calls and approvals after a turn ended arrive right away (background task or subagent wakes the agent); cancel and close stop subagents and background tasks | +| 1.5.13 | Shell commands run in the session's folder; attached file contents are honored; retries are silent | + +- Launch: ` acp --gemini-dir --app-data-dir antigravity-acp` [t3]. +- Version floor: 1.5.14, on every platform and for custom binaries too. Below it, sessions don't + start and the row says what to do. Reasons [v, changelog]: 1.5.10 delivers what the agent does + after a turn ends, 1.5.13 honors attached file contents, and 1.5.14 fixes a Windows flaw where + a network path in a file mention or rule could send Windows credentials to a remote host. The + floor is a constant next to the release code with these reasons in its comment. (T3 accepts + 1.5.0; ours is stricter on purpose.) +- Source of releases: Google's update feed. Accept a manifest only when the URL is under the + storage folder above with the file name Google uses for that build, and the version is plain + semver. Keep the host allowlist on every redirect hop (`makeHttpsFetch`). +- Download and unpack checks must not get weaker than today's. The feed gives sha512 and no + sizes, and the shared downloader wants an exact size and hashes sha256, so it needs a sha512 + streaming path with a size cap. Unix builds are `tar.gz` and Windows is a bare `.exe` [t3]: + the tarball gets its own limit on unpacked size and entry count, exact entry names, and no + links or paths that leave the folder; the disk-space check budgets the download plus what it + unpacks to. Sizes learned on install go in the marker so the "files intact" check still works. +- Keep what we built on 2026-11-23: a built-in fallback release (now a CLI release with its + sha512 per build), an hourly check that never blocks a status refresh for more than a few + seconds, backoff while the feed is down, user-clicked Update only, never installing an older + version than the one in place, a start-up check of the new copy before switching to it. +- Stop the CLI updating itself: `AGY_CLI_DISABLE_AUTO_UPDATE=1`, and make the installed files + read-only [t3]. Not the version folder: `ManagedRuntimeStore` writes its leases inside it, so a + read-only folder would pass the install check and then fail the first real launch. +- Builds: the six we have, and Linux musl (the feed has `_musl` builds; pick by detecting musl, + as T3 does), so a Threadlines server on Alpine gets a managed install. +- The weekly drift check (`scripts/check-upstream-drift.ts`) compares the built-in release with + the feed instead of the registry. +- Remove what the registry route needed and nothing else uses (`builtIn` recipes in + `AcpRegistryCatalog`, the zip range reader), unless the new code reuses it. +- Two kinds of existing install, each with its own way forward: + - Managed: the old marker names two files (server and harness). The new reader must still + recognize it, so the row says "Update needed" with Update, not "Install", and the old copy + keeps its leases until the CLI is activated. It is pruned once nothing runs on it. + - A custom binary path pointing at the old server: managed Update can't fix it and adding + `acp` to it doesn't make it the CLI. The row says the path must be Google's `agy` (or be + cleared to use the managed copy), with both choices one click away. +- A thread started before the switch: its saved session may not resume on the CLI. The existing + failed-resume path then starts a fresh session with the thread's context + (`contextSeedOnResumeFailure`). The foundation stage checks that the next prompt really carries + the kept conversation. + +### 2. Sign-in + +- The 1.5 CLI keeps Google sign-ins in one OS keyring entry shared by every profile unless it + thinks it runs over SSH; T3 sets `SSH_CONNECTION` for Google-account sign-ins so each profile + keeps its own sign-in in a file (`antigravity-acp/antigravity-oauth-token`) and signs in with + `agy acp --login`, where Google ends on an antigravity.google page that shows a code to paste + back [t3]. We need the same isolation: extra accounts must not share one sign-in, and a + Threadlines sign-out must not sign the user's terminal `agy` out. Confirm the mechanism against + the binary and the changelog before copying it; if Google has a real switch for file storage by + now, use that. +- The paste-a-code sign-in is a new flow, not a variant of today's. Today the paste field shows + only for a loopback redirect, and the server replays a pasted address to the agent's local + port. A code from the antigravity.google page fits neither. Foundation builds code entry end to + end: tied to the instance and the sign-in attempt that asked, handed privately to the waiting + `agy acp --login` process, and reachable from setup, Settings, a phone, and a browser on + another computer. +- Whether the old `acp_token.json` sign-in carries over is unknown. If it does not, say so once on + the row ("Sign in again") instead of failing a chat. +- Sign-in errors get their own words: the agent didn't start, Google didn't answer (with the + IPv6 hint), Google refused, subscription required, account verification needed (link to + Google's page) [t3 has the first four merged; the link is an open PR there]. +- Keep the four methods we have, the key check, and the gcloud lookup for Vertex AI. + +### 3. Identity, models, modes + +- Client identity: `{ name: "threadlines", title: "Threadlines", version: }` (Google's + PR #31158 did this for T3). We never pretend to be another editor. +- Models come from the session, as now. Claude and GPT models will appear for plans that have + them. The reasoning level is its own setting (`thought_level`) in current versions [t3]; keep + the name-suffix folding only as a fallback. The saved model list stays tagged with the agent + version. +- Access levels: Supervised is `default`; Auto-accept edits is `accept-edits`; Auto is the CLI's + own `auto` when the session offers it, else `accept-edits`; Full access has no CLI mode (it + rejects `yolo` [t3]), so it runs in `default` and Threadlines approves requests itself, as the + ACP core already does for full access. Questions with fixed choices still need an answer. +- Plan: use the CLI's `plan` mode if it produces the same plan file our plan card reads; else + keep the `/plan` prefix. The plan card stays. +- Our own MCP tools (room, browser, pages) follow the rule Claude and Codex threads already + follow for the same access level. Do not invent a looser one. + +### 4. Turns + +- Design these four together, before anything else touches the adapter's prompt path: + - A reply the agent starts on its own, after a background command or subagent finishes, shows + in the thread (the core's `agentTurns`, which Grok uses). + - Between the prompt ending and that reply, the thread still shows "working" with Stop. + `agentTurns` alone doesn't do this: the adapter clears the active turn when the prompt + settles and only opens a new one when output arrives. Grok gets explicit background and end + notices from its agent. Antigravity needs its own source of "work is pending" (tool calls + that outlive the prompt, wake-ups, subagents), with an upper bound on a silent wait + [t3: 30 minutes]. + - A message sent mid-turn steers the turn (CLI 1.5.0+). The core's prompt helper keeps one + "prompt in flight" flag and closes the current text segment per request, so a second prompt + sent while the first is open needs its own handling of responses, or either response clears + the flag for both. + - Stop cancels the prompt and the pending work, and the thread settles once. +- Failures are failures: 5xx and 429 are retryable, a quota failure carries its reset time into + the usage-limit notice, a session Google can no longer continue starts fresh with the thread's + context. Use what the prompt response and error carry first. Read the agent's own session + files only where the protocol truly gives nothing, and isolate that reader in one module. +- Subagents show as child work with role, prompt and steps, in whatever view Threadlines already + has for other agents' subagents. +- Tool rows: an MCP call made through `call_mcp_tool` shows the tool's name; edits land at their + real lines; long command text keeps its start; tool text is capped without cutting a character + in half. +- Attachments: images and audio inline, PDFs and text files as documents, MIME parameters + stripped, everything else as a file path. +- The agent's own slash commands list in the composer (`available_commands`), including `/goal` + and `/compact` when offered. +- Antigravity runs a skill when a message starts with `/`, so its skills belong in + the same `/` list. The provider status already lists them (stage 2), but the composer's skill + menu only asks for Codex's today. Stage 3 shows the status's skills in the `/` list before a + session has opened and merges the agent's own list once it has. A `$name` chip is wrong for + Antigravity: it would arrive as plain text. +- Editing an earlier message starts a fresh Antigravity session seeded with the kept turns, + since the agent cannot rewind. + +### 5. The user's own setup + +- Link `~/.gemini/AGENTS.md`, `GEMINI.md`, `config/skills.json` and the global skills folders into + each private profile (copy on Windows) [t3]. Credentials, hooks and the user's MCP config stay + out of the profile. +- List Antigravity's skills where Threadlines lists other agents' skills, with T3's lookup order + as the reference (`.gemini/skills`, `.agents/skills`, `.agent/skills`, global folders, + `skills.json` with `inherits`, `include_only`, `exclude`). + +### 6. Usage + +- Tokens per turn come from the prompt response's `usage` (input plus cached read; output as + sent, since 1.5 already counts thinking in it) [t3]. This needs its own conversion: the generic + one subtracts cached reads from input, which is right for fx and would undercount here. The + ledger only knows `fx` today, and the usage contract lists provider kinds that older clients + negotiate, so the ledger, the contract and both clients change together. Gemini 4 prices are + added. The context meter uses `usage_update` (1.5.8+). +- Plan limits: read them the way T3 does, from Google's `retrieveUserQuotaSummary`, with the + access token the CLI saved in our own profile. Rules: never renew or rewrite the token (when it + has expired, say "start a chat to refresh" and keep the last numbers); never touch the OS + keyring; send our own User-Agent first and only come back to Will if Google refuses it; fail + soft. Rows look like Grok's: family, window, percent used, reset time. This is an unpublished + Google API and can break; that is accepted, and the code says so. +- Limits and email belong to one sign-in. Switching an instance to an API key keeps the earlier + Google sign-in on disk on purpose, so a saved token alone proves nothing: read limits only + when the instance's method is a Google sign-in, and key what is cached by the sign-in + fingerprint, so a per-use account never shows a subscription's limits or someone's email. +- Show the signed-in Google account's email on the row if the same call path gives it cheaply. +- Not building: usage history for runs made outside Threadlines (it needs Google's private + file format), and T3's CLIProxyAPI hub. + +### 7. Swarm (Google's open PR #40368) + +Native swarm is not in a released `agy` yet [t3 PR text]. Build it last. The client sends its +capabilities in `initialize` before it hears the agent's, so once Threadlines can handle swarm +messages it always offers `clientCapabilities._meta.antigravity.swarm`; whether the native path +is used is decided from the agent's answer or its `_antigravity/swarm` notifications. The +`swarm/members.json` fallback for released 1.5 builds is judged on its own, not behind that +gate. Workers show as subagents with live steps, and the thread stays working while they run. +Re-read the PR when starting: it is still changing. + +## Order + +1. **Foundation**: decisions 1 to 3, including the code-entry sign-in and both migration paths. + Everything else depends on the CLI being the runtime. +2. **Turn lifecycle**: the four items at the top of decision 4, failures, and tokens per turn + (they settle in the same prompt-completion path). One builder owns the ACP adapter here. + **Alongside it**, since neither touches the adapter: the user's setup and skills (decision 5), + and plan limits with the account email (decision 6, without tokens). +3. **The rest of decision 4**, after stage 2's adapter work lands: subagents, tool rows, + attachments, slash commands, edit-earlier-message. +4. **Swarm**, decision 7, on top of 3. + +Each stage ends with gates green, an outside review of its diff, and a short list of what Will +should click to check it signed in. + +## Checking it + +- No test can sign in to Google. Unit and integration tests use the stand-in ACP agent + (`apps/server/scripts/acp-mock-agent.ts`) and shapes taken from T3's fixtures and Google's + changelog. +- The real binary can be started signed out in a temp profile to read `initialize` (version, + sign-in methods, modes, capabilities). If a permission guard refuses that, stop and say so. +- Will does the signed-in pass on a dev build at the end of each stage. Each stage's report ends + with the exact things to click. +- `docs/providers/antigravity.md` and the app guide topic change with each stage. diff --git a/docs/providers/antigravity.md b/docs/providers/antigravity.md index af8847b37..e3f299b89 100644 --- a/docs/providers/antigravity.md +++ b/docs/providers/antigravity.md @@ -1,8 +1,285 @@ # Antigravity -Antigravity is Google's coding agent. Threadlines downloads and checks Google's own Antigravity -server for you (`Install` on the Antigravity row in `Settings -> Providers`), so there is nothing to -install by hand. +Antigravity is Google's coding agent. Threadlines runs Google's Antigravity CLI (`agy`) in its ACP +mode (`agy acp`), and downloads and checks the CLI for you (`Install` on the Antigravity row in +`Settings -> Providers`), so there is nothing to install by hand. Each Antigravity account in +Threadlines has its own profile, separate from your own `~/.gemini`. + +Threadlines needs Antigravity 1.5.14 or newer, for the managed copy and for one you point it at +(`Binary path`). That version is the first that delivers what the agent does after a turn ends, +honors attached file contents, and closes a Windows flaw where a network path in a file mention +could send your Windows credentials to another computer. An older custom `agy` is refused with a +message saying so; run `agy update`, or clear the path to use the copy Threadlines installs. + +## Updates + +Threadlines asks Google's CLI update feed for a newer Antigravity at most once an hour. When there is +one, the Antigravity row shows `Update`; nothing installs until you click it. New models arrive this +way, since each Antigravity version lists its own. + +Threadlines only offers a release from Google's own download folder under the name Google uses for +your computer's build, with a plain version and a sha512. It checks the download against that hash +and a size cap (the feed lists no sizes), unpacks only the one `antigravity` file (refusing links, +extra files and anything outside its folder), and starts the new copy once to make sure it's +Antigravity at that version before switching to it. The installed file is read-only, and the CLI's +own self-update is turned off, so only Threadlines changes it. If the feed can't be read, the +version built into Threadlines is offered instead, and an installed copy is never replaced by an +older one. Linux computers that use musl (Alpine) get Google's musl build. + +A weekly GitHub check (`.github/workflows/upstream-drift.yml`) opens an issue when Google's version +is ahead of the built-in one, or when Google's feed changes so Threadlines would refuse it. + +### Moving From Google's Old Antigravity Server + +Before 1.5.14, Threadlines ran Google's older `agy_acp_server` package. If you had it installed, the +Antigravity row says `Antigravity now runs on Google's Antigravity CLI. Update it to keep using it.` +with `Update`. The old copy stays until no chat uses it, then Threadlines deletes it. + +A `Binary path` that points at the old server (`agy_acp_server`) can't be updated. The row says to +point it at Google's `agy`, or to clear it so Threadlines uses its own copy. + +The CLI keeps its sign-in in a different file, so a Google account or Gemini Enterprise sign-in made +with the old server needs one more sign-in; the row says `Sign in again`. Threads from before the +move continue: when the CLI can't reopen an old conversation, Threadlines starts a new one with the +thread's earlier turns as context. + +## Models and Access Levels + +The model picker lists the models your account has, Claude and GPT models included where your plan +has them. The reasoning level is its own choice next to the model. + +| Access level | What Antigravity runs | +| ----------------- | ------------------------------------------------------------------------------ | +| Supervised | `default`: asks before edits and commands | +| Auto-accept edits | `accept-edits` | +| Auto | The CLI's own `auto` where your session offers it, otherwise `accept-edits` | +| Full access | `default`, and Threadlines approves each request; questions still wait for you | + +Plan mode sends the task as `/plan`, and the plan shows on the plan card for review. Writing that +plan (`brain//plan.md` in the account's profile) is the one thing approved without asking, +and only an edit of that file alone qualifies; anything else Antigravity asks to do in Supervised +mode waits for you, even if it names the plan file. A message +that starts with one of Antigravity's own commands or skills goes as typed instead (see Commands and +Skills in the Composer). + +## Your Rules and Skills + +Each Antigravity account runs in its own profile, so Threadlines brings your own global setup from +`~/.gemini` into it before every start. These are shared: + +- Rules: `AGENTS.md` and `GEMINI.md`, both in `~/.gemini` and in `~/.gemini/config`, the + `~/.gemini/config/rules` folder, and `~/.gemini/config/rules.json`. +- Skills: the `~/.gemini/config/skills` and `~/.gemini/antigravity-cli/skills` folders, and + `~/.gemini/config/skills.json`. + +On macOS and Linux each one is a link, so an edit shows up in the next chat. On Windows the folders +are junctions and the files are copies, refreshed at each start; a copy changed inside the profile +is left alone from then on. Something you add later is picked up at the next start. Your sign-in, +hooks, plugins, subagents (`agents.json`) and MCP servers (`mcp_config.json`) stay out, so an +Antigravity account in Threadlines never runs them. + +These files can themselves be links, into a dotfiles repository for example. Threadlines follows a +link to see where it leads, and skips it when it leads to a sign-in or token file, hooks, MCP or +plugin settings, anywhere else in `~/.gemini`, or Threadlines' own data folder. + +Because the shared folders are links, what Antigravity writes in them lands in your real folders, +exactly as when you run `agy` in a terminal: a skill it creates in `config/skills` is a skill in +`~/.gemini/config/skills`. Threadlines itself only adds and removes its own links and copies. It +keeps a list of them beside the profile and never replaces or deletes anything else, and it skips +any profile folder that is itself a link, so it can't write into your own `~/.gemini` by accident. + +Project rules and skills come from the project as usual: `AGENTS.md` and `GEMINI.md`, and skills in +`.agents/skills`, `.gemini/skills` and the older `.agent/skills`. + +Threadlines reads which skills Antigravity loads, the way Antigravity finds them, and Settings +search lists them. Global skills are read through the account's profile, so the list matches what +that account's agent sees, including skills the agent keeps in its own profile. When two have the same name, the first wins in this order: +`~/.gemini/config/skills`, the project's `.gemini/skills`, `~/.gemini/antigravity-cli/skills`, the +project's `.agents/skills`, then `.agent/skills`. Folders a `skills.json` declares come after those: the project's +`.agents/skills.json` in the project and each folder above it up to the repository root, then +`~/.gemini/config/skills.json`. Threadlines follows the same rules as Antigravity for these files: +`inherits` reads another file, `include_only` and `exclude` match names exactly, a nested skill +loads only when `include_only` names it (`category/my-skill`), `~` is not expanded, and a project's +file can only point inside the project. A project skill folder that is a link to somewhere outside +the project is not listed, though Antigravity may still load it: Threadlines doesn't read outside a +project for it. Skills of plugins installed in that account's profile are listed unless the plugin +is turned off. Descriptions are cut to 1,024 characters. The list is read from the folder Threadlines runs in, like +other agents' lists, so a project's own skills show only when Threadlines runs inside it. + +To use a skill, start the message with `/` and its name, as in a terminal (`/review this diff`). +Antigravity also picks a skill on its own when the task matches its description. The composer's +`$` skill list is for Codex only; Antigravity's skills are in its `/` list (below). + +## Commands and Skills in the Composer + +Typing `/` in the composer lists Antigravity's skills and its own commands, under Threadlines' own +(`/model`, `/plan`, `/theme`, `/default`). Picking one puts `/name ` in the message. In a room, the +list is the one of the agent the message goes to. + +- Before Antigravity runs in a thread, the list has the skills Threadlines found (above). +- While it runs, it sends the commands that session offers (`available_commands_update`, the list + Google fixed in 1.5.2 to be the session's agent's). They join the list, and where a command and a + skill share a name, Antigravity's entry is the one shown. `/goal` and `/compact` show only when + Antigravity offers them. The list lives only as long as the session: Threadlines doesn't save + it, and after a restart the skills fill the list until Antigravity sends its own again. +- Antigravity's `/plan`, `/login` and `/logout` are left out: plan mode is the composer's `/plan`, + and signing in or out is on the Antigravity row in Settings, where it also stops that account's + chats. Typed by hand, they still go to Antigravity. +- Threadlines keeps at most 200 commands from a list, only names made of letters, digits, `_`, + `.`, `:` and `-`, and short descriptions. A list that keeps changing reaches the composer at most + every 5 seconds. + +A message runs one of Antigravity's commands when the words you typed (spaces in front don't +matter) start with `/` and the name of a command that session offers or a skill Threadlines lists. +That message goes to Antigravity alone, as typed, since Antigravity only runs a command at the very +start of a message: in plan mode without the `/plan` prefix, and without what Threadlines would put +in front of your words (the project's instructions, the thread's history after a switch, an edit or +a move, the summary a fork starts from, notes from other threads). That waits for your next +ordinary message, also across a restart. Everything else is ordinary text: a name Antigravity +doesn't offer (`/etc is missing`), a path (`/tmp/out.log is empty`), a message sent as plain text, +and one an agent or a scheduled task wrote. + +The thread's history counts as given to Antigravity only once the message carrying it actually went +out to Antigravity, not when Threadlines took the message: if Antigravity fails before that (setting +its model or mode, say), the next message carries the history again. + +## Turns + +Antigravity answers a message while work it started goes on: a command it waits for, a timer it +set (`schedule`), or a subagent it launched. When that work ends, the agent wakes and replies by +itself. Threadlines keeps the turn open meanwhile, so the thread shows it working and Stop stays on +screen, and the reply lands in the same turn. A dev server or other daemon doesn't hold the turn. +Stop cancels the turn and that work together (Antigravity 1.5.10 stops its commands and subagents on +a cancel). A turn that was only waiting on that work shows cancelled at once, but Threadlines keeps +track of the commands and subagents until the agent shows they ended (a command's end, or the +subagent's record saying it stopped), and a message sent meanwhile waits for that. If the agent +hasn't answered or ended that work 15 seconds after Stop, Threadlines restarts it and the turn ends +cancelled; a message that was waiting fails, and the next message picks the conversation up again. +A timer gives no word when a cancel ends it, so a stop doesn't wait on one. Stopping the session (or +Threadlines) while a turn is held ends that turn as interrupted. A reply the agent starts after the +turn ended opens a turn of its own, except the CLI's "request was cancelled" notice after a Stop, +which never shows. Threadlines waits 30 seconds for that notice; after that, a reply counts again. + +Two limits keep a lost wake from leaving the thread working forever: a turn held only by commands +and subagents ends after 30 minutes without a word from the agent, and a reply the agent started +by itself ends 2 minutes after its last output if its closing usage update never comes. Both count +from the agent's last activity. A timer +holds the turn until it fires. When a reply ends with subagents still counted, Threadlines reads the +CLI's records of them (see Subagents below) and holds the turn only for the ones still at work, so +several reports answered in one reply, or a subagent the agent stopped, end the hold. A launch +counts only for the child its own call started, so a resumed conversation's older subagents never +stand in for a new one, and only the newest reading counts. When the records can't tie every +launch to its child (one not written yet, or a batch launch from before 1.5), each report (a reply +no finished command or timer woke) frees one subagent, and a batch launch counts each subagent in +it. If the +agent exits while a turn is held, the turn fails with that reason and the next message starts it +again. + +A message sent while Antigravity is answering waits for that turn to end, as with other agents. One +sent while the turn only waits on work Antigravity started ends that turn, and goes at once. +Prompts reach the agent in the order they were sent, each turn's mode and model setup first. +Threadlines can also steer a running turn with a second prompt, which the CLI takes into it +(1.5.0+), but that ships off (`ANTIGRAVITY_STEERS` in +`apps/server/src/provider/antigravity/AntigravityTurns.ts`): a steer is recorded as accepted before +it is written, so an agent that exits at that moment would leave a steer shown that it never got. + +All of this is one state machine (`apps/server/src/provider/acp/AcpTurnMachine.ts`), stepped in +order with the agent's updates. A prompt's answer takes its place among those updates where the +CLI wrote it, a step and the commands it issues run as one unit, and stopping the session is an +event the machine takes after everything already received (an answered prompt's usage included). +The machine's test walks every sequence of up to nine events with steering on and ten with it off, +and checks that each turn ends exactly once, Stop always has a deadline until the work it stopped +is over, every message hears back, and a hold with nothing left ends. + +### Subagents + +When Antigravity launches a subagent (its `invoke_subagent` tool), the subagent shows in the thread +like other agents' subagents: its role, its prompt, whether it runs, and the report it sent back. +Open it to read its recent steps. ACP says only that a launch happened, so the rest is read from the +CLI's own records in the profile (`antigravity-acp/brain/`, a private format read only for this; +the code is `apps/server/src/provider/antigravity/AntigravityChildRecords.ts`). They are read when +each reply ends and when the turn ends: + +- A subagent that sent its report shows as done, with the report. +- One the agent stopped (`manage_subagents`) shows as stopped. +- Stop ends every running subagent with the turn. +- A subagent the records don't name shows as done once its turn has ended, and its view says + "Antigravity did not record which subagent this started". A later reading that finds it still at + work shows it running again. +- When the records can't be read (one the CLI is still writing, say), nothing is marked done; the + next reading tries again. + +The view is read-only: you can't message a subagent directly. The same records decide how long the +turn stays open (see Turns above). + +### Tool rows + +- An MCP tool the agent reaches through `call_mcp_tool` shows as that tool (server and name), not + as a shell command, and doesn't hold the turn like a command. Only a call that is plainly that + wrapper does: one that also carries a command or an edit stays a command or an edit. Its approval + is asked the same way as any command's, and names the server, the tool and its arguments. + If a later update shows the call is something else, it goes back to what that update says. +- An approval shows everything known about its call, even when Antigravity's request names only + the call. If an update while you decide shows the approval is for something else, the card is + withdrawn and asked again in the new words; the old card can't be answered. +- A command line longer than 8,000 characters keeps its start; output keeps its end. A cut never + splits a character, and the timeline keeps a long command's start too. +- Screenshots and other inline images in a tool's result are left out of what Threadlines stores. +- Edits show the files they change with their added and removed lines; the turn's diff shows them at + their real line numbers. + +### Attachments + +Images (PNG, JPEG, WebP, BMP) and audio go to Antigravity inline. PDFs go as a link to the saved file, +which Antigravity reads as a document. Text files go as text, in UTF-8, or UTF-16 when the file +starts with its byte order mark; one over 100 KB goes as a path instead, so it doesn't crowd the +conversation. Anything else (a spreadsheet, a video) goes as the saved file's path for the agent to +open with its tools. Images, audio and text each need Antigravity to say it reads that kind; +otherwise the file goes as a path. Antigravity 1.5.15 reads images and embedded text, not audio, so +audio goes as a path today. A PDF link needs nothing: every ACP agent reads links. A MIME +type's parameters (`; charset=utf-8`) don't change the choice. Files are read as they are on disk, +never through a link, up to each kind's limit and 50 MB inline per message. + +### When a turn fails + +Antigravity sometimes ends a turn normally while the reply is really an upstream error. Threadlines +reads the error the CLI reports (1.5.9+) and, where the CLI reports none, the last step of the +turn in the CLI's own session log (`antigravity-acp/conversations/.db` in the profile, a +private format read only for this). The log doesn't say which prompt wrote a step, so an error +counts for the newest prompt when it is the log's last step and was written after that prompt went +out. That never hides the newest prompt's own failure; the cost is that an older prompt's late +error, with nothing written after it, fails a turn whose steer was answered. When the log can't be +read, the prompt's own answer stands (the agent's words about the error stay in its reply). The turn then fails with Google's words and a +Retry. An +exhausted quota fails with its reset time, so the usage-limit notice above the composer says when +it resets and can continue then. A conversation Google can no longer continue (a model rejected a +saved thinking block) stops its session, and the next message starts a new one with the thread's +history, also one sent in the moment the session is stopping. A message whose mode or model couldn't be +set never reaches Antigravity: its turn fails, and the earlier conversation Threadlines had put in +front of it goes with the next message instead. + +### Editing an Earlier Message + +Antigravity can't rewind its own conversation. When you edit an earlier message (or undo back to +one), Threadlines first stops anything Antigravity still runs for the thread (a running turn, its +commands and subagents, by a cancel, then a moment to wind down) and ends that session, so nothing +it ran can write over the files being restored. Then it restores the files. It also drops the +saved conversation from its own record of the thread, so the next message starts a new Antigravity +session and sends it the turns that are left: Antigravity no longer remembers the removed ones, +also when Threadlines restarts before that message. Nothing is started to do this when Antigravity +wasn't running. If Threadlines can't update that record, the thread says Antigravity still +remembers the reverted turns. If Antigravity can't be stopped at all, no file is restored and the +revert fails, saying so. If the files can't be restored after Antigravity was reset, the revert +fails and says both: the files stayed as they were, and Antigravity no longer remembers those +turns. + +### Tokens + +Each turn's tokens come from the CLI's answer to the prompt: input is its input plus cached reads, +and output already includes thinking. They count on the Usage page under Antigravity, priced at +Google's Gemini 4 API rates (an equivalent, not what a Google plan bills). A reply the agent starts +by itself reports no tokens, so it isn't counted. The context meter beside the composer reads the +CLI's context usage updates (1.5.8+). ## Sign-In Methods @@ -24,12 +301,62 @@ starts what the method needs: a Google sign-in for Gemini Enterprise, a key chec key, a check of the project and Google Cloud sign-in for Vertex AI. Switching back to Google account keeps its earlier sign-in, so it needs no new one. +### Signing In With Google + +`Sign in with Google` (and Gemini Enterprise's sign-in) opens Google's sign-in page on the device you +started from: this computer, another one, or your phone. After you approve, Google shows an +Antigravity page with a code. Paste that code (or the page's whole address) into the box Threadlines +shows, and Threadlines hands it to Antigravity on the computer that runs Threadlines. Sign-in then +opens a session to make sure it works. + +The sign-in is kept in that Antigravity account's own profile, not in your computer's keychain, so +each Threadlines account has its own, and your own `agy` in a terminal keeps its sign-in. + +If sign-in fails, the message says why: Antigravity didn't start, it couldn't reach Google (broken +IPv6 is a common cause), Google refused the code, the account needs an eligible plan, or Google +wants you to verify the account first (with a link to Google's page). + Running chats stop when you switch, as with any change to a provider's settings. +### Plan Limits + +An account signed in with Google (Google account or Gemini Enterprise) shows how much of the +Google plan is used: on the Antigravity row in Settings, on the Usage page, in the ring beside the +send button, and on each model in the picker. Google meters groups of models apart, so there is a +row for each: Gemini, each Gemini 4 model that has a limit of its own (such as Gemini 4 Argon), and +Claude & GPT, which share one. Each has a 5-hour and a weekly window with its reset time. Gemini +Enterprise accounts (and accounts Google only reports per model) are metered per model, with no +window length, so each model gets its own row. A group that runs out stops only its own models. +When a limit stops a chat and Antigravity doesn't say when it resets, the reset time comes from +these numbers, so Continue at reset still works. The row also shows the signed-in +Google account's email (blurred until you show it). + +The numbers come from Google, not from Antigravity: Threadlines asks Google's Cloud Code service +(`retrieveUserQuotaSummary`, the call Google's own Antigravity apps make) with the sign-in +Antigravity saved in this account's profile, under Threadlines' own name. Google doesn't publish +this API, so it can change or stop answering; the row then says it couldn't read the limits and +keeps the last numbers. + +When the numbers can be stale: + +- They are read every few minutes, when the provider status refreshes, so a chat's usage shows up + within about five minutes. When one of Google's two hosts doesn't answer, the rows only it gave + stay from the last read, with their age. +- Threadlines never renews the sign-in itself. Antigravity renews it while it runs, so after an + hour or so without a chat the saved sign-in lapses. The last numbers stay, with their age, and a + line says to start a chat to refresh them. +- A Gemini API key or Vertex AI bills per request and has no plan to meter, even if an earlier + Google sign-in is still in the profile. + +Requests go only to `daily-cloudcode-pa.googleapis.com`, `cloudcode-pa.googleapis.com` and, for the +email when the sign-in doesn't carry it, `www.googleapis.com`. Redirects are refused, so the +sign-in can't be carried anywhere else. The code is `apps/server/src/provider/antigravity/AntigravityUsage.ts`. + ### Per-Use Billing -With a Gemini API key or Vertex AI, Google bills every request to you. These requests don't show on -Threadlines' Usage page; check Google AI Studio or the Google Cloud console for spending. +With a Gemini API key or Vertex AI, Google bills every request to you. Threadlines' Usage page counts +the tokens of chats run in Threadlines at Google's list prices, but not what you run elsewhere; +check Google AI Studio or the Google Cloud console for what Google bills. ### Where Keys Are Kept @@ -73,5 +400,6 @@ Google account and another a Gemini API key. ## Signing Out -Google account and Gemini Enterprise have `Sign out` on the Account tab. Key methods have -`Remove key` instead. +Google account and Gemini Enterprise have `Sign out` on the Account tab. It removes the sign-in from +that Antigravity account's profile and nothing else, so your own `agy` stays signed in. Key methods +have `Remove key` instead. diff --git a/packages/contracts/src/provider.ts b/packages/contracts/src/provider.ts index bdf836eee..81c821c4f 100644 --- a/packages/contracts/src/provider.ts +++ b/packages/contracts/src/provider.ts @@ -413,6 +413,30 @@ export const ProviderTurnStartResult = Schema.Struct({ threadId: ThreadId, turnId: TurnId, resumeCursor: Schema.optional(Schema.Unknown), + /** + * The provider was sent only the person's typed text (`typed.text`), as one + * of its own commands, without the context in front of it (`typed.context`) + * or context the driver holds. Nothing that context carried was delivered: + * the caller keeps every debt it paid for the next message. + */ + contextDeferred: Schema.optional(Schema.Literal(true)), + /** + * The prompt that carried this message was never written to the provider: + * its setup (the mode, the model) failed first, or the session ended + * before it went out. Neither the message nor the context in front of it + * was delivered; the driver keeps the context it held for the next + * message, the caller keeps every debt it was to pay, and the turn ends + * failed. Absent: the prompt was written (a driver returns only after it + * was, or after its setup failed). + */ + undelivered: Schema.optional(Schema.Literal(true)), + /** + * The send reopened a runtime that had gone and the provider could not + * reopen its conversation (`resumeFailed`): the message went to a new + * conversation without the thread's history. The caller owes that history + * to its next message, as after any start that couldn't resume. + */ + historyOwed: Schema.optional(Schema.Literal(true)), }); export type ProviderTurnStartResult = typeof ProviderTurnStartResult.Type; diff --git a/packages/contracts/src/providerRuntime.ts b/packages/contracts/src/providerRuntime.ts index c77323735..be6746cfb 100644 --- a/packages/contracts/src/providerRuntime.ts +++ b/packages/contracts/src/providerRuntime.ts @@ -417,6 +417,14 @@ const SessionExitedPayload = Schema.Struct({ resendTurn: Schema.optional( Schema.Struct({ ...ProviderTurnResend.fields, error: TrimmedNonEmptyStringSchema }), ), + /** + * The agent can't go on with this conversation (a model refused its saved + * thinking, say): the server forgets it, so the next start opens a new + * one seeded with the thread's history. Names the session by its start + * time (ProviderSession.createdAt): only a binding that still holds that + * session forgets, so a late exit never touches its replacement. + */ + conversationLost: Schema.optional(Schema.Struct({ sessionCreatedAt: IsoDateTime })), }); export type SessionExitedPayload = typeof SessionExitedPayload.Type; diff --git a/packages/contracts/src/server.ts b/packages/contracts/src/server.ts index df5cc8fe1..008d3df5b 100644 --- a/packages/contracts/src/server.ts +++ b/packages/contracts/src/server.ts @@ -160,6 +160,13 @@ export const ServerProviderAuth = Schema.Struct({ label: Schema.optional(TrimmedNonEmptyString), email: Schema.optional(TrimmedNonEmptyString), usageEmail: Schema.optional(TrimmedNonEmptyString), + /** + * An opaque name for the signed-in account, for a provider that can't + * always say its email (Antigravity). Two snapshots with different ones + * belong to different accounts, so one's usage never carries over to the + * other. Never shown. + */ + accountId: Schema.optional(TrimmedNonEmptyString), capabilities: Schema.optional(ServerProviderAuthCapabilities), signInEnds: Schema.optional(ServerProviderSignInEnds), /** The workspaces this sign-in can switch between (the `switch-workspace` sign-in flow). */ @@ -198,6 +205,19 @@ export const ServerProviderScopedUsageWindow = Schema.Struct({ // Provider-reported severity (e.g. "normal" | "warning"); anything other // than "normal" should surface ambient warning affordances. severity: Schema.optional(TrimmedNonEmptyString), + /** + * The models this window holds, for a limit that covers a family of models + * (Antigravity's "Claude & GPT" pool): a model whose name has one of these + * as whole words. Absent: a model whose name has `scopeLabel` (Claude's + * per-model limits). + */ + scopeModels: Schema.optional(Schema.Array(TrimmedNonEmptyString)), + /** + * Models left out even when `scopeModels` holds them, by the same rule: + * those with a window of their own (Antigravity's Gemini 4 Argon beside + * the default Gemini pool). + */ + scopeExcludes: Schema.optional(Schema.Array(TrimmedNonEmptyString)), /** When this window was last read from the provider; see `ServerProviderUsageWindow`. */ checkedAt: Schema.optional(IsoDateTime), }); @@ -296,6 +316,13 @@ export const ServerProviderAccountTokenUsage = Schema.Struct({ export type ServerProviderAccountTokenUsage = typeof ServerProviderAccountTokenUsage.Type; export const ServerProviderAccountUsage = Schema.Struct({ + /** + * Which kind of reading it is. Closed on the wire: a client from before a + * new value rejects it, and with it the whole server config. Add no value; + * a new provider reports under one whose handling suits it and names its + * reading in its limit's `limitName` (Antigravity: `grok-billing`, which + * clients handle by its label alone). Tell providers apart by `driver`. + */ source: Schema.Literals([ "codex-rate-limits", "claude-oauth-usage", @@ -363,6 +390,13 @@ export const ServerProviderSlashCommand = Schema.Struct({ }); export type ServerProviderSlashCommand = typeof ServerProviderSlashCommand.Type; +export const ServerProviderSessionCommands = Schema.Struct({ + /** Session keys: a thread id, or a room agent's `participantSessionKey`. */ + sessions: Schema.Array(TrimmedNonEmptyString), + commands: Schema.Array(ServerProviderSlashCommand), +}); +export type ServerProviderSessionCommands = typeof ServerProviderSessionCommands.Type; + export const ServerProviderSkill = Schema.Struct({ name: TrimmedNonEmptyString, description: Schema.optional(TrimmedNonEmptyString), @@ -541,6 +575,22 @@ export const ServerProvider = Schema.Struct({ Schema.withDecodingDefault(Effect.succeed([])), ), skills: Schema.Array(ServerProviderSkill).pipe(Schema.withDecodingDefault(Effect.succeed([]))), + /** + * The agent runs a skill when a message starts with `/` + * (Antigravity), so the composer lists `skills` in its `/` list and inserts + * them that way; a running session's own list (OrchestrationThread.agentCommands) + * joins them. Absent: skills go the provider's usual way. + */ + slashSkills: Schema.optionalKey(Schema.Boolean), + /** + * Live state, never history: the slash commands this instance's running + * sessions listed (ACP `available_commands_update`), each list once with + * the sessions that listed it. A session's entry goes when the session + * ends, and none survive a restart; until a session lists its own, the + * composer offers `slashCommands` and `skills`. Capped and cleaned on the + * server (`@threadlines/shared/slashCommands`). + */ + sessionCommands: Schema.optionalKey(Schema.Array(ServerProviderSessionCommands)), versionAdvisory: Schema.optionalKey(ServerProviderVersionAdvisory), updateState: Schema.optionalKey(ServerProviderUpdateState), detection: Schema.optionalKey(ServerProviderDetection), diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index 48151b22c..4b2c5b77d 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -670,7 +670,7 @@ export const AntigravitySettings = makeProviderSettingsSchema( Schema.annotateKey({ title: "Binary path", description: - "Leave empty to use the Antigravity runtime Threadlines installs. Set it to run your own agy_acp_server.", + "Leave empty to use the Antigravity CLI Threadlines installs. Set it to run your own `agy` (1.5.14 or newer).", providerSettingsForm: { placeholder: "Managed by Threadlines", clearWhenEmpty: "omit" }, }), ), diff --git a/packages/contracts/src/usage.ts b/packages/contracts/src/usage.ts index 492ed1bf2..740b7fe7f 100644 --- a/packages/contracts/src/usage.ts +++ b/packages/contracts/src/usage.ts @@ -40,6 +40,7 @@ export const UsageProviderKind = Schema.Literals([ "muse", "opencode", "fx", + "antigravity", ]); export type UsageProviderKind = typeof UsageProviderKind.Type; diff --git a/packages/effect-acp/src/client.ts b/packages/effect-acp/src/client.ts index 1a4043154..cfb5cf045 100644 --- a/packages/effect-acp/src/client.ts +++ b/packages/effect-acp/src/client.ts @@ -37,6 +37,8 @@ export interface AcpClientOptions { type AcpClientRaw = { readonly notifications: Stream.Stream; readonly request: (method: string, payload: unknown) => Effect.Effect; + /** A request whose answer keeps its place among the notifications (`AcpPatchedProtocol.requestInOrder`). */ + readonly requestInOrder: AcpProtocol.AcpPatchedProtocol["requestInOrder"]; readonly notify: (method: string, payload: unknown) => Effect.Effect; }; @@ -466,6 +468,7 @@ export const make = Effect.fn("effect-acp/AcpClient.make")(function* ( raw: { notifications: transport.incoming, request: transport.request, + requestInOrder: transport.requestInOrder, notify: transport.notify, }, agent: { diff --git a/packages/effect-acp/src/protocol.test.ts b/packages/effect-acp/src/protocol.test.ts index 0d0f448c3..b3de75f18 100644 --- a/packages/effect-acp/src/protocol.test.ts +++ b/packages/effect-acp/src/protocol.test.ts @@ -1,5 +1,6 @@ import * as Path from "effect/Path"; import * as AcpError from "./errors.ts"; +import * as Cause from "effect/Cause"; import * as Effect from "effect/Effect"; import * as Deferred from "effect/Deferred"; import * as Fiber from "effect/Fiber"; @@ -7,6 +8,8 @@ import * as Queue from "effect/Queue"; import * as Schema from "effect/Schema"; import * as Stream from "effect/Stream"; import * as Ref from "effect/Ref"; +import * as Sink from "effect/Sink"; +import * as Stdio from "effect/Stdio"; import { ChildProcess, ChildProcessSpawner } from "effect/process"; import { it, assert } from "@effect/vitest"; @@ -228,6 +231,126 @@ it.layer(NodeServices.layer)("effect-acp protocol", (it) => { }), ); + it.effect("hands an in-order request's answer over where it was read among the updates", () => + Effect.gen(function* () { + const { stdio, input, output } = yield* makeInMemoryStdio(); + const seen: Array = []; + const transport = yield* AcpProtocol.makeAcpPatchedProtocol({ + stdio, + serverRequestMethods: new Set(), + onNotification: () => Effect.sync(() => void seen.push("update")), + }); + const update = yield* encodeJsonl(SessionUpdateNotification, { + jsonrpc: "2.0", + method: "session/update", + params: { sessionId: "session-1", update: { sessionUpdate: "plan", entries: [] } }, + }); + const answered = yield* Deferred.make(); + yield* transport.requestInOrder("x/test", { hello: "world" }, (answer) => + Effect.sync(() => { + seen.push(answer._tag === "Success" ? "answer" : "failure"); + }).pipe(Effect.andThen(Deferred.succeed(answered, undefined))), + ); + // Returns once the request is out, before any answer. + assert.deepEqual((yield* decodeExtRequest(yield* Queue.take(output))).id, 1); + assert.deepEqual(seen, []); + // An update, the answer, and an update the agent wrote right after it. + yield* Queue.offer(input, update); + yield* Queue.offer( + input, + yield* encodeJsonl(ExtResponse, { jsonrpc: "2.0", id: 1, result: { ok: true } }), + ); + yield* Queue.offer(input, update); + yield* Deferred.await(answered); + for (let attempt = 0; attempt < 100 && seen.length < 3; attempt += 1) yield* Effect.yieldNow; + assert.deepEqual(seen, ["update", "answer", "update"]); + }), + ); + + it.effect("counts an in-order request sent only once the agent's stdin took it", () => + Effect.gen(function* () { + // The agent's stdin takes nothing until `gate` opens, then fails (it + // closed its end). + const gate = yield* Deferred.make(); + const reached = yield* Deferred.make(); + const input = yield* Queue.unbounded>(); + const stdio = Stdio.make({ + args: Effect.succeed([]), + stdin: Stream.fromQueue(input), + stdout: () => + Sink.forEach(() => + Deferred.succeed(reached, undefined).pipe( + Effect.andThen(Deferred.await(gate)), + Effect.andThen(Effect.die(new Error("EPIPE: the agent closed its stdin"))), + ), + ), + stderr: () => Sink.drain, + }); + const transport = yield* AcpProtocol.makeAcpPatchedProtocol({ + stdio, + serverRequestMethods: new Set(), + }); + const answers: Array = []; + const sending = yield* transport + .requestInOrder("x/test", { hello: "world" }, (answer) => + Effect.sync(() => void answers.push(answer._tag)), + ) + .pipe(Effect.exit, Effect.forkScoped); + yield* Deferred.await(reached); + for (let tick = 0; tick < 20; tick += 1) yield* Effect.yieldNow; + // Queued and handed to the sink, but not taken: not sent yet. + assert.isUndefined(sending.pollUnsafe()); + yield* Deferred.succeed(gate, undefined); + const exit = yield* Fiber.join(sending); + assert.isTrue(exit._tag === "Failure"); + // Never written, so never answered either. + assert.deepEqual(answers, []); + }), + ); + + it.effect("never answers or queues a request once the agent's output has ended", () => + Effect.gen(function* () { + // The agent's stdin takes nothing and never fails; its stdout ends + // while a request waits to be written. + const reached = yield* Deferred.make(); + const input = yield* Queue.unbounded>(); + const stdio = Stdio.make({ + args: Effect.succeed([]), + stdin: Stream.fromQueue(input), + stdout: () => + Sink.forEach(() => + Deferred.succeed(reached, undefined).pipe(Effect.andThen(Effect.never)), + ), + stderr: () => Sink.drain, + }); + const transport = yield* AcpProtocol.makeAcpPatchedProtocol({ + stdio, + serverRequestMethods: new Set(), + }); + const answers: Array = []; + const note = (answer: { readonly _tag: string }) => + Effect.sync(() => void answers.push(answer._tag)); + const first = yield* transport + .requestInOrder("x/test", { n: 1 }, note) + .pipe(Effect.exit, Effect.forkScoped); + yield* Deferred.await(reached); + // A second request queues behind the frame the sink holds. + const second = yield* transport + .requestInOrder("x/test", { n: 2 }, note) + .pipe(Effect.exit, Effect.forkScoped); + for (let tick = 0; tick < 20; tick += 1) yield* Effect.yieldNow; + yield* Queue.end(input); + // Neither was written: both fail, and neither is reported answered. + assert.isTrue((yield* Fiber.join(first))._tag === "Failure"); + assert.isTrue((yield* Fiber.join(second))._tag === "Failure"); + assert.deepEqual(answers, []); + // A request made afterwards fails at once instead of waiting forever. + const late = yield* transport.requestInOrder("x/test", { n: 3 }, note).pipe(Effect.exit); + assert.isTrue(late._tag === "Failure"); + assert.deepEqual(answers, []); + }), + ); + it.effect("keeps reading the agent while an extension request waits for its answer", () => Effect.gen(function* () { const { stdio, input, output } = yield* makeInMemoryStdio(); diff --git a/packages/effect-acp/src/protocol.ts b/packages/effect-acp/src/protocol.ts index bc237efbf..3a1ae1fd2 100644 --- a/packages/effect-acp/src/protocol.ts +++ b/packages/effect-acp/src/protocol.ts @@ -65,6 +65,20 @@ export interface AcpPatchedProtocol { readonly serverProtocol: RpcServer.Protocol["Service"]; readonly incoming: Stream.Stream; readonly request: (method: string, payload: unknown) => Effect.Effect; + /** + * Sends a request and returns once the agent's stdin took it (frames go + * out in the order they were sent). A request that can't be written + * fails here, and `onAnswer` never runs. Its answer goes to `onAnswer`, + * which runs on the reader as the response is read, before any message + * that follows it is handled (notifications run there too), so the answer + * keeps its place among them. If the connection ends first, `onAnswer` + * gets that failure. + */ + readonly requestInOrder: ( + method: string, + payload: unknown, + onAnswer: (answer: Exit.Exit) => Effect.Effect, + ) => Effect.Effect; readonly notify: (method: string, payload: unknown) => Effect.Effect; } @@ -93,12 +107,51 @@ export const makeAcpPatchedProtocol = Effect.fn("makeAcpPatchedProtocol")(functi const clientQueue = yield* Queue.unbounded(); const notificationQueue = yield* Queue.unbounded(); const disconnects = yield* Queue.unbounded(); - const outgoing = yield* Queue.unbounded>(); + const outgoing = yield* Queue.unbounded>(); const nextRequestId = yield* Ref.make(1); const terminationHandled = yield* Ref.make(false); const extPending = yield* Ref.make( new Map>(), ); + /** `requestInOrder`'s requests, answered on the reader. */ + const orderedPending = yield* Ref.make( + new Map< + string | number, + (answer: Exit.Exit) => Effect.Effect + >(), + ); + const takeOrderedPending = (requestId: string | number) => + Ref.modify(orderedPending, (pending) => { + const onAnswer = pending.get(requestId); + if (onAnswer === undefined) return [undefined, pending] as const; + const next = new Map(pending); + next.delete(requestId); + return [onAnswer, next] as const; + }); + + // The frame the writer holds and has not seen taken by the agent's stdin, + // and, once the pipe to the agent is gone either way, why nothing more + // can be sent. + let handedOver: OutgoingFrame | undefined; + let pipeDown: AcpError.AcpError | undefined; + /** + * Fails every frame the agent's stdin has not taken, with the in-order + * requests they carried: a request never written was never sent, so it is + * never answered either (its `onAnswer` hears nothing). + */ + const failUnwrittenFrames = (error: AcpError.AcpError) => + Effect.gen(function* () { + pipeDown ??= error; + const unwritten = [ + ...(handedOver === undefined ? [] : [handedOver]), + ...(yield* Queue.clear(outgoing).pipe(Effect.orElseSucceed(() => []))), + ]; + handedOver = undefined; + for (const frame of unwritten) { + if (frame.requestId !== undefined) yield* takeOrderedPending(frame.requestId); + if (frame.written !== undefined) yield* Deferred.fail(frame.written, error); + } + }); const logProtocol = (event: AcpProtocolLogEvent) => { if (event.direction === "incoming" && !options.logIncoming) { @@ -115,6 +168,8 @@ export const makeAcpPatchedProtocol = Effect.fn("makeAcpPatchedProtocol")(functi const offerOutgoing = Effect.fn("offerOutgoing")(function* ( message: RpcMessage.FromClientEncoded | RpcMessage.FromServerEncoded, + written?: Deferred.Deferred, + requestId?: string | number, ) { // The RPC client's own control messages (an interrupted request, a stream // ack) would go out as `@effect/rpc/*` methods no ACP agent knows. @@ -141,7 +196,11 @@ export const makeAcpPatchedProtocol = Effect.fn("makeAcpPatchedProtocol")(functi payload: typeof encoded === "string" ? encoded : new TextDecoder().decode(encoded), }); - yield* Queue.offer(outgoing, encoded).pipe(Effect.asVoid); + // Nothing queues behind a pipe that is gone: it would wait forever. + if (pipeDown !== undefined) return yield* Effect.fail(pipeDown); + yield* Queue.offer(outgoing, { data: encoded, written, requestId }).pipe(Effect.asVoid); + } else if (written !== undefined) { + yield* Deferred.succeed(written, undefined); } }); @@ -175,14 +234,13 @@ export const makeAcpPatchedProtocol = Effect.fn("makeAcpPatchedProtocol")(functi const completeExtPendingSuccess = (requestId: string | number, value: unknown) => resolveExtPending(requestId, (deferred) => Deferred.succeed(deferred, value)); - const failAllExtPending = (error: AcpError.AcpError) => - Ref.getAndSet(extPending, new Map()).pipe( - Effect.flatMap((pending) => - Effect.forEach([...pending.values()], (deferred) => Deferred.fail(deferred, error), { - discard: true, - }), - ), - ); + const failAllExtPending = (error: AcpError.AcpError): Effect.Effect => + Effect.gen(function* () { + const pending = yield* Ref.getAndSet(extPending, new Map()); + for (const deferred of pending.values()) yield* Deferred.fail(deferred, error); + const ordered = yield* Ref.getAndSet(orderedPending, new Map()); + for (const onAnswer of ordered.values()) yield* onAnswer(Exit.fail(error)); + }); const dispatchNotification = (notification: AcpIncomingNotification) => Queue.offer(notificationQueue, notification).pipe( @@ -217,6 +275,9 @@ export const makeAcpPatchedProtocol = Effect.fn("makeAcpPatchedProtocol")(functi if (!error) { return; } + // The agent can answer nothing more: what its stdin has not taken + // was never sent, and is not reported as answered. + yield* failUnwrittenFrames(error); yield* failAllExtPending(error); yield* emitClientProtocolError(error); if (options.onTermination) { @@ -327,9 +388,17 @@ export const makeAcpPatchedProtocol = Effect.fn("makeAcpPatchedProtocol")(functi return Queue.offer(serverQueue, message).pipe(Effect.asVoid); }; - const handleExitEncoded = (received: RpcMessage.ResponseExitEncoded) => { + const handleExitEncoded = (received: RpcMessage.ResponseExitEncoded): Effect.Effect => { const message = asRequestFailure(received); - return Ref.get(extPending).pipe( + return takeOrderedPending(message.requestId).pipe( + Effect.flatMap((onAnswer) => + onAnswer === undefined ? routeExit(message) : onAnswer(responseExit(message)), + ), + ); + }; + + const routeExit = (message: RpcMessage.ResponseExitEncoded): Effect.Effect => + Ref.get(extPending).pipe( Effect.flatMap((pending) => { if (!pending.has(message.requestId)) { return Queue.offer(clientQueue, message).pipe(Effect.asVoid); @@ -350,7 +419,6 @@ export const makeAcpPatchedProtocol = Effect.fn("makeAcpPatchedProtocol")(functi ); }), ); - }; const routeDecodedMessage = ( message: RpcMessage.FromClientEncoded | RpcMessage.FromServerEncoded, @@ -454,7 +522,35 @@ export const makeAcpPatchedProtocol = Effect.fn("makeAcpPatchedProtocol")(functi Effect.forkScoped, ); - yield* Stream.fromQueue(outgoing).pipe(Stream.run(options.stdio.stdout()), Effect.forkScoped); + // The writer. The sink asks for the next frame only once `write()` took + // the last one without an error it reports at once (a closed pipe makes + // it return false, and the sink waits, then fails): that is when the last + // frame counts as handed to the agent. When the writer stops, every frame + // not handed over fails, and so does every request it carried: none is + // left waiting on a write that can no longer happen. + const nextFrame = Effect.gen(function* () { + const last = handedOver; + handedOver = undefined; + if (last?.written !== undefined) yield* Deferred.succeed(last.written, undefined); + const next = yield* Queue.take(outgoing); + handedOver = next; + return next.data; + }); + const failUnwritten = (cause: Cause.Cause) => + Effect.gen(function* () { + const error = new AcpError.AcpTransportError({ + detail: "Failed to write to the ACP agent", + cause: Cause.squash(cause), + }); + yield* failUnwrittenFrames(error); + // Requests written earlier can no longer be answered over this pipe. + yield* failAllExtPending(error); + }); + yield* Stream.fromEffectRepeat(nextFrame).pipe( + Stream.run(options.stdio.stdout()), + Effect.onExit((exit) => (Exit.isSuccess(exit) ? Effect.void : failUnwritten(exit.cause))), + Effect.forkScoped, + ); const clientProtocol = RpcClient.Protocol.of({ run: (_clientId, f) => @@ -507,7 +603,7 @@ export const makeAcpPatchedProtocol = Effect.fn("makeAcpPatchedProtocol")(functi } const encoded = `${exit.value}\n`; yield* logProtocol({ direction: "outgoing", stage: "raw", payload: encoded }); - yield* Queue.offer(outgoing, encoded).pipe(Effect.asVoid); + yield* Queue.offer(outgoing, { data: encoded }).pipe(Effect.asVoid); }); const sendRequest = Effect.fn("sendRequest")(function* (method: string, payload: unknown) { @@ -531,6 +627,31 @@ export const makeAcpPatchedProtocol = Effect.fn("makeAcpPatchedProtocol")(functi ); }); + const sendRequestInOrder = Effect.fn("sendRequestInOrder")(function* ( + method: string, + payload: unknown, + onAnswer: (answer: Exit.Exit) => Effect.Effect, + ) { + const requestId = yield* Ref.modify( + nextRequestId, + (current) => [current, current + 1] as const, + ); + yield* Ref.update(orderedPending, (pending) => new Map(pending).set(requestId, onAnswer)); + const written = yield* Deferred.make(); + // Returns once the agent's stdin took it; a request never written was + // never sent, so it fails here and `onAnswer` hears nothing. + yield* offerOutgoing( + { _tag: "Request", id: requestId, tag: method, payload, headers: [] }, + written, + requestId, + ).pipe( + Effect.andThen(Deferred.await(written)), + Effect.catch((error) => + takeOrderedPending(requestId).pipe(Effect.andThen(Effect.fail(error))), + ), + ); + }); + return { clientProtocol, serverProtocol, @@ -538,6 +659,7 @@ export const makeAcpPatchedProtocol = Effect.fn("makeAcpPatchedProtocol")(functi return Stream.fromQueue(notificationQueue); }, request: sendRequest, + requestInOrder: sendRequestInOrder, notify: sendNotification, } satisfies AcpPatchedProtocol; }); @@ -571,6 +693,27 @@ function asRequestFailure(message: RpcMessage.ResponseExitEncoded): RpcMessage.R }; } +/** A frame on its way to the agent, and who hears once the agent's stdin took it. */ +interface OutgoingFrame { + readonly data: string | Uint8Array; + readonly written?: Deferred.Deferred | undefined; + /** An in-order request's id: never written, it is never answered either. */ + readonly requestId?: string | number | undefined; +} + +/** A response as its caller sees it: the value, or the request's failure. */ +function responseExit( + message: RpcMessage.ResponseExitEncoded, +): Exit.Exit { + if (message.exit._tag === "Success") return Exit.succeed(message.exit.value); + const failure = message.exit.cause.find((entry) => entry._tag === "Fail"); + return Exit.fail( + failure && isProtocolError(failure.error) + ? AcpError.AcpRequestError.fromProtocolError(failure.error) + : AcpError.AcpRequestError.internalError("Request failed"), + ); +} + function isProtocolError( value: unknown, ): value is { code: number; message: string; data?: unknown } { diff --git a/packages/shared/package.json b/packages/shared/package.json index f058d722b..a8994ce79 100644 --- a/packages/shared/package.json +++ b/packages/shared/package.json @@ -239,6 +239,10 @@ "types": "./src/queuedFollowUps.ts", "import": "./src/queuedFollowUps.ts" }, + "./slashCommands": { + "types": "./src/slashCommands.ts", + "import": "./src/slashCommands.ts" + }, "./checkBacks": { "types": "./src/checkBacks.ts", "import": "./src/checkBacks.ts" diff --git a/packages/shared/src/slashCommands.test.ts b/packages/shared/src/slashCommands.test.ts new file mode 100644 index 000000000..3c4e508f6 --- /dev/null +++ b/packages/shared/src/slashCommands.test.ts @@ -0,0 +1,52 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { + cleanSlashCommands, + SLASH_COMMAND_DESCRIPTION_MAX, + SLASH_COMMANDS_MAX, + slashCommandAtStart, +} from "./slashCommands.ts"; + +describe("cleanSlashCommands", () => { + it("keeps only names a message can start with, each once", () => { + expect( + cleanSlashCommands([ + { name: "/compact", description: " Summarize " }, + { name: "compact", description: "again" }, + { name: "foo/bar" }, + { name: "two words" }, + { name: "rtl‮evil" }, + { name: "skill:review", input: { hint: "what" } }, + ]), + ).toEqual([ + { name: "compact", description: "Summarize" }, + { name: "skill:review", input: { hint: "what" } }, + ]); + }); + + it("caps the count and the text without splitting a character, and drops control characters", () => { + const many = Array.from({ length: SLASH_COMMANDS_MAX + 50 }, (_, index) => ({ + name: `c${index}`, + })); + expect(cleanSlashCommands(many)).toHaveLength(SLASH_COMMANDS_MAX); + const [long] = cleanSlashCommands([ + { name: "long", description: `a‮${"😀".repeat(SLASH_COMMAND_DESCRIPTION_MAX)}` }, + ]); + const kept = Array.from(long?.description ?? ""); + expect(kept).toHaveLength(SLASH_COMMAND_DESCRIPTION_MAX); + expect(kept[0]).toBe("a"); + expect(kept.at(-1)).toBe("…"); + expect(long?.description).not.toContain("‮"); + expect(long?.description?.includes("�")).toBe(false); + }); +}); + +describe("slashCommandAtStart", () => { + it("reads a command only at the very start, never a path", () => { + expect(slashCommandAtStart("/compact")).toBe("compact"); + expect(slashCommandAtStart("/review the diff")).toBe("review"); + expect(slashCommandAtStart(" /compact")).toBeUndefined(); + expect(slashCommandAtStart("/tmp/out.log is empty")).toBeUndefined(); + expect(slashCommandAtStart("see /compact")).toBeUndefined(); + }); +}); diff --git a/packages/shared/src/slashCommands.ts b/packages/shared/src/slashCommands.ts new file mode 100644 index 000000000..2f1d4a697 --- /dev/null +++ b/packages/shared/src/slashCommands.ts @@ -0,0 +1,91 @@ +import type { ServerProviderSlashCommand } from "@threadlines/contracts"; + +/** + * Rules for the slash commands an agent advertises (ACP + * `available_commands_update`) and for telling a message that runs one. + * An agent's list is untrusted input that reaches every client, so it is + * capped and cleaned before anything stores or sends it. + */ + +/** The most commands kept from one list; the rest are dropped. */ +export const SLASH_COMMANDS_MAX = 200; +/** Longest description and input hint kept, in characters (code points). */ +export const SLASH_COMMAND_DESCRIPTION_MAX = 300; +export const SLASH_COMMAND_HINT_MAX = 120; + +/** + * A name a message can start with: a letter, digit or `_`, then up to 63 of + * those or `.`, `:` and `-`. No `/` (a path is not a command), no spaces, no + * invisible or direction-changing characters. + */ +const SLASH_COMMAND_NAME = /^[\p{L}\p{N}_][\p{L}\p{N}_.:-]{0,63}$/u; + +export function isSlashCommandName(name: string): boolean { + return SLASH_COMMAND_NAME.test(name); +} + +/** + * The command a message starts with: `/` then a name, then whitespace or + * the end. `undefined` for anything else, a leading space or a path + * (`/tmp/out.log`) included. + */ +export function slashCommandAtStart(text: string): string | undefined { + const match = /^\/([^\s/]+)(?=\s|$)/u.exec(text); + const name = match?.[1]; + return name !== undefined && isSlashCommandName(name) ? name : undefined; +} + +/** Drops control and format characters (bidi overrides among them) and caps the length without splitting a character. */ +function cleanText(text: string, max: number): string | undefined { + const cleaned = Array.from(text.replace(/[\p{Cc}\p{Cf}]/gu, " ").trim()); + if (cleaned.length === 0) return undefined; + return cleaned.length > max ? `${cleaned.slice(0, max - 1).join("")}…` : cleaned.join(""); +} + +/** + * An advertised list in the composer's terms: names without a leading `/`, + * each once (the first wins), only valid names, capped in count and length. + */ +export function cleanSlashCommands( + commands: ReadonlyArray<{ + readonly name: string; + readonly description?: string | null | undefined; + readonly input?: { readonly hint: string } | null | undefined; + }>, +): ReadonlyArray { + const seen = new Set(); + const cleaned: Array = []; + for (const command of commands) { + if (cleaned.length >= SLASH_COMMANDS_MAX) break; + const name = command.name.trim().replace(/^\//u, ""); + if (!isSlashCommandName(name) || seen.has(name)) continue; + seen.add(name); + const description = cleanText(command.description ?? "", SLASH_COMMAND_DESCRIPTION_MAX); + const hint = cleanText(command.input?.hint ?? "", SLASH_COMMAND_HINT_MAX); + cleaned.push({ + name, + ...(description ? { description } : {}), + ...(hint ? { input: { hint } } : {}), + }); + } + return cleaned; +} + +/** Whether two command lists say the same thing, in the same order. */ +export function sameSlashCommands( + left: ReadonlyArray, + right: ReadonlyArray, +): boolean { + return ( + left.length === right.length && + left.every((command, index) => { + const other = right[index]; + return ( + other !== undefined && + command.name === other.name && + command.description === other.description && + command.input?.hint === other.input?.hint + ); + }) + ); +} diff --git a/packages/shared/src/usageLimits.test.ts b/packages/shared/src/usageLimits.test.ts index d3ea80b62..af1e50233 100644 --- a/packages/shared/src/usageLimits.test.ts +++ b/packages/shared/src/usageLimits.test.ts @@ -1,7 +1,11 @@ import type { ServerProviderAccountUsage } from "@threadlines/contracts"; import { describe, expect, it } from "vite-plus/test"; -import { isAccountUsageNearLimit } from "./usageLimits.ts"; +import { + isAccountUsageNearLimit, + usageLimitForModel, + usageScopeHoldsModel, +} from "./usageLimits.ts"; const NOW_MS = Date.parse("2026-11-06T12:00:00.000Z"); const reading = ( @@ -42,3 +46,58 @@ describe("isAccountUsageNearLimit", () => { expect(isAccountUsageNearLimit(undefined, NOW_MS, 90)).toBe(false); }); }); + +describe("Antigravity's family limits", () => { + const gemini = { name: "Gemini", models: ["Gemini"], excludes: ["Argon"] }; + const shared = { name: "Claude & GPT", models: ["Claude", "GPT"] }; + + it("hold the models of their family and leave out those with a pool of their own", () => { + expect(usageScopeHoldsModel(gemini, "Gemini 3.1 Pro")).toBe(true); + expect(usageScopeHoldsModel(gemini, "Gemini 4 Argon")).toBe(false); + expect( + usageScopeHoldsModel({ name: "Gemini 4 Argon", models: ["Argon"] }, "Gemini 4 Argon"), + ).toBe(true); + expect(usageScopeHoldsModel(shared, "Claude Sonnet 5.5")).toBe(true); + expect(usageScopeHoldsModel(shared, "GPT-OSS 120B")).toBe(true); + expect(usageScopeHoldsModel(shared, "Gemini 3.1 Pro")).toBe(false); + // A model's own limit (Claude's) still matches its name as whole words. + expect(usageScopeHoldsModel({ name: "Opus 5" }, "Claude Opus 5.5")).toBe(false); + expect(usageScopeHoldsModel({ name: "Fable" }, "Claude Fable 5.2")).toBe(true); + }); + + it("stop a model only on its own family's spent window", () => { + const resetsAt = NOW_MS + 3_600_000; + const usage: ServerProviderAccountUsage = { + source: "grok-billing", + checkedAt: "2026-11-06T11:59:00.000Z", + limits: [ + { + limitId: "antigravity", + scoped: [ + { + scopeLabel: "Gemini", + scopeModels: ["Gemini"], + usedPercent: 40, + remainingPercent: 60, + }, + { + scopeLabel: "Claude & GPT", + scopeModels: ["Claude", "GPT"], + usedPercent: 100, + remainingPercent: 0, + resetsAt, + windowDurationMins: 300, + }, + ], + }, + ], + }; + expect(usageLimitForModel(usage, "Claude Opus 5.5", NOW_MS)).toEqual({ + window: "session", + resetsAt: new Date(resetsAt).toISOString(), + }); + expect(usageLimitForModel(usage, "Gemini 3.1 Pro", NOW_MS)).toBeUndefined(); + // Past its reset, the reading is older than the window. + expect(usageLimitForModel(usage, "Claude Opus 5.5", resetsAt + 1)).toBeUndefined(); + }); +}); diff --git a/packages/shared/src/usageLimits.ts b/packages/shared/src/usageLimits.ts index e21e52689..2f1927fc6 100644 --- a/packages/shared/src/usageLimits.ts +++ b/packages/shared/src/usageLimits.ts @@ -147,6 +147,12 @@ export interface ProviderUsageWindowReading { readonly resetsAtMs: number | undefined; /** When this window was last read: a reading can carry a window over from an earlier one. */ readonly readAtMs: number; + /** + * For a window that covers one family of models (`scopeModels`, Antigravity), + * the family: a spent one stops only threads on that family's models. + * Undefined for every other window. + */ + readonly family?: string; } /** @@ -174,6 +180,7 @@ export function listProviderUsageWindows( ServerProviderUsageWindow, "usedPercent" | "remainingPercent" | "resetsAt" | "checkedAt" >, + family?: string, ) => { const resetsAtMs = usageResetTimeMs(window.resetsAt); const readAtMs = Date.parse(window.checkedAt ?? accountUsage.checkedAt); @@ -182,6 +189,7 @@ export function listProviderUsageWindows( spent: isUsedUpTo(window, 100) && (resetsAtMs === undefined || resetsAtMs > nowMs), resetsAtMs, readAtMs: Number.isFinite(readAtMs) ? readAtMs : 0, + ...(family !== undefined ? { family } : {}), }); }; accountUsage.limits.forEach((limit, index) => { @@ -190,7 +198,11 @@ export function listProviderUsageWindows( if (limit.secondary) add(`${limitKey}:secondary`, limit.secondary); // One label can name a model's session, daily and weekly windows at once. for (const scoped of limit.scoped ?? []) { - add(`${limitKey}:scoped:${scoped.scopeLabel}:${scoped.windowDurationMins ?? ""}`, scoped); + add( + `${limitKey}:scoped:${scoped.scopeLabel}:${scoped.windowDurationMins ?? ""}`, + scoped, + scoped.scopeModels !== undefined ? scoped.scopeLabel : undefined, + ); } }); return windows; @@ -212,3 +224,71 @@ export function usageLimitFromAccountUsage( resetsAt: new Date(block.resetsAtMs).toISOString(), }; } + +/** What a model-scoped window covers: its name, and for a family limit the names it holds and leaves out. */ +export interface UsageScope { + readonly name: string; + readonly models?: ReadonlyArray | undefined; + readonly excludes?: ReadonlyArray | undefined; +} + +const nameWords = (name: string) => name.toLowerCase().split(/\s+/).filter(Boolean); +/** Family names also split at hyphens and slashes, so "GPT" holds "GPT-OSS 120B". */ +const familyWords = (name: string) => + name + .toLowerCase() + .split(/[^\p{L}\p{N}.]+/u) + .filter(Boolean); + +const holdsWords = (model: ReadonlyArray, words: ReadonlyArray) => + words.length > 0 && + model.some((_, start) => words.every((word, offset) => model[start + offset] === word)); + +/** + * Whether a model-scoped window holds the model named `modelName`. Providers + * name such a limit, not the model's id, so it matches whole words: "Fable" + * holds "Claude Fable 5.2" but "Opus 5" doesn't hold "Opus 5.5". A family + * limit (`models`) holds a model with any of its names and none of its + * `excludes`. + */ +export function usageScopeHoldsModel(scope: UsageScope, modelName: string): boolean { + if (scope.models === undefined) return holdsWords(nameWords(modelName), nameWords(scope.name)); + const model = familyWords(modelName); + return ( + scope.models.some((name) => holdsWords(model, familyWords(name))) && + !(scope.excludes ?? []).some((name) => holdsWords(model, familyWords(name))) + ); +} + +/** + * `usageLimitFromAccountUsage` for one model: also the model's own windows + * (`scoped` ones that hold it), for providers whose limits each cover a family + * of models (Antigravity). The latest reset among the spent windows wins. + */ +export function usageLimitForModel( + accountUsage: ServerProviderAccountUsage | undefined, + modelName: string, + nowMs: number, +): RuntimeUsageLimit | undefined { + const planWide = usageLimitFromAccountUsage(accountUsage, nowMs); + if (planWide !== undefined || accountUsage === undefined) return planWide; + let latest: { resetsAtMs: number; minutes: number | undefined } | undefined; + for (const limit of accountUsage.limits) { + for (const window of limit.scoped ?? []) { + const scope = { + name: window.scopeLabel, + models: window.scopeModels, + excludes: window.scopeExcludes, + }; + if (!isUsedUpTo(window, 100) || !usageScopeHoldsModel(scope, modelName)) continue; + const resetsAtMs = usageResetTimeMs(window.resetsAt); + if (resetsAtMs === undefined || resetsAtMs <= nowMs) continue; + if (latest === undefined || resetsAtMs > latest.resetsAtMs) { + latest = { resetsAtMs, minutes: window.windowDurationMins }; + } + } + } + if (latest === undefined) return undefined; + const window = usageLimitWindowFromMinutes(latest.minutes); + return { ...(window ? { window } : {}), resetsAt: new Date(latest.resetsAtMs).toISOString() }; +} diff --git a/scripts/check-upstream-drift.test.ts b/scripts/check-upstream-drift.test.ts new file mode 100644 index 000000000..c60168c1c --- /dev/null +++ b/scripts/check-upstream-drift.test.ts @@ -0,0 +1,66 @@ +import { assert, it } from "@effect/vitest"; + +import { + type DriftItem, + evaluateDrift, + issueBody, + issueMarker, + newestStable, + planIssueActions, +} from "./check-upstream-drift.ts"; + +const item = (title: string, pinned: string): DriftItem => ({ + id: title.toLowerCase().replaceAll(/[^a-z]+/g, "-"), + title, + name: "the thing at", + source: "The vendor", + pinned, + file: "apps/server/src/thing.ts", + howToUpdate: ({ version }) => [`Bump it to ${version}.`], +}); + +it("flags a pin only when a newer stable release is published", () => { + const pin = item("Upstream drift: thing", "v0.11.3"); + const status = (version: string, ref?: string) => + evaluateDrift(pin, { ok: true, published: ref ? { version, ref } : { version } }).status; + + assert.equal(status("1.34.1", "schema-v1.34.1"), "drift"); + assert.equal(status("0.11.10"), "drift"); + assert.equal(status("0.11.3"), "current"); + assert.equal(status("0.11.2"), "current"); + assert.equal(status("0.12.0-beta.1"), "drift"); + assert.equal(status("not a version"), "unchecked"); + assert.equal(evaluateDrift(pin, { ok: false, reason: "timed out" }).status, "unchecked"); + + // Numeric order, not text order; prereleases never count as newest. + assert.equal(newestStable(["v24.9.0", "v24.10.0", "v24.11.0-rc.1", "junk"]), "v24.10.0"); +}); + +it("opens, rewrites and closes one issue per pin, and leaves unchecked pins alone", () => { + const drifting = item("Upstream drift: drifting", "1.0.0"); + const stale = item("Upstream drift: stale body", "1.0.0"); + const caughtUp = item("Upstream drift: caught up", "2.0.0"); + const unreachable = item("Upstream drift: unreachable", "1.0.0"); + const unchanged = item("Upstream drift: unchanged", "1.0.0"); + const results = [ + evaluateDrift(drifting, { ok: true, published: { version: "1.1.0" } }), + evaluateDrift(stale, { ok: true, published: { version: "1.2.0" } }), + evaluateDrift(caughtUp, { ok: true, published: { version: "2.0.0" } }), + evaluateDrift(unreachable, { ok: false, reason: "403" }), + evaluateDrift(unchanged, { ok: true, published: { version: "1.1.0" } }), + ]; + const openIssues = [ + // Renamed by a maintainer: still found by its marker. + { number: 1, title: "Bump the stale thing", body: issueBody(stale, { version: "1.1.0" }) }, + { number: 2, title: caughtUp.title, body: `${issueMarker(caughtUp.id)}\nold` }, + { number: 3, title: unreachable.title, body: `${issueMarker(unreachable.id)}\nold` }, + { number: 4, title: unchanged.title, body: `${issueBody(unchanged, { version: "1.1.0" })}\n` }, + // Filed by hand under the same title: never edited or closed. + { number: 5, title: drifting.title, body: "Filed by hand" }, + ]; + + const actions = planIssueActions(results, openIssues).map((action) => + action.kind === "open" ? `open ${action.title}` : `${action.kind} #${action.number}`, + ); + assert.deepStrictEqual(actions, ["open Upstream drift: drifting", "update #1", "close #2"]); +}); diff --git a/scripts/check-upstream-drift.ts b/scripts/check-upstream-drift.ts new file mode 100644 index 000000000..705042f40 --- /dev/null +++ b/scripts/check-upstream-drift.ts @@ -0,0 +1,622 @@ +#!/usr/bin/env node +// @effect-diagnostics globalConsole:off nodeBuiltinImport:off +/** + * Warns when a version we typed into the code by hand has fallen behind what + * its vendor publishes. Dependabot covers package.json; this covers the pins + * it can't see (Antigravity, managed Node.js, the ACP and Codex protocol + * schemas). `.github/workflows/upstream-drift.yml` runs it weekly. + * + * node scripts/check-upstream-drift.ts # dry run: prints results and the issue plan + * node scripts/check-upstream-drift.ts --apply # also opens, updates and closes issues with `gh` + * + * Each pin that is behind gets one open issue, labelled `upstream-drift` and + * marked with the pin's id in a hidden line of its body. Its body is rewritten while we stay behind, and the issue + * is closed once we catch up. A source that can't be reached is reported as + * "couldn't check" and leaves its issue alone. Exits 0 whether or not + * anything drifted; nonzero means the script itself failed. + */ +import { execFile } from "node:child_process"; +import { readFile } from "node:fs/promises"; +import { dirname, join } from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import { promisify } from "node:util"; + +import { fetchWithNetworkRetry } from "./fetch-with-network-retry.ts"; + +export const DRIFT_LABEL = "upstream-drift"; + +/** A published release, as we would write it into our pin. */ +export interface PublishedRelease { + readonly version: string; + /** What to type into the file when it differs from `version` (a git tag). */ + readonly ref?: string; + /** Anything else a maintainer must know before updating, one line each. */ + readonly notes?: ReadonlyArray; +} + +export interface DriftItem { + /** Names the pin's issue in a hidden line of its body (`issueMarker`), so a renamed issue is still found. */ + readonly id: string; + /** Issue title. */ + readonly title: string; + readonly name: string; + /** Where the published version comes from, as a reader would say it. */ + readonly source: string; + readonly pinned: string; + /** Repo-relative path of the file holding the pin. */ + readonly file: string; + readonly howToUpdate: (published: PublishedRelease) => ReadonlyArray; +} + +export type LookupOutcome = + | { readonly ok: true; readonly published: PublishedRelease } + | { readonly ok: false; readonly reason: string }; + +export type DriftResult = + | { + readonly status: "drift" | "current"; + readonly item: DriftItem; + readonly published: PublishedRelease; + } + | { readonly status: "unchecked"; readonly item: DriftItem; readonly reason: string }; + +export interface OpenIssue { + readonly number: number; + readonly title: string; + readonly body: string; +} + +export type IssueAction = + | { readonly kind: "open"; readonly title: string; readonly body: string } + | { + readonly kind: "update"; + readonly number: number; + readonly title: string; + readonly body: string; + } + | { + readonly kind: "close"; + readonly number: number; + readonly title: string; + readonly comment: string; + }; + +// ── Versions ───────────────────────────────────────────────────────── + +interface ParsedVersion { + readonly core: readonly [number, number, number]; + readonly prerelease: ReadonlyArray; +} + +const VERSION_PATTERN = + /^(?:schema-|rust-)?v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/; + +/** Parses `1.2.3`, `v1.2.3`, `schema-v1.2.3` or `rust-v1.2.3`, with an optional prerelease. */ +export function parseVersion(text: string): ParsedVersion | undefined { + const match = VERSION_PATTERN.exec(text.trim()); + if (!match) return undefined; + return { + core: [Number(match[1]), Number(match[2]), Number(match[3])], + prerelease: match[4] ? match[4].split(".") : [], + }; +} + +function comparePrereleasePart(a: string, b: string): number { + const aNumeric = /^\d+$/.test(a); + const bNumeric = /^\d+$/.test(b); + if (aNumeric && bNumeric) return Number(a) - Number(b); + if (aNumeric !== bNumeric) return aNumeric ? -1 : 1; + return a < b ? -1 : a > b ? 1 : 0; +} + +/** Semver order: negative when `a` is older than `b`. Throws on text that isn't a version. */ +export function compareVersions(a: string, b: string): number { + const left = parseVersion(a); + const right = parseVersion(b); + if (!left || !right) throw new Error(`Not a version: ${left ? b : a}`); + for (let index = 0; index < 3; index += 1) { + const delta = left.core[index]! - right.core[index]!; + if (delta !== 0) return delta; + } + // A release sorts after its own prereleases. + if (left.prerelease.length === 0 || right.prerelease.length === 0) { + return right.prerelease.length - left.prerelease.length; + } + const length = Math.max(left.prerelease.length, right.prerelease.length); + for (let index = 0; index < length; index += 1) { + const l = left.prerelease[index]; + const r = right.prerelease[index]; + if (l === undefined || r === undefined) return l === undefined ? -1 : 1; + const delta = comparePrereleasePart(l, r); + if (delta !== 0) return delta; + } + return 0; +} + +/** The newest stable (non-prerelease) version among `versions`, if any. */ +export function newestStable(versions: ReadonlyArray): string | undefined { + let newest: string | undefined; + for (const version of versions) { + const parsed = parseVersion(version); + if (!parsed || parsed.prerelease.length > 0) continue; + if (newest === undefined || compareVersions(version, newest) > 0) newest = version; + } + return newest; +} + +// ── Pure decisions ─────────────────────────────────────────────────── + +export function evaluateDrift(item: DriftItem, outcome: LookupOutcome): DriftResult { + if (!outcome.ok) return { status: "unchecked", item, reason: outcome.reason }; + if (!parseVersion(outcome.published.version)) { + return { + status: "unchecked", + item, + reason: `${item.source} returned "${outcome.published.version}", which is not a version`, + }; + } + const behind = compareVersions(outcome.published.version, item.pinned) > 0; + return { status: behind ? "drift" : "current", item, published: outcome.published }; +} + +const display = (published: PublishedRelease) => published.ref ?? published.version; + +/** + * The hidden line that marks an issue as this check's issue for one pin. Only + * issues carrying it are edited or closed, so one filed by hand is left alone. + */ +export const issueMarker = (id: string) => ``; + +export function issueBody(item: DriftItem, published: PublishedRelease): string { + return [ + issueMarker(item.id), + `We pin ${item.name} **${item.pinned}**. ${item.source} now has **${display(published)}**.`, + "", + `The pin lives in \`${item.file}\`. To update:`, + "", + ...item.howToUpdate(published).map((step) => `- ${step}`), + ...(published.notes && published.notes.length > 0 + ? ["", ...published.notes.map((note) => `**${note}**`)] + : []), + "", + "Kept up to date by the weekly upstream drift check (`.github/workflows/upstream-drift.yml`). It closes this issue once the pin catches up.", + ].join("\n"); +} + +/** + * What to do with the drift issues: open one per drifting item that has none, + * rewrite a body that changed, and close the issue of an item that caught up. + * Items that couldn't be checked leave their issue as it is. + */ +export function planIssueActions( + results: ReadonlyArray, + openIssues: ReadonlyArray, +): ReadonlyArray { + const actions: Array = []; + for (const result of results) { + const { title } = result.item; + const marker = issueMarker(result.item.id); + const existing = openIssues.find((issue) => issue.body.includes(marker)); + if (result.status === "drift") { + const body = issueBody(result.item, result.published); + if (!existing) actions.push({ kind: "open", title, body }); + else if (existing.body.trim() !== body.trim()) { + actions.push({ kind: "update", number: existing.number, title, body }); + } + } else if (result.status === "current" && existing) { + actions.push({ + kind: "close", + number: existing.number, + title, + comment: `We pin ${result.item.pinned} now, and ${result.item.source} has ${display(result.published)}. Closing.`, + }); + } + } + return actions; +} + +// ── The pins ───────────────────────────────────────────────────────── + +const ROOT = join(dirname(fileURLToPath(import.meta.url)), ".."); + +const ANTIGRAVITY_FILE = "apps/server/src/provider/antigravity/AntigravityRelease.ts"; +const MANAGED_NODE_FILE = "apps/server/src/provider/managedRuntime/ManagedNode.ts"; +const ACP_GENERATE_FILE = "packages/effect-acp/scripts/generate.ts"; +const CODEX_GENERATE_FILE = "packages/effect-codex-app-server/scripts/generate.ts"; + +const NODE_INDEX_URL = "https://nodejs.org/dist/index.json"; +const ACP_RELEASES_URL = + "https://api.github.com/repos/agentclientprotocol/agent-client-protocol/releases?per_page=100"; +const CODEX_NPM_URL = "https://registry.npmjs.org/@openai%2fcodex"; + +/** Reads an exported string at `path` from a module that has no side effects on import. */ +async function importedString(file: string, read: (module: unknown) => unknown): Promise { + const module: unknown = await import(pathToFileURL(join(ROOT, file)).href); + const value = read(module); + if (typeof value !== "string") throw new Error(`No pinned version found in ${file}`); + return value; +} + +/** Reads `const NAME = "..."` from a script that runs when imported, so can't be. */ +async function constantFromSource(file: string, name: string): Promise { + const source = await readFile(join(ROOT, file), "utf8"); + const match = new RegExp(`^const ${name} = "([^"]+)";$`, "m").exec(source); + if (!match?.[1]) throw new Error(`No \`const ${name} = "..."\` found in ${file}`); + return match[1]; +} + +const field = (value: unknown, key: string): unknown => + typeof value === "object" && value !== null ? (value as Record)[key] : undefined; + +interface PinnedLookup { + readonly item: DriftItem; + readonly lookup: () => Promise; +} + +export async function loadPins(): Promise> { + const [antigravity, node, acpSchema, codexProtocol] = await Promise.all([ + importedString(ANTIGRAVITY_FILE, (module) => + field(field(module, "ANTIGRAVITY_RELEASE"), "version"), + ), + importedString(MANAGED_NODE_FILE, (module) => + field(field(module, "MANAGED_NODE_RELEASE"), "version"), + ), + constantFromSource(ACP_GENERATE_FILE, "CURRENT_SCHEMA_RELEASE"), + constantFromSource(CODEX_GENERATE_FILE, "CODEX_PROTOCOL_VERSION"), + ]); + const nodeMajor = parseVersion(node)?.core[0]; + if (nodeMajor === undefined) throw new Error(`Managed Node pin "${node}" is not a version`); + + return [ + { + item: { + id: "antigravity", + title: "Upstream drift: Antigravity", + name: "Google's Antigravity CLI at", + source: "Google's CLI update feed", + pinned: antigravity, + file: ANTIGRAVITY_FILE, + howToUpdate: ({ version }) => [ + `Users are already offered ${version} through Settings (\`AntigravityReleaseSource\`) wherever the feed's manifest fits; this pin is what installs when the feed can't be read, and the oldest version offered.`, + "Read Google's changelog (https://github.com/google-antigravity/antigravity-cli) for `agy acp` changes, and check the sign-in behavior noted in `apps/server/src/provider/antigravity/AntigravitySignInMethod.ts` and `AntigravityAuth.ts` against it.", + `Then set the built-in release to ${version}: take each build's url and sha512 from its manifest (\`antigravityFeedUrl\`), and measure each download's size and its unpacked \`antigravity\` file's size.`, + ], + }, + lookup: async () => { + const module: unknown = await import(pathToFileURL(join(ROOT, ANTIGRAVITY_FILE)).href); + const feedUrl = field(module, "antigravityFeedUrl"); + const parse = field(module, "parseAntigravityFeedManifest"); + if (typeof feedUrl !== "function" || typeof parse !== "function") { + throw new Error(`No feed reader in ${ANTIGRAVITY_FILE}`); + } + const manifests = await Promise.all( + ANTIGRAVITY_BUILDS.map(async (assetKey) => { + const manifest = await fetchJson(feedUrl(assetKey) as string); + return { assetKey, manifest, fits: parse(manifest, assetKey) !== undefined }; + }), + ); + const versions = manifests.map(({ manifest }) => field(manifest, "version")); + // The newest any build has: a release can reach one platform first. + const version = versions + .filter( + (value): value is string => + typeof value === "string" && parseVersion(value) !== undefined, + ) + .reduce( + (newest, value) => + newest === undefined || compareVersions(value, newest) > 0 ? value : newest, + undefined, + ); + if (version === undefined) throw new Error("the feed named no version"); + const behind = manifests + .filter((_, index) => versions[index] !== version) + .map(({ assetKey }) => assetKey); + const refused = manifests.filter(({ fits }) => !fits).map(({ assetKey }) => assetKey); + return { + version, + ...(refused.length > 0 || behind.length > 0 + ? { + notes: [ + ...(behind.length > 0 + ? [`The feed doesn't list ${version} for ${behind.join(", ")} yet.`] + : []), + ...(refused.length > 0 + ? [ + `Threadlines won't offer the feed's release on ${refused.join(", ")}: its manifest changed (download host, folder, file name or hash), so \`parseAntigravityFeedManifest\` refuses it. Check what changed and teach Threadlines to install it.`, + ] + : []), + ], + } + : {}), + }; + }, + }, + { + item: { + id: "managed-node", + title: "Upstream drift: managed Node.js", + name: "Node.js", + source: `nodejs.org (the ${nodeMajor}.x line)`, + pinned: node, + file: MANAGED_NODE_FILE, + howToUpdate: ({ version }) => [ + `Change the version and the six archive URLs to v${version}.`, + `Take each archive's sha256 from https://nodejs.org/dist/v${version}/SHASUMS256.txt, and its size and unpacked size from the download.`, + "Only this major line is checked. Moving to a new major is a separate decision.", + ], + }, + lookup: async () => { + const index = await fetchJson(NODE_INDEX_URL); + if (!Array.isArray(index)) throw new Error("index.json is not a list"); + const versions = index + .map((entry: unknown) => field(entry, "version")) + .filter((version): version is string => typeof version === "string") + .filter((version) => parseVersion(version)?.core[0] === nodeMajor); + const newest = newestStable(versions); + if (!newest) throw new Error(`no ${nodeMajor}.x release in index.json`); + return { version: newest.replace(/^v/, "") }; + }, + }, + { + item: { + id: "acp-schema", + title: "Upstream drift: ACP schema", + name: "the ACP schema at", + source: "agentclientprotocol/agent-client-protocol", + pinned: acpSchema, + file: ACP_GENERATE_FILE, + howToUpdate: (published) => [ + `Set \`CURRENT_SCHEMA_RELEASE\` to \`${display(published)}\`. Schema releases are tagged \`schema-v*\` now; the plain \`v*\` tags are the Rust crate and carry no schema.`, + "Run `node packages/effect-acp/scripts/generate.ts`, then fix what the new bindings break and run the ACP driver tests.", + ], + }, + lookup: async () => { + // Releases alternate between the Rust crate (`v*`, no files) and the + // schema (`schema-v*`), so "latest release" can't be trusted. Take the + // newest stable release that ships the file the generator downloads. + const releases = await fetchJson(ACP_RELEASES_URL, githubHeaders()); + if (!Array.isArray(releases)) throw new Error("the releases list is not a list"); + const tags = releases + .filter((release: unknown) => field(release, "draft") !== true) + .filter((release: unknown) => field(release, "prerelease") !== true) + .filter((release: unknown) => { + const assets = field(release, "assets"); + return ( + Array.isArray(assets) && + assets.some((asset: unknown) => field(asset, "name") === "schema.unstable.json") + ); + }) + .map((release: unknown) => field(release, "tag_name")) + .filter((tag): tag is string => typeof tag === "string"); + const newest = newestStable(tags); + if (!newest) throw new Error("no stable release with schema.unstable.json"); + return { version: newest.replace(/^schema-v|^v/, ""), ref: newest }; + }, + }, + { + item: { + id: "codex-protocol", + title: "Upstream drift: Codex app-server protocol", + name: "the Codex app-server protocol at", + source: "npm (`@openai/codex` latest)", + pinned: codexProtocol, + file: CODEX_GENERATE_FILE, + howToUpdate: ({ version }) => [ + `Set \`CODEX_PROTOCOL_VERSION\` to \`${version}\`. The generator runs \`codex\` and refuses any other version, so install \`@openai/codex@${version}\` or point \`THREADLINES_CODEX_SCHEMA_BINARY\` at that build.`, + "Run `node packages/effect-codex-app-server/scripts/generate.ts`, then fix what the new bindings break.", + "Run the Codex replay tests in `apps/server/integration/replay`.", + ], + }, + lookup: async () => { + // npm `latest` is the stable CLI release; `rust-v*` tags on GitHub + // also include alphas. The generator checks `codex --version` against + // the pin, and that version is the npm one. + const packument = await fetchJson(CODEX_NPM_URL); + const latest = field(field(packument, "dist-tags"), "latest"); + if (typeof latest !== "string") throw new Error("no latest dist-tag"); + return { version: latest }; + }, + }, + ]; +} + +/** Threadlines' name for each Antigravity build (`AntigravityAssetKey`). */ +const ANTIGRAVITY_BUILDS = [ + "darwin-arm64", + "darwin-x64", + "linux-arm64", + "linux-x64", + "linux-arm64-musl", + "linux-x64-musl", + "win32-arm64", + "win32-x64", +] as const; + +// ── I/O ────────────────────────────────────────────────────────────── + +const FETCH_TIMEOUT_MS = 20_000; +const USER_AGENT = "threadlines-drift-check"; + +function githubHeaders(): Record { + const token = process.env.GITHUB_TOKEN ?? process.env.GH_TOKEN; + return { + accept: "application/vnd.github+json", + ...(token ? { authorization: `Bearer ${token}` } : {}), + }; +} + +async function fetchJson(url: string, headers: Record = {}): Promise { + const response = await fetchWithNetworkRetry(url, { + maxAttempts: 2, + timeoutMs: FETCH_TIMEOUT_MS, + // The ACP CDN answers 403 to some default user agents. + fetchImplementation: (input, init) => + fetch(input, { ...init, headers: { "user-agent": USER_AGENT, ...headers } }), + }); + if (!response.ok) throw new Error(`${url} answered ${response.status}`); + return response.json(); +} + +async function checkPin(pin: PinnedLookup): Promise { + try { + return evaluateDrift(pin.item, { ok: true, published: await pin.lookup() }); + } catch (error) { + const reason = error instanceof Error ? error.message : String(error); + return evaluateDrift(pin.item, { ok: false, reason }); + } +} + +const execFileAsync = promisify(execFile); +const GH_TIMEOUT_MS = 60_000; + +async function gh(args: ReadonlyArray): Promise { + const { stdout } = await execFileAsync("gh", [...args], { + timeout: GH_TIMEOUT_MS, + maxBuffer: 8 * 1024 * 1024, + }); + return stdout; +} + +async function listOpenDriftIssues(): Promise> { + const output = await gh([ + "issue", + "list", + "--label", + DRIFT_LABEL, + "--state", + "open", + "--limit", + "100", + "--json", + "number,title,body", + ]); + const parsed: unknown = JSON.parse(output); + if (!Array.isArray(parsed)) throw new Error("gh issue list did not return a list"); + return parsed.flatMap((issue: unknown) => { + const number = field(issue, "number"); + const title = field(issue, "title"); + const body = field(issue, "body"); + return typeof number === "number" && typeof title === "string" + ? [{ number, title, body: typeof body === "string" ? body : "" }] + : []; + }); +} + +async function applyAction(action: IssueAction): Promise { + switch (action.kind) { + case "open": + await gh([ + "issue", + "create", + "--title", + action.title, + "--body", + action.body, + "--label", + DRIFT_LABEL, + ]); + return; + case "update": + await gh(["issue", "edit", String(action.number), "--body", action.body]); + return; + case "close": + await gh(["issue", "close", String(action.number), "--comment", action.comment]); + return; + } +} + +function describeResult(result: DriftResult): string { + const { item } = result; + const label = item.title.replace(/^Upstream drift: /, ""); + switch (result.status) { + case "drift": + return `DRIFT ${label}: we pin ${item.pinned}, ${item.source} has ${display(result.published)}`; + case "current": + return `current ${label}: ${item.pinned} (${item.source} has ${display(result.published)})`; + case "unchecked": + return `unchecked ${label}: couldn't check (${result.reason})`; + } +} + +function describeAction(action: IssueAction): string { + switch (action.kind) { + case "open": + return `open issue "${action.title}"`; + case "update": + return `update issue #${action.number} "${action.title}"`; + case "close": + return `close issue #${action.number} "${action.title}"`; + } +} + +async function main(argv: ReadonlyArray): Promise { + const unknownFlags = argv.filter((arg) => arg !== "--apply" && arg !== "--dry-run"); + if (unknownFlags.length > 0) throw new Error(`Unknown arguments: ${unknownFlags.join(" ")}`); + if (argv.includes("--apply") && argv.includes("--dry-run")) { + throw new Error("Pass --apply or --dry-run, not both."); + } + const apply = argv.includes("--apply"); + + const pins = await loadPins(); + const results = await Promise.all(pins.map(checkPin)); + for (const result of results) console.log(describeResult(result)); + + if (process.env.GITHUB_ACTIONS === "true") { + for (const result of results) { + if (result.status === "unchecked") { + console.log(`::warning title=${result.item.title}::Couldn't check: ${result.reason}`); + } + } + } + + let openIssues: ReadonlyArray; + try { + openIssues = await listOpenDriftIssues(); + } catch (error) { + if (apply) throw error; + console.log(`\n(gh couldn't list issues, so the plan assumes none are open: ${String(error)})`); + openIssues = []; + } + + const actions = planIssueActions(results, openIssues); + console.log(apply ? "\nIssue changes:" : "\nIssue changes (dry run, nothing written):"); + if (actions.length === 0) console.log(" none"); + for (const action of actions) console.log(` ${describeAction(action)}`); + if (!apply) { + for (const action of actions) { + if (action.kind !== "close") console.log(`\n--- ${action.title} ---\n${action.body}`); + } + return; + } + + if (actions.some((action) => action.kind === "open")) { + await gh([ + "label", + "create", + DRIFT_LABEL, + "--color", + "FBCA04", + "--description", + "A version pinned in code is behind its vendor's latest release.", + "--force", + ]); + } + // One failed change doesn't stop the others; the run still fails at the end. + let failures = 0; + for (const action of actions) { + try { + await applyAction(action); + } catch (error) { + failures += 1; + console.error(`Couldn't ${describeAction(action)}: ${String(error)}`); + } + } + if (failures > 0) throw new Error(`${failures} issue change(s) failed`); +} + +if (import.meta.main) { + main(process.argv.slice(2)).catch((error: unknown) => { + console.error(error); + process.exitCode = 1; + }); +}