From 698c0203f26a9c1302653309ad36e27c4e6c27dd Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Mon, 23 Nov 2026 00:43:51 -0500 Subject: [PATCH 01/59] fix(antigravity): install Antigravity 1.5.2, so Gemini 4 models show up Threadlines pinned Google's Antigravity agent at 1.3.0, which only knows Gemini 3.x models. Pin 1.5.2 (the ACP registry's current entry) on all six platforms. The saved model list now records the agent version that listed it, so an update lists models afresh instead of showing the old list. --- .../src/provider/acp/AntigravityAcpSupport.ts | 33 ++++++++---- .../antigravity/AntigravityProfile.ts | 14 +++-- .../antigravity/AntigravityRelease.ts | 52 +++++++++---------- .../AntigravitySignInMethod.test.ts | 27 +++++++++- .../antigravity/AntigravitySignInMethod.ts | 2 +- 5 files changed, 87 insertions(+), 41 deletions(-) diff --git a/apps/server/src/provider/acp/AntigravityAcpSupport.ts b/apps/server/src/provider/acp/AntigravityAcpSupport.ts index 863f7f4ee..328e6ddb4 100644 --- a/apps/server/src/provider/acp/AntigravityAcpSupport.ts +++ b/apps/server/src/provider/acp/AntigravityAcpSupport.ts @@ -492,6 +492,15 @@ export function makeAntigravityDescriptor( } : null; + /** + * The managed runtime version the next agent runs, or undefined for a + * custom binary. Tags the saved model list (`readAntigravityCatalog`). + */ + const managedAgentVersion = (settings: AntigravitySettings) => + settings.binaryPath.trim() || !runtime + ? Effect.succeed(undefined) + : runtime.installed.pipe(Effect.map((installed) => installed?.version)); + const spawnFailure = (cause: unknown) => new EffectAcpErrors.AcpSpawnError({ command: "agy_acp_server", cause }); @@ -604,16 +613,19 @@ export function makeAntigravityDescriptor( }, 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, - }); - }, + onSessionConfigOptions: (settings, configOptions) => + Effect.gen(function* () { + const choices = modelChoices(configOptions); + if (choices.length === 0) return; + const currentValue = selectConfigOptionCurrentValue(findModelConfigOption(configOptions)); + const agentVersion = yield* managedAgentVersion(settings); + yield* writeAntigravityCatalog(paths.profileDir, { + choices, + ...(currentValue ? { currentValue } : {}), + fingerprint, + ...(agentVersion ? { agentVersion } : {}), + }); + }), notInstalledMessage: "Antigravity is not installed. Install it to use it in Threadlines.", // 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 @@ -676,6 +688,7 @@ export function makeAntigravityDescriptor( const catalog = yield* readAntigravityCatalog(paths.profileDir, { fingerprint, isGoogleAccount: signIn.method === "oauth-personal", + agentVersion: version ?? undefined, }); return { installed: true, diff --git a/apps/server/src/provider/antigravity/AntigravityProfile.ts b/apps/server/src/provider/antigravity/AntigravityProfile.ts index 0a014a3a9..278a998d1 100644 --- a/apps/server/src/provider/antigravity/AntigravityProfile.ts +++ b/apps/server/src/provider/antigravity/AntigravityProfile.ts @@ -213,6 +213,8 @@ export interface AntigravityCatalogCache { readonly currentValue?: string; /** 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"); @@ -221,11 +223,16 @@ const catalogPath = (profileDir: string) => join(profileDir, "threadlines-models * 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,7 +243,7 @@ export const readAntigravityCatalog = ( parsed.fingerprint === undefined ? sign.isGoogleAccount : parsed.fingerprint === sign.fingerprint; - if (!matches) return undefined; + if (!matches || parsed.agentVersion !== sign.agentVersion) return undefined; const choices = Array.isArray(parsed.choices) ? parsed.choices.filter( (choice): choice is AntigravityModelChoice => @@ -250,6 +257,7 @@ export const readAntigravityCatalog = ( ? { currentValue: parsed.currentValue } : {}), fingerprint: sign.fingerprint, + ...(sign.agentVersion ? { agentVersion: sign.agentVersion } : {}), } : undefined; } catch { diff --git a/apps/server/src/provider/antigravity/AntigravityRelease.ts b/apps/server/src/provider/antigravity/AntigravityRelease.ts index 6251cf74b..b72c648ad 100644 --- a/apps/server/src/provider/antigravity/AntigravityRelease.ts +++ b/apps/server/src/provider/antigravity/AntigravityRelease.ts @@ -57,45 +57,45 @@ const WINDOWS_FILES = (executableBytes: number, harnessBytes: number) => ({ const RELEASES_URL = "https://dl.google.com/agy-extensions/releases"; -/** Registry entry `antigravity-acp` 1.3.0. */ +/** Registry entry `antigravity-acp` 1.5.2. */ export const ANTIGRAVITY_RELEASE: AntigravityRelease = { - version: "1.3.0", + version: "1.5.2", 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), + url: `${RELEASES_URL}/macos/agy-acp-server-1.5.2-darwin-arm64.zip`, + sha256: "123a16d5c40a8ac99e20f01a62b68dd860fd96b1c528dfb8eaa37ca8733d4845", + archiveBytes: 100_309_778, + ...POSIX_FILES(179_921_328, 129_208_672), }, "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), + url: `${RELEASES_URL}/macos/agy-acp-server-1.5.2-darwin-x86_64.zip`, + sha256: "92addb5580577b5356d35484d72d1a113d9c5312ad766bcb304983aa8e3fbb06", + archiveBytes: 106_351_992, + ...POSIX_FILES(184_312_784, 134_350_320), }, "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), + url: `${RELEASES_URL}/linux/agy-acp-server-1.5.2-linux-arm64.zip`, + sha256: "e729e05ef54ef0763e48900032466b47fa7c9939cde257f93ba49410ab577acb", + archiveBytes: 264_270_419, + ...POSIX_FILES(721_649_155, 132_598_576), }, "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), + url: `${RELEASES_URL}/linux/agy-acp-server-1.5.2-linux-x86_64.zip`, + sha256: "99dd8612450805011619d7b8447ce374c289e00549d8557f36790e1dd6256852", + archiveBytes: 273_964_075, + ...POSIX_FILES(714_384_320, 139_194_456), }, "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), + url: `${RELEASES_URL}/windows/agy-acp-server-1.5.2-windows-arm64.zip`, + sha256: "8a4b2ea8df2ffefae33309348752e9119d21a6d36090c0eb48631c2e8f5781ab", + archiveBytes: 108_049_351, + ...WINDOWS_FILES(65_130_848, 146_707_096), }, "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), + url: `${RELEASES_URL}/windows/agy-acp-server-1.5.2-windows-x86_64.zip`, + sha256: "5cbadd4f4df698572473d8890fc26ec2dc1724501f06e3a963941daec2bd21d6", + archiveBytes: 105_407_645, + ...WINDOWS_FILES(58_368_800, 155_357_336), }, }, }; diff --git a/apps/server/src/provider/antigravity/AntigravitySignInMethod.test.ts b/apps/server/src/provider/antigravity/AntigravitySignInMethod.test.ts index 321fe96c6..abf5a3ff2 100644 --- a/apps/server/src/provider/antigravity/AntigravitySignInMethod.test.ts +++ b/apps/server/src/provider/antigravity/AntigravitySignInMethod.test.ts @@ -7,7 +7,11 @@ import { assert, describe, expect, 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, @@ -336,3 +340,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..48c177059 100644 --- a/apps/server/src/provider/antigravity/AntigravitySignInMethod.ts +++ b/apps/server/src/provider/antigravity/AntigravitySignInMethod.ts @@ -308,7 +308,7 @@ 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. */ +/** The OAuth clients Antigravity signs in with, per method (same in 1.3.0 and 1.5.2). */ const GOOGLE_ACCOUNT_CLIENT_ID = "1071006060591-tmhssin2h21lcre235vtolojh4g403ep.apps.googleusercontent.com"; const GEMINI_ENTERPRISE_CLIENT_ID = From 2b07c73c00e76ff67168a9e6553851e682b952cc Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Mon, 23 Nov 2026 01:00:24 -0500 Subject: [PATCH 02/59] feat(antigravity): offer Google's newest Antigravity as an update, not just the built-in one The update checker compared the installed Antigravity against a version written into Threadlines, so a new Google release (and its models) never showed until someone edited the code. Antigravity now reads Google's antigravity-acp entry from the ACP registry (through the shared community-agent catalog, which now keeps built-in agents' recipes apart) at most once an hour, and offers it as Install or Update when it is newer than the built-in release. Nothing installs on its own. Install checks stay as strict as for the built-in release: only Google's download host on every redirect hop, the listed sha256, exact archive and file sizes read from the zip's index with small range requests, the usual start-up check, nothing offered while the registry's quarantine list is unknown, and no action ever installs an older version than the one in place. --- apps/server/src/guide/topics.ts | 2 + .../src/provider/Drivers/AntigravityDriver.ts | 41 +++- .../src/provider/acp/AntigravityAcpSupport.ts | 61 +++-- .../acpRegistry/AcpRegistryAgents.test.ts | 1 + .../provider/acpRegistry/AcpRegistryAgents.ts | 9 +- .../acpRegistry/AcpRegistryCatalog.test.ts | 17 +- .../acpRegistry/AcpRegistryCatalog.ts | 42 +++- .../antigravity/AntigravityRelease.ts | 95 +++++++- .../antigravity/AntigravityReleaseSource.ts | 133 +++++++++++ .../antigravity/AntigravityRuntime.test.ts | 167 ++++++++++--- .../antigravity/AntigravityRuntime.ts | 219 ++++++++++++++++-- docs/providers/antigravity.md | 16 ++ 12 files changed, 703 insertions(+), 100 deletions(-) create mode 100644 apps/server/src/provider/antigravity/AntigravityReleaseSource.ts diff --git a/apps/server/src/guide/topics.ts b/apps/server/src/guide/topics.ts index f8c71366e..0153a1836 100644 --- a/apps/server/src/guide/topics.ts +++ b/apps/server/src/guide/topics.ts @@ -311,6 +311,8 @@ 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. +Antigravity's models come from Google's Antigravity program, which Threadlines downloads itself. New Gemini models arrive with a newer Antigravity: when Google publishes one, the Antigravity card offers Update, and the picker lists the new models after 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, 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. Clicking a limit there opens {place:usage}. 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. diff --git a/apps/server/src/provider/Drivers/AntigravityDriver.ts b/apps/server/src/provider/Drivers/AntigravityDriver.ts index afb566eb4..a84eaf4db 100644 --- a/apps/server/src/provider/Drivers/AntigravityDriver.ts +++ b/apps/server/src/provider/Drivers/AntigravityDriver.ts @@ -23,7 +23,15 @@ import { validateAntigravityRuntime, } from "../acp/AntigravityAcpSupport.ts"; import { type AcpProviderDriverEnv, makeAcpProviderDriver } from "../acp/AcpProviderDriver.ts"; +import { + acpRegistryCacheDir, + sharedAcpRegistryCatalog, +} from "../acpRegistry/AcpRegistryCatalog.ts"; import { antigravityReleaseFor } from "../antigravity/AntigravityRelease.ts"; +import { + type AntigravityReleaseSource, + makeAntigravityReleaseSource, +} from "../antigravity/AntigravityReleaseSource.ts"; import { makeAntigravityAuthFlows } from "../antigravity/AntigravityAuth.ts"; import { antigravityInstancePaths, @@ -57,6 +65,29 @@ 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, + platform: process.platform, + catalog: sharedAcpRegistryCatalog({ + cacheDir: acpRegistryCacheDir(stateDir), + platform: process.platform, + arch: process.arch, + }), + }); + releaseSourcesByStateDir.set(stateDir, source); + } + return source; +}; export const AntigravityDriver: ProviderDriver = { driverKind: ANTIGRAVITY_DRIVER_KIND, @@ -78,11 +109,13 @@ 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( @@ -113,7 +146,7 @@ export const AntigravityDriver: ProviderDriver { - const { paths, runtime, release, gate, signIn } = input; + const { paths, runtime, releases, gate, signIn } = input; const platform = process.platform; const fingerprint = antigravityCredentialFingerprint(signIn); - 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: AntigravityReleaseOffer, + ): 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. + run: Effect.gen(function* () { + const installed = yield* runtime.installed; + if (installed && compareSemverVersions(installed.version, offer.version) >= 0) { + return { output: `Antigravity ${installed.version} is already installed.` }; + } + yield* runtime.install(yield* offer.release); + return { output: `Antigravity ${offer.version} is installed.` }; + }).pipe(Effect.mapError((error) => ({ message: error.message }))), + }); /** * The managed runtime version the next agent runs, or undefined for a @@ -512,12 +524,15 @@ 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 compareSemverVersions(installed.version, offer.version) < 0 + ? { ...MANUAL_ONLY, update: runtimeAction(runtime, "Update", offer) } + : MANUAL_ONLY; }), spawn: (settings, cwd, environment) => Effect.gen(function* () { @@ -640,7 +655,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, @@ -662,7 +677,7 @@ export function makeAntigravityDescriptor( : "Antigravity is not installed. Install it to use it in Threadlines.", } satisfies AcpProviderProbeOutcome; } - const latest = custom ? {} : { latestVersion: ANTIGRAVITY_RELEASE.version }; + const latest = custom ? {} : { latestVersion: (yield* releases!.newest).version }; const usesGoogleSignIn = signIn.method === "oauth-personal" || signIn.method === "oauth-business"; const signInStatus = antigravitySignInStatus({ diff --git a/apps/server/src/provider/acpRegistry/AcpRegistryAgents.test.ts b/apps/server/src/provider/acpRegistry/AcpRegistryAgents.test.ts index 4d253583c..b2664f1f0 100644 --- a/apps/server/src/provider/acpRegistry/AcpRegistryAgents.test.ts +++ b/apps/server/src/provider/acpRegistry/AcpRegistryAgents.test.ts @@ -95,6 +95,7 @@ const snapshotOf = ( stale: false, quarantineKnown: true, unsupportedCount: 0, + builtIn: [], ...overrides, }); diff --git a/apps/server/src/provider/acpRegistry/AcpRegistryAgents.ts b/apps/server/src/provider/acpRegistry/AcpRegistryAgents.ts index e5985cdad..1d5e12c6f 100644 --- a/apps/server/src/provider/acpRegistry/AcpRegistryAgents.ts +++ b/apps/server/src/provider/acpRegistry/AcpRegistryAgents.ts @@ -1,4 +1,3 @@ -// @effect-diagnostics nodeBuiltinImport:off - the registry's cache folder /** * AcpRegistryAgents — what a client can do with community agents: read the * list, add one, update one, remove one. @@ -14,7 +13,6 @@ * * @module provider/acpRegistry/AcpRegistryAgents */ -import * as NodePath from "node:path"; import { ACP_REGISTRY_DRIVER_KIND, @@ -65,7 +63,8 @@ import { type AcpRegistryCatalogEntry, type AcpRegistryCatalogShape, type AcpRegistryCatalogSnapshot, - makeAcpRegistryCatalog, + acpRegistryCacheDir, + sharedAcpRegistryCatalog, toAcpRegistryCatalog, } from "./AcpRegistryCatalog.ts"; import { acpRegistryNodes } from "./AcpRegistryNodes.ts"; @@ -137,8 +136,8 @@ export const makeAcpRegistryAgents = Effect.fn("makeAcpRegistryAgents")(function const catalog = options?.catalog ?? - makeAcpRegistryCatalog({ - cacheDir: NodePath.join(serverConfig.stateDir, "caches", "acp-registry"), + sharedAcpRegistryCatalog({ + cacheDir: acpRegistryCacheDir(serverConfig.stateDir), platform: process.platform, arch: process.arch, }); diff --git a/apps/server/src/provider/acpRegistry/AcpRegistryCatalog.test.ts b/apps/server/src/provider/acpRegistry/AcpRegistryCatalog.test.ts index 0b66e0688..928aa856c 100644 --- a/apps/server/src/provider/acpRegistry/AcpRegistryCatalog.test.ts +++ b/apps/server/src/provider/acpRegistry/AcpRegistryCatalog.test.ts @@ -369,17 +369,25 @@ describe("reduceAcpRegistryIndex", () => { it("hides built-in and quarantined agents without counting them as unsupported", () => { const ids = (quarantined: ReadonlyArray) => { - const { entries, unsupportedCount } = reduce(REGISTRY.agents, { quarantined }); - return { listed: entries.map(({ agent }) => agent.agentId), unsupportedCount }; + const { entries, unsupportedCount, builtIn } = reduce(REGISTRY.agents, { quarantined }); + return { + listed: entries.map(({ agent }) => agent.agentId), + unsupportedCount, + builtIn: builtIn.map((recipe) => `${recipe.agentId}@${recipe.version}`), + }; }; - // Nothing quarantined: crow-cli shows, and fast-agent (Python only) is counted. + // Nothing quarantined: crow-cli shows, and fast-agent (Python only) is + // counted. claude-acp is kept apart, for its own driver to read. assert.deepStrictEqual(ids([]), { listed: ["auggie", "cortex-code", "crow-cli", "goose", "kilo", "sigit"], unsupportedCount: 1, + builtIn: ["claude-acp@0.86.0"], }); - assert.deepStrictEqual(ids(["crow-cli", "fast-agent", "goose"]), { + // A quarantined release of a built-in agent is not offered to its driver either. + assert.deepStrictEqual(ids(["crow-cli", "fast-agent", "goose", "claude-acp"]), { listed: ["auggie", "cortex-code", "kilo", "sigit"], unsupportedCount: 0, + builtIn: [], }); }); @@ -396,6 +404,7 @@ describe("reduceAcpRegistryIndex", () => { stale: false, quarantineKnown: true, unsupportedCount: reduced.unsupportedCount, + builtIn: reduced.builtIn, }); assert.deepStrictEqual( offered.agents.map((agent) => agent.agentId), diff --git a/apps/server/src/provider/acpRegistry/AcpRegistryCatalog.ts b/apps/server/src/provider/acpRegistry/AcpRegistryCatalog.ts index 9bc27bb36..708b309ea 100644 --- a/apps/server/src/provider/acpRegistry/AcpRegistryCatalog.ts +++ b/apps/server/src/provider/acpRegistry/AcpRegistryCatalog.ts @@ -171,6 +171,12 @@ export interface AcpRegistryCatalogSnapshot { readonly quarantineKnown: boolean; /** Agents left out because they have no build for this computer. */ readonly unsupportedCount: number; + /** + * Recipes for this computer of agents Threadlines supports itself + * (`ACP_REGISTRY_BUILT_IN_AGENT_IDS`), never listed: their drivers read + * them to learn of new releases. Quarantined agents are left out here too. + */ + readonly builtIn: ReadonlyArray; } export interface AcpRegistryCatalogShape { @@ -214,6 +220,8 @@ export interface AcpRegistryReduction { readonly entries: ReadonlyArray; /** Well-formed agents with no build for this computer. */ readonly unsupportedCount: number; + /** See `AcpRegistryCatalogSnapshot.builtIn`. */ + readonly builtIn: ReadonlyArray; /** Entries left out for breaking a rule, and which. For the log. */ readonly dropped: ReadonlyArray<{ readonly agentId: string | null; readonly reason: string }>; } @@ -504,7 +512,8 @@ const agentsOfIndex = (index: unknown): ReadonlyArray | undefined => * install. Pure: no icons, no network. * * - Agents Threadlines supports itself and quarantined agents are hidden, - * and are neither listed nor counted. + * and are neither listed nor counted. The recipes of the first kind are + * kept apart in `builtIn`, for their drivers. * - An agent takes its `binary` build for this computer when it has one, * else its npm package. One with neither is counted in `unsupportedCount`. * - An agent that breaks a bound is dropped, never cut to fit, except free @@ -520,6 +529,7 @@ export function reduceAcpRegistryIndex(input: { const agents = agentsOfIndex(input.index) ?? []; const platformKey = acpRegistryPlatformKey(input.platform, input.arch); const entries: Array = []; + const builtIn: Array = []; const dropped: Array<{ readonly agentId: string | null; readonly reason: string }> = []; const seen = new Set(); let unsupportedCount = 0; @@ -536,7 +546,7 @@ export function reduceAcpRegistryIndex(input: { continue; } const agentId = raw.id; - if (ACP_REGISTRY_BUILT_IN_AGENT_IDS.has(agentId) || input.quarantined.has(agentId)) continue; + if (input.quarantined.has(agentId)) continue; if (seen.has(agentId)) { dropped.push({ agentId, reason: "an earlier entry has the same id" }); continue; @@ -544,7 +554,9 @@ export function reduceAcpRegistryIndex(input: { seen.add(agentId); const reduced = reduceAgent(raw, agentId, platformKey); if (Result.isFailure(reduced)) dropped.push({ agentId, reason: reduced.failure }); - else if (reduced.success === undefined) unsupportedCount += 1; + else if (ACP_REGISTRY_BUILT_IN_AGENT_IDS.has(agentId)) { + if (reduced.success !== undefined) builtIn.push(reduced.success.recipe); + } else if (reduced.success === undefined) unsupportedCount += 1; else entries.push(reduced.success); } @@ -557,6 +569,7 @@ export function reduceAcpRegistryIndex(input: { return left.agent.agentId < right.agent.agentId ? -1 : 1; }), unsupportedCount, + builtIn, dropped, }; } @@ -759,6 +772,28 @@ function svgText(bytes: Uint8Array): string | undefined { } /** Builds the catalog for one cache folder. Cheap; holds no resources. */ +/** Where the registry's lists and icons are kept under a state folder. */ +export const acpRegistryCacheDir = (stateDir: string) => + NodePath.join(stateDir, "caches", "acp-registry"); + +const sharedCatalogs = new Map(); + +/** + * The catalog for a cache folder, one per folder in this process: community + * agents and built-in drivers that read it share its reads, memory and files. + */ +export function sharedAcpRegistryCatalog( + options: Omit, +): AcpRegistryCatalogShape { + const key = [options.cacheDir, options.platform, options.arch].join("\u0000"); + let catalog = sharedCatalogs.get(key); + if (!catalog) { + catalog = makeAcpRegistryCatalog(options); + sharedCatalogs.set(key, catalog); + } + return catalog; +} + export function makeAcpRegistryCatalog( options: AcpRegistryCatalogOptions, ): AcpRegistryCatalogShape { @@ -884,6 +919,7 @@ export function makeAcpRegistryCatalog( stale: input.stale, quarantineKnown: input.quarantine !== undefined, unsupportedCount: reduction.unsupportedCount, + builtIn: reduction.builtIn, }; }); diff --git a/apps/server/src/provider/antigravity/AntigravityRelease.ts b/apps/server/src/provider/antigravity/AntigravityRelease.ts index b72c648ad..e53366fe2 100644 --- a/apps/server/src/provider/antigravity/AntigravityRelease.ts +++ b/apps/server/src/provider/antigravity/AntigravityRelease.ts @@ -1,14 +1,22 @@ /** - * AntigravityRelease — the pinned Antigravity ACP server release Threadlines - * installs, one zip per platform. + * AntigravityRelease — which Antigravity ACP server release Threadlines + * installs, one zip per platform: the built-in release below, or a newer one + * Google lists in the ACP registry. * * 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. + * starts. The built-in sizes and hashes were taken from the published + * archives; a listed release takes its hash from the registry and its sizes + * from the zip's own index (`resolveAntigravityListedRelease`). The runtime + * refuses anything that differs. * * @module provider/antigravity/AntigravityRelease */ +import type { AcpRegistryRecipe } from "../acpRegistry/AcpRegistryRecipe.ts"; + +/** Google's id for Antigravity in the ACP registry. */ +export const ANTIGRAVITY_REGISTRY_AGENT_ID = "antigravity-acp"; + export type AntigravityAssetKey = | "darwin-arm64" | "darwin-x64" @@ -55,44 +63,66 @@ const WINDOWS_FILES = (executableBytes: number, harnessBytes: number) => ({ harness: { name: "localharness_external.exe", bytes: harnessBytes }, }); -const RELEASES_URL = "https://dl.google.com/agy-extensions/releases"; +/** The only host Antigravity is downloaded from. */ +export const ANTIGRAVITY_DOWNLOAD_HOST = "dl.google.com"; +const RELEASES_URL = `https://${ANTIGRAVITY_DOWNLOAD_HOST}/agy-extensions/releases`; + +/** Google's folder and file-name suffix for each build. */ +const ARCHIVE_NAMES: Readonly> = { + "darwin-arm64": ["macos", "darwin-arm64"], + "darwin-x64": ["macos", "darwin-x86_64"], + "linux-arm64": ["linux", "linux-arm64"], + "linux-x64": ["linux", "linux-x86_64"], + "win32-arm64": ["windows", "windows-arm64"], + "win32-x64": ["windows", "windows-x86_64"], +}; + +/** Where Google publishes a version's zip for a build. */ +export function antigravityArchiveUrl(version: string, assetKey: AntigravityAssetKey): string { + const [folder, suffix] = ARCHIVE_NAMES[assetKey]; + return `${RELEASES_URL}/${folder}/agy-acp-server-${version}-${suffix}.zip`; +} -/** Registry entry `antigravity-acp` 1.5.2. */ +/** + * Registry entry `antigravity-acp` 1.5.2: the release installed when the + * registry can't be read, and the oldest one offered. A newer one Google + * lists is offered as an update (`antigravityListedRelease`). + */ export const ANTIGRAVITY_RELEASE: AntigravityRelease = { version: "1.5.2", assets: { "darwin-arm64": { - url: `${RELEASES_URL}/macos/agy-acp-server-1.5.2-darwin-arm64.zip`, + url: antigravityArchiveUrl("1.5.2", "darwin-arm64"), sha256: "123a16d5c40a8ac99e20f01a62b68dd860fd96b1c528dfb8eaa37ca8733d4845", archiveBytes: 100_309_778, ...POSIX_FILES(179_921_328, 129_208_672), }, "darwin-x64": { - url: `${RELEASES_URL}/macos/agy-acp-server-1.5.2-darwin-x86_64.zip`, + url: antigravityArchiveUrl("1.5.2", "darwin-x64"), sha256: "92addb5580577b5356d35484d72d1a113d9c5312ad766bcb304983aa8e3fbb06", archiveBytes: 106_351_992, ...POSIX_FILES(184_312_784, 134_350_320), }, "linux-arm64": { - url: `${RELEASES_URL}/linux/agy-acp-server-1.5.2-linux-arm64.zip`, + url: antigravityArchiveUrl("1.5.2", "linux-arm64"), sha256: "e729e05ef54ef0763e48900032466b47fa7c9939cde257f93ba49410ab577acb", archiveBytes: 264_270_419, ...POSIX_FILES(721_649_155, 132_598_576), }, "linux-x64": { - url: `${RELEASES_URL}/linux/agy-acp-server-1.5.2-linux-x86_64.zip`, + url: antigravityArchiveUrl("1.5.2", "linux-x64"), sha256: "99dd8612450805011619d7b8447ce374c289e00549d8557f36790e1dd6256852", archiveBytes: 273_964_075, ...POSIX_FILES(714_384_320, 139_194_456), }, "win32-arm64": { - url: `${RELEASES_URL}/windows/agy-acp-server-1.5.2-windows-arm64.zip`, + url: antigravityArchiveUrl("1.5.2", "win32-arm64"), sha256: "8a4b2ea8df2ffefae33309348752e9119d21a6d36090c0eb48631c2e8f5781ab", archiveBytes: 108_049_351, ...WINDOWS_FILES(65_130_848, 146_707_096), }, "win32-x64": { - url: `${RELEASES_URL}/windows/agy-acp-server-1.5.2-windows-x86_64.zip`, + url: antigravityArchiveUrl("1.5.2", "win32-x64"), sha256: "5cbadd4f4df698572473d8890fc26ec2dc1724501f06e3a963941daec2bd21d6", archiveBytes: 105_407_645, ...WINDOWS_FILES(58_368_800, 155_357_336), @@ -142,3 +172,44 @@ export function antigravityReleaseId(asset: Pick { return platform === "linux" ? ["--uid="] : []; } + +/** A release the ACP registry lists, before its file sizes are known. */ +export interface AntigravityListedRelease { + readonly version: string; + readonly url: string; + /** Lowercase hex sha256 of the zip. */ + readonly sha256: string; +} + +const PLAIN_VERSION = /^\d{1,4}\.\d{1,4}\.\d{1,6}$/u; + +/** + * Google's registry entry for this computer as an installable release, or + * undefined when it isn't one Threadlines knows how to run: a zip on Google's + * own download folder, under the name Google always uses, with a checksum, + * launching the ACP server the usual way with no extra environment. Anything + * else waits for a Threadlines release that knows it. + */ +export function antigravityListedRelease( + recipe: AcpRegistryRecipe, + assetKey: AntigravityAssetKey, + platform: NodeJS.Platform, +): AntigravityListedRelease | undefined { + if (recipe.agentId !== ANTIGRAVITY_REGISTRY_AGENT_ID || recipe.kind !== "download") { + return undefined; + } + const executable = platform === "win32" ? "agy_acp_server.exe" : "agy_acp_server.par"; + const launchArgs = antigravityLaunchArgs(platform); + const fits = + PLAIN_VERSION.test(recipe.version) && + recipe.format === "zip" && + recipe.sha256 !== null && + recipe.url === antigravityArchiveUrl(recipe.version, assetKey) && + recipe.cmd === executable && + recipe.args.length === launchArgs.length && + recipe.args.every((arg, index) => arg === launchArgs[index]) && + Object.keys(recipe.env).length === 0; + return fits && recipe.sha256 !== null + ? { version: recipe.version, url: recipe.url, sha256: recipe.sha256 } + : undefined; +} diff --git a/apps/server/src/provider/antigravity/AntigravityReleaseSource.ts b/apps/server/src/provider/antigravity/AntigravityReleaseSource.ts new file mode 100644 index 000000000..48b9efc0f --- /dev/null +++ b/apps/server/src/provider/antigravity/AntigravityReleaseSource.ts @@ -0,0 +1,133 @@ +/** + * AntigravityReleaseSource — which Antigravity release Threadlines offers. + * + * Google lists each new Antigravity in the ACP registry. When that listing + * is newer than the built-in release and fits what Threadlines knows how to + * run (`antigravityListedRelease`), it is offered, so a new version (and the + * models it brings) reaches users without waiting for a Threadlines release. + * Otherwise, and whenever the registry 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 * as Option from "effect/Option"; + +import type { AcpRegistryCatalogShape } from "../acpRegistry/AcpRegistryCatalog.ts"; +import type { ManagedRuntimeError } from "../managedRuntime/ManagedRuntimeStore.ts"; +import { + ANTIGRAVITY_REGISTRY_AGENT_ID, + type AntigravityAssetKey, + type AntigravityListedRelease, + type AntigravityPlatformRelease, + antigravityListedRelease, +} from "./AntigravityRelease.ts"; +import { type AntigravityFetch, resolveAntigravityListedRelease } from "./AntigravityRuntime.ts"; + +export interface AntigravityReleaseOffer { + readonly version: string; + /** The release with its file sizes, for `AntigravityRuntime.install`. */ + readonly release: Effect.Effect; +} + +export interface AntigravityReleaseSource { + /** + * The release to offer. Never fails. Asks the registry 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 registry couldn't be read, the saved copy is used until then. */ +const RETRY_AFTER_FAILURE_MS = 10 * 60 * 1000; +const WAIT_AT_MOST = Duration.seconds(4); + +export function makeAntigravityReleaseSource(input: { + readonly builtIn: AntigravityPlatformRelease; + readonly assetKey: AntigravityAssetKey; + readonly platform: NodeJS.Platform; + readonly catalog: Pick; + /** Test seam for reading a listed release's sizes. */ + readonly fetch?: AntigravityFetch; +}): AntigravityReleaseSource { + const { builtIn } = input; + const builtInOffer: AntigravityReleaseOffer = { + version: builtIn.version, + release: Effect.succeed(builtIn), + }; + const executableName = builtIn.asset.executable.name; + const harnessName = builtIn.asset.harness.name; + + /** Releases whose sizes were read, so each is read once. */ + const resolved = new Map(); + const offerFor = (listed: AntigravityListedRelease): AntigravityReleaseOffer => ({ + version: listed.version, + release: Effect.suspend(() => { + const key = [listed.version, listed.url, listed.sha256].join("\u0000"); + const known = resolved.get(key); + if (known) return Effect.succeed(known); + return resolveAntigravityListedRelease({ + listed, + executableName, + harnessName, + ...(input.fetch ? { fetch: input.fetch } : {}), + }).pipe(Effect.tap((release) => Effect.sync(() => resolved.set(key, release)))); + }), + }); + + const fromRegistry = (ask: boolean) => + Effect.gen(function* () { + const fresh = ask + ? yield* input.catalog.get().pipe( + Effect.timeoutOption(WAIT_AT_MOST), + Effect.map(Option.getOrUndefined), + Effect.orElseSucceed(() => undefined), + ) + : undefined; + const snapshot = fresh ?? (yield* input.catalog.peek); + // A release the registry has pulled must not be offered, so nothing is + // offered until the list of pulled agents has been read. + const recipe = + snapshot?.quarantineKnown !== true + ? undefined + : snapshot.builtIn.find( + (candidate) => candidate.agentId === ANTIGRAVITY_REGISTRY_AGENT_ID, + ); + const listed = recipe && antigravityListedRelease(recipe, input.assetKey, input.platform); + const offer = + listed && compareSemverVersions(listed.version, builtIn.version) > 0 + ? offerFor(listed) + : builtInOffer; + // Only an answer from the registry counts as asked; a saved copy (the + // registry couldn't be read) is asked again next time. + return { offer, asked: fresh !== undefined && !fresh.stale }; + }); + + let last: { readonly offer: AntigravityReleaseOffer; readonly askedAtMs: number } | undefined; + let failedAtMs: number | undefined; + const within = (sinceMs: number | undefined, nowMs: number, spanMs: number) => + sinceMs !== undefined && nowMs - sinceMs >= 0 && nowMs - sinceMs < spanMs; + const newest = Effect.gen(function* () { + const nowMs = yield* Clock.currentTimeMillis; + if (last && within(last.askedAtMs, nowMs, ASK_EVERY_MS)) return last.offer; + // While the registry is down, every refresh would ask again: wait a while. + const ask = !within(failedAtMs, nowMs, RETRY_AFTER_FAILURE_MS); + const { offer, asked } = yield* fromRegistry(ask); + if (asked) { + last = { offer, askedAtMs: nowMs }; + failedAtMs = undefined; + } else if (ask) { + failedAtMs = nowMs; + } + return offer; + }); + + return { newest }; +} diff --git a/apps/server/src/provider/antigravity/AntigravityRuntime.test.ts b/apps/server/src/provider/antigravity/AntigravityRuntime.test.ts index 5dbb8b663..18de2e3ea 100644 --- a/apps/server/src/provider/antigravity/AntigravityRuntime.test.ts +++ b/apps/server/src/provider/antigravity/AntigravityRuntime.test.ts @@ -11,7 +11,15 @@ import { assert, describe, it } from "@effect/vitest"; import * as Effect from "effect/Effect"; import * as Fiber from "effect/Fiber"; -import type { AntigravityPlatformRelease } from "./AntigravityRelease.ts"; +import type { AcpRegistryCatalogSnapshot } from "../acpRegistry/AcpRegistryCatalog.ts"; +import { AcpRegistryError } from "@threadlines/contracts"; +import type { AcpRegistryDownloadRecipe } from "../acpRegistry/AcpRegistryRecipe.ts"; +import { + type AntigravityPlatformRelease, + antigravityArchiveUrl, + antigravityReleaseFor, +} from "./AntigravityRelease.ts"; +import { makeAntigravityReleaseSource } from "./AntigravityReleaseSource.ts"; import { type AntigravityFetch, type AntigravityInstallProgress, @@ -157,14 +165,13 @@ describe("makeAntigravityRuntime", () => { const { calls, validate } = recordingValidate(); const runtime = makeAntigravityRuntime({ root, - release: fixture.release, 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); @@ -211,7 +218,7 @@ describe("makeAntigravityRuntime", () => { ); // Installing again reuses the files on disk: validated, not downloaded. - yield* runtime.install(); + yield* runtime.install(fixture.release); assert.equal(server.requests.length, 1); assert.equal(calls.length, 2); }), @@ -227,12 +234,11 @@ describe("makeAntigravityRuntime", () => { const { calls, validate } = recordingValidate(); const runtime = makeAntigravityRuntime({ root, - release: fixture.release, 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.deepStrictEqual(yield* listDir(path.join(root, "versions")), []); @@ -262,11 +268,10 @@ describe("makeAntigravityRuntime", () => { for (const fixture of fixtures) { const runtime = makeAntigravityRuntime({ root, - release: fixture.release, validate, fetch: server.fetch, }); - const error = yield* Effect.flip(runtime.install()); + const error = yield* Effect.flip(runtime.install(fixture.release)); assert.equal(error.reason, "archive", fixture.release.version); } assert.deepStrictEqual(yield* listDir(path.join(root, "versions")), []); @@ -282,12 +287,11 @@ describe("makeAntigravityRuntime", () => { 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); @@ -314,7 +318,6 @@ describe("makeAntigravityRuntime", () => { ); const runtime = makeAntigravityRuntime({ root, - release: fixture.release, validate: recordingValidate().validate, fetch, }); @@ -324,7 +327,7 @@ describe("makeAntigravityRuntime", () => { }); const fiber = yield* runtime - .install((update) => { + .install(fixture.release, (update) => { if (update.receivedBytes) markStarted(); }) .pipe(Effect.forkChild); @@ -345,26 +348,24 @@ describe("makeAntigravityRuntime", () => { 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 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); // 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); @@ -401,20 +402,18 @@ describe("makeAntigravityRuntime", () => { 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 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 +422,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"); @@ -456,28 +454,25 @@ describe("makeAntigravityRuntime", () => { 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 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 +496,121 @@ describe("makeAntigravityRuntime", () => { }), ); }); + +describe("makeAntigravityReleaseSource", () => { + const builtIn = antigravityReleaseFor("darwin", "arm64")!; + const listing = ( + overrides: Partial = {}, + ): AcpRegistryDownloadRecipe => ({ + kind: "download", + agentId: "antigravity-acp", + version: "9.0.0", + args: [], + env: {}, + url: antigravityArchiveUrl(overrides.version ?? "9.0.0", "darwin-arm64"), + sha256: "0".repeat(64), + format: "zip", + cmd: EXECUTABLE, + ...overrides, + }); + const catalogListing = ( + recipes: ReadonlyArray | "unreadable", + quarantineKnown = true, + ) => ({ + get: () => + recipes === "unreadable" + ? Effect.fail(new AcpRegistryError({ reason: "catalogUnavailable", detail: "offline" })) + : Effect.succeed({ + entries: [], + fetchedAt: null, + stale: false, + quarantineKnown, + unsupportedCount: 0, + builtIn: recipes, + }), + peek: Effect.succeed(undefined), + }); + + /** Answers range requests with their bytes and the zip's size, like Google's server. */ + function rangeServer(url: string, body: Buffer) { + const ranges: Array = []; + const fetch: AntigravityFetch = async (requested, init) => { + if (requested !== url) return new Response(null, { status: 404 }); + const range = new Headers(init.headers).get("range"); + if (range === null) return new Response(new Uint8Array(body)); + ranges.push(range); + const [, start, end] = /^bytes=(\d+)-(\d+)$/u.exec(range)!; + return new Response(new Uint8Array(body.subarray(Number(start), Number(end) + 1)), { + status: 206, + headers: { "content-range": `bytes ${start}-${end}/${body.length}` }, + }); + }; + return { fetch, ranges }; + } + + it.live("offers Google's newer release and installs it, sizes read from the zip's index", () => + Effect.gen(function* () { + const fixture = makeFixture("listed"); + const recipe = listing({ version: "9.1.0", sha256: fixture.release.asset.sha256 }); + const server = rangeServer(recipe.url, fixture.zip); + const source = makeAntigravityReleaseSource({ + builtIn, + assetKey: "darwin-arm64", + platform: "darwin", + catalog: catalogListing([recipe]), + fetch: server.fetch, + }); + + const offer = yield* source.newest; + assert.equal(offer.version, "9.1.0"); + const release = yield* offer.release; + assert.deepStrictEqual(release, { + version: "9.1.0", + asset: { ...fixture.release.asset, url: recipe.url }, + }); + // The index only: far less than the whole zip. + assert.isAbove(server.ranges.length, 0); + + const root = yield* tempRoot; + const runtime = makeAntigravityRuntime({ + root, + validate: recordingValidate().validate, + fetch: server.fetch, + }); + yield* runtime.install(release); + assert.equal((yield* runtime.installed)?.version, "9.1.0"); + }), + ); + + it.live("keeps the built-in release unless Google lists a newer one Threadlines can run", () => + Effect.gen(function* () { + const offered = ( + recipes: ReadonlyArray | "unreadable", + quarantineKnown = true, + ) => + makeAntigravityReleaseSource({ + builtIn, + assetKey: "darwin-arm64", + platform: "darwin", + catalog: catalogListing(recipes, quarantineKnown), + }).newest.pipe(Effect.map((offer) => offer.version)); + + assert.equal(yield* offered([listing()]), "9.0.0"); + // Until the registry's list of pulled releases is known, nothing listed is offered. + assert.equal(yield* offered([listing()], false), builtIn.version); + const keepsBuiltIn = [ + "unreadable" as const, + [] as const, + [listing({ version: "1.0.0" })], + [listing({ url: "https://example.com/agy-acp-server-9.0.0-darwin-arm64.zip" })], + [listing({ args: ["--debug"] })], + [listing({ env: { GEMINI_HOME: "/tmp" } })], + [listing({ sha256: null })], + [listing({ cmd: "other.par" })], + ]; + for (const recipes of keepsBuiltIn) { + assert.equal(yield* offered(recipes), builtIn.version, JSON.stringify(recipes)); + } + }), + ); +}); diff --git a/apps/server/src/provider/antigravity/AntigravityRuntime.ts b/apps/server/src/provider/antigravity/AntigravityRuntime.ts index 3af6fb2ff..e714a5317 100644 --- a/apps/server/src/provider/antigravity/AntigravityRuntime.ts +++ b/apps/server/src/provider/antigravity/AntigravityRuntime.ts @@ -1,7 +1,7 @@ // @effect-diagnostics nodeBuiltinImport:off - streams the download and zip entries to disk /** * AntigravityRuntime — Threadlines' own copy of the Antigravity ACP server. - * It downloads the pinned release, verifies and unpacks it, and keeps it in a + * 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). @@ -14,6 +14,7 @@ import { createWriteStream } from "node:fs"; import * as NodeFS from "node:fs/promises"; import * as NodePath from "node:path"; +import { PassThrough, Readable } from "node:stream"; import { pipeline } from "node:stream/promises"; import * as Effect from "effect/Effect"; @@ -34,8 +35,11 @@ import { makeManagedRuntimeStore, statIfExists, } from "../managedRuntime/ManagedRuntimeStore.ts"; +import { makeHttpsFetch } from "../managedRuntime/HttpsFetch.ts"; import { type DownloadFetch, downloadVerified } from "../managedRuntime/VerifiedDownload.ts"; import { + ANTIGRAVITY_DOWNLOAD_HOST, + type AntigravityListedRelease, type AntigravityPlatformRelease, type AntigravityReleaseAsset, type AntigravityReleaseFile, @@ -57,16 +61,25 @@ export type AntigravityInstallProgress = ManagedInstallProgress; /** The part of `fetch` the runtime uses; tests pass a stub. */ export type AntigravityFetch = DownloadFetch; +/** + * Downloads from Google's download 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 unpacked files are `release` and work (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: runs in `acquire` after the active version is resolved, before its lease is written. */ readonly beforeLeaseWritten?: (versionDir: string) => Effect.Effect; @@ -76,11 +89,12 @@ 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>; /** @@ -257,14 +271,173 @@ async function extractArchive(input: { } } -/** Builds the runtime for one root and release. Cheap; holds no resources. */ +// ── A listed release's sizes ───────────────────────────────────────── + +/** Far above any real build (the largest 1.5.2 zip is 274 MB). */ +const MAX_LISTED_ARCHIVE_BYTES = 2 * 1024 ** 3; +const MAX_LISTED_FILE_BYTES = 4 * 1024 ** 3; +const LISTED_INDEX_TIMEOUT_MS = 60_000; + +/** + * Bytes `start` to `end` (exclusive) of `url`, and the file's total size when + * the server names it. Reads no more than asked for, whatever the server sends. + */ +async function readRange( + fetchRange: AntigravityFetch, + url: string, + start: number, + end: number, + signal: AbortSignal, +): Promise<{ readonly bytes: Uint8Array; readonly total: number | undefined }> { + const response = await fetchRange(url, { + headers: { range: `bytes=${start}-${end - 1}`, "accept-encoding": "identity" }, + redirect: "follow", + signal, + }); + if (response.status !== 206 || response.body === null) { + await response.body?.cancel().catch(() => undefined); + throw new Error(`${url} answered a range request with ${response.status}`); + } + const wanted = end - start; + const bytes = new Uint8Array(wanted); + let received = 0; + const reader = response.body.getReader(); + try { + for (;;) { + const { done, value } = await reader.read(); + if (done) break; + if (received + value.byteLength > wanted) { + throw new Error(`asked ${url} for ${wanted} bytes, got more`); + } + bytes.set(value, received); + received += value.byteLength; + } + } finally { + await reader.cancel().catch(() => undefined); + } + if (received !== wanted) throw new Error(`asked ${url} for ${wanted} bytes, got ${received}`); + const total = /\/(\d+)$/u.exec(response.headers.get("content-range") ?? "")?.[1]; + return { bytes, total: total === undefined ? undefined : Number(total) }; +} + +/** Reads byte ranges of a zip on a server, so its index can be read without the download. */ +class RangeReader extends yauzl.RandomAccessReader { + private readonly url: string; + private readonly fetchRange: AntigravityFetch; + private readonly signal: AbortSignal; + + constructor(url: string, fetchRange: AntigravityFetch, signal: AbortSignal) { + super(); + this.url = url; + this.fetchRange = fetchRange; + this.signal = signal; + } + + override _readStreamForRange(start: number, end: number): Readable { + const out = new PassThrough(); + if (end <= start) { + out.end(); + return out; + } + readRange(this.fetchRange, this.url, start, end, this.signal).then( + (range) => out.end(range.bytes), + (cause: unknown) => out.destroy(cause instanceof Error ? cause : new Error(String(cause))), + ); + return out; + } +} + +/** + * A listed release with its sizes, so its install is checked exactly like + * the built-in release's: the zip's length from Google's server, and each + * file's from the zip's own index, read with a few small range requests + * rather than the whole download. What the sizes come from is checked again + * by the install: the zip must hash to the sha256 the registry lists and + * unpack to these sizes. + */ +export const resolveAntigravityListedRelease = (input: { + readonly listed: AntigravityListedRelease; + /** The two file names the zip must hold (`AntigravityReleaseAsset`). */ + readonly executableName: string; + readonly harnessName: string; + readonly fetch?: AntigravityFetch; +}): Effect.Effect => { + const fetchRange: AntigravityFetch = input.fetch ?? makeAntigravityDownloadFetch(); + const { listed } = input; + const unreachable = runtimeError( + "download", + `Couldn't reach Google to download Antigravity ${listed.version}. Check your internet connection and try again.`, + ); + const malformed = (detail: string) => + runtimeError("archive", MESSAGES.archive, { detail: `${listed.url}: ${detail}` }); + return abortable( + async (signal) => { + const timeout = AbortSignal.timeout(LISTED_INDEX_TIMEOUT_MS); + const both = AbortSignal.any([signal, timeout]); + // The first byte, for the zip's size (`Content-Range: bytes 0-0/`). + const first = await readRange(fetchRange, listed.url, 0, 1, both).catch((cause: unknown) => { + throw runtimeError("download", unreachable.message, { cause }); + }); + const archiveBytes = first.total ?? Number.NaN; + if (!Number.isSafeInteger(archiveBytes) || archiveBytes <= 0) { + throw malformed("the server gave no size"); + } + if (archiveBytes > MAX_LISTED_ARCHIVE_BYTES) throw malformed(`${archiveBytes} bytes`); + const reader = new RangeReader(listed.url, fetchRange, both); + let zip: yauzl.ZipFile; + try { + zip = await yauzl.fromRandomAccessReaderPromise(reader, archiveBytes, { + autoClose: false, + lazyEntries: true, + strictFileNames: true, + validateEntrySizes: true, + }); + } catch (cause) { + throw runtimeError("archive", MESSAGES.archive, { + detail: `${listed.url}: unreadable index`, + cause, + }); + } + try { + const sizes = new Map(); + for await (const entry of zip.eachEntry()) { + if (sizes.has(entry.fileName)) throw malformed(`duplicate entry "${entry.fileName}"`); + sizes.set(entry.fileName, entry.uncompressedSize); + } + const names = [input.executableName, input.harnessName]; + if (sizes.size !== 2 || names.some((name) => !sizes.has(name))) { + throw malformed(`holds ${[...sizes.keys()].join(", ")}, expected ${names.join(", ")}`); + } + const fileOf = (name: string) => { + const bytes = sizes.get(name)!; + if (bytes <= 0 || bytes > MAX_LISTED_FILE_BYTES) + throw malformed(`${name} is ${bytes} bytes`); + return { name, bytes }; + }; + return { + version: listed.version, + asset: { + url: listed.url, + sha256: listed.sha256, + archiveBytes, + executable: fileOf(input.executableName), + harness: fileOf(input.harnessName), + }, + }; + } finally { + zip.close(); + reader.close(() => undefined); + } + }, + (cause) => runtimeError("download", unreachable.message, { cause }), + ); +}; + +/** 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 store = makeManagedRuntimeStore({ root: options.root, label: LABEL, @@ -276,8 +449,8 @@ export function makeAntigravityRuntime( ...(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), @@ -288,9 +461,10 @@ export function makeAntigravityRuntime( /** Downloads the zip into the staging folder and unpacks its two files. */ 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); report({ phase: "downloading", receivedBytes: 0, totalBytes: asset.archiveBytes }); @@ -322,14 +496,15 @@ export function makeAntigravityRuntime( ); yield* fsTry("save Antigravity's files", () => NodeFS.rm(archivePath, { force: true })); 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 }, }; }); - const install: AntigravityRuntime["install"] = (onProgress) => { + const install: AntigravityRuntime["install"] = (release, onProgress) => { + const { asset } = release; const report = (progress: AntigravityInstallProgress) => { try { onProgress?.(progress); @@ -338,11 +513,11 @@ export function makeAntigravityRuntime( } }; 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)), + build: build(release, report), + validate: (version) => validatePaths(pathsOf(version), release), onPhase: (phase) => report({ phase }), }); }; diff --git a/docs/providers/antigravity.md b/docs/providers/antigravity.md index af8847b37..0758655f8 100644 --- a/docs/providers/antigravity.md +++ b/docs/providers/antigravity.md @@ -4,6 +4,22 @@ Antigravity is Google's coding agent. Threadlines downloads and checks Google's server for you (`Install` on the Antigravity row in `Settings -> Providers`), so there is nothing to install by hand. +## Updates + +Threadlines checks Google's listing in the ACP registry 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 +Gemini models arrive this way, since each Antigravity version lists its own models. + +Threadlines only offers a release that comes from Google's own download folder under the usual +name, with a checksum, launched the usual way. It reads the file sizes from the zip's index before +downloading, checks the download against the listed checksum and those sizes, and starts the new +copy once to make sure it's Antigravity at that version before switching to it. If the registry +can't be read, the version built into Threadlines is offered instead, and an installed copy is +never replaced by an older one. + +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 listing changes so Threadlines would refuse it. + ## Sign-In Methods Open `Settings -> Providers`, open the Antigravity row, and pick a method under `Sign-in method` on From c44396a8ac492a15d8d689a3f8dd94b8cd03337d Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Mon, 23 Nov 2026 01:00:24 -0500 Subject: [PATCH 03/59] ci: weekly check for versions we pin by hand that fall behind their vendor Dependabot covers package.json but not versions written into code. A weekly workflow (free on standard runners, since the repo is public) compares the Antigravity built-in release, the managed Node.js release, the ACP schema and the Codex app-server protocol against what their vendors publish. It opens one issue per pin that is behind, keeps its body current, and closes it once the pin catches up. Issues are found by a hidden marker in the body, so a renamed issue is still found and one filed by hand is never touched. For Antigravity it also flags builds whose listing Threadlines' live update would refuse. --- .github/workflows/upstream-drift.yml | 51 +++ scripts/check-upstream-drift.test.ts | 66 +++ scripts/check-upstream-drift.ts | 629 +++++++++++++++++++++++++++ 3 files changed, 746 insertions(+) create mode 100644 .github/workflows/upstream-drift.yml create mode 100644 scripts/check-upstream-drift.test.ts create mode 100644 scripts/check-upstream-drift.ts 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/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..8f87aa877 --- /dev/null +++ b/scripts/check-upstream-drift.ts @@ -0,0 +1,629 @@ +#!/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 ACP_REGISTRY_URL = "https://cdn.agentclientprotocol.com/registry/v1/latest/registry.json"; +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: "the Antigravity agent at", + source: "The ACP registry", + pinned: antigravity, + file: ANTIGRAVITY_FILE, + howToUpdate: ({ version }) => [ + `Users are already offered ${version} through Settings (\`AntigravityReleaseSource\`) wherever the listing fits; this pin is what installs when the registry can't be read, and the oldest version offered.`, + 'Check the sign-in behavior noted in `apps/server/src/provider/antigravity/AntigravitySignInMethod.ts` against the new version, and update its "Verified against" line.', + `Then set the built-in release to ${version}: the sha256 values are in ${ACP_REGISTRY_URL}, and \`resolveAntigravityListedRelease\` (or any zip index reader) gives the sizes.`, + ], + }, + lookup: async () => { + const registry = await fetchJson(ACP_REGISTRY_URL); + const agents = field(registry, "agents"); + const agent = Array.isArray(agents) + ? agents.find((entry: unknown) => field(entry, "id") === "antigravity-acp") + : undefined; + const version = field(agent, "version"); + if (typeof version !== "string") + throw new Error("no antigravity-acp entry in the registry"); + const refused = await antigravityBuildsThreadlinesRefuses(version, agent); + return { + version, + ...(refused.length > 0 + ? { + notes: [ + `Threadlines won't offer this release on ${refused.join(", ")}: Google's listing changed (archive name, command, arguments or environment), so \`antigravityListedRelease\` refuses it. Check what changed and teach Threadlines to run 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 }; + }, + }, + ]; +} + +/** The registry's name for each Antigravity build, by Threadlines' name and Node platform. */ +const ANTIGRAVITY_BUILDS = [ + ["darwin-aarch64", "darwin-arm64", "darwin"], + ["darwin-x86_64", "darwin-x64", "darwin"], + ["linux-aarch64", "linux-arm64", "linux"], + ["linux-x86_64", "linux-x64", "linux"], + ["windows-aarch64", "win32-arm64", "win32"], + ["windows-x86_64", "win32-x64", "win32"], +] as const; + +/** + * The builds of Google's listing that Threadlines' live update would refuse + * (`antigravityListedRelease`), so users there never see the new version. + * Mirrors the registry reader's shaping of a download entry, simplified. + */ +async function antigravityBuildsThreadlinesRefuses( + version: string, + agent: unknown, +): Promise> { + const module: unknown = await import(pathToFileURL(join(ROOT, ANTIGRAVITY_FILE)).href); + const fits = field(module, "antigravityListedRelease"); + if (typeof fits !== "function") + throw new Error(`No antigravityListedRelease in ${ANTIGRAVITY_FILE}`); + const binary = field(field(agent, "distribution"), "binary"); + return ANTIGRAVITY_BUILDS.flatMap(([registryKey, assetKey, platform]) => { + const build = field(binary, registryKey); + const archive = field(build, "archive"); + const cmd = field(build, "cmd"); + const sha256 = field(build, "sha256"); + const recipe = { + kind: "download", + agentId: "antigravity-acp", + version, + args: field(build, "args") ?? [], + env: field(build, "env") ?? {}, + url: archive, + sha256: typeof sha256 === "string" ? sha256.toLowerCase() : null, + format: typeof archive === "string" && archive.endsWith(".zip") ? "zip" : "other", + cmd: typeof cmd === "string" ? cmd.replace(/^\.\//u, "") : cmd, + }; + const ok = typeof archive === "string" && fits(recipe, assetKey, platform) !== undefined; + return ok ? [] : [registryKey]; + }); +} + +// ── 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; + }); +} From 81c5d3aa81a1c13cdfa63c5e2aef53cfcc5fb3a8 Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Mon, 23 Nov 2026 01:29:36 -0500 Subject: [PATCH 04/59] docs: plan for moving Antigravity to Google's CLI and matching T3 Code Google does its ACP work in the Antigravity CLI (agy acp), which is at 1.5.14 while the registry package we install is at 1.5.2. The plan covers the runtime switch, sign-in, models and modes, turn handling, the user's own rules and skills, usage, and the swarm work from Google's open T3 PR, in four stages. Reviewed once by an outside model; its eight findings are in. --- docs/providers/antigravity-cli-plan.md | 222 +++++++++++++++++++++++++ 1 file changed, 222 insertions(+) create mode 100644 docs/providers/antigravity-cli-plan.md diff --git a/docs/providers/antigravity-cli-plan.md b/docs/providers/antigravity-cli-plan.md new file mode 100644 index 000000000..96900ea76 --- /dev/null +++ b/docs/providers/antigravity-cli-plan.md @@ -0,0 +1,222 @@ +# 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. +- 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. From b74ee5e19480ae4218c47774d18df40f05e0e524 Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Mon, 23 Nov 2026 02:07:40 -0500 Subject: [PATCH 05/59] feat(acp): introduce Threadlines by name, tell agents' mode maps what a session offers, check an agent after initialize - `initialize` now sends Threadlines' own name, title and version (`THREADLINES_ACP_CLIENT_INFO`) instead of a 0.0.0 placeholder. - `agentModeFor` gets the modes the session offers, so a descriptor can pick a mode only when it exists. - A descriptor's `verifyAgent` sees the `initialize` answer before a session opens and can refuse an agent too old to run. - The stand-in agent can report an `agentInfo` and refuse to reopen a saved session; a test shows a refused reopen starts a fresh session marked `resumeFailed`, which makes the next message carry the thread's history. --- apps/server/scripts/acp-mock-agent.ts | 35 +++++++++++-------- .../src/provider/acp/AcpAdapter.test.ts | 28 +++++++++++++++ apps/server/src/provider/acp/AcpAdapter.ts | 4 ++- apps/server/src/provider/acp/AcpProvider.ts | 3 +- .../src/provider/acp/AcpProviderDescriptor.ts | 11 ++++++ .../src/provider/acp/AcpProviderRuntime.ts | 8 +++++ .../src/provider/acp/AcpSessionRuntime.ts | 9 +++++ .../src/provider/acp/AcpTextGeneration.ts | 5 ++- apps/server/src/provider/acp/acpClientInfo.ts | 13 +++++++ 9 files changed, 99 insertions(+), 17 deletions(-) create mode 100644 apps/server/src/provider/acp/acpClientInfo.ts 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/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..46ffdb09d 100644 --- a/apps/server/src/provider/acp/AcpAdapter.ts +++ b/apps/server/src/provider/acp/AcpAdapter.ts @@ -126,6 +126,7 @@ import { acpTurnUsageTotals, parsePermissionRequest, } from "./AcpRuntimeModel.ts"; +import { THREADLINES_ACP_CLIENT_INFO } from "./acpClientInfo.ts"; import { type AcpSessionRuntimeShape } from "./AcpSessionRuntime.ts"; const encodeUnknownJsonStringExit = Schema.encodeUnknownExit(Schema.fromJsonString(Schema.Unknown)); @@ -1124,6 +1125,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 && @@ -1387,7 +1389,7 @@ 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 } : {}), diff --git a/apps/server/src/provider/acp/AcpProvider.ts b/apps/server/src/provider/acp/AcpProvider.ts index d102e0861..6668d92bc 100644 --- a/apps/server/src/provider/acp/AcpProvider.ts +++ b/apps/server/src/provider/acp/AcpProvider.ts @@ -9,6 +9,7 @@ * * @module provider/acp/AcpProvider */ +import { THREADLINES_ACP_CLIENT_INFO } from "./acpClientInfo.ts"; import type { ModelCapabilities, ServerProvider, @@ -270,7 +271,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); diff --git a/apps/server/src/provider/acp/AcpProviderDescriptor.ts b/apps/server/src/provider/acp/AcpProviderDescriptor.ts index a32d9ea7a..bfd7f7dc0 100644 --- a/apps/server/src/provider/acp/AcpProviderDescriptor.ts +++ b/apps/server/src/provider/acp/AcpProviderDescriptor.ts @@ -421,7 +421,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 diff --git a/apps/server/src/provider/acp/AcpProviderRuntime.ts b/apps/server/src/provider/acp/AcpProviderRuntime.ts index 1d0d350a8..2d2f24c50 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, @@ -44,6 +45,7 @@ export interface AcpProviderRuntimeInput e | "sessionControls" | "spawn" | "stderrFailure" + | "verifyInitialize" > { readonly childProcessSpawner: ChildProcessSpawner.ChildProcessSpawner["Service"]; readonly settings: Settings; @@ -123,6 +125,12 @@ export const makeAcpProviderRuntime = ( ...(descriptor.initializeMeta ? { initializeMeta: descriptor.initializeMeta } : {}), ...(descriptor.cancelMeta ? { cancelMeta: descriptor.cancelMeta } : {}), ...(descriptor.contextUsage ? { contextUsage: descriptor.contextUsage } : {}), + ...(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/AcpSessionRuntime.ts b/apps/server/src/provider/acp/AcpSessionRuntime.ts index 0e5d8218e..75c43243a 100644 --- a/apps/server/src/provider/acp/AcpSessionRuntime.ts +++ b/apps/server/src/provider/acp/AcpSessionRuntime.ts @@ -98,8 +98,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 @@ -740,6 +748,7 @@ const makeAcpSessionRuntime = ( ); yield* Ref.set(initializeResultRef, initializeResult); + if (options.verifyInitialize) yield* options.verifyInitialize(initializeResult); if (shouldAuthenticate(options.authMethodId, initializeResult.authMethods)) { const authenticatePayload = { 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/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; From 1b4f735161d66c21ad33e8368e2f24cccf9a136b Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Mon, 23 Nov 2026 02:07:40 -0500 Subject: [PATCH 06/59] ci: weekly drift check compares Antigravity with Google's CLI update feed It reads every build's manifest, takes the newest version any build has (a release can reach one platform first), and notes builds whose manifest Threadlines would refuse. --- scripts/check-upstream-drift.ts | 111 +++++++++++++++----------------- 1 file changed, 52 insertions(+), 59 deletions(-) diff --git a/scripts/check-upstream-drift.ts b/scripts/check-upstream-drift.ts index 8f87aa877..705042f40 100644 --- a/scripts/check-upstream-drift.ts +++ b/scripts/check-upstream-drift.ts @@ -224,7 +224,6 @@ const MANAGED_NODE_FILE = "apps/server/src/provider/managedRuntime/ManagedNode.t const ACP_GENERATE_FILE = "packages/effect-acp/scripts/generate.ts"; const CODEX_GENERATE_FILE = "packages/effect-codex-app-server/scripts/generate.ts"; -const ACP_REGISTRY_URL = "https://cdn.agentclientprotocol.com/registry/v1/latest/registry.json"; 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"; @@ -273,32 +272,59 @@ export async function loadPins(): Promise> { item: { id: "antigravity", title: "Upstream drift: Antigravity", - name: "the Antigravity agent at", - source: "The ACP registry", + 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 listing fits; this pin is what installs when the registry can't be read, and the oldest version offered.`, - 'Check the sign-in behavior noted in `apps/server/src/provider/antigravity/AntigravitySignInMethod.ts` against the new version, and update its "Verified against" line.', - `Then set the built-in release to ${version}: the sha256 values are in ${ACP_REGISTRY_URL}, and \`resolveAntigravityListedRelease\` (or any zip index reader) gives the sizes.`, + `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 registry = await fetchJson(ACP_REGISTRY_URL); - const agents = field(registry, "agents"); - const agent = Array.isArray(agents) - ? agents.find((entry: unknown) => field(entry, "id") === "antigravity-acp") - : undefined; - const version = field(agent, "version"); - if (typeof version !== "string") - throw new Error("no antigravity-acp entry in the registry"); - const refused = await antigravityBuildsThreadlinesRefuses(version, agent); + 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 + ...(refused.length > 0 || behind.length > 0 ? { notes: [ - `Threadlines won't offer this release on ${refused.join(", ")}: Google's listing changed (archive name, command, arguments or environment), so \`antigravityListedRelease\` refuses it. Check what changed and teach Threadlines to run it.`, + ...(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.`, + ] + : []), ], } : {}), @@ -394,51 +420,18 @@ export async function loadPins(): Promise> { ]; } -/** The registry's name for each Antigravity build, by Threadlines' name and Node platform. */ +/** Threadlines' name for each Antigravity build (`AntigravityAssetKey`). */ const ANTIGRAVITY_BUILDS = [ - ["darwin-aarch64", "darwin-arm64", "darwin"], - ["darwin-x86_64", "darwin-x64", "darwin"], - ["linux-aarch64", "linux-arm64", "linux"], - ["linux-x86_64", "linux-x64", "linux"], - ["windows-aarch64", "win32-arm64", "win32"], - ["windows-x86_64", "win32-x64", "win32"], + "darwin-arm64", + "darwin-x64", + "linux-arm64", + "linux-x64", + "linux-arm64-musl", + "linux-x64-musl", + "win32-arm64", + "win32-x64", ] as const; -/** - * The builds of Google's listing that Threadlines' live update would refuse - * (`antigravityListedRelease`), so users there never see the new version. - * Mirrors the registry reader's shaping of a download entry, simplified. - */ -async function antigravityBuildsThreadlinesRefuses( - version: string, - agent: unknown, -): Promise> { - const module: unknown = await import(pathToFileURL(join(ROOT, ANTIGRAVITY_FILE)).href); - const fits = field(module, "antigravityListedRelease"); - if (typeof fits !== "function") - throw new Error(`No antigravityListedRelease in ${ANTIGRAVITY_FILE}`); - const binary = field(field(agent, "distribution"), "binary"); - return ANTIGRAVITY_BUILDS.flatMap(([registryKey, assetKey, platform]) => { - const build = field(binary, registryKey); - const archive = field(build, "archive"); - const cmd = field(build, "cmd"); - const sha256 = field(build, "sha256"); - const recipe = { - kind: "download", - agentId: "antigravity-acp", - version, - args: field(build, "args") ?? [], - env: field(build, "env") ?? {}, - url: archive, - sha256: typeof sha256 === "string" ? sha256.toLowerCase() : null, - format: typeof archive === "string" && archive.endsWith(".zip") ? "zip" : "other", - cmd: typeof cmd === "string" ? cmd.replace(/^\.\//u, "") : cmd, - }; - const ok = typeof archive === "string" && fits(recipe, assetKey, platform) !== undefined; - return ok ? [] : [registryKey]; - }); -} - // ── I/O ────────────────────────────────────────────────────────────── const FETCH_TIMEOUT_MS = 20_000; From a355d3e51824561991a4aa818a0341cc33bf2a34 Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Mon, 23 Nov 2026 02:07:40 -0500 Subject: [PATCH 07/59] feat(antigravity): run Google's Antigravity CLI (agy acp) instead of the old ACP server Google moved its ACP work into the Antigravity CLI; the agy_acp_server package from the ACP registry was stuck at 1.5.2 while the CLI is at 1.5.14. Install and update - Releases come from Google's CLI update feed (sha512, no sizes) with a built-in 1.5.14 fallback whose download and executable sizes were measured. Hosts are allowlisted on every redirect hop, feed releases are capped, the tarball must hold exactly one regular file named `antigravity` (shared archive extractor: no links, no escapes), Windows gets the bare agy.exe, and Linux musl systems get Google's musl build. - The installed file is read-only on macOS and Linux (the version folder stays writable for leases), and AGY_CLI_DISABLE_AUTO_UPDATE stops the CLI updating itself. - Sessions need 1.5.14 or newer, managed or custom (checked on `initialize`; a refused custom agy is shown on the row until it changes). - An install of the old server shows Update, keeps its leases, and is pruned once nothing runs on it. A custom path to the old server says to point it at agy or clear it. - The registry hook added for the old route is removed. Sign-in - Google account and Gemini Enterprise sign in with `agy acp --login`: the Google page opens on the device that started it, the code from the Antigravity page is asked for in the panel and handed only to the waiting process, and a session must open before the sign-in counts. - Each profile keeps its sign-in in its own file; sign-out deletes that file only, so the user's terminal agy and the OS keyring are untouched. - Failures say what happened: didn't start, couldn't reach Google (IPv6 hint), Google refused, plan needed, or account verification with Google's page offered to open. An old-server sign-in asks once to sign in again. Models and modes - The reasoning level is its own option (`thought_level`); each model's levels are remembered as sessions report them, and name folding stays as a fallback. A custom binary's saved model list is tied to the file. - Supervised runs `default`, Auto-accept edits `accept-edits`, Auto the CLI's `auto` where offered (else `accept-edits`), Full access `default` with Threadlines approving each request. --- apps/server/src/guide/topics.ts | 2 +- .../src/provider/Drivers/AntigravityDriver.ts | 26 +- .../acp/AntigravityAcpSupport.test.ts | 122 +++- .../src/provider/acp/AntigravityAcpSupport.ts | 409 ++++++++--- .../acpRegistry/AcpRegistryAgents.test.ts | 1 - .../provider/acpRegistry/AcpRegistryAgents.ts | 9 +- .../acpRegistry/AcpRegistryCatalog.test.ts | 17 +- .../acpRegistry/AcpRegistryCatalog.ts | 42 +- .../antigravity/AntigravityAuth.test.ts | 300 +++++++- .../provider/antigravity/AntigravityAuth.ts | 476 ++++++++---- .../antigravity/AntigravityProfile.ts | 168 ++++- .../antigravity/AntigravityRelease.ts | 362 ++++++---- .../antigravity/AntigravityReleaseSource.ts | 181 ++--- .../antigravity/AntigravityRuntime.test.ts | 680 +++++++++++------- .../antigravity/AntigravityRuntime.ts | 501 +++++-------- .../AntigravitySignInMethod.test.ts | 59 +- .../antigravity/AntigravitySignInMethod.ts | 120 ++-- .../managedRuntime/VerifiedDownload.ts | 77 +- docs/providers/antigravity.md | 83 ++- packages/contracts/src/settings.ts | 2 +- 20 files changed, 2366 insertions(+), 1271 deletions(-) diff --git a/apps/server/src/guide/topics.ts b/apps/server/src/guide/topics.ts index 0153a1836..5794d63b2 100644 --- a/apps/server/src/guide/topics.ts +++ b/apps/server/src/guide/topics.ts @@ -311,7 +311,7 @@ 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. -Antigravity's models come from Google's Antigravity program, which Threadlines downloads itself. New Gemini models arrive with a newer Antigravity: when Google publishes one, the Antigravity card offers Update, and the picker lists the new models after it. +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. 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, 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. Clicking a limit there opens {place:usage}. diff --git a/apps/server/src/provider/Drivers/AntigravityDriver.ts b/apps/server/src/provider/Drivers/AntigravityDriver.ts index a84eaf4db..bc3df8327 100644 --- a/apps/server/src/provider/Drivers/AntigravityDriver.ts +++ b/apps/server/src/provider/Drivers/AntigravityDriver.ts @@ -23,10 +23,6 @@ import { validateAntigravityRuntime, } from "../acp/AntigravityAcpSupport.ts"; import { type AcpProviderDriverEnv, makeAcpProviderDriver } from "../acp/AcpProviderDriver.ts"; -import { - acpRegistryCacheDir, - sharedAcpRegistryCatalog, -} from "../acpRegistry/AcpRegistryCatalog.ts"; import { antigravityReleaseFor } from "../antigravity/AntigravityRelease.ts"; import { type AntigravityReleaseSource, @@ -58,6 +54,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); /** @@ -74,16 +79,7 @@ const releaseSourceFor = ( ): AntigravityReleaseSource => { let source = releaseSourcesByStateDir.get(stateDir); if (!source) { - source = makeAntigravityReleaseSource({ - builtIn, - assetKey: builtIn.assetKey, - platform: process.platform, - catalog: sharedAcpRegistryCatalog({ - cacheDir: acpRegistryCacheDir(stateDir), - platform: process.platform, - arch: process.arch, - }), - }); + source = makeAntigravityReleaseSource({ builtIn, assetKey: builtIn.assetKey }); releaseSourcesByStateDir.set(stateDir, source); } return source; @@ -101,7 +97,7 @@ export const AntigravityDriver: ProviderDriver { }); 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", + ]); }); }); diff --git a/apps/server/src/provider/acp/AntigravityAcpSupport.ts b/apps/server/src/provider/acp/AntigravityAcpSupport.ts index fafb9c8f0..9cce9a2ba 100644 --- a/apps/server/src/provider/acp/AntigravityAcpSupport.ts +++ b/apps/server/src/provider/acp/AntigravityAcpSupport.ts @@ -3,16 +3,22 @@ * 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. * - Edits carry exact ACP `diff` content, and the agent writes the files @@ -24,7 +30,7 @@ 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 { join, resolve as resolvePath, sep } from "node:path"; import { createInterface } from "node:readline"; import { @@ -48,21 +54,23 @@ import * as EffectAcpErrors from "effect-acp/errors"; import type * as EffectAcpSchema from "effect-acp/schema"; import { + ANTIGRAVITY_MIN_VERSION, antigravityLaunchArgs, type AntigravityPlatformRelease, } from "../antigravity/AntigravityRelease.ts"; -import type { - AntigravityReleaseOffer, - AntigravityReleaseSource, -} from "../antigravity/AntigravityReleaseSource.ts"; +import type { AntigravityReleaseSource } from "../antigravity/AntigravityReleaseSource.ts"; import { acquireAntigravityTempDir, recordAntigravityAgent, antigravityEnvironment, + type AntigravityCatalogCache, type AntigravityInstancePaths, type AntigravityModelChoice, + type AntigravityThoughtLevels, prepareAntigravityProfile, + readAntigravityAgentRefusal, readAntigravityCatalog, + writeAntigravityAgentRefusal, writeAntigravityCatalog, } from "../antigravity/AntigravityProfile.ts"; import { holdLaunchGate, type LaunchGate } from "../managedRuntime/LaunchGate.ts"; @@ -75,12 +83,16 @@ import { readAntigravitySignInCheck, resolveAntigravityAdc, } from "../antigravity/AntigravitySignInMethod.ts"; -import type { AntigravityRuntime } from "../antigravity/AntigravityRuntime.ts"; +import type { + AntigravityInstalledRuntime, + AntigravityRuntime, +} from "../antigravity/AntigravityRuntime.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, @@ -100,30 +112,82 @@ 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. + */ +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: "; @@ -236,6 +300,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. @@ -347,27 +501,30 @@ const brainDir = (profileDir: string) => join(profileDir, "antigravity-acp", "br // ── 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, }); @@ -408,19 +565,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("; ")}.`); @@ -452,9 +607,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, @@ -464,6 +616,14 @@ 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. */ @@ -482,39 +642,59 @@ export function makeAntigravityDescriptor( const { paths, runtime, releases, gate, signIn } = input; const platform = process.platform; const fingerprint = antigravityCredentialFingerprint(signIn); + const isGoogleAccount = signIn.method === "oauth-personal"; const runtimeAction = ( runtime: AntigravityRuntime, verb: "Install" | "Update", - offer: AntigravityReleaseOffer, + 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. + // 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 && compareSemverVersions(installed.version, offer.version) >= 0) { + if ( + installed?.kind === "cli" && + compareSemverVersions(installed.version, offer.version) >= 0 + ) { return { output: `Antigravity ${installed.version} is already installed.` }; } - yield* runtime.install(yield* offer.release); + yield* runtime.install(offer); return { output: `Antigravity ${offer.version} is installed.` }; }).pipe(Effect.mapError((error) => ({ message: error.message }))), }); /** - * The managed runtime version the next agent runs, or undefined for a - * custom binary. Tags the saved model list (`readAntigravityCatalog`). + * 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 managedAgentVersion = (settings: AntigravitySettings) => - settings.binaryPath.trim() || !runtime - ? Effect.succeed(undefined) - : runtime.installed.pipe(Effect.map((installed) => installed?.version)); + 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, @@ -530,7 +710,8 @@ export function makeAntigravityDescriptor( if (!installed) return { ...MANUAL_ONLY, install: runtimeAction(runtime, "Install", offer) }; // Never back: a newer copy stays when only an older release is offered. - return compareSemverVersions(installed.version, offer.version) < 0 + return installed.kind === "legacy" || + compareSemverVersions(installed.version, offer.version) < 0 ? { ...MANUAL_ONLY, update: runtimeAction(runtime, "Update", offer) } : MANUAL_ONLY; }), @@ -547,10 +728,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( @@ -558,8 +740,10 @@ 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); const tempDir = yield* acquireAntigravityTempDir(paths.tempRoot).pipe( @@ -567,31 +751,41 @@ export function makeAntigravityDescriptor( ); 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.", @@ -630,18 +824,16 @@ export function makeAntigravityDescriptor( isolateTextGeneration: true, onSessionConfigOptions: (settings, configOptions) => Effect.gen(function* () { - const choices = modelChoices(configOptions); - if (choices.length === 0) return; - const currentValue = selectConfigOptionCurrentValue(findModelConfigOption(configOptions)); - const agentVersion = yield* managedAgentVersion(settings); + const agentVersion = yield* agentTag(settings); + const next = nextAntigravityCatalog(yield* readCatalog(agentVersion), configOptions); + if (!next) return; yield* writeAntigravityCatalog(paths.profileDir, { - choices, - ...(currentValue ? { currentValue } : {}), + ...next, fingerprint, ...(agentVersion ? { agentVersion } : {}), }); }), - notInstalledMessage: "Antigravity is not installed. Install it to use it in Threadlines.", + 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. @@ -664,27 +856,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 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 @@ -700,25 +926,26 @@ export function makeAntigravityDescriptor( ...latest, } satisfies AcpProviderProbeOutcome; } - const catalog = yield* readAntigravityCatalog(paths.profileDir, { - fingerprint, - isGoogleAccount: signIn.method === "oauth-personal", - agentVersion: version ?? undefined, - }); + const catalog = yield* readCatalog(tag); return { installed: true, version, ...signInStatus, ...latest, - ...(catalog ? { models: antigravityModelsFromChoices(catalog.choices) } : {}), + ...(catalog ? { models: antigravityModelsFromCatalog(catalog) } : {}), } satisfies AcpProviderProbeOutcome; }), 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/acpRegistry/AcpRegistryAgents.test.ts b/apps/server/src/provider/acpRegistry/AcpRegistryAgents.test.ts index b2664f1f0..4d253583c 100644 --- a/apps/server/src/provider/acpRegistry/AcpRegistryAgents.test.ts +++ b/apps/server/src/provider/acpRegistry/AcpRegistryAgents.test.ts @@ -95,7 +95,6 @@ const snapshotOf = ( stale: false, quarantineKnown: true, unsupportedCount: 0, - builtIn: [], ...overrides, }); diff --git a/apps/server/src/provider/acpRegistry/AcpRegistryAgents.ts b/apps/server/src/provider/acpRegistry/AcpRegistryAgents.ts index 1d5e12c6f..e5985cdad 100644 --- a/apps/server/src/provider/acpRegistry/AcpRegistryAgents.ts +++ b/apps/server/src/provider/acpRegistry/AcpRegistryAgents.ts @@ -1,3 +1,4 @@ +// @effect-diagnostics nodeBuiltinImport:off - the registry's cache folder /** * AcpRegistryAgents — what a client can do with community agents: read the * list, add one, update one, remove one. @@ -13,6 +14,7 @@ * * @module provider/acpRegistry/AcpRegistryAgents */ +import * as NodePath from "node:path"; import { ACP_REGISTRY_DRIVER_KIND, @@ -63,8 +65,7 @@ import { type AcpRegistryCatalogEntry, type AcpRegistryCatalogShape, type AcpRegistryCatalogSnapshot, - acpRegistryCacheDir, - sharedAcpRegistryCatalog, + makeAcpRegistryCatalog, toAcpRegistryCatalog, } from "./AcpRegistryCatalog.ts"; import { acpRegistryNodes } from "./AcpRegistryNodes.ts"; @@ -136,8 +137,8 @@ export const makeAcpRegistryAgents = Effect.fn("makeAcpRegistryAgents")(function const catalog = options?.catalog ?? - sharedAcpRegistryCatalog({ - cacheDir: acpRegistryCacheDir(serverConfig.stateDir), + makeAcpRegistryCatalog({ + cacheDir: NodePath.join(serverConfig.stateDir, "caches", "acp-registry"), platform: process.platform, arch: process.arch, }); diff --git a/apps/server/src/provider/acpRegistry/AcpRegistryCatalog.test.ts b/apps/server/src/provider/acpRegistry/AcpRegistryCatalog.test.ts index 928aa856c..0b66e0688 100644 --- a/apps/server/src/provider/acpRegistry/AcpRegistryCatalog.test.ts +++ b/apps/server/src/provider/acpRegistry/AcpRegistryCatalog.test.ts @@ -369,25 +369,17 @@ describe("reduceAcpRegistryIndex", () => { it("hides built-in and quarantined agents without counting them as unsupported", () => { const ids = (quarantined: ReadonlyArray) => { - const { entries, unsupportedCount, builtIn } = reduce(REGISTRY.agents, { quarantined }); - return { - listed: entries.map(({ agent }) => agent.agentId), - unsupportedCount, - builtIn: builtIn.map((recipe) => `${recipe.agentId}@${recipe.version}`), - }; + const { entries, unsupportedCount } = reduce(REGISTRY.agents, { quarantined }); + return { listed: entries.map(({ agent }) => agent.agentId), unsupportedCount }; }; - // Nothing quarantined: crow-cli shows, and fast-agent (Python only) is - // counted. claude-acp is kept apart, for its own driver to read. + // Nothing quarantined: crow-cli shows, and fast-agent (Python only) is counted. assert.deepStrictEqual(ids([]), { listed: ["auggie", "cortex-code", "crow-cli", "goose", "kilo", "sigit"], unsupportedCount: 1, - builtIn: ["claude-acp@0.86.0"], }); - // A quarantined release of a built-in agent is not offered to its driver either. - assert.deepStrictEqual(ids(["crow-cli", "fast-agent", "goose", "claude-acp"]), { + assert.deepStrictEqual(ids(["crow-cli", "fast-agent", "goose"]), { listed: ["auggie", "cortex-code", "kilo", "sigit"], unsupportedCount: 0, - builtIn: [], }); }); @@ -404,7 +396,6 @@ describe("reduceAcpRegistryIndex", () => { stale: false, quarantineKnown: true, unsupportedCount: reduced.unsupportedCount, - builtIn: reduced.builtIn, }); assert.deepStrictEqual( offered.agents.map((agent) => agent.agentId), diff --git a/apps/server/src/provider/acpRegistry/AcpRegistryCatalog.ts b/apps/server/src/provider/acpRegistry/AcpRegistryCatalog.ts index 708b309ea..9bc27bb36 100644 --- a/apps/server/src/provider/acpRegistry/AcpRegistryCatalog.ts +++ b/apps/server/src/provider/acpRegistry/AcpRegistryCatalog.ts @@ -171,12 +171,6 @@ export interface AcpRegistryCatalogSnapshot { readonly quarantineKnown: boolean; /** Agents left out because they have no build for this computer. */ readonly unsupportedCount: number; - /** - * Recipes for this computer of agents Threadlines supports itself - * (`ACP_REGISTRY_BUILT_IN_AGENT_IDS`), never listed: their drivers read - * them to learn of new releases. Quarantined agents are left out here too. - */ - readonly builtIn: ReadonlyArray; } export interface AcpRegistryCatalogShape { @@ -220,8 +214,6 @@ export interface AcpRegistryReduction { readonly entries: ReadonlyArray; /** Well-formed agents with no build for this computer. */ readonly unsupportedCount: number; - /** See `AcpRegistryCatalogSnapshot.builtIn`. */ - readonly builtIn: ReadonlyArray; /** Entries left out for breaking a rule, and which. For the log. */ readonly dropped: ReadonlyArray<{ readonly agentId: string | null; readonly reason: string }>; } @@ -512,8 +504,7 @@ const agentsOfIndex = (index: unknown): ReadonlyArray | undefined => * install. Pure: no icons, no network. * * - Agents Threadlines supports itself and quarantined agents are hidden, - * and are neither listed nor counted. The recipes of the first kind are - * kept apart in `builtIn`, for their drivers. + * and are neither listed nor counted. * - An agent takes its `binary` build for this computer when it has one, * else its npm package. One with neither is counted in `unsupportedCount`. * - An agent that breaks a bound is dropped, never cut to fit, except free @@ -529,7 +520,6 @@ export function reduceAcpRegistryIndex(input: { const agents = agentsOfIndex(input.index) ?? []; const platformKey = acpRegistryPlatformKey(input.platform, input.arch); const entries: Array = []; - const builtIn: Array = []; const dropped: Array<{ readonly agentId: string | null; readonly reason: string }> = []; const seen = new Set(); let unsupportedCount = 0; @@ -546,7 +536,7 @@ export function reduceAcpRegistryIndex(input: { continue; } const agentId = raw.id; - if (input.quarantined.has(agentId)) continue; + if (ACP_REGISTRY_BUILT_IN_AGENT_IDS.has(agentId) || input.quarantined.has(agentId)) continue; if (seen.has(agentId)) { dropped.push({ agentId, reason: "an earlier entry has the same id" }); continue; @@ -554,9 +544,7 @@ export function reduceAcpRegistryIndex(input: { seen.add(agentId); const reduced = reduceAgent(raw, agentId, platformKey); if (Result.isFailure(reduced)) dropped.push({ agentId, reason: reduced.failure }); - else if (ACP_REGISTRY_BUILT_IN_AGENT_IDS.has(agentId)) { - if (reduced.success !== undefined) builtIn.push(reduced.success.recipe); - } else if (reduced.success === undefined) unsupportedCount += 1; + else if (reduced.success === undefined) unsupportedCount += 1; else entries.push(reduced.success); } @@ -569,7 +557,6 @@ export function reduceAcpRegistryIndex(input: { return left.agent.agentId < right.agent.agentId ? -1 : 1; }), unsupportedCount, - builtIn, dropped, }; } @@ -772,28 +759,6 @@ function svgText(bytes: Uint8Array): string | undefined { } /** Builds the catalog for one cache folder. Cheap; holds no resources. */ -/** Where the registry's lists and icons are kept under a state folder. */ -export const acpRegistryCacheDir = (stateDir: string) => - NodePath.join(stateDir, "caches", "acp-registry"); - -const sharedCatalogs = new Map(); - -/** - * The catalog for a cache folder, one per folder in this process: community - * agents and built-in drivers that read it share its reads, memory and files. - */ -export function sharedAcpRegistryCatalog( - options: Omit, -): AcpRegistryCatalogShape { - const key = [options.cacheDir, options.platform, options.arch].join("\u0000"); - let catalog = sharedCatalogs.get(key); - if (!catalog) { - catalog = makeAcpRegistryCatalog(options); - sharedCatalogs.set(key, catalog); - } - return catalog; -} - export function makeAcpRegistryCatalog( options: AcpRegistryCatalogOptions, ): AcpRegistryCatalogShape { @@ -919,7 +884,6 @@ export function makeAcpRegistryCatalog( stale: input.stale, quarantineKnown: input.quarantine !== undefined, unsupportedCount: reduction.unsupportedCount, - builtIn: reduction.builtIn, }; }); 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/AntigravityProfile.ts b/apps/server/src/provider/antigravity/AntigravityProfile.ts index 278a998d1..8e33750a7 100644 --- a/apps/server/src/provider/antigravity/AntigravityProfile.ts +++ b/apps/server/src/provider/antigravity/AntigravityProfile.ts @@ -2,13 +2,12 @@ * 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 */ @@ -20,6 +19,7 @@ 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"; export interface AntigravityInstancePaths { /** `GEMINI_HOME` for this instance. */ @@ -43,16 +43,32 @@ export function antigravityInstancePaths( } /** 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 +81,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 +100,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,29 +205,47 @@ 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. */ @@ -219,6 +254,43 @@ export interface AntigravityCatalogCache { 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: @@ -244,18 +316,15 @@ export const readAntigravityCatalog = ( ? sign.isGoogleAccount : parsed.fingerprint === sign.fingerprint; if (!matches || parsed.agentVersion !== sign.agentVersion) return undefined; - const choices = Array.isArray(parsed.choices) - ? parsed.choices.filter( - (choice): choice is AntigravityModelChoice => - typeof choice?.value === "string" && typeof choice?.name === "string", - ) - : []; + 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 } : {}), } @@ -279,3 +348,34 @@ export const prepareAntigravityProfile = (profileDir: string) => Effect.promise(() => fs.mkdir(antigravityAgentDir(profileDir), { recursive: true, mode: 0o700 }), ).pipe(Effect.asVoid); + +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 e53366fe2..e2fa69f34 100644 --- a/apps/server/src/provider/antigravity/AntigravityRelease.ts +++ b/apps/server/src/provider/antigravity/AntigravityRelease.ts @@ -1,45 +1,53 @@ /** - * AntigravityRelease — which Antigravity ACP server release Threadlines - * installs, one zip per platform: the built-in release below, or a newer one - * Google lists in the ACP registry. + * 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 built-in sizes and hashes were taken from the published - * archives; a listed release takes its hash from the registry and its sizes - * from the zip's own index (`resolveAntigravityListedRelease`). 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 */ -import type { AcpRegistryRecipe } from "../acpRegistry/AcpRegistryRecipe.ts"; - -/** Google's id for Antigravity in the ACP registry. */ -export const ANTIGRAVITY_REGISTRY_AGENT_ID = "antigravity-acp"; +/** + * 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 { @@ -47,98 +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`; -const WINDOWS_FILES = (executableBytes: number, harnessBytes: number) => ({ - executable: { name: "agy_acp_server.exe", bytes: executableBytes }, - harness: { name: "localharness_external.exe", bytes: harnessBytes }, -}); +/** The host of Google's update feed for the CLI. */ +export const ANTIGRAVITY_FEED_HOST = + "antigravity-cli-auto-updater-974169037036.us-central1.run.app"; -/** The only host Antigravity is downloaded from. */ -export const ANTIGRAVITY_DOWNLOAD_HOST = "dl.google.com"; -const RELEASES_URL = `https://${ANTIGRAVITY_DOWNLOAD_HOST}/agy-extensions/releases`; - -/** Google's folder and file-name suffix for each build. */ -const ARCHIVE_NAMES: Readonly> = { - "darwin-arm64": ["macos", "darwin-arm64"], - "darwin-x64": ["macos", "darwin-x86_64"], - "linux-arm64": ["linux", "linux-arm64"], - "linux-x64": ["linux", "linux-x86_64"], - "win32-arm64": ["windows", "windows-arm64"], - "win32-x64": ["windows", "windows-x86_64"], +/** + * 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 publishes a version's zip for a build. */ -export function antigravityArchiveUrl(version: string, assetKey: AntigravityAssetKey): string { - const [folder, suffix] = ARCHIVE_NAMES[assetKey]; - return `${RELEASES_URL}/${folder}/agy-acp-server-${version}-${suffix}.zip`; +/** 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 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 BUILD_1_5_14 = "1.5.14-5302690847260672"; + /** - * Registry entry `antigravity-acp` 1.5.2: the release installed when the - * registry can't be read, and the oldest one offered. A newer one Google - * lists is offered as an update (`antigravityListedRelease`). + * 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.5.2", + version: "1.5.14", assets: { - "darwin-arm64": { - url: antigravityArchiveUrl("1.5.2", "darwin-arm64"), - sha256: "123a16d5c40a8ac99e20f01a62b68dd860fd96b1c528dfb8eaa37ca8733d4845", - archiveBytes: 100_309_778, - ...POSIX_FILES(179_921_328, 129_208_672), - }, - "darwin-x64": { - url: antigravityArchiveUrl("1.5.2", "darwin-x64"), - sha256: "92addb5580577b5356d35484d72d1a113d9c5312ad766bcb304983aa8e3fbb06", - archiveBytes: 106_351_992, - ...POSIX_FILES(184_312_784, 134_350_320), - }, - "linux-arm64": { - url: antigravityArchiveUrl("1.5.2", "linux-arm64"), - sha256: "e729e05ef54ef0763e48900032466b47fa7c9939cde257f93ba49410ab577acb", - archiveBytes: 264_270_419, - ...POSIX_FILES(721_649_155, 132_598_576), - }, - "linux-x64": { - url: antigravityArchiveUrl("1.5.2", "linux-x64"), - sha256: "99dd8612450805011619d7b8447ce374c289e00549d8557f36790e1dd6256852", - archiveBytes: 273_964_075, - ...POSIX_FILES(714_384_320, 139_194_456), - }, - "win32-arm64": { - url: antigravityArchiveUrl("1.5.2", "win32-arm64"), - sha256: "8a4b2ea8df2ffefae33309348752e9119d21a6d36090c0eb48631c2e8f5781ab", - archiveBytes: 108_049_351, - ...WINDOWS_FILES(65_130_848, 146_707_096), - }, - "win32-x64": { - url: antigravityArchiveUrl("1.5.2", "win32-x64"), - sha256: "5cbadd4f4df698572473d8890fc26ec2dc1724501f06e3a963941daec2bd21d6", - archiveBytes: 105_407_645, - ...WINDOWS_FILES(58_368_800, 155_357_336), - }, + "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: @@ -146,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, @@ -161,55 +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(); } -/** Arguments the ACP server is launched with. Linux builds take an empty `--uid=`. */ -export function antigravityLaunchArgs(platform: NodeJS.Platform): ReadonlyArray { - return platform === "linux" ? ["--uid="] : []; -} +/** The agent's state folder inside the profile, as `--app-data-dir` names it. */ +export const ANTIGRAVITY_APP_DATA_DIR = "antigravity-acp"; -/** A release the ACP registry lists, before its file sizes are known. */ -export interface AntigravityListedRelease { - readonly version: string; - readonly url: string; - /** Lowercase hex sha256 of the zip. */ - readonly sha256: string; +/** + * `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]; } 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); /** - * Google's registry entry for this computer as an installable release, or - * undefined when it isn't one Threadlines knows how to run: a zip on Google's - * own download folder, under the name Google always uses, with a checksum, - * launching the ACP server the usual way with no extra environment. Anything - * else waits for a Threadlines release that knows it. + * 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 antigravityListedRelease( - recipe: AcpRegistryRecipe, +export function parseAntigravityFeedManifest( + manifest: unknown, assetKey: AntigravityAssetKey, - platform: NodeJS.Platform, -): AntigravityListedRelease | undefined { - if (recipe.agentId !== ANTIGRAVITY_REGISTRY_AGENT_ID || recipe.kind !== "download") { +): 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; } - const executable = platform === "win32" ? "agy_acp_server.exe" : "agy_acp_server.par"; - const launchArgs = antigravityLaunchArgs(platform); - const fits = - PLAIN_VERSION.test(recipe.version) && - recipe.format === "zip" && - recipe.sha256 !== null && - recipe.url === antigravityArchiveUrl(recipe.version, assetKey) && - recipe.cmd === executable && - recipe.args.length === launchArgs.length && - recipe.args.every((arg, index) => arg === launchArgs[index]) && - Object.keys(recipe.env).length === 0; - return fits && recipe.sha256 !== null - ? { version: recipe.version, url: recipe.url, sha256: recipe.sha256 } - : 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 index 48b9efc0f..054340d55 100644 --- a/apps/server/src/provider/antigravity/AntigravityReleaseSource.ts +++ b/apps/server/src/provider/antigravity/AntigravityReleaseSource.ts @@ -1,13 +1,13 @@ /** * AntigravityReleaseSource — which Antigravity release Threadlines offers. * - * Google lists each new Antigravity in the ACP registry. When that listing + * 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 - * run (`antigravityListedRelease`), it is offered, so a new version (and the - * models it brings) reaches users without waiting for a Threadlines release. - * Otherwise, and whenever the registry can't be read, the built-in release - * is offered. Nothing installs on its own: the offer becomes the Install or - * Update button. + * 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 */ @@ -15,118 +15,119 @@ 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 * as Option from "effect/Option"; -import type { AcpRegistryCatalogShape } from "../acpRegistry/AcpRegistryCatalog.ts"; -import type { ManagedRuntimeError } from "../managedRuntime/ManagedRuntimeStore.ts"; +import { makeHttpsFetch } from "../managedRuntime/HttpsFetch.ts"; +import type { DownloadFetch } from "../managedRuntime/VerifiedDownload.ts"; import { - ANTIGRAVITY_REGISTRY_AGENT_ID, + ANTIGRAVITY_FEED_HOST, type AntigravityAssetKey, - type AntigravityListedRelease, type AntigravityPlatformRelease, - antigravityListedRelease, + antigravityFeedUrl, + parseAntigravityFeedManifest, } from "./AntigravityRelease.ts"; -import { type AntigravityFetch, resolveAntigravityListedRelease } from "./AntigravityRuntime.ts"; - -export interface AntigravityReleaseOffer { - readonly version: string; - /** The release with its file sizes, for `AntigravityRuntime.install`. */ - readonly release: Effect.Effect; -} export interface AntigravityReleaseSource { /** - * The release to offer. Never fails. Asks the registry at most once an - * hour and waits for it at most a few seconds; a slow answer is used by - * the next call. + * 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; + readonly newest: Effect.Effect; } /** Like the other providers' newest-version checks (`providerMaintenance`). */ const ASK_EVERY_MS = 60 * 60 * 1000; -/** After the registry couldn't be read, the saved copy is used until then. */ +/** 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; - readonly platform: NodeJS.Platform; - readonly catalog: Pick; - /** Test seam for reading a listed release's sizes. */ - readonly fetch?: AntigravityFetch; + /** Test seam for reading the feed. */ + readonly fetch?: DownloadFetch; }): AntigravityReleaseSource { - const { builtIn } = input; - const builtInOffer: AntigravityReleaseOffer = { - version: builtIn.version, - release: Effect.succeed(builtIn), - }; - const executableName = builtIn.asset.executable.name; - const harnessName = builtIn.asset.harness.name; + const { builtIn, assetKey } = input; + const fetchFeed = input.fetch ?? makeAntigravityFeedFetch(); - /** Releases whose sizes were read, so each is read once. */ - const resolved = new Map(); - const offerFor = (listed: AntigravityListedRelease): AntigravityReleaseOffer => ({ - version: listed.version, - release: Effect.suspend(() => { - const key = [listed.version, listed.url, listed.sha256].join("\u0000"); - const known = resolved.get(key); - if (known) return Effect.succeed(known); - return resolveAntigravityListedRelease({ - listed, - executableName, - harnessName, - ...(input.fetch ? { fetch: input.fetch } : {}), - }).pipe(Effect.tap((release) => Effect.sync(() => resolved.set(key, release)))); - }), - }); - - const fromRegistry = (ask: boolean) => - Effect.gen(function* () { - const fresh = ask - ? yield* input.catalog.get().pipe( - Effect.timeoutOption(WAIT_AT_MOST), - Effect.map(Option.getOrUndefined), - Effect.orElseSucceed(() => undefined), - ) - : undefined; - const snapshot = fresh ?? (yield* input.catalog.peek); - // A release the registry has pulled must not be offered, so nothing is - // offered until the list of pulled agents has been read. - const recipe = - snapshot?.quarantineKnown !== true - ? undefined - : snapshot.builtIn.find( - (candidate) => candidate.agentId === ANTIGRAVITY_REGISTRY_AGENT_ID, - ); - const listed = recipe && antigravityListedRelease(recipe, input.assetKey, input.platform); - const offer = - listed && compareSemverVersions(listed.version, builtIn.version) > 0 - ? offerFor(listed) - : builtInOffer; - // Only an answer from the registry counts as asked; a saved copy (the - // registry couldn't be read) is asked again next time. - return { offer, asked: fresh !== undefined && !fresh.stale }; - }); + /** 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: AntigravityReleaseOffer; readonly askedAtMs: number } | undefined; + 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; - if (last && within(last.askedAtMs, nowMs, ASK_EVERY_MS)) return last.offer; - // While the registry is down, every refresh would ask again: wait a while. - const ask = !within(failedAtMs, nowMs, RETRY_AFTER_FAILURE_MS); - const { offer, asked } = yield* fromRegistry(ask); - if (asked) { - last = { offer, askedAtMs: nowMs }; - failedAtMs = undefined; - } else if (ask) { - failedAtMs = nowMs; + 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 offer; + 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 18de2e3ea..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,16 +8,19 @@ 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 { AcpRegistryCatalogSnapshot } from "../acpRegistry/AcpRegistryCatalog.ts"; -import { AcpRegistryError } from "@threadlines/contracts"; -import type { AcpRegistryDownloadRecipe } from "../acpRegistry/AcpRegistryRecipe.ts"; +import type { DownloadFetch } from "../managedRuntime/VerifiedDownload.ts"; +import { makeTar, type TarEntry } from "../testUtils/archiveFixtures.ts"; import { + ANTIGRAVITY_RELEASE, type AntigravityPlatformRelease, - antigravityArchiveUrl, + antigravityFeedUrl, antigravityReleaseFor, + parseAntigravityFeedManifest, } from "./AntigravityRelease.ts"; import { makeAntigravityReleaseSource } from "./AntigravityReleaseSource.ts"; import { @@ -27,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; -} +class HandshakeFailed extends Data.TaggedError("HandshakeFailed")<{ readonly message: string }> {} -/** 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]); -} +const sha512 = (data: Buffer) => createHash("sha512").update(data).digest("hex"); -const sha256 = (data: Buffer) => createHash("sha256").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. */ @@ -156,18 +111,16 @@ 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, - validate, - fetch: server.fetch, - }); + const runtime = makeAntigravityRuntime({ root, validate, fetch: server.fetch }); assert.isUndefined(yield* runtime.installed); const progress: Array = []; @@ -175,35 +128,33 @@ describe("makeAntigravityRuntime", () => { 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]); @@ -212,70 +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(fixture.release); - assert.equal(server.requests.length, 1); - assert.equal(calls.length, 2); + 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, - validate, + validate: recordingValidate().validate, fetch: server.fetch, + platform: "win32", }); + 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, - validate, - fetch: server.fetch, - }); + 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"))); }), ); @@ -283,7 +328,7 @@ 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, @@ -294,7 +339,7 @@ describe("makeAntigravityRuntime", () => { 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")), []); }), ); @@ -309,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; @@ -344,18 +389,13 @@ 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, - validate, - fetch: server.fetch, - }); - const runtimeB = makeAntigravityRuntime({ - root, - 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(a.release); @@ -364,6 +404,7 @@ describe("makeAntigravityRuntime", () => { 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(b.release); assert.equal((yield* runtimeB.installed)?.releaseId, b.releaseId); @@ -387,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); @@ -398,18 +440,13 @@ 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, - validate, - fetch: server.fetch, - }); - const runtimeB = makeAntigravityRuntime({ - root, - 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(b.release); @@ -450,18 +487,13 @@ 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, - validate, - fetch: server.fetch, - }); - const runtimeB = makeAntigravityRuntime({ - root, - 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(b.release); @@ -497,120 +529,264 @@ 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 listing = ( - overrides: Partial = {}, - ): AcpRegistryDownloadRecipe => ({ - kind: "download", - agentId: "antigravity-acp", + 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", - args: [], - env: {}, - url: antigravityArchiveUrl(overrides.version ?? "9.0.0", "darwin-arm64"), - sha256: "0".repeat(64), - format: "zip", - cmd: EXECUTABLE, + url: downloadUrl("9.0.0"), + sha512: FEED_SHA512, ...overrides, }); - const catalogListing = ( - recipes: ReadonlyArray | "unreadable", - quarantineKnown = true, - ) => ({ - get: () => - recipes === "unreadable" - ? Effect.fail(new AcpRegistryError({ reason: "catalogUnavailable", detail: "offline" })) - : Effect.succeed({ - entries: [], - fetchedAt: null, - stale: false, - quarantineKnown, - unsupportedCount: 0, - builtIn: recipes, - }), - peek: Effect.succeed(undefined), - }); - /** Answers range requests with their bytes and the zip's size, like Google's server. */ - function rangeServer(url: string, body: Buffer) { - const ranges: Array = []; - const fetch: AntigravityFetch = async (requested, init) => { - if (requested !== url) return new Response(null, { status: 404 }); - const range = new Headers(init.headers).get("range"); - if (range === null) return new Response(new Uint8Array(body)); - ranges.push(range); - const [, start, end] = /^bytes=(\d+)-(\d+)$/u.exec(range)!; - return new Response(new Uint8Array(body.subarray(Number(start), Number(end) + 1)), { - status: 206, - headers: { "content-range": `bytes ${start}-${end}/${body.length}` }, - }); + /** 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, ranges }; + return { fetch, urls }; } + const json = (body: unknown) => () => new Response(JSON.stringify(body)); - it.live("offers Google's newer release and installs it, sizes read from the zip's index", () => + it.effect("offers the feed's release when it is newer than the built-in one", () => Effect.gen(function* () { - const fixture = makeFixture("listed"); - const recipe = listing({ version: "9.1.0", sha256: fixture.release.asset.sha256 }); - const server = rangeServer(recipe.url, fixture.zip); + const server = feed(json(manifest())); const source = makeAntigravityReleaseSource({ builtIn, assetKey: "darwin-arm64", - platform: "darwin", - catalog: catalogListing([recipe]), fetch: server.fetch, }); - const offer = yield* source.newest; - assert.equal(offer.version, "9.1.0"); - const release = yield* offer.release; - assert.deepStrictEqual(release, { - version: "9.1.0", - asset: { ...fixture.release.asset, url: recipe.url }, - }); - // The index only: far less than the whole zip. - assert.isAbove(server.ranges.length, 0); - - const root = yield* tempRoot; - const runtime = makeAntigravityRuntime({ - root, - validate: recordingValidate().validate, - 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 }, + }, }); - yield* runtime.install(release); - assert.equal((yield* runtime.installed)?.version, "9.1.0"); + assert.deepStrictEqual(server.urls, [antigravityFeedUrl("darwin-arm64")]); }), ); - it.live("keeps the built-in release unless Google lists a newer one Threadlines can run", () => + it.effect("keeps the built-in release unless the feed lists a newer one it can install", () => Effect.gen(function* () { - const offered = ( - recipes: ReadonlyArray | "unreadable", - quarantineKnown = true, - ) => - makeAntigravityReleaseSource({ + 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", - platform: "darwin", - catalog: catalogListing(recipes, quarantineKnown), - }).newest.pipe(Effect.map((offer) => offer.version)); - - assert.equal(yield* offered([listing()]), "9.0.0"); - // Until the registry's list of pulled releases is known, nothing listed is offered. - assert.equal(yield* offered([listing()], false), builtIn.version); - const keepsBuiltIn = [ - "unreadable" as const, - [] as const, - [listing({ version: "1.0.0" })], - [listing({ url: "https://example.com/agy-acp-server-9.0.0-darwin-arm64.zip" })], - [listing({ args: ["--debug"] })], - [listing({ env: { GEMINI_HOME: "/tmp" } })], - [listing({ sha256: null })], - [listing({ cmd: "other.par" })], - ]; - for (const recipes of keepsBuiltIn) { - assert.equal(yield* offered(recipes), builtIn.version, JSON.stringify(recipes)); + 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 e714a5317..e9a18f13f 100644 --- a/apps/server/src/provider/antigravity/AntigravityRuntime.ts +++ b/apps/server/src/provider/antigravity/AntigravityRuntime.ts @@ -1,59 +1,62 @@ -// @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. + * 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 { PassThrough, Readable } from "node:stream"; -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, statIfExists, } from "../managedRuntime/ManagedRuntimeStore.ts"; -import { makeHttpsFetch } from "../managedRuntime/HttpsFetch.ts"; import { type DownloadFetch, downloadVerified } from "../managedRuntime/VerifiedDownload.ts"; import { ANTIGRAVITY_DOWNLOAD_HOST, - type AntigravityListedRelease, 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; @@ -62,7 +65,7 @@ export type AntigravityInstallProgress = ManagedInstallProgress; export type AntigravityFetch = DownloadFetch; /** - * Downloads from Google's download host only, on every redirect hop too, so + * 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 => @@ -72,15 +75,17 @@ export interface AntigravityRuntimeOptions { /** Directory the runtime owns, e.g. `/tools/agy/`. */ readonly root: string; /** - * Proves unpacked files are `release` and 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, 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; } @@ -99,7 +104,8 @@ export interface AntigravityRuntime { ) => 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; /** @@ -112,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; @@ -143,308 +186,84 @@ 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}`); } -} - -// ── A listed release's sizes ───────────────────────────────────────── - -/** Far above any real build (the largest 1.5.2 zip is 274 MB). */ -const MAX_LISTED_ARCHIVE_BYTES = 2 * 1024 ** 3; -const MAX_LISTED_FILE_BYTES = 4 * 1024 ** 3; -const LISTED_INDEX_TIMEOUT_MS = 60_000; - -/** - * Bytes `start` to `end` (exclusive) of `url`, and the file's total size when - * the server names it. Reads no more than asked for, whatever the server sends. - */ -async function readRange( - fetchRange: AntigravityFetch, - url: string, - start: number, - end: number, - signal: AbortSignal, -): Promise<{ readonly bytes: Uint8Array; readonly total: number | undefined }> { - const response = await fetchRange(url, { - headers: { range: `bytes=${start}-${end - 1}`, "accept-encoding": "identity" }, - redirect: "follow", - signal, - }); - if (response.status !== 206 || response.body === null) { - await response.body?.cancel().catch(() => undefined); - throw new Error(`${url} answered a range request with ${response.status}`); + 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}`); } - const wanted = end - start; - const bytes = new Uint8Array(wanted); - let received = 0; - const reader = response.body.getReader(); - try { - for (;;) { - const { done, value } = await reader.read(); - if (done) break; - if (received + value.byteLength > wanted) { - throw new Error(`asked ${url} for ${wanted} bytes, got more`); - } - bytes.set(value, received); - received += value.byteLength; - } - } finally { - await reader.cancel().catch(() => undefined); - } - if (received !== wanted) throw new Error(`asked ${url} for ${wanted} bytes, got ${received}`); - const total = /\/(\d+)$/u.exec(response.headers.get("content-range") ?? "")?.[1]; - return { bytes, total: total === undefined ? undefined : Number(total) }; + await NodeFS.rename(unpacked, input.target); + return stat.size; } -/** Reads byte ranges of a zip on a server, so its index can be read without the download. */ -class RangeReader extends yauzl.RandomAccessReader { - private readonly url: string; - private readonly fetchRange: AntigravityFetch; - private readonly signal: AbortSignal; - - constructor(url: string, fetchRange: AntigravityFetch, signal: AbortSignal) { - super(); - this.url = url; - this.fetchRange = fetchRange; - this.signal = signal; - } - - override _readStreamForRange(start: number, end: number): Readable { - const out = new PassThrough(); - if (end <= start) { - out.end(); - return out; - } - readRange(this.fetchRange, this.url, start, end, this.signal).then( - (range) => out.end(range.bytes), - (cause: unknown) => out.destroy(cause instanceof Error ? cause : new Error(String(cause))), - ); - return out; - } -} - -/** - * A listed release with its sizes, so its install is checked exactly like - * the built-in release's: the zip's length from Google's server, and each - * file's from the zip's own index, read with a few small range requests - * rather than the whole download. What the sizes come from is checked again - * by the install: the zip must hash to the sha256 the registry lists and - * unpack to these sizes. - */ -export const resolveAntigravityListedRelease = (input: { - readonly listed: AntigravityListedRelease; - /** The two file names the zip must hold (`AntigravityReleaseAsset`). */ - readonly executableName: string; - readonly harnessName: string; - readonly fetch?: AntigravityFetch; -}): Effect.Effect => { - const fetchRange: AntigravityFetch = input.fetch ?? makeAntigravityDownloadFetch(); - const { listed } = input; - const unreachable = runtimeError( - "download", - `Couldn't reach Google to download Antigravity ${listed.version}. Check your internet connection and try again.`, - ); - const malformed = (detail: string) => - runtimeError("archive", MESSAGES.archive, { detail: `${listed.url}: ${detail}` }); - return abortable( - async (signal) => { - const timeout = AbortSignal.timeout(LISTED_INDEX_TIMEOUT_MS); - const both = AbortSignal.any([signal, timeout]); - // The first byte, for the zip's size (`Content-Range: bytes 0-0/`). - const first = await readRange(fetchRange, listed.url, 0, 1, both).catch((cause: unknown) => { - throw runtimeError("download", unreachable.message, { cause }); - }); - const archiveBytes = first.total ?? Number.NaN; - if (!Number.isSafeInteger(archiveBytes) || archiveBytes <= 0) { - throw malformed("the server gave no size"); - } - if (archiveBytes > MAX_LISTED_ARCHIVE_BYTES) throw malformed(`${archiveBytes} bytes`); - const reader = new RangeReader(listed.url, fetchRange, both); - let zip: yauzl.ZipFile; - try { - zip = await yauzl.fromRandomAccessReaderPromise(reader, archiveBytes, { - autoClose: false, - lazyEntries: true, - strictFileNames: true, - validateEntrySizes: true, - }); - } catch (cause) { - throw runtimeError("archive", MESSAGES.archive, { - detail: `${listed.url}: unreadable index`, - cause, - }); - } - try { - const sizes = new Map(); - for await (const entry of zip.eachEntry()) { - if (sizes.has(entry.fileName)) throw malformed(`duplicate entry "${entry.fileName}"`); - sizes.set(entry.fileName, entry.uncompressedSize); - } - const names = [input.executableName, input.harnessName]; - if (sizes.size !== 2 || names.some((name) => !sizes.has(name))) { - throw malformed(`holds ${[...sizes.keys()].join(", ")}, expected ${names.join(", ")}`); - } - const fileOf = (name: string) => { - const bytes = sizes.get(name)!; - if (bytes <= 0 || bytes > MAX_LISTED_FILE_BYTES) - throw malformed(`${name} is ${bytes} bytes`); - return { name, bytes }; - }; - return { - version: listed.version, - asset: { - url: listed.url, - sha256: listed.sha256, - archiveBytes, - executable: fileOf(input.executableName), - harness: fileOf(input.harnessName), - }, - }; - } finally { - zip.close(); - reader.close(() => undefined); - } - }, - (cause) => runtimeError("download", unreachable.message, { cause }), - ); -}; - /** Builds the runtime for one root. Cheap; holds no resources. */ export function makeAntigravityRuntime( options: AntigravityRuntimeOptions, ): AntigravityRuntime { 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 } : {}), }); @@ -459,48 +278,86 @@ 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 = (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: 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"] = (release, onProgress) => { @@ -512,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: antigravityReleaseId(asset), version: release.version, - neededBytes: asset.archiveBytes + asset.executable.bytes + asset.harness.bytes, + neededBytes, build: build(release, report), - validate: (version) => validatePaths(pathsOf(version), release), + validate: (version) => validatePaths(installedRuntimeOf(version), release), onPhase: (phase) => report({ phase }), }); }; @@ -527,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/AntigravitySignInMethod.test.ts b/apps/server/src/provider/antigravity/AntigravitySignInMethod.test.ts index abf5a3ff2..44570f526 100644 --- a/apps/server/src/provider/antigravity/AntigravitySignInMethod.test.ts +++ b/apps/server/src/provider/antigravity/AntigravitySignInMethod.test.ts @@ -3,7 +3,7 @@ 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"; @@ -19,7 +19,6 @@ import { antigravitySignInStatus, type AntigravitySignInConfig, checkGeminiApiKey, - classifyAntigravityGoogleToken, mergeAntigravityProfileSettings, resolveAntigravityAdc, } from "./AntigravitySignInMethod.ts"; @@ -94,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"]); @@ -190,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, @@ -271,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( diff --git a/apps/server/src/provider/antigravity/AntigravitySignInMethod.ts b/apps/server/src/provider/antigravity/AntigravitySignInMethod.ts index 48c177059..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 signs in with, per method (same in 1.3.0 and 1.5.2). */ -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/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 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 checks Google's listing in the ACP registry 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 -Gemini models arrive this way, since each Antigravity version lists its own models. +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 that comes from Google's own download folder under the usual -name, with a checksum, launched the usual way. It reads the file sizes from the zip's index before -downloading, checks the download against the listed checksum and those sizes, and starts the new -copy once to make sure it's Antigravity at that version before switching to it. If the registry -can't be read, the version built into Threadlines is offered instead, and an installed copy is -never replaced by an older one. +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 listing changes so Threadlines would refuse it. +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. ## Sign-In Methods @@ -40,6 +77,21 @@ 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. ### Per-Use Billing @@ -89,5 +141,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/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" }, }), ), From 2835f42af8df37478950e312c85d44d7520ce2ef Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Mon, 23 Nov 2026 02:25:16 -0500 Subject: [PATCH 08/59] feat(antigravity): each profile follows the user's own global rules and skills Each Antigravity instance runs with a private GEMINI_HOME, so the agent never saw the user's global rules and skills in ~/.gemini. Before every start, Threadlines now links AGENTS.md and GEMINI.md (top level and config/), config/rules, config/rules.json, config/skills.json and the two global skill folders into the profile. Windows gets junctions for folders and copies for files, refreshed when the source changes. A record of what Threadlines made means a link or copy is only replaced or removed when it is ours; a real file or a non-empty folder the agent wrote stays. Sign-in files, hooks, plugins, agents.json and the MCP config stay out. --- .../src/provider/acp/AntigravityAcpSupport.ts | 10 +- .../antigravity/AntigravityProfile.ts | 22 +- .../antigravity/AntigravityUserConfig.test.ts | 213 +++++++++++++ .../antigravity/AntigravityUserConfig.ts | 280 ++++++++++++++++++ 4 files changed, 520 insertions(+), 5 deletions(-) create mode 100644 apps/server/src/provider/antigravity/AntigravityUserConfig.test.ts create mode 100644 apps/server/src/provider/antigravity/AntigravityUserConfig.ts diff --git a/apps/server/src/provider/acp/AntigravityAcpSupport.ts b/apps/server/src/provider/acp/AntigravityAcpSupport.ts index 9cce9a2ba..d1d8e3f89 100644 --- a/apps/server/src/provider/acp/AntigravityAcpSupport.ts +++ b/apps/server/src/provider/acp/AntigravityAcpSupport.ts @@ -29,7 +29,7 @@ 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 { homedir, tmpdir } from "node:os"; import { join, resolve as resolvePath, sep } from "node:path"; import { createInterface } from "node:readline"; @@ -73,6 +73,7 @@ import { writeAntigravityAgentRefusal, writeAntigravityCatalog, } from "../antigravity/AntigravityProfile.ts"; +import { antigravityUserHome } from "../antigravity/AntigravityUserConfig.ts"; import { holdLaunchGate, type LaunchGate } from "../managedRuntime/LaunchGate.ts"; import { antigravityCredentialEnvironment, @@ -641,6 +642,8 @@ export function makeAntigravityDescriptor( ): AcpProviderDescriptor { const { paths, runtime, releases, gate, signIn } = input; const platform = process.platform; + const userHomeFor = (environment: NodeJS.ProcessEnv | undefined) => + antigravityUserHome(platform, environment ?? process.env, homedir()); const fingerprint = antigravityCredentialFingerprint(signIn); const isGoogleAccount = signIn.method === "oauth-personal"; @@ -745,7 +748,10 @@ export function makeAntigravityDescriptor( } executable = leased.executable; } - yield* prepareAntigravityProfile(paths.profileDir); + yield* prepareAntigravityProfile(paths.profileDir, { + userHome: userHomeFor(environment), + platform, + }); const tempDir = yield* acquireAntigravityTempDir(paths.tempRoot).pipe( Effect.mapError(spawnFailure), ); diff --git a/apps/server/src/provider/antigravity/AntigravityProfile.ts b/apps/server/src/provider/antigravity/AntigravityProfile.ts index 8e33750a7..1c901a164 100644 --- a/apps/server/src/provider/antigravity/AntigravityProfile.ts +++ b/apps/server/src/provider/antigravity/AntigravityProfile.ts @@ -20,6 +20,7 @@ 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. */ @@ -343,11 +344,26 @@ 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, + }), + ), + ); const agentRefusalPath = (profileDir: string) => join(profileDir, "threadlines-agent-check.json"); 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..b30da097d --- /dev/null +++ b/apps/server/src/provider/antigravity/AntigravityUserConfig.test.ts @@ -0,0 +1,213 @@ +// @effect-diagnostics nodeBuiltinImport:off - builds a fake home and profile 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 { + ANTIGRAVITY_SHARED_DIRS, + ANTIGRAVITY_SHARED_FILES, + antigravityUserHome, + shareAntigravityUserConfigNow, +} from "./AntigravityUserConfig.ts"; + +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("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", + ); + }); +}); + diff --git a/apps/server/src/provider/antigravity/AntigravityUserConfig.ts b/apps/server/src/provider/antigravity/AntigravityUserConfig.ts new file mode 100644 index 000000000..0de1a3060 --- /dev/null +++ b/apps/server/src/provider/antigravity/AntigravityUserConfig.ts @@ -0,0 +1,280 @@ +/** + * 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. Credentials, hooks, plugins and the user's + * MCP config are never brought in. + * + * Runs before every agent start, so a source that appears later is picked + * up then, and one that goes away takes its link with it (a dangling link + * would stop the agent creating the folder itself). A link or copy is only + * replaced or removed when Threadlines made it: a real file or a non-empty + * folder the agent wrote stays as it is. + * + * @module provider/antigravity/AntigravityUserConfig + */ +import { createHash, randomBytes } from "node:crypto"; +import * as fs from "node:fs/promises"; +import { dirname, join, resolve } from "node:path"; + +import * as Effect from "effect/Effect"; + +/** + * 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`. Left out on purpose: `config/hooks.json`, + * `config/mcp_config.json`, `config/plugins` and `plugins.json` (plugins + * carry MCP servers and hooks), `config/agents.json`, and every sign-in file. + */ +export const ANTIGRAVITY_SHARED_FILES = [ + "AGENTS.md", + "GEMINI.md", + "config/AGENTS.md", + "config/GEMINI.md", + "config/skills.json", + "config/rules.json", +] as const; + +/** Copies above this size are skipped: the CLI cuts a rule file off far below it. */ +const MAX_COPY_BYTES = 1_000_000; + +/** 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 what was written. */ + copies: Record; +} + +const recordPath = (profileDir: string) => join(profileDir, "threadlines-shared-config.json"); + +const stringRecord = (raw: unknown): Record => { + if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return {}; + return Object.fromEntries( + Object.entries(raw).filter((entry): entry is [string, string] => typeof entry[1] === "string"), + ); +}; + +async function readRecord(profileDir: string): Promise { + const raw = await fs.readFile(recordPath(profileDir), "utf8").catch(() => undefined); + try { + const parsed = raw === undefined ? undefined : (JSON.parse(raw) as Partial); + return { links: stringRecord(parsed?.links), copies: stringRecord(parsed?.copies) }; + } catch { + return { links: {}, copies: {} }; + } +} + +async function writeRecord(profileDir: string, record: SharedConfigRecord): Promise { + const target = recordPath(profileDir); + const temp = `${target}.${randomBytes(4).toString("hex")}.tmp`; + await fs.writeFile(temp, JSON.stringify(record)); + 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 sourceIs = async (path: string, kind: EntryKind) => { + const stat = await fs.stat(path).catch(() => undefined); + return kind === "dir" ? stat?.isDirectory() === true : stat?.isFile() === true; +}; + +/** 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, "")); +}; + +/** + * Links one shared folder or file. Returns the target to record when the + * link is Threadlines', or undefined when there is none (or it isn't ours). + */ +async function shareByLink(input: { + readonly link: string; + readonly target: string; + readonly kind: EntryKind; + readonly platform: NodeJS.Platform; + readonly recorded: string | undefined; +}): Promise { + const { link, target, kind } = input; + const present = await sourceIs(target, kind); + const stat = await fs.lstat(link).catch(() => undefined); + if (stat?.isSymbolicLink()) { + const current = await linkTarget(link); + if (current === target && present) return target; + // Another target (the home moved) or a source that went away: replaced + // or removed only when Threadlines made it. + if (current !== target && current !== input.recorded) return undefined; + await fs.rm(link, { force: true }); + } else if (stat?.isDirectory()) { + if (!present || kind !== "dir") return undefined; + // 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(link).then( + () => true, + () => false, + ); + if (!removed) return undefined; + } else if (stat) { + // A real file the agent or the user put there. + return undefined; + } + if (!present) return undefined; + await fs.mkdir(dirname(link), { recursive: true, mode: 0o700 }); + const type = kind === "file" ? "file" : input.platform === "win32" ? "junction" : "dir"; + try { + await fs.symlink(target, link, type); + } catch (error) { + // Another start of the same instance linked it first. + if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error; + if ((await linkTarget(link).catch(() => undefined)) !== target) throw error; + } + return target; +} + +const sha256 = (content: Buffer) => createHash("sha256").update(content).digest("hex"); + +const readSmallFile = async (path: string) => { + const stat = await fs.stat(path).catch(() => undefined); + if (!stat?.isFile() || stat.size > MAX_COPY_BYTES) return undefined; + return fs.readFile(path).catch(() => undefined); +}; + +/** + * Copies one shared file (Windows, where a file link needs elevation). + * Returns the hash to record when the copy is Threadlines', or undefined. + */ +async function shareByCopy(input: { + readonly copy: string; + readonly source: string; + readonly recorded: string | undefined; +}): Promise { + const stat = await fs.lstat(input.copy).catch(() => undefined); + const current = stat?.isFile() ? await fs.readFile(input.copy) : undefined; + // Anything else there, or a copy changed since Threadlines wrote it, is + // the agent's or the user's own. + if (stat && (current === undefined || sha256(current) !== input.recorded)) return undefined; + const source = await readSmallFile(input.source); + if (source === undefined) { + if (current !== undefined) await fs.rm(input.copy, { force: true }); + return undefined; + } + const hash = sha256(source); + if (current !== undefined && sha256(current) === hash) return hash; + await fs.mkdir(dirname(input.copy), { recursive: true, mode: 0o700 }); + const temp = `${input.copy}.${randomBytes(4).toString("hex")}.tmp`; + await fs.writeFile(temp, source, { mode: 0o600 }); + await fs.rename(temp, input.copy); + return hash; +} + +export interface ShareAntigravityUserConfigInput { + readonly profileDir: string; + readonly userHome: string; + readonly platform: NodeJS.Platform; +} + +/** Brings the user's shared rules and skills into the profile; returns what failed. */ +export async function shareAntigravityUserConfigNow( + input: ShareAntigravityUserConfigInput, +): Promise> { + const userGemini = antigravityUserGeminiDir(input.userHome); + const before = await readRecord(input.profileDir); + const after: SharedConfigRecord = { links: {}, copies: {} }; + 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 inProfile = join(input.profileDir, ...rel.split("/")); + const source = join(userGemini, ...rel.split("/")); + try { + if (kind === "file" && input.platform === "win32") { + const hash = await shareByCopy({ copy: inProfile, source, recorded: before.copies[rel] }); + if (hash) after.copies[rel] = hash; + } else { + const target = await shareByLink({ + link: inProfile, + target: source, + kind, + platform: input.platform, + recorded: before.links[rel], + }); + if (target) after.links[rel] = target; + } + } catch (error) { + problems.push({ path: inProfile, error: String(error) }); + // Still Threadlines' when it fails to change: keep the record so the + // next start can try again. + if (before.links[rel]) after.links[rel] = before.links[rel]; + if (before.copies[rel]) after.copies[rel] = before.copies[rel]; + } + } + if (JSON.stringify(before) !== JSON.stringify(after)) { + await writeRecord(input.profileDir, after).catch((error: unknown) => + problems.push({ path: recordPath(input.profileDir), error: String(error) }), + ); + } + return problems; +} + +/** + * `shareAntigravityUserConfigNow` as an effect that never fails: 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.flatMap((problems) => + problems.length === 0 + ? Effect.void + : Effect.logWarning("Some of the user's Antigravity rules or skills are not shared.", { + problems, + }), + ), + ); From a467ac2fb0a12dc4f65c3b445d7d2c09a9d28eb2 Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Mon, 23 Nov 2026 02:25:16 -0500 Subject: [PATCH 09/59] feat(antigravity): list Antigravity's skills in the provider status A new reader finds the skills Google's CLI loads, in its own order: the global and project skill folders, then folders declared by skills.json (project manifests up to the repository root, confined to it, then the global one), then plugins in the instance's profile. It follows inherits, literal include_only and exclude (lists may be null), nested include_only names, and no ~ expansion, and it reads front matter only within a size and entry budget. The ACP core gets an optional listSkills hook so a status check can carry the list into the snapshot's skills. --- .../src/provider/Drivers/AntigravityDriver.ts | 1 + apps/server/src/provider/acp/AcpProvider.ts | 9 + .../src/provider/acp/AcpProviderDescriptor.ts | 10 + .../src/provider/acp/AntigravityAcpSupport.ts | 9 + .../antigravity/AntigravitySkills.test.ts | 238 ++++++++++ .../provider/antigravity/AntigravitySkills.ts | 433 ++++++++++++++++++ .../antigravity/AntigravityUserConfig.test.ts | 66 +++ 7 files changed, 766 insertions(+) create mode 100644 apps/server/src/provider/antigravity/AntigravitySkills.test.ts create mode 100644 apps/server/src/provider/antigravity/AntigravitySkills.ts diff --git a/apps/server/src/provider/Drivers/AntigravityDriver.ts b/apps/server/src/provider/Drivers/AntigravityDriver.ts index bc3df8327..ebf904544 100644 --- a/apps/server/src/provider/Drivers/AntigravityDriver.ts +++ b/apps/server/src/provider/Drivers/AntigravityDriver.ts @@ -145,6 +145,7 @@ export const AntigravityDriver: ProviderDriver(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()) @@ -502,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, @@ -585,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, @@ -592,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 bfd7f7dc0..293fe7d21 100644 --- a/apps/server/src/provider/acp/AcpProviderDescriptor.ts +++ b/apps/server/src/provider/acp/AcpProviderDescriptor.ts @@ -21,6 +21,7 @@ import type { ServerProvider, ServerProviderDetection, ServerProviderModel, + ServerProviderSkill, ThreadId, TurnId, UserInputQuestion, @@ -544,6 +545,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/AntigravityAcpSupport.ts b/apps/server/src/provider/acp/AntigravityAcpSupport.ts index d1d8e3f89..b79dce45d 100644 --- a/apps/server/src/provider/acp/AntigravityAcpSupport.ts +++ b/apps/server/src/provider/acp/AntigravityAcpSupport.ts @@ -73,6 +73,7 @@ import { writeAntigravityAgentRefusal, writeAntigravityCatalog, } from "../antigravity/AntigravityProfile.ts"; +import { listAntigravitySkills } from "../antigravity/AntigravitySkills.ts"; import { antigravityUserHome } from "../antigravity/AntigravityUserConfig.ts"; import { holdLaunchGate, type LaunchGate } from "../managedRuntime/LaunchGate.ts"; import { @@ -635,6 +636,8 @@ export interface AntigravityDescriptorInput { 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; } export function makeAntigravityDescriptor( @@ -941,6 +944,12 @@ export function makeAntigravityDescriptor( ...(catalog ? { models: antigravityModelsFromCatalog(catalog) } : {}), } satisfies AcpProviderProbeOutcome; }), + listSkills: (_settings, environment) => + listAntigravitySkills({ + cwd: input.skillsCwd ?? process.cwd(), + userHome: userHomeFor(environment), + 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 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..49662d540 --- /dev/null +++ b/apps/server/src/provider/antigravity/AntigravitySkills.test.ts @@ -0,0 +1,238 @@ +// @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 { listAntigravitySkillsNow } from "./AntigravitySkills.ts"; + +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); + }); +}); diff --git a/apps/server/src/provider/antigravity/AntigravitySkills.ts b/apps/server/src/provider/antigravity/AntigravitySkills.ts new file mode 100644 index 000000000..2a56b8046 --- /dev/null +++ b/apps/server/src/provider/antigravity/AntigravitySkills.ts @@ -0,0 +1,433 @@ +/** + * 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`. + * + * 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. `~/.gemini/config/skills` + * 2. `/.gemini/skills` + * 3. `~/.gemini/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 `~/.gemini/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 instance's own 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) and may be null, a nested item loads only + * when `include_only` names it (`category/my-skill`), `~` is not expanded, + * and a project manifest + * only reaches inside the project or its repository root. + * + * The scan reads front matter only and has a size and entry budget, so a + * huge skills folder can't stall a status check; past the budget it stops + * and lists 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 Effect from "effect/Effect"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; + +import { antigravityUserGeminiDir } from "./AntigravityUserConfig.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; + +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"; + +/** 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 === "" || (!rel.startsWith(`..${sep}`) && rel !== ".." && !isAbsolute(rel)); +}; + +const statOf = (path: string) => fs.stat(path).catch(() => undefined); + +/** The nearest folder at or above `cwd` holding `.git`, or `cwd` when there is none. */ +async function repositoryRoot(cwd: string): Promise { + for (let dir = cwd; ; dir = dirname(dir)) { + if (await fs.lstat(join(dir, ".git")).catch(() => undefined)) return dir; + if (dirname(dir) === dir) return cwd; + } +} + +/** 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 runs out; the scan stops and keeps what it found. */ + exhausted = false; + readonly skills = new Map(); + + private spendEntries(count: number) { + if (count > this.remainingEntries) { + this.exhausted = true; + return false; + } + this.remainingEntries -= count; + return true; + } + + private async readDir(dir: string) { + const names = await fs.readdir(dir).catch(() => undefined); + if (names === undefined || this.exhausted) return undefined; + return this.spendEntries(names.length) ? names : undefined; + } + + /** Reads a skill file up to the end of its front matter, within the budget. */ + private async readHead(path: string): Promise { + const limit = Math.min(MAX_SKILL_BYTES, this.remainingBytes); + const handle = await fs.open(path, "r").catch(() => undefined); + if (!handle) 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 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 handle.close(); + } + } + + /** 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() || this.skills.has(name)) return; + const description = parsed.value.description?.trim(); + this.skills.set(name, { + name, + path: 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 statOf(path))?.isFile() ? path : undefined; + } + + /** + * A skills folder: a skill itself when it holds a `SKILL.md`, otherwise + * each folder directly inside it (the ones `filter` lets through) plus + * nested items `include_only` names. + */ + async scanFolder( + dir: string, + scope: Scope, + filter: NameFilter = NO_FILTER, + accept?: (path: string) => Promise, + ) { + if (this.exhausted || !(await statOf(dir))?.isDirectory()) return; + const names = await this.readDir(dir); + if (names === undefined) return; + const own = await this.skillFileIn(dir, names); + if (own) { + if (!accept || (await accept(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 (!(await statOf(child))?.isDirectory()) continue; + const skillFile = await this.skillFileIn(child); + if (skillFile && (!accept || (await accept(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, + accept?: (path: string) => Promise, + ) { + const stat = await statOf(path); + if (stat?.isFile()) { + if (!this.spendEntries(1)) return; + if (basename(path).toLowerCase() !== "skill.md") return; + if (!passesFilter(basename(dirname(path)), filter)) return; + if (!accept || (await accept(path))) await this.addSkill(path, scope); + return; + } + await this.scanFolder(path, scope, filter, accept); + } + + /** + * A `skills.json`: its `inherits` first, then its `entries`. `accept` + * confines a project manifest to the project. + */ + 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 accept?: (path: string) => Promise; + 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; + const stat = await statOf(path); + if (!stat?.isFile()) return; + if (input.accept && !(await input.accept(path))) return; + if (stat.size > Math.min(MAX_SKILL_BYTES, this.remainingBytes)) { + this.exhausted = true; + return; + } + const raw = await fs.readFile(path, "utf8").catch(() => undefined); + if (raw === undefined) return; + this.remainingBytes -= Buffer.byteLength(raw, "utf8"); + 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.accept ? { accept: input.accept } : {}), + visited: nextVisited, + depth: depth + 1, + }); + } + for (const entry of manifest.value.entries ?? []) { + if (this.exhausted) return; + const entryPath = resolveEntry(entry.path); + if (input.accept && !(await input.accept(entryPath))) continue; + await this.scanEntry(entryPath, input.scope, narrowFilter(input.filter, entry), input.accept); + } + } +} + +export interface ListAntigravitySkillsInput { + /** The folder a session would run in. */ + readonly cwd: string; + /** The user's home, whose `.gemini` holds their global skills (`antigravityUserHome`). */ + readonly userHome: string; + /** The instance's profile (`GEMINI_HOME`), where plugins it installed live. */ + readonly profileDir: string; +} + +export interface AntigravitySkillListing { + readonly skills: ReadonlyArray; + /** The scan hit its budget, 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, +): Promise { + const cwd = resolve(input.cwd); + const userGemini = antigravityUserGeminiDir(input.userHome); + const scan = new SkillScan(); + + const roots: ReadonlyArray = [ + [join(userGemini, "config", "skills"), "user"], + [join(cwd, ".gemini", "skills"), "project"], + [join(userGemini, "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); + + // Project manifests load from inside the project or its repository root + // only: entries leaving it by an absolute path, `..` or a link are skipped. + const root = await repositoryRoot(cwd); + const realRoot = await fs.realpath(root).catch(() => root); + const insideProject = async (path: string) => + isInside(realRoot, await fs.realpath(path).catch(() => resolve(path))); + 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, + accept: insideProject, + }); + } + if (dir === root || dirname(dir) === dir) break; + } + await scan.scanManifest({ + path: join(userGemini, "config", "skills.json"), + scope: "user", + filter: NO_FILTER, + }); + + const pluginsDir = join(input.profileDir, "config", "plugins"); + const plugins = await fs.readdir(pluginsDir).catch(() => [] as Array); + if (plugins.length > 0) { + const settings = await fs + .readFile(join(input.profileDir, "config", "config.json"), "utf8") + .then(decodePluginSettings, () => Option.none()); + const pluginStates = Option.isSome(settings) ? (settings.value.plugins ?? {}) : {}; + for (const plugin of plugins.toSorted()) { + if (pluginStates[plugin]?.enabled === false) continue; + await scan.scanFolder(join(pluginsDir, plugin, "skills"), "user"); + } + } + + return { + skills: [...scan.skills.values()].toSorted((left, right) => + left.name.localeCompare(right.name), + ), + truncated: scan.exhausted, + }; +} + +/** `listAntigravitySkillsNow` as an effect that never fails; a cut-short scan is logged. */ +export const listAntigravitySkills = (input: ListAntigravitySkillsInput) => + Effect.promise(() => + listAntigravitySkillsNow(input).catch((): AntigravitySkillListing => ({ + skills: [], + truncated: true, + })), + ).pipe( + Effect.tap((listing) => + listing.truncated + ? Effect.logWarning("Antigravity's skill list stopped at its scan limit.", { + cwd: input.cwd, + }) + : Effect.void, + ), + Effect.map((listing) => listing.skills), + ); diff --git a/apps/server/src/provider/antigravity/AntigravityUserConfig.test.ts b/apps/server/src/provider/antigravity/AntigravityUserConfig.test.ts index b30da097d..a6eab71b4 100644 --- a/apps/server/src/provider/antigravity/AntigravityUserConfig.test.ts +++ b/apps/server/src/provider/antigravity/AntigravityUserConfig.test.ts @@ -3,8 +3,18 @@ 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 { ANTIGRAVITY_SHARED_DIRS, ANTIGRAVITY_SHARED_FILES, @@ -12,6 +22,7 @@ import { shareAntigravityUserConfigNow, } from "./AntigravityUserConfig.ts"; +const decodeAntigravitySettings = Schema.decodeSync(AntigravitySettings); const roots: Array = []; afterEach(async () => { @@ -211,3 +222,58 @@ describe("antigravityUserHome", () => { }); }); +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 }, + ]); + }); +}); From 3fbda6a052e27e317cf65510aac26809a8d734e1 Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Mon, 23 Nov 2026 02:25:16 -0500 Subject: [PATCH 10/59] docs(antigravity): where Antigravity reads the user's rules and skills --- apps/server/src/guide/topics.ts | 2 ++ docs/providers/antigravity.md | 35 +++++++++++++++++++++++++++++++++ 2 files changed, 37 insertions(+) diff --git a/apps/server/src/guide/topics.ts b/apps/server/src/guide/topics.ts index 5794d63b2..afb71b120 100644 --- a/apps/server/src/guide/topics.ts +++ b/apps/server/src/guide/topics.ts @@ -313,6 +313,8 @@ Claude's models come from Claude Code itself, so a new one shows up without a Th 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. +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 when a message starts with / and its name. + 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, 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. Clicking a limit there opens {place:usage}. 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. diff --git a/docs/providers/antigravity.md b/docs/providers/antigravity.md index 9f62779be..42557fc2c 100644 --- a/docs/providers/antigravity.md +++ b/docs/providers/antigravity.md @@ -57,6 +57,41 @@ has them. The reasoning level is its own choice next to the model. Plan mode sends the task as `/plan`, and the plan shows on the plan card for review. +## 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. + +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. 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. Skills of plugins installed in that account's profile are +listed unless the plugin is turned off. 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. + ## Sign-In Methods Open `Settings -> Providers`, open the Antigravity row, and pick a method under `Sign-in method` on From 9470f3b02559f76916beea22ee2f6e82910f82a6 Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Mon, 23 Nov 2026 02:27:11 -0500 Subject: [PATCH 11/59] docs: Antigravity plan, skills go in the composer's slash list in stage 3 --- docs/providers/antigravity-cli-plan.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/docs/providers/antigravity-cli-plan.md b/docs/providers/antigravity-cli-plan.md index 96900ea76..fd193cd85 100644 --- a/docs/providers/antigravity-cli-plan.md +++ b/docs/providers/antigravity-cli-plan.md @@ -151,6 +151,11 @@ The registry package we install today is the old channel: it is at 1.5.2 while t 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. From d0d86871d51e2237ef5ad246641bd965568fcdba Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Mon, 23 Nov 2026 02:28:00 -0500 Subject: [PATCH 12/59] feat(usage): plan limits that cover one family of models Antigravity meters groups of models apart (Gemini, each Gemini 4 model with its own pool, Claude and GPT together), so a spent group stops only its own models. A scoped usage window can now name the models it holds (scopeModels) and the ones it leaves out (scopeExcludes); without them a scoped window matches its label as before (Claude's per-model limits). - contracts: the antigravity-quota usage source and the two fields - shared: usageScopeHoldsModel, the one matching rule, and usageLimitForModel, the limit a model is stopped on, for Continue at reset - web: model rows use the shared rule; two compact lines that share a short label keep their period; a provider other than Claude can show its own usage notice (auth.capabilities.usage.detail) --- apps/web/src/lib/providerUsage.test.ts | 116 ++++++++++++++++++++++++ apps/web/src/lib/providerUsage.ts | 90 +++++++++++++----- packages/contracts/src/server.ts | 14 +++ packages/shared/src/usageLimits.test.ts | 61 ++++++++++++- packages/shared/src/usageLimits.ts | 68 ++++++++++++++ 5 files changed, 324 insertions(+), 25 deletions(-) diff --git a/apps/web/src/lib/providerUsage.test.ts b/apps/web/src/lib/providerUsage.test.ts index 97162e1b2..99eddb835 100644 --- a/apps/web/src/lib/providerUsage.test.ts +++ b/apps/web/src/lib/providerUsage.test.ts @@ -999,6 +999,79 @@ describe("deriveProviderAccountUsagePresentationForProvider", () => { ), ).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: "antigravity-quota", + checkedAt, + primaryLimitId: "antigravity", + limits: [ + { + limitId: "antigravity", + 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 => ({ @@ -1153,6 +1226,49 @@ describe("a model's own usage limit", () => { expect(label(100)).toMatchObject({ text: "Limit · resets in 3d 16h", tone: "reached" }); }); + const antigravity = deriveProviderAccountUsagePresentation( + { + source: "antigravity-quota", + checkedAt: "2026-07-03T00:00:00.000Z", + primaryLimitId: "antigravity", + limits: [ + { + limitId: "antigravity", + 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 6b7ff8138..e67b0feda 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 @@ -39,8 +40,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; }; @@ -329,6 +329,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 ? [ @@ -344,7 +351,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, @@ -494,7 +504,13 @@ function formatScopedUsageWindowPresentation( reachedLimit, warning: reachedLimit || severityWarning || usedPercent >= USAGE_WARNING_THRESHOLD_PERCENT, ...(elapsedPercent !== undefined ? { 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, + }, }; } @@ -666,6 +682,7 @@ const PROVIDER_USAGE_SOURCE_LABELS: Record 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, @@ -903,26 +951,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/packages/contracts/src/server.ts b/packages/contracts/src/server.ts index df5cc8fe1..361b7ba27 100644 --- a/packages/contracts/src/server.ts +++ b/packages/contracts/src/server.ts @@ -198,6 +198,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), }); @@ -301,6 +314,7 @@ export const ServerProviderAccountUsage = Schema.Struct({ "claude-oauth-usage", "muse-subscription-usage", "grok-billing", + "antigravity-quota", ]), checkedAt: IsoDateTime, primaryLimitId: Schema.optional(TrimmedNonEmptyString), diff --git a/packages/shared/src/usageLimits.test.ts b/packages/shared/src/usageLimits.test.ts index d3ea80b62..ebd27a051 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: "antigravity-quota", + 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..a67a31e63 100644 --- a/packages/shared/src/usageLimits.ts +++ b/packages/shared/src/usageLimits.ts @@ -212,3 +212,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() }; +} From 83bef028bc6608c210b7a5dcda4baa22d1911087 Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Mon, 23 Nov 2026 02:28:00 -0500 Subject: [PATCH 13/59] feat(server): HttpsFetch sends text-body requests and never redirects them The allowlisted fetch only did GETs. It now takes a method and a text body, sets its length, and refuses to follow a redirect of a request with a body, so a POST carrying a sign-in can't be sent on to another address. GETs behave as before. --- .../managedRuntime/HttpsFetch.test.ts | 24 +++++++++++++ .../src/provider/managedRuntime/HttpsFetch.ts | 35 ++++++++++++++----- 2 files changed, 50 insertions(+), 9 deletions(-) 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 From ca768e78872ef8eb7edbb1d2dbada929fb1206e6 Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Mon, 23 Nov 2026 02:28:00 -0500 Subject: [PATCH 14/59] feat(antigravity): show the Google plan's limits and the signed-in email For an instance signed in with Google (Google account or Gemini Enterprise), Threadlines reads the plan's limits from Google's unpublished Cloud Code API (retrieveUserQuotaSummary, with fetchAvailableModels to fill in), with the access token the CLI saved in the instance's own profile, and shows a 5-hour and a weekly window per model family wherever other plans show theirs. The account email comes from the same sign-in. - One module, AntigravityUsage.ts, so it comes out in one piece. - Never renews, rewrites or removes the token and never reads the keyring; an expired token keeps the last numbers with "start a chat to refresh". - Only for Google sign-in methods; readings are keyed by the sign-in fingerprint and Google account. - Threadlines' own User-Agent; only the two Cloud Code hosts and userinfo, no redirects; 10 s per request, 30 s per read, one read at a time in the background so a status check never waits; sign-in and sign-out cancel it. --- apps/server/src/guide/topics.ts | 2 +- .../src/provider/Drivers/AntigravityDriver.ts | 15 +- .../src/provider/acp/AntigravityAcpSupport.ts | 11 +- .../antigravity/AntigravityUsage.test.ts | 560 +++++++++++++ .../provider/antigravity/AntigravityUsage.ts | 759 ++++++++++++++++++ docs/providers/antigravity.md | 31 + 6 files changed, 1374 insertions(+), 4 deletions(-) create mode 100644 apps/server/src/provider/antigravity/AntigravityUsage.test.ts create mode 100644 apps/server/src/provider/antigravity/AntigravityUsage.ts diff --git a/apps/server/src/guide/topics.ts b/apps/server/src/guide/topics.ts index 5794d63b2..a1d46d159 100644 --- a/apps/server/src/guide/topics.ts +++ b/apps/server/src/guide/topics.ts @@ -313,7 +313,7 @@ Claude's models come from Claude Code itself, so a new one shows up without a Th 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. -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, 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. Clicking a limit there opens {place:usage}. +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, 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. 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. diff --git a/apps/server/src/provider/Drivers/AntigravityDriver.ts b/apps/server/src/provider/Drivers/AntigravityDriver.ts index bc3df8327..a1a5eafa3 100644 --- a/apps/server/src/provider/Drivers/AntigravityDriver.ts +++ b/apps/server/src/provider/Drivers/AntigravityDriver.ts @@ -47,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"; @@ -139,15 +140,23 @@ 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/acp/AntigravityAcpSupport.ts b/apps/server/src/provider/acp/AntigravityAcpSupport.ts index 9cce9a2ba..60eca18f2 100644 --- a/apps/server/src/provider/acp/AntigravityAcpSupport.ts +++ b/apps/server/src/provider/acp/AntigravityAcpSupport.ts @@ -87,6 +87,10 @@ import type { AntigravityInstalledRuntime, AntigravityRuntime, } from "../antigravity/AntigravityRuntime.ts"; +import { + type AntigravityUsageReader, + withAntigravityUsage, +} from "../antigravity/AntigravityUsage.ts"; import { detectionAt } from "../providerDetection.ts"; import type { ProviderMaintenanceCapabilities, @@ -634,12 +638,14 @@ export interface AntigravityDescriptorInput { readonly gate?: LaunchGate; /** The instance's sign-in method, project and key (fixed for an instance build). */ readonly signIn: AntigravitySignInConfig; + /** 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, releases, gate, signIn } = input; + const { paths, runtime, releases, gate, signIn, usage } = input; const platform = process.platform; const fingerprint = antigravityCredentialFingerprint(signIn); const isGoogleAccount = signIn.method === "oauth-personal"; @@ -927,13 +933,14 @@ export function makeAntigravityDescriptor( } satisfies AcpProviderProbeOutcome; } const catalog = yield* readCatalog(tag); - return { + const outcome = { installed: true, version, ...signInStatus, ...latest, ...(catalog ? { models: antigravityModelsFromCatalog(catalog) } : {}), } satisfies AcpProviderProbeOutcome; + return usage ? withAntigravityUsage(outcome, yield* usage.status) : outcome; }), modelDiscoveryTimeoutMs: ANTIGRAVITY_DISCOVERY_TIMEOUT_MS, // Discovery mirrors the selected model's options (its reasoning levels) 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..7fb00b071 --- /dev/null +++ b/apps/server/src/provider/antigravity/AntigravityUsage.test.ts @@ -0,0 +1,560 @@ +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 { + ANTIGRAVITY_USAGE_EXPIRED_DETAIL, + ANTIGRAVITY_USAGE_FAILED_DETAIL, + ANTIGRAVITY_USAGE_USER_AGENT, + makeAntigravityUsageReader, +} 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; +}) => + 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, + }); + let snapshot = signedInSnapshot(method); + let published = yield* Deferred.make(); + reader.publishTo((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 }; + }); + +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")); + assert.equal(snapshot.accountUsage!.source, "antigravity-quota"); + 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; + // The fullest Gemini model stands for the family; Claude stays the summary's shared pool. + assert.deepEqual(windowsOf(snapshot), [ + { label: "Gemini", minutes: undefined, used: 40 }, + { label: "Gemini Hydrogen", minutes: undefined, used: 5 }, + { label: "Claude & GPT", minutes: 300, used: 56 }, + { label: "Claude & GPT", minutes: 10080, used: 100 }, + ]); + const gemini = snapshot.accountUsage!.limits[0]!.scoped![0]!; + assert.deepEqual(gemini.scopeExcludes, ["Hydrogen"]); + }), + ); + + 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", minutes: undefined, used: 40 }, + { label: "Gemini Hydrogen", minutes: undefined, used: 5 }, + { label: "Claude", minutes: undefined, used: 80 }, + ]); + }), + ); + + it.effect("folds an Enterprise answer's per-model buckets into one row per family", () => + 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; + assert.deepEqual(windowsOf(snapshot), [ + { label: "Gemini", minutes: undefined, used: 50 }, + { label: "Gemini Argon", minutes: undefined, used: 90 }, + { label: "Claude", minutes: undefined, used: 70 }, + { label: "GPT", minutes: undefined, used: 5 }, + ]); + const argon = snapshot.accountUsage!.limits[0]!.scoped![1]!; + assert.equal(argon.resetsAt, Date.parse("2026-11-24T00:00:00Z")); + }), + ); + + 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.endsWith("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); + }), + ); +}); diff --git a/apps/server/src/provider/antigravity/AntigravityUsage.ts b/apps/server/src/provider/antigravity/AntigravityUsage.ts new file mode 100644 index 000000000..7c3e231b4 --- /dev/null +++ b/apps/server/src/provider/antigravity/AntigravityUsage.ts @@ -0,0 +1,759 @@ +/** + * 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, + ServerProvider, + 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 { 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"; + +/** 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), + 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. */ +interface Family { + readonly key: string; + readonly label: string; + /** Names a model holds to be in the family; undefined: the label. */ + readonly models?: ReadonlyArray; +} + +const GEMINI: Family = { key: "gemini", label: "Gemini", models: ["Gemini"] }; +const SHARED_3P: Family = { key: "3p", label: "Claude & GPT", models: ["Claude", "GPT"] }; +const CLAUDE: Family = { key: "claude", label: "Claude", models: ["Claude"] }; +const GPT: Family = { key: "gpt", label: "GPT", models: ["GPT"] }; + +/** + * Gemini 4's own quota families as Google has named them so far. An Enterprise + * answer meters per model and has no pool to learn them from, so a per-model + * bucket is placed by these and by the pools in the same answer. + */ +const KNOWN_GEMINI_SUBFAMILIES = ["argon", "carbon", "neon", "hydrogen"]; + +const capitalize = (word: string) => word.charAt(0).toUpperCase() + word.slice(1); + +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)], + }; +} + +interface QuotaWindow { + readonly family: Family; + readonly period: Period; + /** 0 to 100, unrounded. */ + readonly usedPercent: number; + readonly resetsAtMs: number | undefined; +} + +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 family's quota is as tight as its + * tightest model. + */ +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 family a model's id belongs to, for per-model quotas. */ +function modelFamily( + modelId: string, + provider: string | undefined, + subfamilies: ReadonlySet, +): Family | undefined { + const id = modelId.toLowerCase(); + if (provider === "MODEL_PROVIDER_GOOGLE" || id.startsWith("gemini-")) { + const words = id.split(/[^a-z0-9]+/); + const sub = words.find((word) => subfamilies.has(word)); + return sub ? geminiSubfamily(sub, undefined) : GEMINI; + } + if (provider === "MODEL_PROVIDER_ANTHROPIC" || id.startsWith("claude-")) return CLAUDE; + if (provider === "MODEL_PROVIDER_OPENAI" || id.startsWith("gpt-")) return GPT; + return undefined; +} + +/** + * The windows in one `retrieveUserQuotaSummary` answer, requested at + * `requestedAtMs`. Pools (`5h`, `weekly`) keep their own rows; an Enterprise + * answer's per-model buckets fold into one row per family. + */ +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 buckets = (groups ?? []).flatMap((group) => + (group.buckets ?? []) + .filter((bucket) => !bucket.disabled) + .map((bucket) => ({ bucket, groupName: group.displayName })), + ); + // Pools first: they name the Gemini sub-families this account has. + const subfamilies = new Set(KNOWN_GEMINI_SUBFAMILIES); + for (const { bucket } of buckets) { + const sub = /^gemini-([a-z]+)-/.exec(bucket.bucketId)?.[1]; + if (sub && (bucket.window === "5h" || bucket.window === "weekly")) subfamilies.add(sub); + } + const windows = new Map(); + for (const { bucket, groupName } of buckets) { + 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; + let family: Family | undefined; + if (id.startsWith("3p-")) family = SHARED_3P; + else if (/^gemini-(5h|weekly|quota)$/.test(id)) family = GEMINI; + else if (pooled && /^gemini-[a-z]+-/.test(id)) { + family = geminiSubfamily(/^gemini-([a-z]+)-/.exec(id)![1]!, groupName); + } else if (!pooled) family = modelFamily(id, undefined, subfamilies); + family ??= { + key: `other-${id}`, + label: groupName?.trim() || bucket.displayName?.trim() || id, + }; + // 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, + * folded per family. 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 subfamilies = new Set(KNOWN_GEMINI_SUBFAMILIES); + const windows = new Map(); + for (const [modelId, model] of Object.entries(decoded.value.models)) { + if (model.isInternal) continue; + const family = modelFamily(modelId, model.modelProvider, subfamilies); + 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.key.startsWith("gemini-") + ? 1 + : family === SHARED_3P || family.key === "claude" || family.key === "gpt" + ? 2 + : 3; +const PERIOD_ORDER: Record = { "5h": 0, weekly: 1, quota: 2 }; + +/** + * A reading as the snapshot carries it: every window is one family's own + * (`scoped`), since a spent family never stops the others. The default Gemini + * pool leaves out the sub-families that have their own. + */ +export function antigravityAccountUsage( + windows: ReadonlyArray, + checkedAt: string, +): ServerProviderAccountUsage { + const ownPools = [ + ...new Set( + windows + .filter((window) => window.family.key.startsWith("gemini-")) + .flatMap((window) => window.family.models ?? []), + ), + ]; + 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 = Math.round(window.usedPercent); + const minutes = PERIOD_MINUTES[window.period]; + return { + scopeLabel: window.family.label, + ...(window.family.models ? { scopeModels: window.family.models } : {}), + ...(window.family.key === "gemini" && ownPools.length > 0 + ? { scopeExcludes: ownPools } + : {}), + usedPercent, + remainingPercent: 100 - usedPercent, + ...(window.resetsAtMs !== undefined ? { resetsAt: window.resetsAtMs } : {}), + ...(minutes !== undefined ? { windowDurationMins: minutes } : {}), + checkedAt, + }; + }); + return { + source: "antigravity-quota", + checkedAt, + primaryLimitId: "antigravity", + limits: [{ limitId: "antigravity", scoped }], + }; +} + +// ── Requests ───────────────────────────────────────────────────────── + +/** Why a request failed, in words that never carry the token. */ +class UsageRequestError extends Schema.TaggedError()( + "AntigravityUsageRequestError", + { reason: Schema.String }, +) {} + +const requestJson = ( + fetch: DownloadFetch, + url: string, + init: { method: "GET" | "POST"; accessToken: string; body?: string }, +) => + 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: REQUEST_TIMEOUT, + orElse: () => + Effect.fail(new UsageRequestError({ reason: `${new URL(url).host} timed out` })), + }), + ); + +/** 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, +) => + 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: "{}", + }); + return { answered: true, windows: parse(answer, requestedAtMs) }; + }).pipe(Effect.orElseSucceed(() => ({ answered: false, windows: [] as const }))), + { concurrency: "unbounded" }, + ).pipe( + Effect.map((answers) => ({ + answered: answers.some((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) => + Effect.gen(function* () { + const summary = yield* askHosts( + fetch, + method, + accessToken, + "retrieveUserQuotaSummary", + antigravitySummaryWindows, + ); + const hasGemini = summary.windows.some((window) => window.family.key.startsWith("gemini")); + if (hasGemini) return summary.windows; + const models = yield* askHosts( + fetch, + method, + accessToken, + "fetchAvailableModels", + antigravityModelWindows, + ); + if (summary.windows.length === 0) return models.windows; + return [ + ...summary.windows, + ...models.windows.filter((window) => window.family.key.startsWith("gemini")), + ]; + }); + +const readEmail = (fetch: DownloadFetch, accessToken: string) => + requestJson(fetch, USERINFO_URL, { method: "GET", accessToken }).pipe( + Effect.map((answer) => { + const decoded = decodeUserInfo(answer); + return decoded._tag === "Some" ? cleanEmail(decoded.value.email) : undefined; + }), + Effect.orElseSucceed(() => undefined), + ); + +// ── 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 { + readonly accountUsage?: ServerProviderAccountUsage; + readonly email?: string; + /** Set when there is something to say: an expired token, or a failed read. */ + readonly usage?: ServerProviderAuthCapability; +} + +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; + /** Where a finished read publishes, once the instance's snapshot exists. */ + readonly publishTo: ( + patch: (update: (current: ServerProvider) => ServerProvider | null) => Effect.Effect, + ) => void; + /** The limit the last reading says `modelName` is stopped on, for Continue at reset. */ + readonly usageLimitFor: (modelName: 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; +} + +interface Reading { + readonly key: string; + 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 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 publish: + | ((update: (current: ServerProvider) => ServerProvider | null) => Effect.Effect) + | 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 { + ...(kept ? { accountUsage: kept } : {}), + ...(email ? { email } : {}), + ...(usage ? { usage } : {}), + }; + }; + + const publishStatus = (status: AntigravityUsageStatus) => + publish + ? publish((current) => { + if ( + !current.enabled || + current.auth.status !== "authenticated" || + current.auth.type !== input.method + ) { + return null; + } + return withAntigravityUsage(current, status); + }) + : Effect.void; + + const read = (token: SavedToken, key: string, method: GoogleMethod) => + Effect.gen(function* () { + const started = generation; + const windows = yield* readQuotaWindows(fetch, method, token.accessToken); + const email = + token.email ?? emails.get(key) ?? (yield* readEmail(fetch, token.accessToken)); + // Signed in or out meanwhile, or another account's sign-in is on disk now. + const current = yield* readSavedToken(input.profileDir); + if (generation !== started || current === undefined || keyOf(current) !== key) return; + const nowMs = yield* Clock.currentTimeMillis; + if (windows.length > 0) { + reading = { + key, + accountUsage: antigravityAccountUsage(windows, new Date(nowMs).toISOString()), + }; + } + if (email) emails.set(key, email); + lastAttempt = { key, atMs: lastAttempt?.atMs ?? nowMs, failed: windows.length === 0 }; + yield* publishStatus(statusFor(token, key, nowMs)); + }).pipe( + Effect.timeoutOrElse({ + duration: READ_TIMEOUT, + orElse: () => + Effect.gen(function* () { + if (lastAttempt?.key === key) lastAttempt = { ...lastAttempt, failed: true }; + yield* publishStatus(statusFor(token, key, yield* Clock.currentTimeMillis)); + }), + }), + // 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({}))); + + return { + status, + reset: Effect.gen(function* () { + generation += 1; + yield* FiberHandle.clear(inFlight); + reading = undefined; + emails = new Map(); + lastAttempt = undefined; + }), + publishTo: (patch) => { + publish = patch; + }, + usageLimitFor: (modelName) => + 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, + modelName, + yield* Clock.currentTimeMillis, + ); + }), + } satisfies AntigravityUsageReader; + }); + +/** + * A snapshot (or status) with a usage status folded in: the reading, the + * email, and the line about it. A status without a reading keeps the one + * already there, which is the last good one. + */ +export function withAntigravityUsage< + T extends { + readonly auth: ServerProviderAuth; + readonly accountUsage?: ServerProviderAccountUsage | undefined; + }, +>(target: T, status: AntigravityUsageStatus): T { + const { capabilities, ...auth } = target.auth; + const { usage: _previous, ...others } = capabilities ?? {}; + const nextCapabilities = { ...others, ...(status.usage ? { usage: status.usage } : {}) }; + return { + ...target, + auth: { + ...auth, + ...(status.email ? { email: status.email } : {}), + ...(Object.keys(nextCapabilities).length > 0 ? { capabilities: nextCapabilities } : {}), + }, + ...(status.accountUsage ? { accountUsage: status.accountUsage } : {}), + }; +} diff --git a/docs/providers/antigravity.md b/docs/providers/antigravity.md index 9f62779be..9c61e4f2b 100644 --- a/docs/providers/antigravity.md +++ b/docs/providers/antigravity.md @@ -94,6 +94,37 @@ 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 are metered per model, with no window length; their rows show each group's +fullest model. A group that runs out stops only its own models. 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. +- 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 From 4907f2fc3a9697a39ee80cd0bdd59346b1b4bc3a Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Mon, 23 Nov 2026 02:36:30 -0500 Subject: [PATCH 15/59] feat(usage): Antigravity joins the Usage page, priced at Gemini 4 rates Antigravity turns go to the usage ledger like fx's, so the contract, the ledger and the web page learn a new provider kind together (older clients still never receive one they can't decode). Gemini 4 Carbon, Argon, Neon and Hydrogen get built-in Standard-tier rates from Google's price list; Carbon and Argon double on December 1, 2026, so a built-in rate can now change on a known day and records are priced at the rate of their own day. A model id with an effort or role suffix (gemini-4-argon-high) is priced as its family. Antigravity takes a teal that passes the color-blind and normal-vision separation checks against every provider in both themes. --- apps/server/src/usage/usageAggregation.ts | 7 +- apps/server/src/usage/usageLedger.ts | 8 +- apps/server/src/usage/usagePricing.test.ts | 22 +++++ apps/server/src/usage/usagePricing.ts | 81 +++++++++++++++++-- apps/server/src/usage/usageTranscripts.ts | 1 + apps/web/src/components/chat/AgentsPanel.tsx | 3 + apps/web/src/components/usage/UsageView.tsx | 2 + .../src/components/usage/usageView.logic.ts | 5 ++ apps/web/src/index.css | 6 +- packages/contracts/src/usage.ts | 1 + 10 files changed, 127 insertions(+), 9 deletions(-) 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..a4a33ebaa 100644 --- a/apps/server/src/usage/usagePricing.test.ts +++ b/apps/server/src/usage/usagePricing.test.ts @@ -104,4 +104,26 @@ 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); + }); }); diff --git a/apps/server/src/usage/usagePricing.ts b/apps/server/src/usage/usagePricing.ts index b38910266..84083c8da 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,27 @@ 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]; + for (const name of family === undefined ? [normalized] : [normalized, family]) { + const rate = table.get(name) ?? BUILT_IN_RATES.get(name) ?? datedRate(name, atMs); + if (rate !== undefined) return rate; + } + return null; +} + +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 +235,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 +250,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 +270,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/usage/UsageView.tsx b/apps/web/src/components/usage/UsageView.tsx index 896d37da3..f75fbb785 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 986b5472a..0235a5da4 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", ]; /** @@ -1009,6 +1013,7 @@ const USAGE_PROVIDER_BY_DRIVER: ReadonlyMap Date: Mon, 23 Nov 2026 02:36:38 -0500 Subject: [PATCH 16/59] feat(antigravity): turns stay working while the agent's work runs, steer, and fail with Google's real error agy acp 1.5 answers a prompt while a command it awaits, a timer or a subagent goes on, then wakes and replies by itself. The ACP core gains three descriptor hooks, unused by every other agent: - heldTurns: the turn stays open (working, with Stop) while such work runs, and the reply the agent starts when it ends lands in the same turn. A reply ends with its usage_update. Commands and subagents release the turn after 30 silent minutes; a timer holds it until it fires. Stop cancels the work and settles the turn once. Output or a permission request with no turn open starts one of its own. - steerWithPrompt: a message sent mid-turn goes as another session/prompt; the newest prompt's answer settles the turn and an older one's is ignored. The session runtime now counts prompts in flight instead of one flag. - promptOutcome: reads how a prompt really ended. Antigravity's reads the JSON-RPC error (1.5.9+) and, for a normal end, the turn's last step in the CLI's own session log (one module, marked as a private format). 5xx and 429 fail the turn; an exhausted quota carries its reset time to the usage-limit notice; a lost thinking signature stops the session so the next message starts a new one seeded with the thread's history. turnUsageTotals lets Antigravity count input as input plus cached reads, and its turns go to the usage ledger. A stand-in agy (scripts/antigravity-mock- agent.ts) drives the real descriptor in tests. --- apps/server/scripts/antigravity-mock-agent.ts | 249 +++++ apps/server/src/guide/topics.ts | 4 +- apps/server/src/provider/acp/AcpAdapter.ts | 894 ++++++++++++++---- .../src/provider/acp/AcpProviderDescriptor.ts | 83 +- .../src/provider/acp/AcpSessionRuntime.ts | 26 +- .../src/provider/acp/AntigravityAcpSupport.ts | 3 + .../antigravity/AntigravitySessionLog.ts | 126 +++ .../antigravity/AntigravityTurns.test.ts | 414 ++++++++ .../provider/antigravity/AntigravityTurns.ts | 294 ++++++ docs/providers/antigravity.md | 43 +- 10 files changed, 1935 insertions(+), 201 deletions(-) create mode 100644 apps/server/scripts/antigravity-mock-agent.ts create mode 100644 apps/server/src/provider/antigravity/AntigravitySessionLog.ts create mode 100644 apps/server/src/provider/antigravity/AntigravityTurns.test.ts create mode 100644 apps/server/src/provider/antigravity/AntigravityTurns.ts diff --git a/apps/server/scripts/antigravity-mock-agent.ts b/apps/server/scripts/antigravity-mock-agent.ts new file mode 100644 index 000000000..70997fc7f --- /dev/null +++ b/apps/server/scripts/antigravity-mock-agent.ts @@ -0,0 +1,249 @@ +#!/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. + * - `subagent`: launches a subagent, ends its prompt, and replies with the + * subagent's report later. + * - `wake`: ends its prompt with nothing running, then replies by itself. + * - `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. + */ +import { appendFileSync, mkdirSync } 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(); + } +} + +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 } }); + const modelCallEnds = (sessionId: string) => + update(sessionId, { sessionUpdate: "usage_update", used: 9_000, 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: {} } }, + }), + ); + yield* agent.handleCreateSession(() => + Effect.sync(() => { + sessionCount += 1; + return { + sessionId: `agy-session-${sessionCount}`, + modes: { + currentModeId: "default", + availableModes: [ + { id: "default", name: "Default" }, + { id: "accept-edits", name: "Accept edits" }, + { id: "plan", name: "Plan" }, + ], + }, + }; + }), + ); + 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", + }); + } + }), + ); + + yield* agent.handlePrompt((request) => + Effect.gen(function* () { + const sessionId = String(request.sessionId); + promptsSeen += 1; + if (scenario === "steer") { + if (promptsSeen === 1) { + yield* say(sessionId, "Working on it."); + // Answered once the steer arrives, as 1.5.11 does. + yield* Deferred.await(secondPrompt); + return { stopReason: "end_turn" as const }; + } + yield* Deferred.succeed(secondPrompt, undefined); + yield* Effect.sleep("50 millis"); + 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 === "background" || scenario === "hang") { + 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 === "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 === "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 }; + } + yield* say(sessionId, "hello from agy"); + yield* modelCallEnds(sessionId); + return { stopReason: "end_turn" as const }; + }), + ); + + 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 5794d63b2..08885a2d0 100644 --- a/apps/server/src/guide/topics.ts +++ b/apps/server/src/guide/topics.ts @@ -311,7 +311,7 @@ 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. -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. +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 meanwhile steers the turn. Its turns count on {place:usage}. 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, 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. Clicking a limit there opens {place:usage}. @@ -329,7 +329,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/provider/acp/AcpAdapter.ts b/apps/server/src/provider/acp/AcpAdapter.ts index 46ffdb09d..c00a2435a 100644 --- a/apps/server/src/provider/acp/AcpAdapter.ts +++ b/apps/server/src/provider/acp/AcpAdapter.ts @@ -24,6 +24,7 @@ import { type RuntimeMode, type ThreadId, TurnId, + type UsageTokenTotals, } from "@threadlines/contracts"; import { withFailureCategory } from "../providerFailureCategory.ts"; import { makeAgentProcessLedger } from "../agentProcessLedger.ts"; @@ -109,9 +110,13 @@ import { import { makeAcpNativeLoggers } from "./AcpNativeLogging.ts"; import type { AcpExtensionContext, + AcpPromptFailure, + AcpPromptOutcome, + AcpPromptPlanMode, AcpProviderDescriptor, AcpProviderSettings, AcpTurnOutcome, + AcpWorkAfterPrompt, } from "./AcpProviderDescriptor.ts"; import { applyAcpModelSelection, @@ -145,6 +150,15 @@ 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); +/** How often a held turn (`heldTurns`) looks whether the agent's work is done. */ +const ACP_HELD_TURN_CHECK = Duration.millis(250); +/** + * 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); /** * The most turns a resume cursor remembers the agent's prompt positions for * (see `conversationHistory`); a revert further back trims Threadlines' turn @@ -288,9 +302,90 @@ interface AcpSessionContext { | undefined; /** The newest position the agent has listed, so a later prompt is placed after it. */ newestPosition: number | undefined; + /** The turn whose prompts run or last ran (a steered turn has several). */ + turnRun: AcpTurnRun | undefined; + /** The turn kept open while the agent's work goes on (`heldTurns`). */ + held: AcpHeldTurn | undefined; + /** Work the agent goes on with after its prompt answered, by tool call id (`heldTurns`). */ + readonly workAfterPrompt: Map; + /** Subagent launches counted so far, by tool call id, so a repeated update counts once. */ + readonly subagentLaunches: Set; + /** Subagents launched and not heard back from (a reply the agent started by itself ended since). */ + subagentsOut: number; + /** A reply the agent started by itself has output and no closing `usage_update` yet. */ + replyOpen: boolean; + /** When the agent last sent anything, for a held turn's quiet limits (ms since epoch). */ + lastAgentActivityMs: number; stopped: boolean; } +/** + * One turn's prompts: the first, and each one a steer sent after it + * (`steerWithPrompt`). The newest prompt's answer settles the turn; the agent + * answers an older one as the newer takes over. + */ +interface AcpTurnRun { + readonly turnId: TurnId; + readonly planMode: AcpPromptPlanMode | undefined; + readonly resolvedModel: string | undefined; + /** The first prompt's text, for placing it in the agent's history. */ + readonly promptText: string; + readonly newestBefore: number | undefined; + /** The open prompt (`openPrompt`) while one runs; undefined between prompts. */ + phase: NonNullable | undefined; + /** How many prompts the turn has sent; the newest is this one. */ + prompts: number; + /** Tokens every answered prompt of the turn reported, added up. */ + usage: UsageTokenTotals | null; + /** Reads how the turn's prompts really ended (`promptOutcome`). */ + checkOutcome: AcpPromptOutcomeCheck | undefined; +} + +type AcpPromptOutcomeCheck = Effect.Success>; + +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 } : {}), + }; +} + +/** Two token counts added up (a steered turn's prompts each report their own). */ +function addUsageTotals(total: UsageTokenTotals | null, next: UsageTokenTotals): UsageTokenTotals { + if (total === null) return next; + return { + uncachedInputTokens: total.uncachedInputTokens + next.uncachedInputTokens, + cachedInputTokens: total.cachedInputTokens + next.cachedInputTokens, + cacheCreationTokens: total.cacheCreationTokens + next.cacheCreationTokens, + outputTokens: total.outputTokens + next.outputTokens, + reasoningTokens: total.reasoningTokens + next.reasoningTokens, + }; +} + +/** + * A turn kept open after its prompt answered: the prompt's own completion, + * sent when the work is done, or none for a turn the agent started itself. + */ +interface AcpHeldTurn { + readonly turnId: TurnId; + readonly completion: + | { + readonly payload: AcpTurnCompletedPayload; + readonly model: string | undefined; + readonly usage: UsageTokenTotals | null; + } + | undefined; +} + /** Plan-gate replies are one short sentence; more text than this is content. */ const PLAN_GATE_SCAN_MAX_CHARS = 500; @@ -609,6 +704,11 @@ export function makeAcpAdapter( } >(); const adapterScope = yield* Scope.Scope; + /** + * Agent sessions that can't go on (`AcpPromptFailure.sessionLost`): a + * restart opens a new session instead, seeded with the thread's history. + */ + const lostSessions = new Set(); const threadLocksRef = yield* SynchronizedRef.make(new Map()); const runtimeEventPubSub = yield* PubSub.unbounded(); @@ -850,7 +950,7 @@ export function makeAcpAdapter( ctx: AcpSessionContext, turnId: TurnId, model: string | undefined, - usage: EffectAcpSchema.Usage | null | undefined, + totals: UsageTokenTotals | null, ) => Effect.gen(function* () { const costUsd = @@ -863,7 +963,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({ @@ -898,6 +997,15 @@ export function makeAcpAdapter( ctx.activeTurnId = turnId; ctx.agentTurn = { turnId, ended: yield* Deferred.make() }; ctx.agentTurnLastActivityMs = Date.now(); + // An agent whose own replies end with a `usage_update` (`heldTurns`) + // keeps the turn open by that, and by the work the reply starts. + const held: AcpHeldTurn | undefined = + descriptor.heldTurns !== undefined ? { turnId, completion: undefined } : undefined; + if (held !== undefined) { + ctx.held = held; + ctx.replyOpen = true; + ctx.lastAgentActivityMs = Date.now(); + } ctx.history.push({ turnId, agentTurn: true }); recordHistory(ctx); resetTurnState(ctx); @@ -915,7 +1023,9 @@ export function makeAcpAdapter( payload: raw.payload, }, }); - yield* watchAgentTurnQuiet(ctx, turnId).pipe(Effect.forkIn(ctx.scope)); + yield* ( + held !== undefined ? watchHeldTurn(ctx, held) : watchAgentTurnQuiet(ctx, turnId) + ).pipe(Effect.forkIn(ctx.scope)); }); /** @@ -968,6 +1078,7 @@ export function makeAcpAdapter( } yield* closeReasoning(ctx); ctx.agentTurn = undefined; + if (ctx.held?.turnId === agentTurn.turnId) ctx.held = undefined; if (ctx.agentTurnAhead?.turnId === agentTurn.turnId) ctx.agentTurnAhead = undefined; if (ctx.activeTurnId === agentTurn.turnId) ctx.activeTurnId = undefined; ctx.session = { ...ctx.session, activeTurnId: undefined, updatedAt: yield* nowIso }; @@ -1014,6 +1125,148 @@ export function makeAcpAdapter( } }); + /** + * The agent sent something (`heldTurns`). Outside a prompt that is a + * reply it started by itself, open until its closing `usage_update`. + */ + const noteAgentOutput = (ctx: AcpSessionContext) => { + if (descriptor.heldTurns === undefined) return; + ctx.lastAgentActivityMs = Date.now(); + if (ctx.turnRun?.phase === undefined) ctx.replyOpen = true; + }; + + /** + * The `usage_update` that ends each model call (`heldTurns`): a reply the + * agent started by itself is over, and with it the report it woke to + * give. Subagents are known to end only by such a report, so one ending + * frees them all: a later subagent's report opens a turn of its own. + */ + const noteReplyEnd = (ctx: AcpSessionContext) => { + if (descriptor.heldTurns === undefined) return; + ctx.lastAgentActivityMs = Date.now(); + if (!ctx.replyOpen) return; + ctx.replyOpen = false; + ctx.subagentsOut = 0; + }; + + /** Keeps count of the work a tool call goes on with after its prompt (`heldTurns`). */ + const trackWorkAfterPrompt = (ctx: AcpSessionContext, toolCall: AcpToolCallState) => { + const kind = descriptor.heldTurns?.workAfterPrompt(toolCall); + const id = toolCall.toolCallId; + if (kind === undefined) { + ctx.workAfterPrompt.delete(id); + return; + } + // A launch returns at once; the subagent works on until it reports. + if (kind === "subagent") { + if (toolCall.status === "completed" && !ctx.subagentLaunches.has(id)) { + ctx.subagentLaunches.add(id); + ctx.subagentsOut += 1; + } + return; + } + if (toolCall.status === "completed" || toolCall.status === "failed") { + ctx.workAfterPrompt.delete(id); + } else { + ctx.workAfterPrompt.set(id, kind); + } + }; + + /** Forgets the agent's outstanding work: it was stopped, or failed with its turn. */ + const clearWorkAfterPrompt = (ctx: AcpSessionContext) => { + ctx.workAfterPrompt.clear(); + ctx.subagentsOut = 0; + ctx.replyOpen = false; + }; + + /** + * Ends a held turn, once: the turn the agent started itself as its own + * end would, or a prompt's turn with the completion its prompt answered. + * Run under `turnStartLock`, so a steer or a new message can't race it. + */ + const closeHeldTurn = ( + ctx: AcpSessionContext, + held: AcpHeldTurn, + outcome: "completed" | "cancelled", + ) => + Effect.gen(function* () { + if (ctx.held !== held) return; + ctx.held = undefined; + if (outcome === "cancelled") clearWorkAfterPrompt(ctx); + const completion = held.completion; + if (completion === undefined) { + yield* closeAgentTurn( + ctx, + outcome === "cancelled" + ? { state: "cancelled", stopReason: "cancelled" } + : { state: "completed" }, + ); + return; + } + // The reply the agent started by itself ends with the turn. + yield* ctx.acp.closeAssistantSegment; + yield* ctx.acp.flushEvents(); + yield* closeReasoning(ctx); + if (ctx.activeTurnId === held.turnId) { + ctx.activeTurnId = undefined; + ctx.session = { ...ctx.session, activeTurnId: undefined, updatedAt: yield* nowIso }; + } + if (ctx.turnRun?.turnId === held.turnId) ctx.turnRun = undefined; + yield* offerRuntimeEvent({ + type: "turn.completed", + ...(yield* makeEventStamp()), + provider: PROVIDER, + threadId: ctx.threadId, + turnId: held.turnId, + payload: + outcome === "cancelled" + ? { state: "cancelled", stopReason: "cancelled" } + : completion.payload, + }); + yield* settleTurnUsage(ctx, held.turnId, completion.model, completion.usage); + }); + + /** + * Ends a held turn once the agent's work is done and it has gone quiet, + * or once only commands and subagents hold it and it has said nothing + * for the descriptor's silent limit (a lost wake must not leave the + * thread working forever). A wait on the user's answer is not quiet. + */ + const watchHeldTurn = (ctx: AcpSessionContext, held: AcpHeldTurn) => + Effect.gen(function* () { + const silentLimitMs = Duration.toMillis( + descriptor.heldTurns?.silentLimit ?? ACP_AGENT_TURN_QUIET_LIMIT, + ); + while (ctx.held === held && !ctx.stopped) { + yield* Effect.sleep(ACP_HELD_TURN_CHECK); + if (ctx.held !== held) return; + const now = Date.now(); + if (ctx.pendingApprovals.size > 0 || ctx.pendingUserInputs.size > 0) { + ctx.lastAgentActivityMs = now; + continue; + } + const quietMs = now - ctx.lastAgentActivityMs; + if (ctx.replyOpen && quietMs >= Duration.toMillis(ACP_HELD_REPLY_QUIET_LIMIT)) { + ctx.replyOpen = false; + } + const work = [...ctx.workAfterPrompt.values()]; + const waiting = work.length > 0 || ctx.subagentsOut > 0 || ctx.replyOpen; + const settled = !waiting && quietMs >= Duration.toMillis(ACP_HELD_TURN_SETTLE); + const silent = + waiting && !ctx.replyOpen && !work.includes("wake") && quietMs >= silentLimitMs; + if (!settled && !silent) continue; + const seenAt = ctx.lastAgentActivityMs; + yield* ctx.turnStartLock.withPermit( + Effect.suspend(() => { + // Something arrived while the lock was busy: look again. + if (ctx.held !== held || ctx.lastAgentActivityMs !== seenAt) return Effect.void; + if (silent) clearWorkAfterPrompt(ctx); + return closeHeldTurn(ctx, held, "completed"); + }), + ); + } + }); + /** * 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 +1275,7 @@ export function makeAcpAdapter( const turnForOutput = (ctx: AcpSessionContext, toolCallId?: string) => Effect.gen(function* () { if (ctx.agentTurn !== undefined) ctx.agentTurnLastActivityMs = Date.now(); + noteAgentOutput(ctx); const earlier = toolCallId === undefined ? undefined : ctx.toolCallTurns.get(toolCallId); if (earlier !== undefined) return earlier; if (ctx.activeTurnId !== undefined) return ctx.activeTurnId; @@ -1210,7 +1464,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 @@ -1432,7 +1692,20 @@ 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* () { + // A request the agent makes while no turn runs (`heldTurns`: + // its wake asks for a permission) opens one of its own. + if (descriptor.heldTurns !== undefined && context.activeTurnId === undefined) { + yield* openAgentTurn(context, { + method: "session/request_permission", + payload: {}, + }); + } + noteAgentOutput(context); + yield* showAs(context.activeTurnId); + }), + ); } return shown; }); @@ -1735,11 +2008,17 @@ export function makeAcpAdapter( modelSelection: boundModelSelection, }); + const resumeFailure = + started.resumeFailure ?? + (lostSession !== undefined + ? `${descriptor.presentation.displayName} can no longer continue its earlier conversation.` + : undefined); + if (lostSession !== undefined) lostSessions.delete(lostSession); // 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 @@ -1775,7 +2054,7 @@ export function makeAcpAdapter( projectBriefHash, ), ...(roomToolsRequested ? { roomTools: roomToolsAttached } : {}), - ...(started.resumeFailure !== undefined ? { resumeFailed: true } : {}), + ...(resumeFailure !== undefined ? { resumeFailed: true } : {}), createdAt: now, updatedAt: now, }; @@ -1801,7 +2080,7 @@ export function makeAcpAdapter( // A session reopened from elsewhere has spent an unknown amount. costBaselineUsd: (resumeSessionId !== undefined || forkSession !== undefined) && - started.resumeFailure === undefined + resumeFailure === undefined ? undefined : 0, latestCostUsd: undefined, @@ -1814,7 +2093,9 @@ export function makeAcpAdapter( // A switch from another agent starts without the history: the // thread hands it over. (A failed resume is seeded by the reactor.) pendingContextPreamble: - input.contextSeed !== undefined && resumeSessionId === undefined + input.contextSeed !== undefined && + resumeSessionId === undefined && + lostSession === undefined ? renderThreadContextSeed(input.contextSeed) : undefined, projectBrief, @@ -1829,6 +2110,13 @@ export function makeAcpAdapter( promptOutcome: undefined, openPrompt: undefined, newestPosition: resumedNewestPosition, + turnRun: undefined, + held: undefined, + workAfterPrompt: new Map(), + subagentLaunches: new Set(), + subagentsOut: 0, + replyOpen: false, + lastAgentActivityMs: 0, stopped: false, }; @@ -1865,6 +2153,7 @@ export function makeAcpAdapter( } return; case "ContextUsage": { + noteReplyEnd(ctx); // 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. @@ -1947,6 +2236,8 @@ export function makeAcpAdapter( : []; const toolCallId = event.toolCall.toolCallId; const turnId = yield* turnForOutput(ctx, toolCallId); + if (descriptor.heldTurns !== undefined) + trackWorkAfterPrompt(ctx, event.toolCall); if ( event.toolCall.status === "completed" || event.toolCall.status === "failed" @@ -1974,7 +2265,9 @@ export function makeAcpAdapter( if ( descriptor.cancellationNotice !== undefined && ctx.cancelledTurnId !== undefined && - ctx.cancelledTurnId === ctx.activeTurnId && + // A held turn stopped already: the notice would open another. + (ctx.cancelledTurnId === ctx.activeTurnId || + (descriptor.heldTurns !== undefined && ctx.activeTurnId === undefined)) && event.text.trim() === descriptor.cancellationNotice ) { return; @@ -2034,7 +2327,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()), @@ -2042,7 +2335,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", }, }); @@ -2119,10 +2412,13 @@ export function makeAcpAdapter( 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); + // ACP serializes prompts per session; a turn sent while one is in + // flight starts after it, never interleaved with it (nor with a prompt + // a steer sent meanwhile). + while (ctx.promptFiber !== undefined) { + const promptFiber = ctx.promptFiber; + yield* Fiber.await(promptFiber); + if (ctx.promptFiber === promptFiber) break; } // The reader catches up first, so a turn the agent began before this // message is open (and ended below) rather than taking its output. @@ -2133,8 +2429,12 @@ export function makeAcpAdapter( 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. + // A message sent while the agent runs a turn of its own, or while a + // turn waits on the agent's work, ends that turn here; the agent takes + // the message after it, as Claude does. + if (ctx.held !== undefined) { + yield* closeHeldTurn(ctx, ctx.held, "completed"); + } if (ctx.agentTurn !== undefined) { yield* closeAgentTurn(ctx, { state: "completed" }); } @@ -2202,13 +2502,23 @@ export function makeAcpAdapter( ), ); } + const checkOutcome = yield* watchPromptOutcome(ctx); ctx.activeTurnId = turnId; - const prompt = { + const run: AcpTurnRun = { turnId, - drained: yield* Deferred.make(), - closed: yield* Deferred.make(), + planMode, + resolvedModel, + promptText: promptParts + .flatMap((part) => (part.type === "text" ? [part.text] : [])) + .join("\n"), + newestBefore: ctx.newestPosition, + phase: undefined, + prompts: 0, + usage: null, + checkOutcome, }; - ctx.openPrompt = prompt; + ctx.turnRun = run; + yield* openPromptPhase(ctx, run); resetTurnState(ctx); ctx.pendingContextPreamble = undefined; if (projectBrief.text !== undefined) { @@ -2226,10 +2536,6 @@ export function makeAcpAdapter( ...(input.messageId !== undefined ? { messageId: input.messageId } : {}), }); recordHistory(ctx); - const promptText = promptParts - .flatMap((part) => (part.type === "text" ? [part.text] : [])) - .join("\n"); - const newestBefore = ctx.newestPosition; yield* offerRuntimeEvent({ type: "turn.started", @@ -2240,146 +2546,291 @@ export function makeAcpAdapter( payload: { model: resolvedModel }, }); - const runPrompt = Effect.gen(function* () { - const promptMeta = descriptor.promptMeta?.(turnId); - const exit = yield* Effect.exit( - ctx.acp.prompt({ - prompt: promptParts, - ...(promptMeta ? { _meta: { ...promptMeta } } : {}), - }), - ); - // Deltas travel through the notification fiber; make sure every one - // queued before the prompt returned is out before the turn closes. - // The reader may be past them already, held at a turn the agent - // began after them (`beginAgentTurnInOrder`). - yield* Effect.raceFirst( - ctx.acp.flushEvents(prompt.closed), - Deferred.await(prompt.drained), + yield* sendTurnPrompt(ctx, run, promptParts); + + return { threadId: input.threadId, turnId, resumeCursor: ctx.session.resumeCursor }; + }); + + /** Starts reading how the turn's prompts end (`promptOutcome`); never fails. */ + const watchPromptOutcome = (ctx: AcpSessionContext) => + descriptor.promptOutcome === undefined + ? Effect.succeed(undefined) + : descriptor.promptOutcome.watch(ctx.acpSessionId).pipe( + Effect.catchCause((cause) => + Effect.logWarning("acp.prompt-outcome.watch-failed", { + provider: PROVIDER, + cause: Cause.pretty(cause), + }).pipe(Effect.as(undefined)), + ), ); - // A turn that ends mid-thought (or on one) still settles its row. - yield* closeReasoning(ctx); - // Where the prompt landed, known before the turn reads as ended, - // so a revert or a stop right after it keeps it. - if (Exit.isSuccess(exit) || !Cause.hasInterruptsOnly(exit.cause)) { - yield* recordPromptPosition(ctx, turnId, promptText, newestBefore); - } - if (Exit.isSuccess(exit)) { - const result = exit.value; - ctx.turns.push({ id: turnId, items: [{ prompt: promptParts, result }] }); - const planMarkdown = planMode ? ctx.planMarkdown?.trim() : undefined; - if (planMarkdown && result.stopReason !== "cancelled") { - yield* offerRuntimeEvent({ - type: "turn.proposed.completed", - ...(yield* makeEventStamp()), + + /** The turn's prompts' answer as the agent's own words tell it (`promptOutcome`). */ + const checkPromptOutcome = ( + run: AcpTurnRun, + answer: Parameters[0], + ): Effect.Effect => + run.checkOutcome === undefined + ? Effect.succeed(undefined) + : run.checkOutcome(answer).pipe( + Effect.catchCause((cause) => + Effect.logWarning("acp.prompt-outcome.check-failed", { provider: PROVIDER, - threadId: input.threadId, - turnId, - payload: { planMarkdown }, - }); - } - ctx.session = { - ...ctx.session, - 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; + cause: Cause.pretty(cause), + }).pipe(Effect.as(undefined)), + ), + ); + + /** The turn's open prompt (`openPrompt`), opened now unless a prompt is already open. */ + const openPromptPhase = (ctx: AcpSessionContext, run: AcpTurnRun) => + Effect.gen(function* () { + if (run.phase !== undefined) return run.phase; + const phase = { + turnId: run.turnId, + drained: yield* Deferred.make(), + closed: yield* Deferred.make(), + }; + run.phase = phase; + ctx.openPrompt = phase; + // What the agent did by itself is over: this prompt carries the turn on. + ctx.replyOpen = false; + return phase; + }); + + /** + * Sends one of a turn's prompts: its first, or a steer + * (`steerWithPrompt`). It runs in the session scope; the newest prompt's + * answer settles the turn. + */ + const sendTurnPrompt = ( + ctx: AcpSessionContext, + run: AcpTurnRun, + promptParts: ReadonlyArray, + ) => + Effect.gen(function* () { + run.prompts += 1; + const promptNumber = run.prompts; + const phase = yield* openPromptPhase(ctx, run); + ctx.promptFiber = yield* Effect.forkIn( + runTurnPrompt(ctx, run, phase, promptNumber, promptParts), + ctx.scope, + ); + }); + + const runTurnPrompt = ( + ctx: AcpSessionContext, + run: AcpTurnRun, + prompt: NonNullable, + promptNumber: number, + promptParts: ReadonlyArray, + ) => { + const turnId = run.turnId; + const threadId = ctx.threadId; + const { planMode, resolvedModel, promptText, newestBefore } = run; + const usageTotals = descriptor.turnUsageTotals ?? acpTurnUsageTotals; + /** A newer prompt took the turn over (a steer): this one's answer settles nothing. */ + const superseded = () => promptNumber !== run.prompts; + let lostSession = false; + return Effect.gen(function* () { + const promptMeta = descriptor.promptMeta?.(turnId); + const exit = yield* Effect.exit( + ctx.acp.prompt({ + prompt: [...promptParts], + ...(promptMeta ? { _meta: { ...promptMeta } } : {}), + }), + ); + if (Exit.isSuccess(exit)) { + const totals = usageTotals(exit.value.usage); + if (totals !== null) run.usage = addUsageTotals(run.usage, totals); + } + if (superseded()) return; + // Deltas travel through the notification fiber; make sure every one + // queued before the prompt returned is out before the turn closes. + // The reader may be past them already, held at a turn the agent + // began after them (`beginAgentTurnInOrder`). + yield* Effect.raceFirst(ctx.acp.flushEvents(prompt.closed), Deferred.await(prompt.drained)); + // A steer sent while the reader caught up carries the turn on. + if (superseded()) return; + // A turn that ends mid-thought (or on one) still settles its row. + yield* closeReasoning(ctx); + // Where the prompt landed, known before the turn reads as ended, + // so a revert or a stop right after it keeps it. + if (Exit.isSuccess(exit) || !Cause.hasInterruptsOnly(exit.cause)) { + yield* recordPromptPosition(ctx, turnId, promptText, newestBefore); + } + if (Exit.isSuccess(exit)) { + const result = exit.value; + ctx.turns.push({ id: turnId, items: [{ prompt: promptParts, result }] }); + const planMarkdown = planMode ? ctx.planMarkdown?.trim() : undefined; + if (planMarkdown && result.stopReason !== "cancelled") { yield* offerRuntimeEvent({ - type: "turn.completed", + type: "turn.proposed.completed", ...(yield* makeEventStamp()), provider: PROVIDER, - threadId: input.threadId, + 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: { planMarkdown }, }); - yield* settleTurnUsage(ctx, turnId, resolvedModel, result.usage); - return; } - if (Cause.hasInterruptsOnly(exit.cause)) { + ctx.session = { + ...ctx.session, + updatedAt: yield* nowIso, + ...(resolvedModel !== undefined ? { model: resolvedModel } : {}), + }; + // An agent that ends a turn normally on an upstream error says so + // in its own records (`promptOutcome`). + const hidden = + result.stopReason === "cancelled" + ? undefined + : yield* checkPromptOutcome(run, { response: result }); + // 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; + const payload: AcpTurnCompletedPayload = hidden + ? failedTurnPayload(hidden, result.stopReason ?? null) + : 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, + }; + lostSession = hidden?.sessionLost === true; + // The agent goes on with work it started (`heldTurns`): the turn + // stays open, working and stoppable, until that work is done. + if ( + payload.state === "completed" && + descriptor.heldTurns !== undefined && + (ctx.workAfterPrompt.size > 0 || ctx.subagentsOut > 0) + ) { + const held: AcpHeldTurn = { + turnId, + completion: { payload, model: resolvedModel, usage: run.usage }, + }; + ctx.held = held; + ctx.replyOpen = false; + ctx.lastAgentActivityMs = Date.now(); + yield* watchHeldTurn(ctx, held).pipe(Effect.forkIn(ctx.scope)); return; } - // The agent may never have taken the prompt: the brief goes again. - 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); + if (payload.state !== "completed") clearWorkAfterPrompt(ctx); yield* offerRuntimeEvent({ type: "turn.completed", ...(yield* makeEventStamp()), provider: PROVIDER, - threadId: input.threadId, + threadId, turnId, - payload: { - state: "failed", - stopReason: isProviderPlanGateMessage(detail) ? "plan_gated" : null, - errorMessage: ctx.lastProviderStatus - ? `${detail} Provider status: ${ctx.lastProviderStatus}` - : detail, - ...withFailureCategory(failureCategory), - }, + payload, }); - // No result, so no tokens; a running cost the agent reported still counts. - yield* settleTurnUsage(ctx, turnId, resolvedModel, undefined); - }).pipe( - Effect.ensuring( - Effect.gen(function* () { + yield* settleTurnUsage(ctx, turnId, resolvedModel, run.usage); + return; + } + if (Cause.hasInterruptsOnly(exit.cause)) { + return; + } + clearWorkAfterPrompt(ctx); + // The agent may never have taken the prompt: the brief goes again. + if (ctx.projectBriefCarrier?.turnId === turnId) requeueProjectBrief(ctx); + const failure = Cause.squash(exit.cause); + yield* notifyAuthRequired(failure); + const reported = yield* checkPromptOutcome(run, { error: failure }); + if (reported !== undefined) { + lostSession = reported.sessionLost === true; + yield* offerRuntimeEvent({ + type: "turn.completed", + ...(yield* makeEventStamp()), + provider: PROVIDER, + threadId, + turnId, + payload: failedTurnPayload(reported, null), + }); + yield* settleTurnUsage(ctx, turnId, resolvedModel, run.usage); + return; + } + 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, + threadId, + "session/prompt", + failure as EffectAcpErrors.AcpError, + ).message + : String(failure); + yield* offerRuntimeEvent({ + type: "turn.completed", + ...(yield* makeEventStamp()), + provider: PROVIDER, + threadId, + turnId, + payload: { + state: "failed", + stopReason: isProviderPlanGateMessage(detail) ? "plan_gated" : null, + errorMessage: ctx.lastProviderStatus + ? `${detail} Provider status: ${ctx.lastProviderStatus}` + : detail, + ...withFailureCategory(failureCategory), + }, + }); + // No result, so no tokens (but what a steered prompt before it + // reported); a running cost the agent reported still counts. + yield* settleTurnUsage(ctx, turnId, resolvedModel, run.usage); + }).pipe( + Effect.ensuring( + Effect.gen(function* () { + if (superseded()) return; + if (run.phase === prompt) run.phase = undefined; + if (ctx.held?.turnId !== turnId) { if (ctx.activeTurnId === turnId) { ctx.activeTurnId = undefined; ctx.session = { ...ctx.session, activeTurnId: undefined, updatedAt: yield* nowIso }; } - if (ctx.openPrompt === prompt) ctx.openPrompt = undefined; - yield* Deferred.succeed(prompt.closed, undefined); - }), - ), - ); - ctx.promptFiber = yield* Effect.forkIn(runPrompt, ctx.scope); - - return { threadId: input.threadId, turnId, resumeCursor: ctx.session.resumeCursor }; - }); + if (ctx.turnRun === run) ctx.turnRun = undefined; + } + if (ctx.openPrompt === prompt) ctx.openPrompt = undefined; + yield* Deferred.succeed(prompt.closed, undefined); + // The agent can't go on with this session: it is stopped, and + // the next message opens a new one with the thread's history. + if (lostSession) { + lostSessions.add(ctx.acpSessionId); + yield* withThreadLock( + ctx.threadId, + Effect.suspend(() => + sessions.get(ctx.threadId) === ctx ? stopSessionInternal(ctx) : Effect.void, + ), + ).pipe(Effect.forkIn(adapterScope)); + } + }), + ), + ); + }; /** * A prompt that outlived `ACP_CANCEL_DEADLINE` after `session/cancel`: @@ -2429,6 +2880,19 @@ export function makeAcpAdapter( ), ), ); + // A turn waiting on the agent's work (`heldTurns`) has no prompt to + // wait on: the cancel stopped that work, and the turn ends here. + if (descriptor.heldTurns !== undefined && turnId !== undefined) { + const closedHeld = yield* ctx.turnStartLock.withPermit( + Effect.suspend(() => { + const held = ctx.held; + return held?.turnId === turnId + ? closeHeldTurn(ctx, held, "cancelled").pipe(Effect.as(true)) + : Effect.succeed(false); + }), + ); + if (closedHeld) return; + } // The agent's own turn has no prompt to wait on; its end notice // settles it, and the same deadline applies. const agentTurn = ctx.agentTurn?.turnId === turnId ? ctx.agentTurn : undefined; @@ -2449,45 +2913,103 @@ export function makeAcpAdapter( } }); - /** A message sent mid-turn, added to the running turn (`descriptor.steer`). */ - const steerTurn: AcpAdapterShape["steerTurn"] = descriptor.steer - ? (input) => - Effect.gen(function* () { - const ctx = yield* requireSession(input.threadId); - const turnId = ctx.activeTurnId; - const sessionId = parseAcpResumeCursor(ctx.session.resumeCursor)?.sessionId; - if (turnId === undefined) { - return yield* steerRejectedError( - PROVIDER, - descriptor.presentation.displayName, - "no-active-turn", + /** + * A message sent mid-turn, added to the running turn: by the agent's own + * steer (`descriptor.steer`), or as another prompt (`steerWithPrompt`). + */ + const steerTurn: AcpAdapterShape["steerTurn"] = + descriptor.steer || descriptor.steerWithPrompt + ? (input) => + Effect.gen(function* () { + const ctx = yield* requireSession(input.threadId); + const turnId = ctx.activeTurnId; + const sessionId = parseAcpResumeCursor(ctx.session.resumeCursor)?.sessionId; + if (turnId === undefined) { + return yield* steerRejectedError( + PROVIDER, + descriptor.presentation.displayName, + "no-active-turn", + ); + } + if (turnId !== input.expectedTurnId || !sessionId) { + return yield* new ProviderAdapterRequestError({ + provider: PROVIDER, + method: "turn/steer", + detail: `Expected active turn '${input.expectedTurnId}' but ${descriptor.presentation.displayName} is running '${turnId}'.`, + }); + } + const text = input.input?.trim() ?? ""; + const content = yield* promptContent( + text.length > 0 ? text : undefined, + input.attachments, + "turn/steer", ); - } - if (turnId !== input.expectedTurnId || !sessionId) { - return yield* new ProviderAdapterRequestError({ - provider: PROVIDER, - method: "turn/steer", - detail: `Expected active turn '${input.expectedTurnId}' but ${descriptor.presentation.displayName} is running '${turnId}'.`, - }); - } - const text = input.input?.trim() ?? ""; - const content = yield* promptContent( - text.length > 0 ? text : undefined, - input.attachments, - "turn/steer", - ); - // The text of every block: a file travels as a note naming its path. - const steerText = content - .flatMap((block) => (block.type === "text" ? [block.text] : [])) - .join("\n\n"); - yield* descriptor.steer!({ acp: ctx.acp, sessionId, text: steerText, content }).pipe( - Effect.mapError((cause) => - mapAcpToAdapterError(PROVIDER, input.threadId, "turn/steer", cause), - ), - ); - return { threadId: input.threadId, turnId, resumeCursor: ctx.session.resumeCursor }; - }) - : undefined; + if (descriptor.steer === undefined) { + yield* ctx.turnStartLock.withPermit(steerWithPrompt(ctx, turnId, content)); + return { threadId: input.threadId, turnId, resumeCursor: ctx.session.resumeCursor }; + } + // The text of every block: a file travels as a note naming its path. + const steerText = content + .flatMap((block) => (block.type === "text" ? [block.text] : [])) + .join("\n\n"); + yield* descriptor + .steer({ acp: ctx.acp, sessionId, text: steerText, content }) + .pipe( + Effect.mapError((cause) => + mapAcpToAdapterError(PROVIDER, input.threadId, "turn/steer", cause), + ), + ); + return { threadId: input.threadId, turnId, resumeCursor: ctx.session.resumeCursor }; + }) + : undefined; + + /** + * Steers the running turn with another prompt (`steerWithPrompt`): the + * agent answers the prompt it was on and carries the turn on under this + * one. A turn waiting on the agent's work, or one the agent started by + * itself, takes it the same way: the prompt's answer settles it. + */ + const steerWithPrompt = ( + ctx: AcpSessionContext, + turnId: TurnId, + content: ReadonlyArray, + ) => + Effect.gen(function* () { + // The turn ended while the lock was busy: the message starts its own. + if (ctx.stopped || ctx.activeTurnId !== turnId) { + return yield* steerRejectedError( + PROVIDER, + descriptor.presentation.displayName, + "no-active-turn", + ); + } + if (ctx.held?.turnId === turnId) ctx.held = undefined; + let run = ctx.turnRun; + if (run?.turnId !== turnId) { + // The agent's own turn: the prompt makes it an ordinary one. + const agentTurn = ctx.agentTurn; + if (agentTurn?.turnId === turnId) { + ctx.agentTurn = undefined; + if (ctx.agentTurnAhead?.turnId === turnId) ctx.agentTurnAhead = undefined; + yield* Deferred.succeed(agentTurn.ended, undefined); + } + run = { + turnId, + planMode: undefined, + resolvedModel: resolveModelId(ctx.session.model), + promptText: content + .flatMap((part) => (part.type === "text" ? [part.text] : [])) + .join("\n"), + newestBefore: ctx.newestPosition, + phase: undefined, + prompts: 0, + usage: null, + checkOutcome: yield* watchPromptOutcome(ctx), + }; + ctx.turnRun = run; + } + yield* sendTurnPrompt(ctx, run, content); + }); const respondToRequest: AcpAdapterShape["respondToRequest"] = (threadId, requestId, decision) => Effect.gen(function* () { @@ -2632,7 +3154,9 @@ export function makeAcpAdapter( capabilities: { sessionModelSwitch: "in-session", conversationRollback: "none", - ...(descriptor.steer ? { activeTurnSteering: "supported" as const } : {}), + ...(descriptor.steer || descriptor.steerWithPrompt + ? { activeTurnSteering: "supported" as const } + : {}), ...(descriptor.conversationHistory ? { nativeThreadFork: "supported" as const } : {}), }, startSession, diff --git a/apps/server/src/provider/acp/AcpProviderDescriptor.ts b/apps/server/src/provider/acp/AcpProviderDescriptor.ts index bfd7f7dc0..1ea6d1127 100644 --- a/apps/server/src/provider/acp/AcpProviderDescriptor.ts +++ b/apps/server/src/provider/acp/AcpProviderDescriptor.ts @@ -18,14 +18,17 @@ import type { ProviderRuntimeEvent, ProviderUserInputAnswers, RuntimeMode, + RuntimeUsageLimit, ServerProvider, ServerProviderDetection, ServerProviderModel, 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"; @@ -141,6 +144,64 @@ 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. `watch` runs as a turn's first prompt goes + * out (it may note where the agent's own records stand) and returns the check + * run when the turn's last prompt answers or fails. + */ +export interface AcpPromptOutcome { + readonly watch: (sessionId: string) => Effect.Effect< + ( + 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 + * (`AcpHeldTurns`): a command it awaits, a scheduled wake-up, or a subagent + * it launched. `undefined` for one that ends with the prompt. + */ +export type AcpWorkAfterPrompt = "command" | "wake" | "subagent"; + +/** + * An agent that answers its prompt while work it started goes on, and + * replies by itself when that work ends (Antigravity 1.5.10+). 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. + */ +export interface AcpHeldTurns { + readonly workAfterPrompt: (toolCall: AcpToolCallState) => AcpWorkAfterPrompt | undefined; + /** + * How long the turn waits without a word from the agent while only + * commands and subagents hold it; past it, the turn ends. A scheduled + * wake-up holds it with no limit (a timer is silent until it fires). + */ + readonly silentLimit: Duration.Duration; +} + /** Runtime hooks handed to a vendor's extension registration. */ export interface AcpExtensionContext { readonly threadId: ThreadId; @@ -370,16 +431,34 @@ export interface AcpProviderDescriptor { readonly text: string; readonly content: ReadonlyArray; }) => Effect.Effect; + /** + * A message sent mid-turn goes as another `session/prompt` (Antigravity + * 1.5): the agent answers the running prompt and carries the turn on under + * the new one, its commands and subagents left running. The turn ends with + * the last prompt's answer. Ignored when `steer` is set. + */ + readonly steerWithPrompt?: boolean; + /** Keeps a turn open while work the agent goes on with after its prompt runs. */ + readonly heldTurns?: AcpHeldTurns; + /** How a prompt really ended, where the agent's answer can hide a failure. */ + readonly promptOutcome?: AcpPromptOutcome; /** * 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. diff --git a/apps/server/src/provider/acp/AcpSessionRuntime.ts b/apps/server/src/provider/acp/AcpSessionRuntime.ts index 75c43243a..0f15fe67d 100644 --- a/apps/server/src/provider/acp/AcpSessionRuntime.ts +++ b/apps/server/src/provider/acp/AcpSessionRuntime.ts @@ -495,8 +495,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); @@ -532,7 +533,7 @@ const makeAcpSessionRuntime = ( modeStateRef, toolCallsRef, assistantSegmentRef, - promptInFlightRef, + promptsInFlightRef, liveOutsidePromptRef, itemIdScope, params: notification, @@ -975,15 +976,20 @@ 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; @@ -1081,7 +1087,7 @@ const handleSessionUpdate = ({ modeStateRef, toolCallsRef, assistantSegmentRef, - promptInFlightRef, + promptsInFlightRef, liveOutsidePromptRef, itemIdScope, params, @@ -1091,7 +1097,7 @@ const handleSessionUpdate = ({ 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; @@ -1109,7 +1115,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 diff --git a/apps/server/src/provider/acp/AntigravityAcpSupport.ts b/apps/server/src/provider/acp/AntigravityAcpSupport.ts index 9cce9a2ba..39a8924b6 100644 --- a/apps/server/src/provider/acp/AntigravityAcpSupport.ts +++ b/apps/server/src/provider/acp/AntigravityAcpSupport.ts @@ -59,6 +59,7 @@ import { type AntigravityPlatformRelease, } from "../antigravity/AntigravityRelease.ts"; import type { AntigravityReleaseSource } from "../antigravity/AntigravityReleaseSource.ts"; +import { antigravityTurnBehavior } from "../antigravity/AntigravityTurns.ts"; import { acquireAntigravityTempDir, recordAntigravityAgent, @@ -789,6 +790,8 @@ export function makeAntigravityDescriptor( classifyPermissionRequest: antigravityQuestion, permissionOptionWarning: antigravityOptionWarning, cancellationNotice: "The request was cancelled by the client.", + // Work that outlives a prompt, steering, hidden failures, turn tokens. + ...antigravityTurnBehavior(paths.profileDir), planMode: { promptPrefix: "/plan ", isPlanFile: (toolCall) => { diff --git a/apps/server/src/provider/antigravity/AntigravitySessionLog.ts b/apps/server/src/provider/antigravity/AntigravitySessionLog.ts new file mode 100644 index 000000000..a6ec4b36e --- /dev/null +++ b/apps/server/src/provider/antigravity/AntigravitySessionLog.ts @@ -0,0 +1,126 @@ +// @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. It is the one place 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. + * + * 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 { 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; +} + +/** + * The session's log file when it is a plain file in the profile (no link at + * any step of the path), or `undefined` when there is none yet. + */ +async function sessionLogFile(profileDir: string, sessionId: string): Promise { + const root = await NodeFSP.realpath(profileDir).catch(() => undefined); + if (root === undefined) return undefined; + const segments = [ANTIGRAVITY_APP_DATA_DIR, "conversations", `${sessionId}.db`]; + let current = root; + for (const [index, segment] of segments.entries()) { + current = NodePath.join(current, segment); + const info = await NodeFSP.lstat(current).catch(() => undefined); + const last = index === segments.length - 1; + if (info === undefined || info.isSymbolicLink()) return undefined; + if (last ? !info.isFile() : !info.isDirectory()) return undefined; + } + return current; +} + +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 file = await sessionLogFile(profileDir, sessionId); + if (file === undefined) return -1; + const index = readLog(file, (database) => { + const value = database.prepare("SELECT max(idx) AS idx FROM steps").get()?.idx; + return typeof value === "number" ? value : -1; + }); + return index ?? -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 file = await sessionLogFile(profileDir, sessionId); + if (file === undefined) return undefined; + return readLog(file, (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 }; + }); + }).pipe(Effect.orElseSucceed(() => undefined)); 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..2635e974c --- /dev/null +++ b/apps/server/src/provider/antigravity/AntigravityTurns.test.ts @@ -0,0 +1,414 @@ +// @effect-diagnostics nodeBuiltinImport:off +import * as os from "node:os"; +import * as path from "node:path"; +import { chmod, 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, + ProviderDriverKind, + type ProviderRuntimeEvent, + ThreadId, + type TurnId, +} from "@threadlines/contracts"; +import * as Effect from "effect/Effect"; +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 { ServerConfig } from "../../config.ts"; +import type { UsageLedgerEntry } from "../../usage/usageLedger.ts"; +import { makeAcpAdapter } from "../acp/AcpAdapter.ts"; +import type { AcpToolCallState } from "../acp/AcpRuntimeModel.ts"; +import { makeAntigravityDescriptor } from "../acp/AntigravityAcpSupport.ts"; +import { + antigravityFailure, + antigravityTurnUsageTotals, + antigravityWorkAfterPrompt, +} from "./AntigravityTurns.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); +} + +/** Starts an Antigravity session on the stand-in, collecting every runtime event. */ +const startAgy = (scenario: string) => + Effect.gen(function* () { + const mock = yield* Effect.promise(() => makeAgyMock(scenario)); + const descriptor = 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 usage: Array = []; + const adapter = yield* makeAcpAdapter( + descriptor, + decodeSettings({ enabled: true, binaryPath: mock.wrapper }), + { recordTurnUsage: (entry) => Effect.sync(() => void usage.push(entry)) }, + ); + const events: Array = []; + yield* adapter.streamEvents.pipe( + Stream.runForEach((event) => Effect.sync(() => void events.push(event))), + Effect.forkScoped, + ); + const threadId = ThreadId.make(`agy-${scenario}`); + const session = yield* adapter.startSession({ + threadId, + provider: ProviderDriverKind.make("antigravity"), + cwd: process.cwd(), + runtimeMode: "full-access", + }); + const waitFor = (predicate: (events: ReadonlyArray) => boolean) => + Effect.gen(function* () { + for (let attempt = 0; attempt < 1_000; 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, + threadId, + session, + waitFor, + frames: () => Effect.promise(() => readFrames(mock.log)), + }; + }); + +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(""); + +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"); + + 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" }, + }), + ]); + 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", () => + 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("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"); + 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); + expect(agy.usage.map((entry) => entry.totals.uncachedInputTokens)).toEqual([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( + "starts a new session with the thread's history when Google can't continue the old one", + () => + 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")); + + 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)), + ); +}); + +describe("Antigravity turn reading", () => { + const tool = (fields: Partial): AcpToolCallState => ({ + toolCallId: "call", + data: {}, + ...fields, + }); + + it("tells the work that outlives a prompt from what ends with it", () => { + expect( + antigravityWorkAfterPrompt( + tool({ kind: "execute", data: { rawInput: { CommandLine: "npm test" } } }), + ), + ).toBe("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" }))).toBe( + "wake", + ); + expect( + antigravityWorkAfterPrompt( + tool({ + kind: "other", + title: "Running invoke_subagent", + data: { rawInput: { Role: "Artist", Prompt: "Paint" } }, + }), + ), + ).toBe("subagent"); + 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("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, + }); + }); +}); diff --git a/apps/server/src/provider/antigravity/AntigravityTurns.ts b/apps/server/src/provider/antigravity/AntigravityTurns.ts new file mode 100644 index 000000000..f6efead86 --- /dev/null +++ b/apps/server/src/provider/antigravity/AntigravityTurns.ts @@ -0,0 +1,294 @@ +/** + * 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 { 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, + AcpProviderDescriptor, + AcpProviderSettings, + AcpWorkAfterPrompt, +} from "../acp/AcpProviderDescriptor.ts"; +import type { AcpToolCallState } from "../acp/AcpRuntimeModel.ts"; +import { antigravityLogPosition, antigravityTurnSteps } from "./AntigravitySessionLog.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 subagent launch: the call returns at once and the subagent works on. */ +const SUBAGENT_TITLES = new Set([ + "Running start_subagent", + "Run start_subagent?", + "Running invoke_subagent", + "Run invoke_subagent?", +]); +/** + * 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); + +const isRecord = (value: unknown): value is Record => + typeof value === "object" && value !== null && !Array.isArray(value); + +/** A launch's input: one subagent (`Role`, `Prompt`), or a batch (`Subagents`). */ +function isSubagentLaunch(input: unknown): boolean { + if (!isRecord(input)) return false; + if (typeof input.Role === "string" && typeof input.Prompt === "string") return true; + return Array.isArray(input.Subagents) && input.Subagents.length > 0; +} + +/** + * 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 "wake"; + const input = toolCall.data.rawInput; + if (toolCall.kind === "execute") { + return isRecord(input) && input.IsDaemon === true ? undefined : "command"; + } + if ( + (toolCall.kind === undefined || toolCall.kind === "other") && + toolCall.title !== undefined && + SUBAGENT_TITLES.has(toolCall.title) && + isSubagentLaunch(input) + ) { + return "subagent"; + } + 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.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). + */ +export function antigravityTurnBehavior( + profileDir: string, +): Pick< + AcpProviderDescriptor, + | "agentTurns" + | "heldTurns" + | "steerWithPrompt" + | "promptOutcome" + | "usageLedger" + | "turnUsageTotals" +> { + return { + // What the agent does after a prompt ended is live (1.5.10), and opens a + // turn of its own when no turn is held open for it. + agentTurns: true, + heldTurns: { + workAfterPrompt: antigravityWorkAfterPrompt, + silentLimit: ANTIGRAVITY_SILENT_WORK_LIMIT, + }, + steerWithPrompt: true, + promptOutcome: { + watch: (sessionId) => + Effect.gen(function* () { + const before = yield* antigravityLogPosition(profileDir, sessionId); + return (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 ? 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 antigravityFailure({ + errorText: steps?.errorText, + stopReason, + ...(steps !== undefined ? { reachedModel: steps.reachedModel } : {}), + nowMs, + }); + }); + }), + }, + usageLedger: { provider: "antigravity" }, + turnUsageTotals: antigravityTurnUsageTotals, + }; +} diff --git a/docs/providers/antigravity.md b/docs/providers/antigravity.md index 9f62779be..684e43f15 100644 --- a/docs/providers/antigravity.md +++ b/docs/providers/antigravity.md @@ -57,6 +57,44 @@ has them. The reasoning level is its own choice next to the model. Plan mode sends the task as `/plan`, and the plan shows on the plan card for review. +## 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 reply the agent starts after the turn ended opens a turn of its own. + +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. A timer +holds the turn until it fires. Subagents are only known to finish by the report the agent gives when +one ends, so the first report frees the turn; a later subagent's report opens a turn of its own. + +A message sent while Antigravity works steers the turn instead of waiting: Threadlines sends it as +another prompt, which the CLI takes into the running turn (1.5.0+), leaving its commands and +subagents running. + +### 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 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. + +### 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 Open `Settings -> Providers`, open the Antigravity row, and pick a method under `Sign-in method` on @@ -96,8 +134,9 @@ Running chats stop when you switch, as with any change to a provider's settings. ### 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 From 806876288bceabd15e303f539a3066e684e28a14 Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Mon, 23 Nov 2026 03:06:22 -0500 Subject: [PATCH 17/59] fix(server): a long command line keeps its start in the timeline The activity projection cut every long string to its last 4,000 characters, so a long command lost the program and target it starts with. Command-line fields now keep their start, and a cut never splits a character in half. --- .../Layers/ProviderActivityProjection.test.ts | 22 +++++++++++++++ .../Layers/ProviderActivityProjection.ts | 27 ++++++++++++++++--- 2 files changed, 45 insertions(+), 4 deletions(-) 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") { From 157d3624770efac9e58a24eef49997e00f8b2486 Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Mon, 23 Nov 2026 03:08:25 -0500 Subject: [PATCH 18/59] feat(antigravity): subagents show with their steps and hold the turn until each reports Each invoke_subagent launch now shows as a subagent with its role, prompt, report and recent steps, in the same view other agents' subagents use. ACP says only that a launch happened, so the child, its state and its transcript are read from the CLI's own records under the profile's brain folder (AntigravityChildRecords: read-only, no links, bounded). When the records don't name a child, the view says so and the turn falls back to the old rule. The turn's hold on subagents now lasts until every child reported or was killed, checked at the prompt's end and at the end of each reply the agent starts by itself, keeping the 30-minute limit and Stop. A child killed with manage_subagents no longer keeps the turn running. The auto-approved title agy 1.5 uses ("Run invoke_subagent") now counts as a launch. Tool rows: every tool update is bounded to 8,000 characters per field before the core reads it (a command line keeps its start, output its end, no split characters), inline images are left out, and an MCP call through call_mcp_tool shows as that MCP tool instead of a command. The generic ACP core gains descriptor hooks for this (normalizeSessionUpdate, normalizeToolCall, subagents, and a row type on tool calls); agents that set none behave as before. --- apps/server/scripts/antigravity-mock-agent.ts | 182 +++++++- apps/server/src/provider/acp/AcpAdapter.ts | 252 ++++++++++- .../src/provider/acp/AcpCoreRuntimeEvents.ts | 2 +- .../src/provider/acp/AcpProviderDescriptor.ts | 72 +++ .../src/provider/acp/AcpProviderRuntime.ts | 6 + .../src/provider/acp/AcpRuntimeModel.ts | 6 + .../src/provider/acp/AcpSessionRuntime.ts | 15 +- .../src/provider/acp/AcpSubagentEvents.ts | 121 +++++ .../src/provider/acp/AntigravityAcpSupport.ts | 7 + .../AntigravityChildRecords.test.ts | 121 +++++ .../antigravity/AntigravityChildRecords.ts | 420 ++++++++++++++++++ .../antigravity/AntigravitySessionLog.ts | 43 +- .../antigravity/AntigravitySubagents.ts | 82 ++++ .../antigravity/AntigravityToolCalls.test.ts | 14 + .../antigravity/AntigravityToolCalls.ts | 216 +++++++++ .../antigravity/AntigravityTurns.test.ts | 156 +++++++ .../provider/antigravity/AntigravityTurns.ts | 30 +- 17 files changed, 1690 insertions(+), 55 deletions(-) create mode 100644 apps/server/src/provider/acp/AcpSubagentEvents.ts create mode 100644 apps/server/src/provider/antigravity/AntigravityChildRecords.test.ts create mode 100644 apps/server/src/provider/antigravity/AntigravityChildRecords.ts create mode 100644 apps/server/src/provider/antigravity/AntigravitySubagents.ts create mode 100644 apps/server/src/provider/antigravity/AntigravityToolCalls.test.ts create mode 100644 apps/server/src/provider/antigravity/AntigravityToolCalls.ts diff --git a/apps/server/scripts/antigravity-mock-agent.ts b/apps/server/scripts/antigravity-mock-agent.ts index 70997fc7f..7dfe47e07 100644 --- a/apps/server/scripts/antigravity-mock-agent.ts +++ b/apps/server/scripts/antigravity-mock-agent.ts @@ -13,7 +13,13 @@ * 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. * - `subagent`: launches a subagent, ends its prompt, and replies with the - * subagent's report later. + * subagent's report later. It writes no subagent records. + * - `subagents`: launches two subagents with their records (as 1.5.12+ + * keeps them under `brain/`); the first reports, the agent replies, and + * the second reports a while later. + * - `subagent-killed`: launches a subagent and kills it within the prompt. + * - `tools`: an MCP call through `call_mcp_tool`, a long command line, and + * a screenshot in a tool's content. * - `wake`: ends its prompt with nothing running, then replies by itself. * - `steer`: holds its first prompt until a second arrives, answers the first * `end_turn`, and replies to the second. @@ -21,7 +27,7 @@ * - `quota`: fails the prompt with Google's quota error (1.5.9). * - `lost-signature`: fails the prompt with the refused-thinking error. */ -import { appendFileSync, mkdirSync } from "node:fs"; +import { appendFileSync, mkdirSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { DatabaseSync } from "node:sqlite"; @@ -62,6 +68,74 @@ function appendLogSteps(sessionId: string, steps: 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"); @@ -202,6 +276,110 @@ const program = Effect.gen(function* () { }).pipe(Effect.forkDetach); return { stopReason: "end_turn" as const }; } + if (scenario === "subagents") { + 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", + 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."); + 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 === "subagent-killed") { + recordChild({ + parent: sessionId, + child: "child-stray", + callId: "call_stray", + role: "Explorer", + prompt: "Look around", + state: "SUBAGENT_STATE_ALIVE", + }); + yield* update(sessionId, { + sessionUpdate: "tool_call", + toolCallId: "call_stray", + kind: "other", + title: "Run invoke_subagent", + status: "completed", + rawInput: { Role: "Explorer", Prompt: "Look around" }, + }); + // `manage_subagents` kill only rewrites the record's state. + recordChild({ + parent: sessionId, + child: "child-stray", + callId: "call_stray", + role: "Explorer", + prompt: "Look around", + state: "SUBAGENT_STATE_KILLED", + }); + yield* say(sessionId, "Stopped the explorer."); + yield* modelCallEnds(sessionId); + 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); diff --git a/apps/server/src/provider/acp/AcpAdapter.ts b/apps/server/src/provider/acp/AcpAdapter.ts index c00a2435a..4a110c76e 100644 --- a/apps/server/src/provider/acp/AcpAdapter.ts +++ b/apps/server/src/provider/acp/AcpAdapter.ts @@ -110,20 +110,31 @@ import { import { makeAcpNativeLoggers } from "./AcpNativeLogging.ts"; import type { AcpExtensionContext, + AcpExtensionRuntimeEvent, AcpPromptFailure, AcpPromptOutcome, AcpPromptPlanMode, AcpProviderDescriptor, AcpProviderSettings, + AcpSubagentLaunch, + AcpSubagents, AcpTurnOutcome, AcpWorkAfterPrompt, } from "./AcpProviderDescriptor.ts"; +import { + type AcpSubagentStatus, + acpSubagentSettledEvents, + acpSubagentSnapshotEvent, + acpSubagentStartedEvents, + describeAcpSubagentLaunches, +} from "./AcpSubagentEvents.ts"; import { applyAcpModelSelection, defaultResolveAcpModelId, makeAcpProviderRuntime, } from "./AcpProviderRuntime.ts"; import { + type AcpPermissionRequest, type AcpPlanUpdate, type AcpSessionMode, type AcpSessionModeState, @@ -310,8 +321,21 @@ interface AcpSessionContext { readonly workAfterPrompt: Map; /** Subagent launches counted so far, by tool call id, so a repeated update counts once. */ readonly subagentLaunches: Set; - /** Subagents launched and not heard back from (a reply the agent started by itself ended since). */ - subagentsOut: number; + /** + * Subagents launched and not heard back from, by launching call id. Without + * the agent's records (`subagents`), a reply it started by itself frees + * them all; with them, each stays until its child reported or was killed. + */ + readonly subagentsOut: Set; + /** Subagents shown for this session's launches (`subagents`), by launching call id. */ + readonly subagentRoster: Map< + string, + { + readonly turnId: TurnId | undefined; + readonly launch: AcpSubagentLaunch; + status: AcpSubagentStatus; + } + >; /** A reply the agent started by itself has output and no closing `usage_update` yet. */ replyOpen: boolean; /** When the agent last sent anything, for a held turn's quiet limits (ms since epoch). */ @@ -1125,6 +1149,24 @@ export function makeAcpAdapter( } }); + /** + * A permission request as the descriptor describes its tool call + * (`normalizeToolCall`): an MCP call the agent runs as a command asks as + * a tool call, not a command. + */ + const normalizedPermissionRequest = (request: AcpPermissionRequest): AcpPermissionRequest => { + const normalize = descriptor.normalizeToolCall; + if (normalize === undefined || request.toolCall === undefined) return request; + const toolCall = normalize(request.toolCall); + // A call the descriptor retyped is named by its own detail, not the command's. + const detail = toolCall.itemType !== undefined ? toolCall.detail : request.detail; + return { + kind: toolCall.kind ?? request.kind, + ...(detail !== undefined ? { detail } : {}), + toolCall, + }; + }; + /** * The agent sent something (`heldTurns`). Outside a prompt that is a * reply it started by itself, open until its closing `usage_update`. @@ -1138,16 +1180,136 @@ export function makeAcpAdapter( /** * The `usage_update` that ends each model call (`heldTurns`): a reply the * agent started by itself is over, and with it the report it woke to - * give. Subagents are known to end only by such a report, so one ending - * frees them all: a later subagent's report opens a turn of its own. + * give. Without the agent's records of its subagents, they are known to + * end only by such a report, so one ending frees them all and a later + * subagent's report opens a turn of its own. With them (`subagents`), + * the records say which children are done. */ - const noteReplyEnd = (ctx: AcpSessionContext) => { - if (descriptor.heldTurns === undefined) return; - ctx.lastAgentActivityMs = Date.now(); - if (!ctx.replyOpen) return; - ctx.replyOpen = false; - ctx.subagentsOut = 0; - }; + const noteReplyEnd = (ctx: AcpSessionContext) => + Effect.gen(function* () { + if (descriptor.heldTurns === undefined) return; + ctx.lastAgentActivityMs = Date.now(); + if (!ctx.replyOpen) return; + ctx.replyOpen = false; + if (descriptor.subagents === undefined) { + ctx.subagentsOut.clear(); + return; + } + // The roster changes as the records are read; the reader moves on. + yield* checkSubagents(ctx, "reply").pipe(Effect.forkIn(ctx.scope)); + }); + + /** + * Reads which launched subagents are done (`subagents`): one that + * reported or was killed stops holding its turn and shows as ended. At a + * reply's end a launch the records don't tie to a child is freed as + * before; at a prompt's end it keeps holding, since its report may be + * what wakes the agent next. + */ + const checkSubagents = (ctx: AcpSessionContext, moment: "prompt" | "reply") => + Effect.gen(function* () { + const subagents = descriptor.subagents; + if (subagents === undefined) return; + const running = [...ctx.subagentRoster].flatMap(([id, entry]) => + entry.status === "running" ? [id] : [], + ); + const ids = [...new Set([...running, ...ctx.subagentsOut])]; + if (ids.length === 0) return; + const states = yield* subagents.states({ + sessionId: ctx.acpSessionId, + launchCallIds: ids, + }); + for (const id of ids) { + const state = states?.get(id); + if (state?.state === "working") continue; + if (state === undefined) { + if (moment === "prompt") continue; + ctx.subagentsOut.delete(id); + yield* settleSubagent(ctx, id, "completed", undefined); + continue; + } + ctx.subagentsOut.delete(id); + yield* settleSubagent( + ctx, + id, + state.state === "killed" ? "interrupted" : "completed", + state.report, + ); + } + }); + + /** Emits a subagent's events on the turn that launched it. */ + const emitSubagentEvents = ( + ctx: AcpSessionContext, + turnId: TurnId | undefined, + events: ReadonlyArray, + ) => + Effect.forEach( + events, + (event) => + Effect.gen(function* () { + yield* offerRuntimeEvent({ + ...event, + ...(yield* makeEventStamp()), + provider: PROVIDER, + threadId: ctx.threadId, + ...(turnId ? { turnId } : {}), + } as ProviderRuntimeEvent); + }), + { discard: true }, + ); + + /** The snapshot of the subagents still running (`subagents`). */ + const emitSubagentSnapshot = (ctx: AcpSessionContext) => + emitSubagentEvents(ctx, undefined, [ + acpSubagentSnapshotEvent( + [...ctx.subagentRoster].flatMap(([launchCallId, entry]) => + entry.status === "running" ? [{ launchCallId, launch: entry.launch }] : [], + ), + ), + ]); + + /** Shows a launch as a running subagent, once (`subagents`). */ + const noteSubagentLaunch = ( + ctx: AcpSessionContext, + toolCall: AcpToolCallState, + turnId: TurnId | undefined, + ) => + Effect.gen(function* () { + const subagents = descriptor.subagents; + if (subagents === undefined || toolCall.status !== "completed") return; + const id = toolCall.toolCallId; + if (ctx.subagentRoster.has(id)) return; + const launches = subagents.launches(toolCall); + if (launches === undefined) return; + const launch = describeAcpSubagentLaunches(launches); + ctx.subagentRoster.set(id, { turnId, launch, status: "running" }); + yield* emitSubagentEvents(ctx, turnId, acpSubagentStartedEvents(id, launch)); + yield* emitSubagentSnapshot(ctx); + }); + + /** A shown subagent ended, once. */ + const settleSubagent = ( + ctx: AcpSessionContext, + id: string, + status: Exclude, + report: string | undefined, + ) => + Effect.gen(function* () { + const entry = ctx.subagentRoster.get(id); + if (entry === undefined || entry.status !== "running") return; + entry.status = status; + yield* emitSubagentEvents(ctx, entry.turnId, acpSubagentSettledEvents(id, status, report)); + yield* emitSubagentSnapshot(ctx); + }); + + /** Stop ends the session's subagents with its turn (Antigravity 1.5.10 cancels them). */ + const interruptSubagents = (ctx: AcpSessionContext) => + Effect.forEach( + [...ctx.subagentRoster].flatMap(([id, entry]) => (entry.status === "running" ? [id] : [])), + (id) => settleSubagent(ctx, id, "interrupted", undefined), + { discard: true }, + ); /** Keeps count of the work a tool call goes on with after its prompt (`heldTurns`). */ const trackWorkAfterPrompt = (ctx: AcpSessionContext, toolCall: AcpToolCallState) => { @@ -1161,7 +1323,7 @@ export function makeAcpAdapter( if (kind === "subagent") { if (toolCall.status === "completed" && !ctx.subagentLaunches.has(id)) { ctx.subagentLaunches.add(id); - ctx.subagentsOut += 1; + ctx.subagentsOut.add(id); } return; } @@ -1175,7 +1337,7 @@ export function makeAcpAdapter( /** Forgets the agent's outstanding work: it was stopped, or failed with its turn. */ const clearWorkAfterPrompt = (ctx: AcpSessionContext) => { ctx.workAfterPrompt.clear(); - ctx.subagentsOut = 0; + ctx.subagentsOut.clear(); ctx.replyOpen = false; }; @@ -1250,7 +1412,7 @@ export function makeAcpAdapter( ctx.replyOpen = false; } const work = [...ctx.workAfterPrompt.values()]; - const waiting = work.length > 0 || ctx.subagentsOut > 0 || ctx.replyOpen; + const waiting = work.length > 0 || ctx.subagentsOut.size > 0 || ctx.replyOpen; const settled = !waiting && quietMs >= Duration.toMillis(ACP_HELD_TURN_SETTLE); const silent = waiting && !ctx.replyOpen && !work.includes("wake") && quietMs >= silentLimitMs; @@ -1308,6 +1470,8 @@ export function makeAcpAdapter( ctx.stopped = true; yield* settlePendingApprovalsAsCancelled(ctx.pendingApprovals); yield* settlePendingUserInputsAsEmptyAnswers(ctx.pendingUserInputs); + // The agent's process takes its subagents with it. + yield* interruptSubagents(ctx); if (ctx.promptFiber) { yield* Fiber.interrupt(ctx.promptFiber); } @@ -1898,7 +2062,9 @@ export function makeAcpAdapter( }); return selected(question.optionIdForAnswers(answers)); } - const permissionRequest = parsePermissionRequest(params); + const permissionRequest = normalizedPermissionRequest( + parsePermissionRequest(params), + ); const planFileWrite = permissionRequest.toolCall !== undefined && descriptor.planMode?.isPlanFile(permissionRequest.toolCall) === true; @@ -2114,7 +2280,8 @@ export function makeAcpAdapter( held: undefined, workAfterPrompt: new Map(), subagentLaunches: new Set(), - subagentsOut: 0, + subagentsOut: new Set(), + subagentRoster: new Map(), replyOpen: false, lastAgentActivityMs: 0, stopped: false, @@ -2153,7 +2320,7 @@ export function makeAcpAdapter( } return; case "ContextUsage": { - noteReplyEnd(ctx); + yield* noteReplyEnd(ctx); // 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. @@ -2238,6 +2405,7 @@ export function makeAcpAdapter( const turnId = yield* turnForOutput(ctx, toolCallId); if (descriptor.heldTurns !== undefined) trackWorkAfterPrompt(ctx, event.toolCall); + yield* noteSubagentLaunch(ctx, event.toolCall, turnId); if ( event.toolCall.status === "completed" || event.toolCall.status === "failed" @@ -2717,12 +2885,16 @@ export function makeAcpAdapter( stopReason: result.stopReason ?? null, }; lostSession = hidden?.sessionLost === true; + // A child killed or done within the prompt holds nothing (`subagents`). + if (payload.state === "completed" && ctx.subagentsOut.size > 0) { + yield* checkSubagents(ctx, "prompt"); + } // The agent goes on with work it started (`heldTurns`): the turn // stays open, working and stoppable, until that work is done. if ( payload.state === "completed" && descriptor.heldTurns !== undefined && - (ctx.workAfterPrompt.size > 0 || ctx.subagentsOut > 0) + (ctx.workAfterPrompt.size > 0 || ctx.subagentsOut.size > 0) ) { const held: AcpHeldTurn = { turnId, @@ -2880,6 +3052,7 @@ export function makeAcpAdapter( ), ), ); + yield* interruptSubagents(ctx); // A turn waiting on the agent's work (`heldTurns`) has no prompt to // wait on: the cancel stopped that work, and the turn ends here. if (descriptor.heldTurns !== undefined && turnId !== undefined) { @@ -3142,6 +3315,46 @@ export function makeAcpAdapter( Effect.forEach(Array.from(sessions.values()), stopSessionInternal, { 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.tap(() => PubSub.shutdown(runtimeEventPubSub)), @@ -3174,6 +3387,9 @@ export function makeAcpAdapter( 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..a7f8da337 100644 --- a/apps/server/src/provider/acp/AcpCoreRuntimeEvents.ts +++ b/apps/server/src/provider/acp/AcpCoreRuntimeEvents.ts @@ -204,7 +204,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/AcpProviderDescriptor.ts b/apps/server/src/provider/acp/AcpProviderDescriptor.ts index 4cd40b756..eb920b608 100644 --- a/apps/server/src/provider/acp/AcpProviderDescriptor.ts +++ b/apps/server/src/provider/acp/AcpProviderDescriptor.ts @@ -16,6 +16,7 @@ import type { ProviderInteractionMode, ProviderOptionSelection, ProviderRuntimeEvent, + ProviderSubagentTranscriptEntry, ProviderUserInputAnswers, RuntimeMode, RuntimeUsageLimit, @@ -203,6 +204,60 @@ export interface AcpHeldTurns { readonly silentLimit: Duration.Duration; } +/** 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, and a turn held for + * subagents (`heldTurns`) lasts until every child has reported or been + * killed, as far as the records tell. + */ +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; `undefined` when they can't be read. + */ + readonly states: (input: { + readonly sessionId: string; + readonly launchCallIds: ReadonlyArray; + }) => Effect.Effect | 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; @@ -441,6 +496,8 @@ export interface AcpProviderDescriptor { readonly steerWithPrompt?: boolean; /** Keeps a turn open while work the agent goes on with after its prompt runs. */ readonly heldTurns?: AcpHeldTurns; + /** Subagents launched by a tool call, read from the agent's own records. */ + readonly subagents?: AcpSubagents; /** How a prompt really ended, where the agent's answer can hide a failure. */ readonly promptOutcome?: AcpPromptOutcome; /** @@ -547,6 +604,21 @@ 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`). + */ + readonly normalizeToolCall?: (toolCall: AcpToolCallState) => AcpToolCallState; /** Text the agent appends when a prompt is cancelled; dropped from the reply. */ readonly cancellationNotice?: string; readonly planMode?: AcpPromptPlanMode; diff --git a/apps/server/src/provider/acp/AcpProviderRuntime.ts b/apps/server/src/provider/acp/AcpProviderRuntime.ts index 2d2f24c50..29df26a19 100644 --- a/apps/server/src/provider/acp/AcpProviderRuntime.ts +++ b/apps/server/src/provider/acp/AcpProviderRuntime.ts @@ -125,6 +125,12 @@ 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.verifyAgent ? { verifyInitialize: (response: EffectAcpSchema.InitializeResponse) => diff --git a/apps/server/src/provider/acp/AcpRuntimeModel.ts b/apps/server/src/provider/acp/AcpRuntimeModel.ts index f616858ad..9490a31ae 100644 --- a/apps/server/src/provider/acp/AcpRuntimeModel.ts +++ b/apps/server/src/provider/acp/AcpRuntimeModel.ts @@ -29,6 +29,12 @@ 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; } diff --git a/apps/server/src/provider/acp/AcpSessionRuntime.ts b/apps/server/src/provider/acp/AcpSessionRuntime.ts index 0f15fe67d..72d68f075 100644 --- a/apps/server/src/provider/acp/AcpSessionRuntime.ts +++ b/apps/server/src/provider/acp/AcpSessionRuntime.ts @@ -150,6 +150,12 @@ 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) => AcpToolCallState; /** Context fill carried on the agent's own updates (see `AcpProviderDescriptor.contextUsage`). */ readonly contextUsage?: { readonly usedTokens: (notification: EffectAcpSchema.SessionNotification) => number | undefined; @@ -510,8 +516,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); @@ -538,6 +545,7 @@ const makeAcpSessionRuntime = ( itemIdScope, params: notification, ...(nativeControls ? { configOptionsRef } : {}), + ...(options.normalizeToolCall ? { normalizeToolCall: options.normalizeToolCall } : {}), }); }), ); @@ -1092,6 +1100,7 @@ const handleSessionUpdate = ({ itemIdScope, params, configOptionsRef, + normalizeToolCall, }: { readonly queue: Queue.Queue; readonly modeStateRef: Ref.Ref; @@ -1104,6 +1113,7 @@ const handleSessionUpdate = ({ readonly params: EffectAcpSchema.SessionNotification; /** Given for native controls only: the agent's own option updates land here. */ readonly configOptionsRef?: Ref.Ref>; + readonly normalizeToolCall?: (toolCall: AcpToolCallState) => AcpToolCallState; }): Effect.Effect => Effect.gen(function* () { if (configOptionsRef && params.update.sessionUpdate === "config_option_update") { @@ -1139,7 +1149,8 @@ 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 nextToolCall = normalizeToolCall?.(mergedToolCall) ?? mergedToolCall; const next = new Map(current); if (nextToolCall.status === "completed" || nextToolCall.status === "failed") { next.delete(nextToolCall.toolCallId); 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/AntigravityAcpSupport.ts b/apps/server/src/provider/acp/AntigravityAcpSupport.ts index 905f6a689..4e3cc42ae 100644 --- a/apps/server/src/provider/acp/AntigravityAcpSupport.ts +++ b/apps/server/src/provider/acp/AntigravityAcpSupport.ts @@ -59,6 +59,10 @@ import { type AntigravityPlatformRelease, } from "../antigravity/AntigravityRelease.ts"; import type { AntigravityReleaseSource } from "../antigravity/AntigravityReleaseSource.ts"; +import { + normalizeAntigravitySessionUpdate, + normalizeAntigravityToolCall, +} from "../antigravity/AntigravityToolCalls.ts"; import { antigravityTurnBehavior } from "../antigravity/AntigravityTurns.ts"; import { acquireAntigravityTempDir, @@ -805,6 +809,9 @@ export function makeAntigravityDescriptor( 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, // Work that outlives a prompt, steering, hidden failures, turn tokens. ...antigravityTurnBehavior(paths.profileDir), planMode: { 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..a72df4d88 --- /dev/null +++ b/apps/server/src/provider/antigravity/AntigravityChildRecords.test.ts @@ -0,0 +1,121 @@ +// @effect-diagnostics nodeBuiltinImport:off +import * as os from "node:os"; +import * as path from "node:path"; +import { mkdir, mkdtemp, 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 { antigravityChildStates, antigravityChildTranscript } from "./AntigravityChildRecords.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 }); + }; + return { profile, brain, write, child }; +} + +describe("Antigravity child records", () => { + it.live("reads each child's state from its records, and leaves out what they don't prove", () => + Effect.gen(function* () { + const records = yield* Effect.promise(makeProfile); + 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"); + // Two children claiming one launch: neither is proven its child. + await records.child("child-twin-a", "call_twin"); + await records.child("child-twin-b", "call_twin"); + await records.write([PARENT, ".system_generated", "messages", "report.json"], { + sender: "child-reported", + content: "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 states = yield* antigravityChildStates(records.profile, PARENT, [ + "call_working", + "call_reported", + "call_killed", + "call_twin", + "call_followup", + ]); + expect( + Object.fromEntries([...states!].map(([id, child]) => [id, [child.state, child.report]])), + ).toEqual({ + call_working: ["working", undefined], + call_reported: ["reported", "README.md has 42 lines."], + call_killed: ["killed", undefined], + }); + // Without argumentsJson the role comes from the child's entry and the prompt from its launch. + expect(states!.get("call_working")?.launch).toEqual({ + role: "Line Counter", + prompt: "Count lines in README.md", + }); + // A child with no transcript yet is still named, with its instruction. + const transcript = yield* antigravityChildTranscript(records.profile, PARENT, "call_working"); + expect(transcript?.child.conversationId).toBe("child-working"); + expect(transcript?.entries).toEqual([ + { id: "launch", role: "user", text: "Count lines in README.md", toolUses: [] }, + ]); + yield* Effect.promise(() => rm(records.profile, { recursive: true, force: true })); + }), + ); + + it.live("proves nothing through a link or an unreadable inbox", () => + Effect.gen(function* () { + const records = yield* Effect.promise(makeProfile); + 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 message that isn't JSON could be the one that matters. + yield* Effect.promise(() => + records.write([PARENT, ".system_generated", "messages", "broken.json"], "{not json"), + ); + expect(yield* antigravityChildStates(records.profile, PARENT, ["call_a"])).toBeUndefined(); + // A session id that walks a path is refused outright. + expect(yield* antigravityChildStates(records.profile, "../x", ["call_a"])).toBeUndefined(); + yield* Effect.promise(async () => { + await rm(records.profile, { recursive: true, force: true }); + 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..b563a2868 --- /dev/null +++ b/apps/server/src/provider/antigravity/AntigravityChildRecords.ts @@ -0,0 +1,420 @@ +// @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, 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 NodeFS from "node:fs"; +import * as NodeFSP from "node:fs/promises"; + +import type { ProviderSubagentTranscriptEntry } from "@threadlines/contracts"; +import * as Effect from "effect/Effect"; + +import { antigravityProfileEntry } 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 that started it. */ + 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; +} + +/** + * A small JSON record of the CLI's, or `undefined` when it is missing, + * linked, too big, past the read's budget, or unreadable. + */ +async function readRecord(profileDir: string, segments: ReadonlyArray, budget: ReadBudget) { + const entry = await antigravityProfileEntry(profileDir, segments, "file"); + if (entry === undefined || entry.size > MAX_RECORD_BYTES || entry.size > budget.bytes) + return undefined; + budget.bytes -= entry.size; + const text = await NodeFSP.readFile(entry.path, "utf8").catch(() => undefined); + return text === undefined ? undefined : parseJson(text); +} + +const generated = (conversationId: string, ...rest: ReadonlyArray) => [ + "brain", + conversationId, + ".system_generated", + ...rest, +]; + +/** + * A conversation's inbox: every message, or `undefined` when it can't all be + * read (one unread message could be the one that matters). No inbox is empty. + */ +async function readInbox( + profileDir: string, + conversationId: string, + budget: ReadBudget, +): Promise | undefined> { + const segments = generated(conversationId, "messages"); + const inbox = await antigravityProfileEntry(profileDir, segments, "directory"); + if (inbox === undefined) return []; + const names = await NodeFSP.readdir(inbox.path).catch(() => undefined); + if (names === undefined) return undefined; + const messages = names.filter((name) => name.endsWith(".json") && name !== "read.json"); + if (messages.length > MAX_INBOX_MESSAGES) return undefined; + const read: Array = []; + for (const name of messages) read.push(await readRecord(profileDir, [...segments, name], budget)); + return read.every(isRecord) ? read : undefined; +} + +/** 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) }; +} + +/** + * Every child the session started, with its launch and state, or + * `undefined` when the records can't be read whole. + */ +async function readChildren( + profileDir: string, + parentId: string, +): Promise | undefined> { + if (!NATIVE_ID.test(parentId)) return undefined; + const folder = await antigravityProfileEntry( + profileDir, + generated(parentId, "subagents"), + "directory", + ); + if (folder === undefined) return []; + const names = await NodeFSP.readdir(folder.path).catch(() => undefined); + if (names === undefined) return undefined; + const childIds = names.flatMap((name) => + name.endsWith(".json") && NATIVE_ID.test(name.slice(0, -5)) ? [name.slice(0, -5)] : [], + ); + if (childIds.length > MAX_CHILDREN) return undefined; + const budget: ReadBudget = { bytes: MAX_READ_BYTES }; + const parentInbox = await readInbox(profileDir, parentId, budget); + if (parentInbox === undefined) return undefined; + const children: Array = []; + for (const childId of childIds) { + const record = await readRecord( + profileDir, + generated(parentId, "subagents", `${childId}.json`), + budget, + ); + if (!isRecord(record)) return undefined; + const recordedId = stringField(record, "conversationId"); + if (recordedId !== undefined && recordedId !== childId) return undefined; + const inbox = await readInbox(profileDir, childId, budget); + if (inbox === undefined) return undefined; + const launches = inbox.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.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, + }); + } + return children; +} + +/** The one child a launching call started, or `undefined` when none or several claim it. */ +function childOf(children: ReadonlyArray, launchCallId: string) { + const claimed = children.filter((child) => child.launchCallId === launchCallId); + return claimed.length === 1 ? claimed[0] : undefined; +} + +/** + * What became of the children these launching calls started, by call id. + * A call the records don't tie to exactly one child is left out; `undefined` + * when the records can't be read. + */ +export const antigravityChildStates = ( + profileDir: string, + parentId: string, + launchCallIds: ReadonlyArray, +) => + Effect.tryPromise(async () => { + const children = await readChildren(profileDir, parentId); + if (children === undefined) return undefined; + const states = new Map(); + for (const id of launchCallIds) { + const child = childOf(children, id); + if (child !== undefined) states.set(id, child); + } + return states as ReadonlyMap; + }).pipe(Effect.orElseSucceed(() => undefined)); + +// ── 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 entry = await antigravityProfileEntry( + profileDir, + generated(childId, "logs", "transcript.jsonl"), + "file", + ); + if (entry === undefined) return undefined; + const handle = await NodeFSP.open( + entry.path, + NodeFS.constants.O_RDONLY | (NodeFS.constants.O_NOFOLLOW ?? 0), + ); + try { + const stat = await handle.stat(); + if (!stat.isFile()) return undefined; + const start = Math.max(0, stat.size - TRANSCRIPT_TAIL_BYTES); + // One byte more says whether the window starts on a line boundary. + const readFrom = Math.max(0, start - 1); + const buffer = Buffer.alloc(stat.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 children = await readChildren(profileDir, parentId); + const child = children === undefined ? undefined : childOf(children, 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/AntigravitySessionLog.ts b/apps/server/src/provider/antigravity/AntigravitySessionLog.ts index a6ec4b36e..677a1cb89 100644 --- a/apps/server/src/provider/antigravity/AntigravitySessionLog.ts +++ b/apps/server/src/provider/antigravity/AntigravitySessionLog.ts @@ -2,8 +2,9 @@ /** * 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. It is the one place Threadlines reads - * the CLI's session files, and only for what ACP gives no word of. + * 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 @@ -45,22 +46,44 @@ export interface AntigravityTurnSteps { } /** - * The session's log file when it is a plain file in the profile (no link at - * any step of the path), or `undefined` when there is none yet. + * 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; `undefined` otherwise. 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`). */ -async function sessionLogFile(profileDir: string, sessionId: string): Promise { +export async function antigravityProfileEntry( + profileDir: string, + segments: ReadonlyArray, + kind: "file" | "directory", +): Promise<{ readonly path: string; readonly size: number } | undefined> { const root = await NodeFSP.realpath(profileDir).catch(() => undefined); if (root === undefined) return undefined; - const segments = [ANTIGRAVITY_APP_DATA_DIR, "conversations", `${sessionId}.db`]; let current = root; - for (const [index, segment] of segments.entries()) { + 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 === segments.length - 1; + const last = index === path.length - 1; if (info === undefined || info.isSymbolicLink()) return undefined; - if (last ? !info.isFile() : !info.isDirectory()) return undefined; + if (last && kind === "file" ? !info.isFile() : !info.isDirectory()) return undefined; + size = info.size; } - return current; + return { path: current, size }; +} + +/** + * The session's log file when it is a plain file in the profile (no link at + * any step of the path), or `undefined` when there is none yet. + */ +async function sessionLogFile(profileDir: string, sessionId: string): Promise { + const entry = await antigravityProfileEntry( + profileDir, + ["conversations", `${sessionId}.db`], + "file", + ); + return entry?.path; } function readLog(file: string, read: (database: DatabaseSync) => A): A | undefined { diff --git a/apps/server/src/provider/antigravity/AntigravitySubagents.ts b/apps/server/src/provider/antigravity/AntigravitySubagents.ts new file mode 100644 index 000000000..d2896b073 --- /dev/null +++ b/apps/server/src/provider/antigravity/AntigravitySubagents.ts @@ -0,0 +1,82 @@ +/** + * 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, + antigravityChildStates, + antigravityChildTranscript, +} 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 }) => + antigravityChildStates(profileDir, sessionId, launchCallIds).pipe( + Effect.map((children) => + children === undefined + ? undefined + : new Map( + [...children].map(([id, child]): [string, AcpSubagentState] => [ + id, + { + state: child.state, + ...(child.report !== undefined ? { report: child.report } : {}), + }, + ]), + ), + ), + ), + 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..d3d4e0b9d --- /dev/null +++ b/apps/server/src/provider/antigravity/AntigravityToolCalls.test.ts @@ -0,0 +1,14 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { boundAntigravityCommandLine, boundAntigravityText } from "./AntigravityToolCalls.ts"; + +describe("Antigravity tool text", () => { + it("never cuts a character in half", () => { + // "😀" is two UTF-16 units; a cut between them would leave half a character. + const tail = boundAntigravityText(`a😀${"b".repeat(9)}`, 10); + expect(tail).toBe(`[Earlier output truncated]\n\n${"b".repeat(9)}`); + const head = boundAntigravityCommandLine(`${"c".repeat(9)}😀d`, 10); + expect(head).toBe(`${"c".repeat(9)}\n\n[Command truncated]`); + expect(boundAntigravityText("short")).toBe("short"); + }); +}); diff --git a/apps/server/src/provider/antigravity/AntigravityToolCalls.ts b/apps/server/src/provider/antigravity/AntigravityToolCalls.ts new file mode 100644 index 000000000..c55823e0f --- /dev/null +++ b/apps/server/src/provider/antigravity/AntigravityToolCalls.ts @@ -0,0 +1,216 @@ +/** + * 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. An edit's old and new + * text are the exception: the core counts the edit's lines from them. 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 type * as EffectAcpSchema from "effect-acp/schema"; + +import type { AcpToolCallState } from "../acp/AcpRuntimeModel.ts"; + +/** The most characters one tool text field keeps. */ +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 update, so a huge array or object can't flood it. */ +const UPDATE_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. */ +const COMMAND_LINE_FIELDS = new Set(["CommandLine", "command_line", "commandLine", "command"]); +/** + * Diff text is the file's own content: the ACP core counts an edit's lines + * from it, and a cut copy would miscount them. + */ +const FILE_TEXT_FIELDS = new Set(["oldText", "newText"]); + +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; a lone low surrogate at the cut is dropped. */ +export function boundAntigravityText(text: string, limit = ANTIGRAVITY_TOOL_TEXT_LIMIT): string { + if (text.length <= limit) return text; + const tail = text.slice(-limit).replace(/^[\uDC00-\uDFFF]/u, ""); + return copyText(`${OUTPUT_CUT}${tail}`); +} + +/** Keeps the start of a long command line; a lone high surrogate at the cut is dropped. */ +export function boundAntigravityCommandLine( + text: string, + limit = ANTIGRAVITY_TOOL_TEXT_LIMIT, +): string { + if (text.length <= limit) return text; + const head = text.slice(0, limit).replace(/[\uD800-\uDBFF]$/u, ""); + return copyText(`${head}${COMMAND_CUT}`); +} + +interface Budget { + nodes: number; + text: number; +} + +const isInlineImage = (record: Record) => + record.type === "image" || + (typeof record.mimeType === "string" && record.mimeType.toLowerCase().startsWith("image/")); + +/** + * One JSON value 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; + if (field !== undefined && FILE_TEXT_FIELDS.has(field)) return value; + if (budget.text <= 0) return undefined; + const limit = Math.min(ANTIGRAVITY_TOOL_TEXT_LIMIT, budget.text); + const text = + field !== undefined && COMMAND_LINE_FIELDS.has(field) + ? boundAntigravityCommandLine(value, limit) + : boundAntigravityText(value, limit); + budget.text -= text.length; + return text; + } + 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); + const kept: Record = {}; + for (const [key, entry] of Object.entries(value)) { + if (budget.nodes <= 0) break; + if (image && (key === "data" || key === "blob")) continue; + const bounded = boundValue(entry, budget, depth + 1, key); + if (bounded !== undefined) kept[key] = bounded; + } + return kept; +} + +/** A tool payload (`rawInput`, `rawOutput`, `_meta`) with its text bounded and images left out. */ +export function boundAntigravityToolPayload(payload: unknown): unknown { + return boundValue(payload, { nodes: UPDATE_NODE_BUDGET, text: UPDATE_TEXT_BUDGET }, 0); +} + +/** A tool content entry, or `undefined` for an inline image (its bytes are the only thing in it). */ +function boundContentEntry( + entry: EffectAcpSchema.ToolCallContent, + budget: Budget, +): EffectAcpSchema.ToolCallContent | undefined { + if ( + entry.type === "content" && + (entry.content.type === "image" || entry.content.type === "audio") + ) + return undefined; + const bounded = boundValue(entry, budget, 0); + return isRecord(bounded) ? (bounded as EffectAcpSchema.ToolCallContent) : undefined; +} + +/** + * 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; + } + const budget: Budget = { nodes: UPDATE_NODE_BUDGET, text: UPDATE_TEXT_BUDGET }; + const content = update.content?.flatMap((entry) => { + const bounded = boundContentEntry(entry, budget); + return bounded === undefined ? [] : [bounded]; + }); + return { + ...notification, + update: { + ...update, + ...(typeof update.title === "string" ? { title: boundAntigravityText(update.title) } : {}), + ...(update.rawInput !== undefined + ? { rawInput: boundAntigravityToolPayload(update.rawInput) } + : {}), + ...(update.rawOutput !== undefined + ? { rawOutput: boundAntigravityToolPayload(update.rawOutput) } + : {}), + ...(update.content !== undefined && update.content !== null + ? { content: content ?? [] } + : {}), + ...(update._meta !== undefined && update._meta !== null + ? { _meta: (boundAntigravityToolPayload(update._meta) ?? null) as Record } + : {}), + }, + } as EffectAcpSchema.SessionNotification; +} + +/** + * The MCP tool an Antigravity `call_mcp_tool` call runs. Antigravity reaches + * MCP tools its context budget left out through it: an `execute` call + * titled "MCP Tool " whose input names `ServerName`, `ToolName` and + * `Arguments` (T3 Code 7f928416b2). + */ +export function antigravityProxiedMcpTool(rawInput: unknown): + | { + readonly server: string; + readonly tool: string; + readonly arguments?: Record; + } + | undefined { + if (!isRecord(rawInput)) return undefined; + const server = typeof rawInput.ServerName === "string" ? rawInput.ServerName.trim() : ""; + const tool = typeof rawInput.ToolName === "string" ? rawInput.ToolName.trim() : ""; + if (!server || !tool) return undefined; + return { + server, + tool, + ...(isRecord(rawInput.Arguments) ? { arguments: rawInput.Arguments } : {}), + }; +} + +/** + * A tool call as the timeline should show it. An MCP call through + * `call_mcp_tool` is an MCP tool call with its server and tool, not a + * command (and so never holds a turn as a command would). + */ +export function normalizeAntigravityToolCall(toolCall: AcpToolCallState): AcpToolCallState { + const mcp = antigravityProxiedMcpTool(toolCall.data.rawInput); + if (mcp === undefined) return toolCall; + const { item: _item, command: _command, ...data } = toolCall.data; + const { command: _shown, ...rest } = toolCall; + return { + ...rest, + kind: "other", + itemType: "mcp_tool_call", + // The approval panel names a tool call by its title. + title: mcp.tool, + detail: `${mcp.server} · ${mcp.tool}`, + data: { + ...data, + kind: "other", + server: mcp.server, + tool: mcp.tool, + ...(mcp.arguments !== undefined ? { arguments: mcp.arguments } : {}), + }, + }; +} diff --git a/apps/server/src/provider/antigravity/AntigravityTurns.test.ts b/apps/server/src/provider/antigravity/AntigravityTurns.test.ts index 2635e974c..80b9681ea 100644 --- a/apps/server/src/provider/antigravity/AntigravityTurns.test.ts +++ b/apps/server/src/provider/antigravity/AntigravityTurns.test.ts @@ -118,6 +118,18 @@ const replyTo = (events: ReadonlyArray, turnId: TurnId) => ) .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, @@ -212,6 +224,111 @@ describe("Antigravity turns", () => { }).pipe(Effect.scoped, Effect.provide(testServices)), ); + it.live("holds a turn until every subagent reported, and shows each with its steps", () => + Effect.gen(function* () { + const agy = yield* startAgy("subagents"); + 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("does not hold a turn for a subagent killed within it", () => + Effect.gen(function* () { + const agy = yield* startAgy("subagent-killed"); + const { turnId } = yield* agy.adapter.sendTurn({ + threadId: agy.threadId, + input: "explore, then stop", + attachments: [], + }); + yield* agy.waitFor((events) => completedTurns(events).length === 1); + expect(completedTurns(agy.events)[0]).toMatchObject({ + turnId, + payload: { state: "completed" }, + }); + expect(subagentStatuses(agy.events)).toEqual({ call_stray: "interrupted" }); + }).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"); @@ -412,3 +529,42 @@ describe("Antigravity turn reading", () => { }); }); }); + +describe("Antigravity tool rows", () => { + const toolItem = (events: ReadonlyArray, id: string) => + events.findLast((event) => event.type === "item.completed" && String(event.itemId) === id) as + | Extract + | undefined; + + 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)), + ); + +}); diff --git a/apps/server/src/provider/antigravity/AntigravityTurns.ts b/apps/server/src/provider/antigravity/AntigravityTurns.ts index f6efead86..10c2b5461 100644 --- a/apps/server/src/provider/antigravity/AntigravityTurns.ts +++ b/apps/server/src/provider/antigravity/AntigravityTurns.ts @@ -32,16 +32,10 @@ import type { } from "../acp/AcpProviderDescriptor.ts"; import type { AcpToolCallState } from "../acp/AcpRuntimeModel.ts"; import { antigravityLogPosition, antigravityTurnSteps } from "./AntigravitySessionLog.ts"; +import { antigravitySubagents, 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 subagent launch: the call returns at once and the subagent works on. */ -const SUBAGENT_TITLES = new Set([ - "Running start_subagent", - "Run start_subagent?", - "Running invoke_subagent", - "Run invoke_subagent?", -]); /** * 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 @@ -52,13 +46,6 @@ export const ANTIGRAVITY_SILENT_WORK_LIMIT = Duration.minutes(30); const isRecord = (value: unknown): value is Record => typeof value === "object" && value !== null && !Array.isArray(value); -/** A launch's input: one subagent (`Role`, `Prompt`), or a batch (`Subagents`). */ -function isSubagentLaunch(input: unknown): boolean { - if (!isRecord(input)) return false; - if (typeof input.Role === "string" && typeof input.Prompt === "string") return true; - return Array.isArray(input.Subagents) && input.Subagents.length > 0; -} - /** * 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 @@ -72,14 +59,9 @@ export function antigravityWorkAfterPrompt( if (toolCall.kind === "execute") { return isRecord(input) && input.IsDaemon === true ? undefined : "command"; } - if ( - (toolCall.kind === undefined || toolCall.kind === "other") && - toolCall.title !== undefined && - SUBAGENT_TITLES.has(toolCall.title) && - isSubagentLaunch(input) - ) { - return "subagent"; - } + // Stage 3: one reading of a launch, shared with the subagent rows; it adds + // 1.5's auto-approved title ("Run invoke_subagent"). + if (isAntigravitySubagentLaunch(toolCall)) return "subagent"; return undefined; } @@ -240,6 +222,7 @@ export function antigravityTurnBehavior( AcpProviderDescriptor, | "agentTurns" | "heldTurns" + | "subagents" | "steerWithPrompt" | "promptOutcome" | "usageLedger" @@ -253,6 +236,9 @@ export function antigravityTurnBehavior( workAfterPrompt: antigravityWorkAfterPrompt, silentLimit: ANTIGRAVITY_SILENT_WORK_LIMIT, }, + // Stage 3: each launch shows as a subagent, and the hold on subagents + // lasts until the CLI's records say every child reported or was killed. + subagents: antigravitySubagents(profileDir), steerWithPrompt: true, promptOutcome: { watch: (sessionId) => From fa25a47daed029798430c10a52c13fa76262c0c1 Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Mon, 23 Nov 2026 03:08:37 -0500 Subject: [PATCH 19/59] feat(antigravity): images and audio go inline, PDFs as links, text files as text Antigravity used to get every non-image file as a note naming its saved path. Now, where its initialize answer says it reads them, images (PNG, JPEG, WebP, BMP) and audio go inline, PDFs as a resource_link to the saved file, and text files as an embedded text resource, decoded as UTF-8 or as UTF-16 when the file starts with its byte order mark. MIME parameters are dropped before deciding. Text over 100 KB, audio over 20 MB, more than 50 MB inline per message, text that doesn't decode, and anything else still go as the path note. The core gets an attachmentDelivery descriptor hook and the delivery code (AcpPromptAttachments); agents without the hook send what they sent before. --- apps/server/scripts/antigravity-mock-agent.ts | 6 +- apps/server/src/provider/acp/AcpAdapter.ts | 37 ++++- .../src/provider/acp/AcpPromptAttachments.ts | 132 ++++++++++++++++++ .../src/provider/acp/AcpProviderDescriptor.ts | 12 ++ .../src/provider/acp/AntigravityAcpSupport.ts | 3 + .../antigravity/AntigravityAttachments.ts | 66 +++++++++ .../antigravity/AntigravityTurns.test.ts | 100 ++++++++++++- 7 files changed, 350 insertions(+), 6 deletions(-) create mode 100644 apps/server/src/provider/acp/AcpPromptAttachments.ts create mode 100644 apps/server/src/provider/antigravity/AntigravityAttachments.ts diff --git a/apps/server/scripts/antigravity-mock-agent.ts b/apps/server/scripts/antigravity-mock-agent.ts index 7dfe47e07..c93a34cb6 100644 --- a/apps/server/scripts/antigravity-mock-agent.ts +++ b/apps/server/scripts/antigravity-mock-agent.ts @@ -161,7 +161,11 @@ const program = Effect.gen(function* () { Effect.succeed({ protocolVersion: 1, agentInfo: { name: "agy", title: "Antigravity", version: "1.5.14" }, - agentCapabilities: { loadSession: true, sessionCapabilities: { resume: {} } }, + agentCapabilities: { + loadSession: true, + sessionCapabilities: { resume: {} }, + promptCapabilities: { image: true, audio: true, embeddedContext: true }, + }, }), ); yield* agent.handleCreateSession(() => diff --git a/apps/server/src/provider/acp/AcpAdapter.ts b/apps/server/src/provider/acp/AcpAdapter.ts index 4a110c76e..fef3a701c 100644 --- a/apps/server/src/provider/acp/AcpAdapter.ts +++ b/apps/server/src/provider/acp/AcpAdapter.ts @@ -121,6 +121,7 @@ import type { AcpTurnOutcome, AcpWorkAfterPrompt, } from "./AcpProviderDescriptor.ts"; +import { type AcpAttachmentBudget, acpAttachmentContent } from "./AcpPromptAttachments.ts"; import { type AcpSubagentStatus, acpSubagentSettledEvents, @@ -237,6 +238,8 @@ 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 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 @@ -2243,6 +2246,7 @@ export function makeAcpAdapter( lastProviderStatus: undefined, lastContextUsageKey: undefined, acpSessionId: started.sessionId, + promptCapabilities: started.initializeResult.agentCapabilities?.promptCapabilities, // A session reopened from elsewhere has spent an unknown amount. costBaselineUsd: (resumeSessionId !== undefined || forkSession !== undefined) && @@ -2519,11 +2523,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, @@ -2531,6 +2537,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, @@ -2543,6 +2550,28 @@ 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, + fileSystem, + }).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; @@ -2631,6 +2660,7 @@ export function makeAcpAdapter( : projectBrief.text : contextText; const promptParts = yield* promptContent( + ctx, seededText.length > 0 || planMode ? planMode ? `${planMode.promptPrefix}${seededText}` @@ -3113,6 +3143,7 @@ export function makeAcpAdapter( } const text = input.input?.trim() ?? ""; const content = yield* promptContent( + ctx, text.length > 0 ? text : undefined, input.attachments, "turn/steer", diff --git a/apps/server/src/provider/acp/AcpPromptAttachments.ts b/apps/server/src/provider/acp/AcpPromptAttachments.ts new file mode 100644 index 000000000..14b0b5228 --- /dev/null +++ b/apps/server/src/provider/acp/AcpPromptAttachments.ts @@ -0,0 +1,132 @@ +// @effect-diagnostics nodeBuiltinImport:off -- node:url makes a staged file's file:// 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 } from "@threadlines/contracts"; +import * as Effect from "effect/Effect"; +import type * as FileSystem from "effect/FileSystem"; +import type * as EffectAcpSchema from "effect-acp/schema"; +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), +}); + +/** + * The content blocks for one attachment, sent the way `delivery` says, or + * as its note when it doesn't fit that way. Fails only when the staged file + * can't be read. + */ +export const acpAttachmentContent = (input: { + readonly attachment: ChatAttachment; + readonly path: string; + readonly delivery: AcpAttachmentDelivery; + readonly budget: AcpAttachmentBudget; + readonly fileSystem: FileSystem.FileSystem; +}) => + Effect.gen(function* () { + const { attachment, path, delivery, budget, fileSystem } = input; + const mimeType = bareMimeType(attachment.mimeType); + if (delivery === "note") return [note(attachment, path)]; + if (delivery === "link") { + return [ + { + type: "resource_link", + uri: pathToFileURL(path).href, + name: attachment.name, + mimeType, + size: attachment.sizeBytes, + }, + ] satisfies ReadonlyArray; + } + const audio = mimeType.startsWith("audio/"); + const limit = + delivery === "text" + ? INLINE_TEXT_ATTACHMENT_MAX_BYTES + : audio + ? INLINE_AUDIO_MAX_BYTES + : Number.POSITIVE_INFINITY; + // Sizes are checked before reading, so a large file is never read whole. + if (attachment.sizeBytes > limit) return [note(attachment, path)]; + if ( + delivery === "inline" && + budget.inlineBytes + attachment.sizeBytes > INLINE_MESSAGE_MAX_BYTES + ) + return [note(attachment, path)]; + const bytes = yield* fileSystem.readFile(path); + if (bytes.byteLength > limit) return [note(attachment, path)]; + if (delivery === "text") { + const text = decodeAttachmentText(bytes); + if (text === undefined) return [note(attachment, path)]; + return [ + { + type: "resource", + resource: { uri: pathToFileURL(path).href, mimeType, text }, + }, + ] satisfies ReadonlyArray; + } + budget.inlineBytes += bytes.byteLength; + const data = Buffer.from(bytes).toString("base64"); + return [ + audio + ? { type: "audio", data, mimeType } + : { type: "image", data, mimeType: mimeType || attachment.mimeType }, + ] satisfies ReadonlyArray; + }); diff --git a/apps/server/src/provider/acp/AcpProviderDescriptor.ts b/apps/server/src/provider/acp/AcpProviderDescriptor.ts index eb920b608..c316acfb6 100644 --- a/apps/server/src/provider/acp/AcpProviderDescriptor.ts +++ b/apps/server/src/provider/acp/AcpProviderDescriptor.ts @@ -10,6 +10,7 @@ * @module provider/acp/AcpProviderDescriptor */ import type { + ChatAttachment, ModelCapabilities, ProviderDriverKind, ProviderFailureCategory, @@ -46,6 +47,7 @@ import type { } from "../providerMaintenance.ts"; import type { UsageLedgerProvider } from "../../usage/usageLedger.ts"; import type { ProviderProbeResult, ServerProviderPresentation } from "../providerSnapshot.ts"; +import type { AcpAttachmentDelivery } from "./AcpPromptAttachments.ts"; import type { AcpPlanUpdate, AcpToolCallState } from "./AcpRuntimeModel.ts"; import type { AcpSessionRuntimeShape, AcpSpawnInput } from "./AcpSessionRuntime.ts"; @@ -619,6 +621,16 @@ export interface AcpProviderDescriptor { * left out of its context through a command, `call_mcp_tool`). */ readonly normalizeToolCall?: (toolCall: AcpToolCallState) => 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; diff --git a/apps/server/src/provider/acp/AntigravityAcpSupport.ts b/apps/server/src/provider/acp/AntigravityAcpSupport.ts index 4e3cc42ae..90af092fd 100644 --- a/apps/server/src/provider/acp/AntigravityAcpSupport.ts +++ b/apps/server/src/provider/acp/AntigravityAcpSupport.ts @@ -59,6 +59,7 @@ import { type AntigravityPlatformRelease, } from "../antigravity/AntigravityRelease.ts"; import type { AntigravityReleaseSource } from "../antigravity/AntigravityReleaseSource.ts"; +import { antigravityAttachmentDelivery } from "../antigravity/AntigravityAttachments.ts"; import { normalizeAntigravitySessionUpdate, normalizeAntigravityToolCall, @@ -812,6 +813,8 @@ export function makeAntigravityDescriptor( // 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, // Work that outlives a prompt, steering, hidden failures, turn tokens. ...antigravityTurnBehavior(paths.profileDir), planMode: { diff --git a/apps/server/src/provider/antigravity/AntigravityAttachments.ts b/apps/server/src/provider/antigravity/AntigravityAttachments.ts new file mode 100644 index 000000000..9b7e1673d --- /dev/null +++ b/apps/server/src/provider/antigravity/AntigravityAttachments.ts @@ -0,0 +1,66 @@ +/** + * 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"; + if (capabilities?.embeddedContext !== true) return "note"; + if (attachment.kind === "pdf" || mimeType === "application/pdf") return "link"; + if (attachment.kind === "text" || isTextType(mimeType)) return "text"; + return "note"; +} diff --git a/apps/server/src/provider/antigravity/AntigravityTurns.test.ts b/apps/server/src/provider/antigravity/AntigravityTurns.test.ts index 80b9681ea..87997937a 100644 --- a/apps/server/src/provider/antigravity/AntigravityTurns.test.ts +++ b/apps/server/src/provider/antigravity/AntigravityTurns.test.ts @@ -1,13 +1,14 @@ // @effect-diagnostics nodeBuiltinImport:off import * as os from "node:os"; import * as path from "node:path"; -import { chmod, mkdtemp, readFile, writeFile } from "node:fs/promises"; +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, + type ChatAttachment, ProviderDriverKind, type ProviderRuntimeEvent, ThreadId, @@ -19,6 +20,7 @@ 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 { makeAcpAdapter } from "../acp/AcpAdapter.ts"; @@ -530,7 +532,7 @@ describe("Antigravity turn reading", () => { }); }); -describe("Antigravity tool rows", () => { +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 @@ -567,4 +569,98 @@ describe("Antigravity tool rows", () => { }).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)), + ); }); From 16a80a4e6d5eb2533db67c6d9ceb5ad3aa5a60d7 Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Mon, 23 Nov 2026 03:08:39 -0500 Subject: [PATCH 20/59] docs(antigravity): subagents, tool rows and attachments --- apps/server/src/guide/topics.ts | 2 +- docs/providers/antigravity.md | 41 +++++++++++++++++++++++++++++++-- 2 files changed, 40 insertions(+), 3 deletions(-) diff --git a/apps/server/src/guide/topics.ts b/apps/server/src/guide/topics.ts index 9f75de9c4..d683b0b2a 100644 --- a/apps/server/src/guide/topics.ts +++ b/apps/server/src/guide/topics.ts @@ -311,7 +311,7 @@ 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. -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 meanwhile steers the turn. Its turns count on {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 meanwhile steers the turn. Each subagent Antigravity launches shows like other agents' subagents, with its role, prompt, report and recent steps, and holds the turn until it reports or the agent stops it. 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 when a message starts with / and its name. diff --git a/docs/providers/antigravity.md b/docs/providers/antigravity.md index a6ddda46b..f112b1b3f 100644 --- a/docs/providers/antigravity.md +++ b/docs/providers/antigravity.md @@ -104,13 +104,50 @@ a cancel). A reply the agent starts after the turn ended opens a turn of its own 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. A timer -holds the turn until it fires. Subagents are only known to finish by the report the agent gives when -one ends, so the first report frees the turn; a later subagent's report opens a turn of its own. +holds the turn until it fires. A subagent holds the turn until it has sent the agent its report or +the agent stopped it (see Subagents). Where the CLI's records don't say which subagent a launch +started, the first reply the agent starts by itself frees it, as before. A message sent while Antigravity works steers the turn instead of waiting: Threadlines sends it as another prompt, which the CLI takes into the running turn (1.5.0+), leaving its commands and subagents running. +### 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 checked +when the agent's prompt ends and when each reply it starts by itself ends: + +- A subagent that sent its report shows as done, with the report. +- One the agent stopped (`manage_subagents`) shows as stopped and no longer keeps the turn running. +- Stop ends every running subagent with the turn. +- When the records don't say which subagent a launch started, its view says "Antigravity did not + record which subagent this started", and the turn falls back to the rule above. + +The view is read-only: you can't message a subagent directly. + +### 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. +- 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. Each of these needs Antigravity to say it reads that kind; otherwise the file +goes as a path. A MIME type's parameters (`; charset=utf-8`) don't change the choice. + ### When a turn fails Antigravity sometimes ends a turn normally while the reply is really an upstream error. Threadlines From 42e62a6ad21fbeddf0ef600bc294b23f24849b87 Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Mon, 23 Nov 2026 03:19:56 -0500 Subject: [PATCH 21/59] fix(antigravity): plan limits stay with their account and older clients can read them Review fixes for the Antigravity plan meter. - An older client rejects an unknown usage source, and with it the whole server config. The reading now reports as grok-billing, which clients handle by label alone, and names itself in limitName. The contract says the source list is closed. - Accounts with no email to compare could inherit each other's numbers through the provider registry. Snapshots now carry an opaque auth.accountId; the registry never carries usage across two different ones, and the reader drops another account's numbers and email. - A read that timed out published without checking that the sign-in on disk was still the one it read for. Every read now lands through one path that checks it. - Enterprise and per-model answers folded every model of a family into its fullest, so an unused model showed another's usage. Each model now has its own row, its thinking levels folded together. - A host or the per-model fallback failing dropped the rows only it gave. Those rows now stay from the last read, with their age, and the read counts as failed. - 99.6% used rounded to 100 and read as "limit reached". Only an empty quota is 100 now. - usageLimitFor takes a picker slug and finds the model's name. --- .../src/provider/Drivers/AntigravityDriver.ts | 2 +- .../provider/Layers/ProviderRegistry.test.ts | 41 ++ .../src/provider/Layers/ProviderRegistry.ts | 8 + .../antigravity/AntigravityUsage.test.ts | 235 ++++++++- .../provider/antigravity/AntigravityUsage.ts | 464 ++++++++++++------ apps/web/src/lib/providerUsage.test.ts | 6 +- apps/web/src/lib/providerUsage.ts | 3 +- docs/providers/antigravity.md | 9 +- packages/contracts/src/server.ts | 15 +- 9 files changed, 592 insertions(+), 191 deletions(-) diff --git a/apps/server/src/provider/Drivers/AntigravityDriver.ts b/apps/server/src/provider/Drivers/AntigravityDriver.ts index 1fe76808a..e8ae829f5 100644 --- a/apps/server/src/provider/Drivers/AntigravityDriver.ts +++ b/apps/server/src/provider/Drivers/AntigravityDriver.ts @@ -157,7 +157,7 @@ export const AntigravityDriver: ProviderDriver { + 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/antigravity/AntigravityUsage.test.ts b/apps/server/src/provider/antigravity/AntigravityUsage.test.ts index 7fb00b071..8fc500db1 100644 --- a/apps/server/src/provider/antigravity/AntigravityUsage.test.ts +++ b/apps/server/src/provider/antigravity/AntigravityUsage.test.ts @@ -9,11 +9,15 @@ 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"; @@ -194,6 +198,8 @@ 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; @@ -205,23 +211,33 @@ const setup = (input: { method, fingerprint: "fingerprint-a", fetch: google.fetch, + ...(input.timeouts ? { timeouts: input.timeouts } : {}), }); - let snapshot = signedInSnapshot(method); + let snapshot = { ...signedInSnapshot(method), models: input.models ?? [] }; let published = yield* Deferred.make(); - reader.publishTo((update) => - Effect.gen(function* () { - const next = update(snapshot); - if (next) snapshot = next; - yield* Deferred.succeed(published, snapshot); - }), - ); + 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 }; + return { + profileDir, + reader, + google, + readOnce, + current: Effect.sync(() => snapshot), + setSnapshot: (next: ServerProvider) => Effect.sync(() => void (snapshot = next)), + }; }); const windowsOf = (snapshot: ServerProvider) => @@ -249,7 +265,13 @@ describe("Antigravity plan limits", () => { 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")); - assert.equal(snapshot.accountUsage!.source, "antigravity-quota"); + // 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); @@ -279,15 +301,13 @@ describe("Antigravity plan limits", () => { }), }); const snapshot = yield* readOnce; - // The fullest Gemini model stands for the family; Claude stays the summary's shared pool. + // Each Gemini model keeps its own quota; Claude stays the summary's shared pool. assert.deepEqual(windowsOf(snapshot), [ - { label: "Gemini", minutes: undefined, used: 40 }, - { label: "Gemini Hydrogen", minutes: undefined, used: 5 }, + { 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 }, ]); - const gemini = snapshot.accountUsage!.limits[0]!.scoped![0]!; - assert.deepEqual(gemini.scopeExcludes, ["Hydrogen"]); }), ); @@ -297,14 +317,14 @@ describe("Antigravity plan limits", () => { route: googleRoute({ summary: { status: 404 }, models: { body: MODELS } }), }); assert.deepEqual(windowsOf(yield* readOnce), [ - { label: "Gemini", minutes: undefined, used: 40 }, - { label: "Gemini Hydrogen", minutes: undefined, used: 5 }, - { label: "Claude", minutes: undefined, used: 80 }, + { 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("folds an Enterprise answer's per-model buckets into one row per family", () => + 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", @@ -317,14 +337,31 @@ describe("Antigravity plan limits", () => { }), }); const snapshot = yield* readOnce; + // Opus unused stays unused beside a Sonnet that is 70% through its quota. assert.deepEqual(windowsOf(snapshot), [ - { label: "Gemini", minutes: undefined, used: 50 }, - { label: "Gemini Argon", minutes: undefined, used: 90 }, - { label: "Claude", minutes: undefined, used: 70 }, - { label: "GPT", minutes: undefined, used: 5 }, + { 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 argon = snapshot.accountUsage!.limits[0]!.scoped![1]!; - assert.equal(argon.resetsAt, Date.parse("2026-11-24T00:00:00Z")); + 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); }), ); @@ -557,4 +594,152 @@ describe("Antigravity plan limits", () => { 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 index 7c3e231b4..fc50992b2 100644 --- a/apps/server/src/provider/antigravity/AntigravityUsage.ts +++ b/apps/server/src/provider/antigravity/AntigravityUsage.ts @@ -40,7 +40,6 @@ import * as fs from "node:fs/promises"; import type { AntigravityAuthMethod, RuntimeUsageLimit, - ServerProvider, ServerProviderAccountUsage, ServerProviderAuth, ServerProviderAuthCapability, @@ -54,6 +53,8 @@ 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"; @@ -84,6 +85,9 @@ const HOSTS_BY_METHOD: Record = { 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}`; @@ -174,6 +178,7 @@ const Models = Schema.Struct({ 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), @@ -193,28 +198,29 @@ const PERIOD_MINUTES: Record = { quota: undefined, }; -/** A group of models one quota covers. */ +/** 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"] }; -const SHARED_3P: Family = { key: "3p", label: "Claude & GPT", models: ["Claude", "GPT"] }; -const CLAUDE: Family = { key: "claude", label: "Claude", models: ["Claude"] }; -const GPT: Family = { key: "gpt", label: "GPT", models: ["GPT"] }; - -/** - * Gemini 4's own quota families as Google has named them so far. An Enterprise - * answer meters per model and has no pool to learn them from, so a per-model - * bucket is placed by these and by the pools in the same answer. - */ -const KNOWN_GEMINI_SUBFAMILIES = ["argon", "carbon", "neon", "hydrogen"]; +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 { @@ -222,6 +228,35 @@ function geminiSubfamily(sub: string, groupName: string | undefined): Family { 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, }; } @@ -231,6 +266,8 @@ interface QuotaWindow { /** 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) => @@ -249,8 +286,8 @@ const parseTime = (value: string | undefined) => { /** * Keeps the fuller of two readings of one window; on a tie, the one with a - * reset time, then the earlier reset. A family's quota is as tight as its - * tightest model. + * 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); @@ -266,27 +303,11 @@ function fold(into: Map, window: QuotaWindow) { } } -/** The family a model's id belongs to, for per-model quotas. */ -function modelFamily( - modelId: string, - provider: string | undefined, - subfamilies: ReadonlySet, -): Family | undefined { - const id = modelId.toLowerCase(); - if (provider === "MODEL_PROVIDER_GOOGLE" || id.startsWith("gemini-")) { - const words = id.split(/[^a-z0-9]+/); - const sub = words.find((word) => subfamilies.has(word)); - return sub ? geminiSubfamily(sub, undefined) : GEMINI; - } - if (provider === "MODEL_PROVIDER_ANTHROPIC" || id.startsWith("claude-")) return CLAUDE; - if (provider === "MODEL_PROVIDER_OPENAI" || id.startsWith("gpt-")) return GPT; - return undefined; -} - /** * The windows in one `retrieveUserQuotaSummary` answer, requested at * `requestedAtMs`. Pools (`5h`, `weekly`) keep their own rows; an Enterprise - * answer's per-model buckets fold into one row per family. + * answer's per-model buckets get one row per model, its thinking levels + * folded together. */ export function antigravitySummaryWindows( answer: unknown, @@ -298,62 +319,64 @@ export function antigravitySummaryWindows( const groups = summary.groups?.some((group) => group.buckets?.length) ? summary.groups : [{ displayName: undefined, buckets: summary.buckets }]; - const buckets = (groups ?? []).flatMap((group) => - (group.buckets ?? []) - .filter((bucket) => !bucket.disabled) - .map((bucket) => ({ bucket, groupName: group.displayName })), - ); - // Pools first: they name the Gemini sub-families this account has. - const subfamilies = new Set(KNOWN_GEMINI_SUBFAMILIES); - for (const { bucket } of buckets) { - const sub = /^gemini-([a-z]+)-/.exec(bucket.bucketId)?.[1]; - if (sub && (bucket.window === "5h" || bucket.window === "weekly")) subfamilies.add(sub); - } const windows = new Map(); - for (const { bucket, groupName } of buckets) { - 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; - let family: Family | undefined; - if (id.startsWith("3p-")) family = SHARED_3P; - else if (/^gemini-(5h|weekly|quota)$/.test(id)) family = GEMINI; - else if (pooled && /^gemini-[a-z]+-/.test(id)) { - family = geminiSubfamily(/^gemini-([a-z]+)-/.exec(id)![1]!, groupName); - } else if (!pooled) family = modelFamily(id, undefined, subfamilies); - family ??= { - key: `other-${id}`, - label: groupName?.trim() || bucket.displayName?.trim() || id, - }; - // 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 }); + 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, - * folded per family. Older accounts report quotas this way only, without a - * window length, so none is made up. + * 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 subfamilies = new Set(KNOWN_GEMINI_SUBFAMILIES); const windows = new Map(); for (const [modelId, model] of Object.entries(decoded.value.models)) { if (model.isInternal) continue; - const family = modelFamily(modelId, model.modelProvider, subfamilies); + const family = perModelFamily(modelId, model.displayName); if (!family) continue; for (const [period, quota] of [ ["quota", model.quotaInfo], @@ -379,31 +402,63 @@ function mergeHosts(answers: ReadonlyArray>) { } const FAMILY_ORDER = (family: Family) => - family.key === "gemini" - ? 0 - : family.key.startsWith("gemini-") - ? 1 - : family === SHARED_3P || family.key === "claude" || family.key === "gpt" - ? 2 - : 3; + 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 own - * (`scoped`), since a spent family never stops the others. The default Gemini - * pool leaves out the sub-families that have their own. + * 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 ownPools = [ - ...new Set( - windows - .filter((window) => window.family.key.startsWith("gemini-")) - .flatMap((window) => window.family.models ?? []), - ), + 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) => @@ -412,26 +467,28 @@ export function antigravityAccountUsage( PERIOD_ORDER[a.period] - PERIOD_ORDER[b.period], ) .map((window): ServerProviderScopedUsageWindow => { - const usedPercent = Math.round(window.usedPercent); + 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 } : {}), - ...(window.family.key === "gemini" && ownPools.length > 0 - ? { scopeExcludes: ownPools } - : {}), + ...(excludes.length > 0 ? { scopeExcludes: excludes } : {}), usedPercent, remainingPercent: 100 - usedPercent, ...(window.resetsAtMs !== undefined ? { resetsAt: window.resetsAtMs } : {}), ...(minutes !== undefined ? { windowDurationMins: minutes } : {}), - checkedAt, + checkedAt: window.checkedAt ?? checkedAt, }; }); return { - source: "antigravity-quota", + // 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", scoped }], + limits: [{ limitId: "antigravity", limitName: ANTIGRAVITY_USAGE_LABEL, scoped }], }; } @@ -443,10 +500,16 @@ class UsageRequestError extends Schema.TaggedError()( { 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) => { @@ -474,12 +537,18 @@ const requestJson = ( catch: () => new UsageRequestError({ reason: `${new URL(url).host} did not answer` }), }).pipe( Effect.timeoutOrElse({ - duration: REQUEST_TIMEOUT, + 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, @@ -487,23 +556,25 @@ const askHosts = ( 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: "{}", - }); + 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) => ({ - answered: answers.some((answer) => answer.answered), + Effect.map((answers): QuotaRead => ({ + complete: answers.every((answer) => answer.answered), windows: mergeHosts(answers.map((answer) => answer.windows)), })), ); @@ -513,7 +584,12 @@ const askHosts = ( * 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) => +const readQuotaWindows = ( + fetch: DownloadFetch, + method: GoogleMethod, + accessToken: string, + timeout: Duration.Input, +) => Effect.gen(function* () { const summary = yield* askHosts( fetch, @@ -521,25 +597,28 @@ const readQuotaWindows = (fetch: DownloadFetch, method: GoogleMethod, accessToke accessToken, "retrieveUserQuotaSummary", antigravitySummaryWindows, + timeout, ); - const hasGemini = summary.windows.some((window) => window.family.key.startsWith("gemini")); - if (hasGemini) return summary.windows; + 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 models.windows; - return [ - ...summary.windows, - ...models.windows.filter((window) => window.family.key.startsWith("gemini")), - ]; + 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) => - requestJson(fetch, USERINFO_URL, { method: "GET", accessToken }).pipe( +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; @@ -547,6 +626,23 @@ const readEmail = (fetch: DownloadFetch, accessToken: string) => 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 = @@ -556,12 +652,17 @@ export const ANTIGRAVITY_USAGE_FAILED_DETAIL = /** 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 @@ -571,12 +672,13 @@ export interface AntigravityUsageReader { readonly status: Effect.Effect; /** Cancels a read in flight and forgets every reading: for sign-in and sign-out. */ readonly reset: Effect.Effect; - /** Where a finished read publishes, once the instance's snapshot exists. */ - readonly publishTo: ( - patch: (update: (current: ServerProvider) => ServerProvider | null) => Effect.Effect, - ) => void; - /** The limit the last reading says `modelName` is stopped on, for Continue at reset. */ - readonly usageLimitFor: (modelName: string) => 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 { @@ -586,10 +688,13 @@ export interface AntigravityUsageReaderInput { 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; } @@ -599,6 +704,7 @@ export const makeAntigravityUsageReader = ( 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(); @@ -606,9 +712,7 @@ export const makeAntigravityUsageReader = ( let lastAttempt: { key: string; atMs: number; failed: boolean } | undefined; /** Bumped by `reset`: a read started before it doesn't land. */ let generation = 0; - let publish: - | ((update: (current: ServerProvider) => ServerProvider | null) => Effect.Effect) - | undefined; + let snapshot: AntigravityUsageSnapshot | undefined; const keyOf = (token: SavedToken) => `${input.fingerprint}:${token.accountKey}`; @@ -627,6 +731,7 @@ export const makeAntigravityUsageReader = ( } : undefined; return { + accountId: accountIdOf(key), ...(kept ? { accountUsage: kept } : {}), ...(email ? { email } : {}), ...(usage ? { usage } : {}), @@ -634,8 +739,8 @@ export const makeAntigravityUsageReader = ( }; const publishStatus = (status: AntigravityUsageStatus) => - publish - ? publish((current) => { + snapshot + ? snapshot.patchSnapshot((current) => { if ( !current.enabled || current.auth.status !== "authenticated" || @@ -647,34 +752,58 @@ export const makeAntigravityUsageReader = ( }) : Effect.void; - const read = (token: SavedToken, key: string, method: GoogleMethod) => + /** + * 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 started = generation; - const windows = yield* readQuotaWindows(fetch, method, token.accessToken); - const email = - token.email ?? emails.get(key) ?? (yield* readEmail(fetch, token.accessToken)); - // Signed in or out meanwhile, or another account's sign-in is on disk now. const current = yield* readSavedToken(input.profileDir); if (generation !== started || current === undefined || keyOf(current) !== key) return; const nowMs = yield* Clock.currentTimeMillis; - if (windows.length > 0) { + 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: windows.length === 0 }; - yield* publishStatus(statusFor(token, key, nowMs)); + 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( - Effect.timeoutOrElse({ - duration: READ_TIMEOUT, - orElse: () => - Effect.gen(function* () { - if (lastAttempt?.key === key) lastAttempt = { ...lastAttempt, failed: true }; - yield* publishStatus(statusFor(token, key, yield* Clock.currentTimeMillis)); - }), - }), // Nothing a read does may fail the instance. Effect.catchCause(() => Effect.void), ); @@ -707,6 +836,17 @@ export const makeAntigravityUsageReader = ( 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* () { @@ -716,27 +856,32 @@ export const makeAntigravityUsageReader = ( emails = new Map(); lastAttempt = undefined; }), - publishTo: (patch) => { - publish = patch; + attach: (next) => { + snapshot = next; }, - usageLimitFor: (modelName) => + 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, - modelName, + 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, and the line about it. A status without a reading keeps the one - * already there, which is the last good one. + * 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 { @@ -744,16 +889,21 @@ export function withAntigravityUsage< readonly accountUsage?: ServerProviderAccountUsage | undefined; }, >(target: T, status: AntigravityUsageStatus): T { - const { capabilities, ...auth } = target.auth; + 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 { - ...target, + ...rest, auth: { ...auth, - ...(status.email ? { email: status.email } : {}), + ...(status.accountId ? { accountId: status.accountId } : {}), + ...(email ? { email } : {}), ...(Object.keys(nextCapabilities).length > 0 ? { capabilities: nextCapabilities } : {}), }, - ...(status.accountUsage ? { accountUsage: status.accountUsage } : {}), - }; + ...(accountUsage ? { accountUsage } : {}), + } as T; } diff --git a/apps/web/src/lib/providerUsage.test.ts b/apps/web/src/lib/providerUsage.test.ts index 99eddb835..89df53cb3 100644 --- a/apps/web/src/lib/providerUsage.test.ts +++ b/apps/web/src/lib/providerUsage.test.ts @@ -1003,12 +1003,13 @@ describe("deriveProviderAccountUsagePresentationForProvider", () => { it("says what Antigravity's server says about its limits, in its words", () => { const antigravity = ProviderDriverKind.make("antigravity"); const reading = (checkedAt: string): ServerProviderAccountUsage => ({ - source: "antigravity-quota", + source: "grok-billing", checkedAt, primaryLimitId: "antigravity", limits: [ { limitId: "antigravity", + limitName: "Antigravity usage", scoped: [ { scopeLabel: "Gemini", @@ -1228,12 +1229,13 @@ describe("a model's own usage limit", () => { const antigravity = deriveProviderAccountUsagePresentation( { - source: "antigravity-quota", + 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], diff --git a/apps/web/src/lib/providerUsage.ts b/apps/web/src/lib/providerUsage.ts index e67b0feda..511da0c06 100644 --- a/apps/web/src/lib/providerUsage.ts +++ b/apps/web/src/lib/providerUsage.ts @@ -682,7 +682,6 @@ const PROVIDER_USAGE_SOURCE_LABELS: Record Date: Mon, 23 Nov 2026 03:19:56 -0500 Subject: [PATCH 22/59] fix(antigravity): Continue at reset uses the plan meter's reset and its model families - A quota failure the agent gave no reset time for now takes the reset the meter knows for the turn's model, so Continue at reset can arm. The ACP core passes the turn's model to promptOutcome.watch. - An early continue was vetoed by any spent window. A spent window that covers another family of models than every limit that stopped the thread (Antigravity's scopeModels) no longer vetoes it. Windows without a family, which is every Claude and Codex window, veto as before. --- .../Layers/ContinueAtResetSweeper.test.ts | 80 +++++++++++++++++++ .../Layers/ContinueAtResetSweeper.ts | 13 ++- apps/server/src/provider/acp/AcpAdapter.ts | 8 +- .../src/provider/acp/AcpProviderDescriptor.ts | 6 +- .../src/provider/acp/AntigravityAcpSupport.ts | 2 +- .../antigravity/AntigravityTurns.test.ts | 37 +++++++++ .../provider/antigravity/AntigravityTurns.ts | 36 ++++++--- packages/shared/src/usageLimits.test.ts | 2 +- packages/shared/src/usageLimits.ts | 14 +++- 9 files changed, 178 insertions(+), 20 deletions(-) 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/provider/acp/AcpAdapter.ts b/apps/server/src/provider/acp/AcpAdapter.ts index c00a2435a..19af1c878 100644 --- a/apps/server/src/provider/acp/AcpAdapter.ts +++ b/apps/server/src/provider/acp/AcpAdapter.ts @@ -2502,7 +2502,7 @@ export function makeAcpAdapter( ), ); } - const checkOutcome = yield* watchPromptOutcome(ctx); + const checkOutcome = yield* watchPromptOutcome(ctx, model); ctx.activeTurnId = turnId; const run: AcpTurnRun = { turnId, @@ -2552,10 +2552,10 @@ export function makeAcpAdapter( }); /** Starts reading how the turn's prompts end (`promptOutcome`); never fails. */ - const watchPromptOutcome = (ctx: AcpSessionContext) => + const watchPromptOutcome = (ctx: AcpSessionContext, model: string | undefined) => descriptor.promptOutcome === undefined ? Effect.succeed(undefined) - : descriptor.promptOutcome.watch(ctx.acpSessionId).pipe( + : descriptor.promptOutcome.watch(ctx.acpSessionId, model).pipe( Effect.catchCause((cause) => Effect.logWarning("acp.prompt-outcome.watch-failed", { provider: PROVIDER, @@ -3004,7 +3004,7 @@ export function makeAcpAdapter( phase: undefined, prompts: 0, usage: null, - checkOutcome: yield* watchPromptOutcome(ctx), + checkOutcome: yield* watchPromptOutcome(ctx, ctx.session.model), }; ctx.turnRun = run; } diff --git a/apps/server/src/provider/acp/AcpProviderDescriptor.ts b/apps/server/src/provider/acp/AcpProviderDescriptor.ts index 4cd40b756..e4e4499c5 100644 --- a/apps/server/src/provider/acp/AcpProviderDescriptor.ts +++ b/apps/server/src/provider/acp/AcpProviderDescriptor.ts @@ -169,7 +169,11 @@ export interface AcpPromptFailure { * run when the turn's last prompt answers or fails. */ export interface AcpPromptOutcome { - readonly watch: (sessionId: string) => Effect.Effect< + /** `model`: the picker slug the turn runs on, when known. */ + readonly watch: ( + sessionId: string, + model: string | undefined, + ) => Effect.Effect< ( answer: | { readonly response: EffectAcpSchema.PromptResponse } diff --git a/apps/server/src/provider/acp/AntigravityAcpSupport.ts b/apps/server/src/provider/acp/AntigravityAcpSupport.ts index 905f6a689..72cb1d7f1 100644 --- a/apps/server/src/provider/acp/AntigravityAcpSupport.ts +++ b/apps/server/src/provider/acp/AntigravityAcpSupport.ts @@ -806,7 +806,7 @@ export function makeAntigravityDescriptor( permissionOptionWarning: antigravityOptionWarning, cancellationNotice: "The request was cancelled by the client.", // Work that outlives a prompt, steering, hidden failures, turn tokens. - ...antigravityTurnBehavior(paths.profileDir), + ...antigravityTurnBehavior(paths.profileDir, usage?.usageLimitFor), planMode: { promptPrefix: "/plan ", isPlanFile: (toolCall) => { diff --git a/apps/server/src/provider/antigravity/AntigravityTurns.test.ts b/apps/server/src/provider/antigravity/AntigravityTurns.test.ts index 2635e974c..f898d8f9f 100644 --- a/apps/server/src/provider/antigravity/AntigravityTurns.test.ts +++ b/apps/server/src/provider/antigravity/AntigravityTurns.test.ts @@ -26,6 +26,7 @@ import type { AcpToolCallState } from "../acp/AcpRuntimeModel.ts"; import { makeAntigravityDescriptor } from "../acp/AntigravityAcpSupport.ts"; import { antigravityFailure, + antigravityTurnBehavior, antigravityTurnUsageTotals, antigravityWorkAfterPrompt, } from "./AntigravityTurns.ts"; @@ -394,6 +395,42 @@ describe("Antigravity turn reading", () => { ).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.promptOutcome!.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("counts cached reads as input and thinking inside output", () => { expect( antigravityTurnUsageTotals({ diff --git a/apps/server/src/provider/antigravity/AntigravityTurns.ts b/apps/server/src/provider/antigravity/AntigravityTurns.ts index f6efead86..5066ce3b8 100644 --- a/apps/server/src/provider/antigravity/AntigravityTurns.ts +++ b/apps/server/src/provider/antigravity/AntigravityTurns.ts @@ -17,7 +17,7 @@ * * @module provider/antigravity/AntigravityTurns */ -import type { UsageTokenTotals } from "@threadlines/contracts"; +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"; @@ -232,10 +232,13 @@ function acpErrorText(error: unknown): string | undefined { /** * The descriptor hooks for an Antigravity turn, with the instance's profile - * (where the CLI keeps its session logs). + * (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< AcpProviderDescriptor, | "agentTurns" @@ -255,9 +258,18 @@ export function antigravityTurnBehavior( }, steerWithPrompt: true, promptOutcome: { - watch: (sessionId) => + 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); return (answer) => Effect.gen(function* () { const nowMs = yield* Clock.currentTimeMillis; @@ -270,7 +282,9 @@ export function antigravityTurnBehavior( (parseApiError(errorText) !== undefined || QUOTA_EXHAUSTED.test(errorText) || LOST_THINKING_SIGNATURE.test(errorText)); - return recognized ? antigravityFailure({ errorText, nowMs }) : undefined; + return recognized + ? yield* withMeterReset(antigravityFailure({ errorText, nowMs })) + : undefined; } // A normal end can hide an upstream error that only the // agent's own log records. @@ -279,12 +293,14 @@ export function antigravityTurnBehavior( before === undefined ? undefined : yield* antigravityTurnSteps(profileDir, sessionId, before); - return antigravityFailure({ - errorText: steps?.errorText, - stopReason, - ...(steps !== undefined ? { reachedModel: steps.reachedModel } : {}), - nowMs, - }); + return yield* withMeterReset( + antigravityFailure({ + errorText: steps?.errorText, + stopReason, + ...(steps !== undefined ? { reachedModel: steps.reachedModel } : {}), + nowMs, + }), + ); }); }), }, diff --git a/packages/shared/src/usageLimits.test.ts b/packages/shared/src/usageLimits.test.ts index ebd27a051..af1e50233 100644 --- a/packages/shared/src/usageLimits.test.ts +++ b/packages/shared/src/usageLimits.test.ts @@ -68,7 +68,7 @@ describe("Antigravity's family limits", () => { it("stop a model only on its own family's spent window", () => { const resetsAt = NOW_MS + 3_600_000; const usage: ServerProviderAccountUsage = { - source: "antigravity-quota", + source: "grok-billing", checkedAt: "2026-11-06T11:59:00.000Z", limits: [ { diff --git a/packages/shared/src/usageLimits.ts b/packages/shared/src/usageLimits.ts index a67a31e63..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; From 267734285ca10a3c8f3a75dfae079d2792e8fb71 Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Mon, 23 Nov 2026 03:22:17 -0500 Subject: [PATCH 23/59] fix(antigravity): sharing the user's rules never writes outside the profile or takes what it didn't make Review fixes for the profile linker: - A profile folder that is a link (say to the real ~/.gemini/config) is never written through: every folder on the way must be a real folder inside the profile, and missing ones are made one level at a time. - A source may be a link (dotfiles), but not one leading to a sign-in or token file, hooks, MCP or plugin settings, anywhere else in ~/.gemini, or Threadlines' data folder. - The ownership record moved beside the profile, out of the agent's home, and is read without following links or blocking on a FIFO, with a size cap. Source reads are bounded the same way, and the whole step has a time bound so it can't hold a chat. - Only what the record names is replaced or removed. A matching link Threadlines didn't make is used but never removed. Removal moves the entry aside and checks it first; new links and copies never overwrite. - A copy's record is written before the copy moves and holds both digests while a refresh is in flight, so a crash can't orphan it, and overlapping starts for one profile take turns. --- .../antigravity/AntigravityFileReads.ts | 64 +++ .../antigravity/AntigravityProfile.ts | 6 +- .../antigravity/AntigravityUserConfig.test.ts | 156 ++++++ .../antigravity/AntigravityUserConfig.ts | 500 +++++++++++++----- 4 files changed, 606 insertions(+), 120 deletions(-) create mode 100644 apps/server/src/provider/antigravity/AntigravityFileReads.ts 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 1c901a164..0f22e2523 100644 --- a/apps/server/src/provider/antigravity/AntigravityProfile.ts +++ b/apps/server/src/provider/antigravity/AntigravityProfile.ts @@ -13,7 +13,7 @@ */ 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"; @@ -43,6 +43,9 @@ 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_APP_DATA_DIR); @@ -361,6 +364,7 @@ export const prepareAntigravityProfile = ( profileDir, userHome: user.userHome, platform: user.platform, + threadlinesDir: antigravityStateDirOf(profileDir), }), ), ); diff --git a/apps/server/src/provider/antigravity/AntigravityUserConfig.test.ts b/apps/server/src/provider/antigravity/AntigravityUserConfig.test.ts index a6eab71b4..94bb63b9f 100644 --- a/apps/server/src/provider/antigravity/AntigravityUserConfig.test.ts +++ b/apps/server/src/provider/antigravity/AntigravityUserConfig.test.ts @@ -1,4 +1,6 @@ // @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"; @@ -16,6 +18,7 @@ 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, @@ -209,6 +212,159 @@ describe("shareAntigravityUserConfigNow on Windows", () => { }); }); +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"); diff --git a/apps/server/src/provider/antigravity/AntigravityUserConfig.ts b/apps/server/src/provider/antigravity/AntigravityUserConfig.ts index 0de1a3060..5c4653a3b 100644 --- a/apps/server/src/provider/antigravity/AntigravityUserConfig.ts +++ b/apps/server/src/provider/antigravity/AntigravityUserConfig.ts @@ -7,22 +7,41 @@ * 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. Credentials, hooks, plugins and the user's - * MCP config are never brought in. + * 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. * - * Runs before every agent start, so a source that appears later is picked - * up then, and one that goes away takes its link with it (a dangling link - * would stop the agent creating the folder itself). A link or copy is only - * replaced or removed when Threadlines made it: a real file or a non-empty - * folder the agent wrote stays as it is. + * 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 { dirname, join, resolve } from "node:path"; +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 @@ -38,12 +57,7 @@ export const ANTIGRAVITY_SHARED_DIRS = [ "config/rules", ] as const; -/** - * Global rule files and the skill and rule manifests, relative to - * `GEMINI_HOME`. Left out on purpose: `config/hooks.json`, - * `config/mcp_config.json`, `config/plugins` and `plugins.json` (plugins - * carry MCP servers and hooks), `config/agents.json`, and every sign-in file. - */ +/** Global rule files and the skill and rule manifests, relative to `GEMINI_HOME`. */ export const ANTIGRAVITY_SHARED_FILES = [ "AGENTS.md", "GEMINI.md", @@ -53,40 +67,82 @@ export const ANTIGRAVITY_SHARED_FILES = [ "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 what was written. */ - copies: 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>; } -const recordPath = (profileDir: string) => join(profileDir, "threadlines-shared-config.json"); +/** 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`; -const stringRecord = (raw: unknown): Record => { - if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return {}; - return Object.fromEntries( - Object.entries(raw).filter((entry): entry is [string, string] => typeof entry[1] === "string"), - ); -}; +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 fs.readFile(recordPath(profileDir), "utf8").catch(() => undefined); + const raw = await readRegularFile(antigravitySharedConfigRecordPath(profileDir), { + maxBytes: MAX_RECORD_BYTES, + followLink: false, + }); try { - const parsed = raw === undefined ? undefined : (JSON.parse(raw) as Partial); - return { links: stringRecord(parsed?.links), copies: stringRecord(parsed?.copies) }; + return parseRecord(raw === undefined ? undefined : JSON.parse(raw.toString("utf8"))); } catch { return { links: {}, copies: {} }; } } async function writeRecord(profileDir: string, record: SharedConfigRecord): Promise { - const target = recordPath(profileDir); + const target = antigravitySharedConfigRecordPath(profileDir); const temp = `${target}.${randomBytes(4).toString("hex")}.tmp`; - await fs.writeFile(temp, JSON.stringify(record)); + await fs.writeFile(temp, JSON.stringify(record), { mode: 0o600, flag: "wx" }); await fs.rename(temp, target); } @@ -115,154 +171,355 @@ export const antigravityUserGeminiDir = (userHome: string) => join(userHome, ".g type EntryKind = "dir" | "file"; -const sourceIs = async (path: string, kind: EntryKind) => { - const stat = await fs.stat(path).catch(() => undefined); - return kind === "dir" ? stat?.isDirectory() === true : stat?.isFile() === true; +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); + } +} + /** - * Links one shared folder or file. Returns the target to record when the - * link is Threadlines', or undefined when there is none (or it isn't ours). + * 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 shareByLink(input: { - readonly link: string; - readonly target: string; +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 recorded: string | undefined; -}): Promise { - const { link, target, kind } = input; - const present = await sourceIs(target, kind); - const stat = await fs.lstat(link).catch(() => undefined); + 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(link); - if (current === target && present) return target; - // Another target (the home moved) or a source that went away: replaced - // or removed only when Threadlines made it. - if (current !== target && current !== input.recorded) return undefined; - await fs.rm(link, { force: true }); + 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()) { - if (!present || kind !== "dir") return undefined; + 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(link).then( + const removed = await fs.rmdir(path).then( () => true, () => false, ); - if (!removed) return undefined; + if (!removed) return; } else if (stat) { // A real file the agent or the user put there. - return undefined; + delete record.links[rel]; + return; } - if (!present) return undefined; - await fs.mkdir(dirname(link), { recursive: true, mode: 0o700 }); - const type = kind === "file" ? "file" : input.platform === "win32" ? "junction" : "dir"; + 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 { - await fs.symlink(target, link, type); + // Fails on an existing entry instead of replacing it. + await fs.symlink(source, path, type); } catch (error) { - // Another start of the same instance linked it first. - if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error; - if ((await linkTarget(link).catch(() => undefined)) !== target) throw error; + if (codeOf(error) === "EEXIST" && (await linkTarget(path).catch(() => undefined)) === source) { + return; + } + delete record.links[rel]; + throw error; } - return target; } const sha256 = (content: Buffer) => createHash("sha256").update(content).digest("hex"); -const readSmallFile = async (path: string) => { - const stat = await fs.stat(path).catch(() => undefined); - if (!stat?.isFile() || stat.size > MAX_COPY_BYTES) return undefined; - return fs.readFile(path).catch(() => undefined); -}; +const readCopy = (path: string) => + readRegularFile(path, { maxBytes: MAX_COPY_BYTES, followLink: false }); /** - * Copies one shared file (Windows, where a file link needs elevation). - * Returns the hash to record when the copy is Threadlines', or undefined. + * 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(input: { - readonly copy: string; - readonly source: string; - readonly recorded: string | undefined; -}): Promise { - const stat = await fs.lstat(input.copy).catch(() => undefined); - const current = stat?.isFile() ? await fs.readFile(input.copy) : undefined; - // Anything else there, or a copy changed since Threadlines wrote it, is - // the agent's or the user's own. - if (stat && (current === undefined || sha256(current) !== input.recorded)) return undefined; - const source = await readSmallFile(input.source); +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 (current !== undefined) await fs.rm(input.copy, { force: true }); - return undefined; + if (stat) await removeIfOurs(path, isOurs); + delete record.copies[rel]; + return; } const hash = sha256(source); - if (current !== undefined && sha256(current) === hash) return hash; - await fs.mkdir(dirname(input.copy), { recursive: true, mode: 0o700 }); - const temp = `${input.copy}.${randomBytes(4).toString("hex")}.tmp`; - await fs.writeFile(temp, source, { mode: 0o600 }); - await fs.rename(temp, input.copy); - return hash; + 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. */ -export async function shareAntigravityUserConfigNow( +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 after: SharedConfigRecord = { links: {}, copies: {} }; + 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 inProfile = join(input.profileDir, ...rel.split("/")); - const source = join(userGemini, ...rel.split("/")); + const path = join(input.profileDir, ...rel.split("/")); try { - if (kind === "file" && input.platform === "win32") { - const hash = await shareByCopy({ copy: inProfile, source, recorded: before.copies[rel] }); - if (hash) after.copies[rel] = hash; - } else { - const target = await shareByLink({ - link: inProfile, - target: source, - kind, - platform: input.platform, - recorded: before.links[rel], - }); - if (target) after.links[rel] = target; + 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: inProfile, error: String(error) }); - // Still Threadlines' when it fails to change: keep the record so the - // next start can try again. - if (before.links[rel]) after.links[rel] = before.links[rel]; - if (before.copies[rel]) after.copies[rel] = before.copies[rel]; + problems.push({ path, error: String(error) }); } } - if (JSON.stringify(before) !== JSON.stringify(after)) { - await writeRecord(input.profileDir, after).catch((error: unknown) => - problems.push({ path: recordPath(input.profileDir), 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: a rule or - * skill that can't be brought in is logged, and the agent starts without it. + * `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(() => @@ -270,11 +527,16 @@ export const shareAntigravityUserConfig = (input: ShareAntigravityUserConfigInpu { path: input.profileDir, error: String(error) }, ]), ).pipe( - Effect.flatMap((problems) => - problems.length === 0 - ? Effect.void - : Effect.logWarning("Some of the user's Antigravity rules or skills are not shared.", { - problems, - }), + 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, + }), ), ); From f1e14c32a8c39e706ec2984e71ee7707d0f40817 Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Mon, 23 Nov 2026 03:22:17 -0500 Subject: [PATCH 24/59] fix(antigravity): the skill list reads what the agent sees, within hard limits Review fixes for the skills lister: - Global skills are read through the instance's profile after it is prepared, so the list matches what the agent loads (its own profile skills, and on Windows the copied skills.json resolving beside the copy). - Every directory entry is read one at a time and charged, as is every lookup, the plugin pass and its settings file; the scan stops at a deadline, and the lister keeps the last complete list when one is cut short. - Project roots and manifest folders are checked against the repository boundary before they are listed or opened, so a linked project skill from outside is never read. - Manifest filters apply to a skill folder named directly, as to its SKILL.md. - Descriptions are cut to 1,024 characters without splitting a character, and names over 256 characters are left out. --- .../src/provider/acp/AntigravityAcpSupport.ts | 16 +- .../antigravity/AntigravitySkills.test.ts | 142 +++++++- .../provider/antigravity/AntigravitySkills.ts | 342 +++++++++++------- 3 files changed, 366 insertions(+), 134 deletions(-) diff --git a/apps/server/src/provider/acp/AntigravityAcpSupport.ts b/apps/server/src/provider/acp/AntigravityAcpSupport.ts index 905f6a689..d262c1ce3 100644 --- a/apps/server/src/provider/acp/AntigravityAcpSupport.ts +++ b/apps/server/src/provider/acp/AntigravityAcpSupport.ts @@ -74,7 +74,7 @@ import { writeAntigravityAgentRefusal, writeAntigravityCatalog, } from "../antigravity/AntigravityProfile.ts"; -import { listAntigravitySkills } from "../antigravity/AntigravitySkills.ts"; +import { makeAntigravitySkillsLister } from "../antigravity/AntigravitySkills.ts"; import { antigravityUserHome } from "../antigravity/AntigravityUserConfig.ts"; import { holdLaunchGate, type LaunchGate } from "../managedRuntime/LaunchGate.ts"; import { @@ -652,6 +652,7 @@ export function makeAntigravityDescriptor( ): AcpProviderDescriptor { 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); @@ -954,12 +955,17 @@ export function makeAntigravityDescriptor( } 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) => - listAntigravitySkills({ - cwd: input.skillsCwd ?? process.cwd(), + prepareAntigravityProfile(paths.profileDir, { userHome: userHomeFor(environment), - profileDir: paths.profileDir, - }), + 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 diff --git a/apps/server/src/provider/antigravity/AntigravitySkills.test.ts b/apps/server/src/provider/antigravity/AntigravitySkills.test.ts index 49662d540..710800bd2 100644 --- a/apps/server/src/provider/antigravity/AntigravitySkills.test.ts +++ b/apps/server/src/provider/antigravity/AntigravitySkills.test.ts @@ -4,8 +4,24 @@ 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 } from "./AntigravitySkills.ts"; +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 = []; @@ -235,4 +251,128 @@ describe("listAntigravitySkillsNow", () => { 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 index 2a56b8046..53188ac80 100644 --- a/apps/server/src/provider/antigravity/AntigravitySkills.ts +++ b/apps/server/src/provider/antigravity/AntigravitySkills.ts @@ -3,31 +3,39 @@ * folder, read from disk the way the CLI finds them, for the provider * snapshot's `skills`. * - * 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): + * 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. `~/.gemini/config/skills` + * 1. `/config/skills` * 2. `/.gemini/skills` - * 3. `~/.gemini/antigravity-cli/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 `~/.gemini/config/skills.json`. A project + * 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 instance's own profile + * 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) and may be null, a nested item loads only - * when `include_only` names it (`category/my-skill`), `~` is not expanded, - * and a project manifest - * only reaches inside the project or its repository root. + * 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. * - * The scan reads front matter only and has a size and entry budget, so a - * huge skills folder can't stall a status check; past the budget it stops - * and lists what it found. + * 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 */ @@ -36,17 +44,24 @@ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "nod 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 { antigravityUserGeminiDir } from "./AntigravityUserConfig.ts"; +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({ @@ -83,6 +98,9 @@ const decodePluginSettings = Schema.decodeUnknownOption( 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>; @@ -117,17 +135,15 @@ const byEscapedPath = (left: string, right: string) => { const isInside = (root: string, path: string) => { const rel = relative(root, path); - return rel === "" || (!rel.startsWith(`..${sep}`) && rel !== ".." && !isAbsolute(rel)); + return rel === "" || (!isAbsolute(rel) && rel !== ".." && !rel.startsWith(`..${sep}`)); }; -const statOf = (path: string) => fs.stat(path).catch(() => undefined); - -/** The nearest folder at or above `cwd` holding `.git`, or `cwd` when there is none. */ -async function repositoryRoot(cwd: string): Promise { - for (let dir = cwd; ; dir = dirname(dir)) { - if (await fs.lstat(join(dir, ".git")).catch(() => undefined)) return dir; - if (dirname(dir) === dir) return cwd; - } +/** 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). */ @@ -141,12 +157,19 @@ function frontMatterOf(text: string): string | undefined { class SkillScan { private remainingBytes = MAX_SCAN_BYTES; private remainingEntries = MAX_SCAN_ENTRIES; - /** Set once the budget runs out; the scan stops and keeps what it found. */ + /** Set once the budget or the time runs out; the scan stops and keeps what it found. */ exhausted = false; readonly skills = new Map(); - private spendEntries(count: number) { - if (count > this.remainingEntries) { + 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; } @@ -154,17 +177,37 @@ class SkillScan { return true; } - private async readDir(dir: string) { - const names = await fs.readdir(dir).catch(() => undefined); - if (names === undefined || this.exhausted) return undefined; - return this.spendEntries(names.length) ? names : undefined; + 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 handle = await fs.open(path, "r").catch(() => undefined); - if (!handle) return undefined; + const opened = await openRegularFile(path, { followLink: true }); + if (!opened) return undefined; try { const chunks: Array = []; let total = 0; @@ -172,7 +215,7 @@ class SkillScan { let dashes = 0; while (total <= limit) { const buffer = Buffer.alloc(READ_CHUNK_BYTES); - const { bytesRead } = await handle.read(buffer, 0, READ_CHUNK_BYTES, total); + 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) { @@ -195,8 +238,25 @@ class SkillScan { } return Buffer.concat(chunks).toString("utf8"); } finally { - await handle.close(); + 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. */ @@ -209,11 +269,17 @@ class SkillScan { // 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() || this.skills.has(name)) return; - const description = parsed.value.description?.trim(); + 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, - path: skillFile, + // 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 } : {}), @@ -226,26 +292,26 @@ class SkillScan { const found = listed?.toSorted().find((name) => name.toLowerCase() === "skill.md"); if (found === undefined) return undefined; const path = join(dir, found); - return (await statOf(path))?.isFile() ? path : undefined; + return (await this.stat(path))?.isFile() ? path : undefined; } /** - * A skills folder: a skill itself when it holds a `SKILL.md`, otherwise - * each folder directly inside it (the ones `filter` lets through) plus - * nested items `include_only` names. + * 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 = NO_FILTER, - accept?: (path: string) => Promise, - ) { - if (this.exhausted || !(await statOf(dir))?.isDirectory()) return; + 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 (!accept || (await accept(own))) await this.addSkill(own, scope); + if (passesFilter(basename(dir), filter) && (!confine || (await confine(own)))) { + await this.addSkill(own, scope); + } return; } const nested = filter.includeGroups @@ -257,43 +323,36 @@ class SkillScan { for (const name of candidates) { if (this.exhausted) return; const child = join(dir, ...name.split("/")); - if (!(await statOf(child))?.isDirectory()) continue; + if (confine && !(await confine(child))) continue; + if (!(await this.stat(child))?.isDirectory()) continue; const skillFile = await this.skillFileIn(child); - if (skillFile && (!accept || (await accept(skillFile)))) { + 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, - accept?: (path: string) => Promise, - ) { - const stat = await statOf(path); + 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 (!this.spendEntries(1)) return; if (basename(path).toLowerCase() !== "skill.md") return; if (!passesFilter(basename(dirname(path)), filter)) return; - if (!accept || (await accept(path))) await this.addSkill(path, scope); + await this.addSkill(path, scope); return; } - await this.scanFolder(path, scope, filter, accept); + await this.scanFolder(path, scope, filter, confine); } - /** - * A `skills.json`: its `inherits` first, then its `entries`. `accept` - * confines a project manifest to the project. - */ + /** 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 accept?: (path: string) => Promise; + readonly confine?: Confine; readonly visited?: ReadonlySet; readonly depth?: number; }): Promise { @@ -301,16 +360,9 @@ class SkillScan { const visited = input.visited ?? new Set(); const path = resolve(input.path); if (this.exhausted || depth > MAX_INHERIT_DEPTH || visited.has(path)) return; - const stat = await statOf(path); - if (!stat?.isFile()) return; - if (input.accept && !(await input.accept(path))) return; - if (stat.size > Math.min(MAX_SKILL_BYTES, this.remainingBytes)) { - this.exhausted = true; - return; - } - const raw = await fs.readFile(path, "utf8").catch(() => undefined); + if (input.confine && !(await input.confine(path))) return; + const raw = await this.readSmall(path); if (raw === undefined) return; - this.remainingBytes -= Buffer.byteLength(raw, "utf8"); const manifest = decodeManifest(raw); if (Option.isNone(manifest)) return; const baseDir = input.baseDir ?? dirname(path); @@ -323,58 +375,91 @@ class SkillScan { path: resolveEntry(inherited.path), scope: input.scope, filter: narrowFilter(input.filter, inherited), - ...(input.accept ? { accept: input.accept } : {}), + ...(input.confine ? { confine: input.confine } : {}), visited: nextVisited, depth: depth + 1, }); } for (const entry of manifest.value.entries ?? []) { if (this.exhausted) return; - const entryPath = resolveEntry(entry.path); - if (input.accept && !(await input.accept(entryPath))) continue; - await this.scanEntry(entryPath, input.scope, narrowFilter(input.filter, entry), input.accept); + 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 user's home, whose `.gemini` holds their global skills (`antigravityUserHome`). */ - readonly userHome: string; - /** The instance's profile (`GEMINI_HOME`), where plugins it installed live. */ + /** The instance's profile (`GEMINI_HOME`), already prepared (`prepareAntigravityProfile`). */ readonly profileDir: string; } export interface AntigravitySkillListing { readonly skills: ReadonlyArray; - /** The scan hit its budget, so the list may be missing skills. */ + /** 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 userGemini = antigravityUserGeminiDir(input.userHome); - const scan = new SkillScan(); + 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(userGemini, "config", "skills"), "user"], + [join(profile, "config", "skills"), "user"], [join(cwd, ".gemini", "skills"), "project"], - [join(userGemini, "antigravity-cli", "skills"), "user"], + [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); - - // Project manifests load from inside the project or its repository root - // only: entries leaving it by an absolute path, `..` or a link are skipped. - const root = await repositoryRoot(cwd); - const realRoot = await fs.realpath(root).catch(() => root); - const insideProject = async (path: string) => - isInside(realRoot, await fs.realpath(path).catch(() => resolve(path))); + 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({ @@ -382,29 +467,17 @@ export async function listAntigravitySkillsNow( baseDir: dir, scope: "project", filter: NO_FILTER, - accept: insideProject, + confine: insideProject, }); } - if (dir === root || dirname(dir) === dir) break; + if (dir === root || dirname(dir) === dir || scan.exhausted) break; } await scan.scanManifest({ - path: join(userGemini, "config", "skills.json"), + path: join(profile, "config", "skills.json"), scope: "user", filter: NO_FILTER, }); - - const pluginsDir = join(input.profileDir, "config", "plugins"); - const plugins = await fs.readdir(pluginsDir).catch(() => [] as Array); - if (plugins.length > 0) { - const settings = await fs - .readFile(join(input.profileDir, "config", "config.json"), "utf8") - .then(decodePluginSettings, () => Option.none()); - const pluginStates = Option.isSome(settings) ? (settings.value.plugins ?? {}) : {}; - for (const plugin of plugins.toSorted()) { - if (pluginStates[plugin]?.enabled === false) continue; - await scan.scanFolder(join(pluginsDir, plugin, "skills"), "user"); - } - } + await scan.scanPlugins(profile); return { skills: [...scan.skills.values()].toSorted((left, right) => @@ -414,20 +487,33 @@ export async function listAntigravitySkillsNow( }; } -/** `listAntigravitySkillsNow` as an effect that never fails; a cut-short scan is logged. */ -export const listAntigravitySkills = (input: ListAntigravitySkillsInput) => - Effect.promise(() => - listAntigravitySkillsNow(input).catch((): AntigravitySkillListing => ({ - skills: [], - truncated: true, - })), - ).pipe( - Effect.tap((listing) => - listing.truncated - ? Effect.logWarning("Antigravity's skill list stopped at its scan limit.", { - cwd: input.cwd, - }) - : Effect.void, - ), - Effect.map((listing) => listing.skills), - ); +/** + * 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 ?? [])); + }), + ); + }; +} From 92f56b118043ac40f57e0aa04bc4574b871bb3f7 Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Mon, 23 Nov 2026 03:22:17 -0500 Subject: [PATCH 25/59] docs(antigravity): linked rules, what writes through shared folders, and the skill list's limits --- docs/providers/antigravity.md | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/docs/providers/antigravity.md b/docs/providers/antigravity.md index a6ddda46b..0f515ada2 100644 --- a/docs/providers/antigravity.md +++ b/docs/providers/antigravity.md @@ -73,19 +73,32 @@ is left alone from then on. Something you add later is picked up at the next sta 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. When two have the same name, the first wins in this order: +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. Skills of plugins installed in that account's profile are -listed unless the plugin is turned off. The list is read from the folder Threadlines runs in, like +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`). From 2eea6808d761c943e96c352d769859868e02bcdc Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Mon, 23 Nov 2026 03:22:21 -0500 Subject: [PATCH 26/59] fix(antigravity): held turns, steering and usage hold up under races, exits and restarts Fixes from an outside review of the turn lifecycle: - A prompt settles under the turn lock when steering sends prompts, so a steer lands before the settle (and supersedes it) or after (and finds the turn over or held); each prompt has its own event barrier, released at once when superseded, so a newer prompt's permission request is never stuck. - A send no longer holds the turn lock while it waits for the running prompt, and Stop arms its recycle deadline before it takes the lock: a stuck agent is restarted even with a message waiting. - Tool updates the runtime holds back (a timer's call that never changes) still reach the held-turn count, so a scheduled wake holds its turn. - An agent that exits while a turn is held fails that turn and stops the session, instead of leaving it working. - Each prompt's tokens are written to the ledger as it answers (a steered prompt under an id of its own), so a hold, a stop or a restart loses none, and they are dated when spent. - Each subagent's report frees one subagent, a reply a finished command woke frees none, and a report without its usage update counts after the reply quiet limit. - The CLI's cancellation notice is dropped in the session runtime, before it can start a message (and with it a turn of its own). - Sessions the agent can't continue are kept on disk per instance, so a restart before the next message still starts fresh. - Each prompt reads its outcome from where the session log stood when it went out, so a steer never inherits an older prompt's error. - Before a known Gemini price change, the built-in price history beats the fetched table's current rate. --- apps/server/scripts/antigravity-mock-agent.ts | 109 ++- apps/server/src/provider/acp/AcpAdapter.ts | 713 +++++++++++------- .../src/provider/acp/AcpProviderDescriptor.ts | 6 + .../src/provider/acp/AcpProviderRuntime.ts | 4 + .../src/provider/acp/AcpSessionRuntime.ts | 43 +- .../antigravity/AntigravityTurns.test.ts | 242 +++++- apps/server/src/usage/usagePricing.test.ts | 14 + apps/server/src/usage/usagePricing.ts | 16 +- 8 files changed, 870 insertions(+), 277 deletions(-) diff --git a/apps/server/scripts/antigravity-mock-agent.ts b/apps/server/scripts/antigravity-mock-agent.ts index 70997fc7f..6e4f0ab71 100644 --- a/apps/server/scripts/antigravity-mock-agent.ts +++ b/apps/server/scripts/antigravity-mock-agent.ts @@ -11,7 +11,19 @@ * - `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. + * - `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 whose reports come 3 seconds apart. + * - `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. * - `subagent`: launches a subagent, ends its prompt, and replies with the * subagent's report later. * - `wake`: ends its prompt with nothing running, then replies by itself. @@ -117,6 +129,11 @@ const program = Effect.gen(function* () { 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); } }), ); @@ -125,12 +142,44 @@ const program = Effect.gen(function* () { Effect.gen(function* () { const sessionId = String(request.sessionId); promptsSeen += 1; - if (scenario === "steer") { + if (scenario === "ignore-cancel") { + yield* say(sessionId, "Thinking hard."); + return yield* Effect.never; + } + 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") { 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); - return { stopReason: "end_turn" as const }; + return { + stopReason: "end_turn" as const, + usage: { inputTokens: 100, outputTokens: 5, totalTokens: 105 }, + }; } yield* Deferred.succeed(secondPrompt, undefined); yield* Effect.sleep("50 millis"); @@ -155,10 +204,62 @@ const program = Effect.gen(function* () { yield* say(sessionId, "API error: the request failed."); return { stopReason: "end_turn" as const }; } - if (scenario === "background" || scenario === "hang") { + 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") { + const launch = (toolCallId: string, Role: string) => + update(sessionId, { + sessionUpdate: "tool_call", + toolCallId, + kind: "other", + title: "Running invoke_subagent", + status: "completed", + rawInput: { Role, Prompt: `Work as ${Role}` }, + }); + yield* launch("call_a", "Researcher"); + if (scenario === "subagents") yield* launch("call_b", "Tester"); + 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 === "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"); diff --git a/apps/server/src/provider/acp/AcpAdapter.ts b/apps/server/src/provider/acp/AcpAdapter.ts index c00a2435a..e9b4aab7d 100644 --- a/apps/server/src/provider/acp/AcpAdapter.ts +++ b/apps/server/src/provider/acp/AcpAdapter.ts @@ -134,6 +134,9 @@ import { import { THREADLINES_ACP_CLIENT_INFO } from "./acpClientInfo.ts"; import { type AcpSessionRuntimeShape } from "./AcpSessionRuntime.ts"; +const decodeLostSessions = Schema.decodeUnknownExit( + Schema.fromJsonString(Schema.Array(Schema.String)), +); const encodeUnknownJsonStringExit = Schema.encodeUnknownExit(Schema.fromJsonString(Schema.Unknown)); const ACP_RESUME_VERSION = 1 as const; @@ -167,6 +170,8 @@ const ACP_HELD_REPLY_QUIET_LIMIT = Duration.minutes(2); const ACP_HISTORY_CURSOR_LIMIT = 200; /** How long asking the agent where a prompt landed may take before it goes unanswered. */ const ACP_HISTORY_POSITION_TIMEOUT = Duration.seconds(5); +/** The most lost agent sessions an instance remembers (`markSessionLost`). */ +const ACP_LOST_SESSIONS_LIMIT = 100; const ACP_PLAN_MODE_ALIASES = ["plan", "architect"]; const ACP_IMPLEMENT_MODE_ALIASES = ["code", "agent", "default", "chat", "implement"]; const ACP_APPROVAL_MODE_ALIASES = ["ask"]; @@ -243,8 +248,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. */ @@ -314,6 +317,8 @@ interface AcpSessionContext { subagentsOut: number; /** A reply the agent started by itself has output and no closing `usage_update` yet. */ replyOpen: boolean; + /** A held command or timer ended since the last reply: the next reply is its wake. */ + workEndedSinceReply: boolean; /** When the agent last sent anything, for a held turn's quiet limits (ms since epoch). */ lastAgentActivityMs: number; stopped: boolean; @@ -337,8 +342,6 @@ interface AcpTurnRun { prompts: number; /** Tokens every answered prompt of the turn reported, added up. */ usage: UsageTokenTotals | null; - /** Reads how the turn's prompts really ended (`promptOutcome`). */ - checkOutcome: AcpPromptOutcomeCheck | undefined; } type AcpPromptOutcomeCheck = Effect.Success>; @@ -707,8 +710,50 @@ export function makeAcpAdapter( /** * Agent sessions that can't go on (`AcpPromptFailure.sessionLost`): a * restart opens a new session instead, seeded with the thread's history. + * Kept on disk per instance, so a server restart before the next message + * doesn't reopen one. */ - const lostSessions = new Set(); + const lostSessionsFile = path.join( + serverConfig.stateDir, + "acp-lost-sessions", + `${encodeURIComponent(boundInstanceId)}.json`, + ); + const lostSessions = new Set( + yield* fileSystem.readFileString(lostSessionsFile).pipe( + Effect.map((raw): ReadonlyArray => { + const parsed = decodeLostSessions(raw); + return Exit.isSuccess(parsed) ? parsed.value : []; + }), + Effect.orElseSucceed((): ReadonlyArray => []), + ), + ); + const saveLostSessions = Effect.gen(function* () { + yield* fileSystem.makeDirectory(path.dirname(lostSessionsFile), { recursive: true }); + yield* fileSystem.writeFileString( + lostSessionsFile, + JSON.stringify([...lostSessions].slice(-ACP_LOST_SESSIONS_LIMIT)), + ); + }).pipe( + Effect.catchCause((cause) => + Effect.logWarning("acp.lost-sessions.save-failed", { + provider: PROVIDER, + cause: Cause.pretty(cause), + }), + ), + ); + const markSessionLost = (sessionId: string) => + Effect.suspend(() => { + lostSessions.add(sessionId); + return saveLostSessions; + }); + const forgetLostSession = (sessionId: string) => + Effect.suspend(() => (lostSessions.delete(sessionId) ? saveLostSessions : Effect.void)); + /** + * A turn that can outlive its prompt or span several (`heldTurns`, + * `steerWithPrompt`) writes each prompt's tokens as it answers. + */ + const recordsEachPrompt = + descriptor.heldTurns !== undefined || descriptor.steerWithPrompt === true; const threadLocksRef = yield* SynchronizedRef.make(new Map()); const runtimeEventPubSub = yield* PubSub.unbounded(); @@ -932,7 +977,6 @@ export function makeAcpAdapter( ctx.lastPlanFingerprint = undefined; ctx.activeTurnText = ""; ctx.lastProviderStatus = undefined; - ctx.cancelledTurnId = undefined; ctx.planMarkdown = undefined; ctx.promptOutcome = undefined; ctx.costTurnOpen = true; @@ -981,6 +1025,27 @@ export function makeAcpAdapter( }); }); + /** Writes down one answered prompt's tokens (`recordsEachPrompt`). */ + const recordPromptUsage = ( + ctx: AcpSessionContext, + run: AcpTurnRun, + promptNumber: number, + totals: UsageTokenTotals, + ) => + Effect.gen(function* () { + const record = options?.recordTurnUsage; + if (!record) return; + yield* record({ + atMs: yield* Clock.currentTimeMillis, + sessionId: ctx.acpSessionId, + // The ledger keeps one line per id: a steer's prompt has its own. + turnId: promptNumber === 1 ? run.turnId : `${run.turnId}:${promptNumber}`, + model: run.resolvedModel ?? ctx.session.model ?? "default", + totals, + costUsd: null, + }); + }); + /** * Opens a turn the agent started itself (`agentTurns`): its wake-up * after background work, opened on the extension's notice (in order with @@ -1137,16 +1202,24 @@ export function makeAcpAdapter( /** * The `usage_update` that ends each model call (`heldTurns`): a reply the - * agent started by itself is over, and with it the report it woke to - * give. Subagents are known to end only by such a report, so one ending - * frees them all: a later subagent's report opens a turn of its own. + * agent started by itself is over. */ const noteReplyEnd = (ctx: AcpSessionContext) => { if (descriptor.heldTurns === undefined) return; ctx.lastAgentActivityMs = Date.now(); - if (!ctx.replyOpen) return; + if (ctx.replyOpen) endReply(ctx); + }; + + /** + * A reply the agent started by itself ended (its `usage_update`, or a + * long quiet). Subagents are known to end only by the report they wake + * the agent to give, so a reply that no finished command or timer woke + * counts as one subagent's report. + */ + const endReply = (ctx: AcpSessionContext) => { ctx.replyOpen = false; - ctx.subagentsOut = 0; + if (ctx.workEndedSinceReply) ctx.workEndedSinceReply = false; + else if (ctx.subagentsOut > 0) ctx.subagentsOut -= 1; }; /** Keeps count of the work a tool call goes on with after its prompt (`heldTurns`). */ @@ -1166,7 +1239,11 @@ export function makeAcpAdapter( return; } if (toolCall.status === "completed" || toolCall.status === "failed") { - ctx.workAfterPrompt.delete(id); + // Outside a prompt, its wake (not a subagent's report) is the reply + // that follows. + if (ctx.workAfterPrompt.delete(id) && ctx.turnRun?.phase === undefined) { + ctx.workEndedSinceReply = true; + } } else { ctx.workAfterPrompt.set(id, kind); } @@ -1177,6 +1254,7 @@ export function makeAcpAdapter( ctx.workAfterPrompt.clear(); ctx.subagentsOut = 0; ctx.replyOpen = false; + ctx.workEndedSinceReply = false; }; /** @@ -1187,20 +1265,21 @@ export function makeAcpAdapter( const closeHeldTurn = ( ctx: AcpSessionContext, held: AcpHeldTurn, - outcome: "completed" | "cancelled", + outcome: "completed" | "cancelled" | { readonly failed: string }, ) => Effect.gen(function* () { if (ctx.held !== held) return; ctx.held = undefined; - if (outcome === "cancelled") clearWorkAfterPrompt(ctx); + if (outcome !== "completed") clearWorkAfterPrompt(ctx); + const ended: AcpTurnOutcome | undefined = + outcome === "cancelled" + ? { state: "cancelled", stopReason: "cancelled" } + : outcome === "completed" + ? undefined + : { state: "failed", errorMessage: outcome.failed }; const completion = held.completion; if (completion === undefined) { - yield* closeAgentTurn( - ctx, - outcome === "cancelled" - ? { state: "cancelled", stopReason: "cancelled" } - : { state: "completed" }, - ); + yield* closeAgentTurn(ctx, ended ?? { state: "completed" }); return; } // The reply the agent started by itself ends with the turn. @@ -1219,9 +1298,13 @@ export function makeAcpAdapter( threadId: ctx.threadId, turnId: held.turnId, payload: - outcome === "cancelled" - ? { state: "cancelled", stopReason: "cancelled" } - : completion.payload, + ended === undefined + ? completion.payload + : { + state: ended.state, + stopReason: ended.stopReason ?? null, + ...(ended.errorMessage !== undefined ? { errorMessage: ended.errorMessage } : {}), + }, }); yield* settleTurnUsage(ctx, held.turnId, completion.model, completion.usage); }); @@ -1237,6 +1320,9 @@ export function makeAcpAdapter( const silentLimitMs = Duration.toMillis( descriptor.heldTurns?.silentLimit ?? ACP_AGENT_TURN_QUIET_LIMIT, ); + const replyQuietMs = Duration.toMillis( + descriptor.heldTurns?.replyQuietLimit ?? ACP_HELD_REPLY_QUIET_LIMIT, + ); while (ctx.held === held && !ctx.stopped) { yield* Effect.sleep(ACP_HELD_TURN_CHECK); if (ctx.held !== held) return; @@ -1246,9 +1332,7 @@ export function makeAcpAdapter( continue; } const quietMs = now - ctx.lastAgentActivityMs; - if (ctx.replyOpen && quietMs >= Duration.toMillis(ACP_HELD_REPLY_QUIET_LIMIT)) { - ctx.replyOpen = false; - } + if (ctx.replyOpen && quietMs >= replyQuietMs) endReply(ctx); const work = [...ctx.workAfterPrompt.values()]; const waiting = work.length > 0 || ctx.subagentsOut > 0 || ctx.replyOpen; const settled = !waiting && quietMs >= Duration.toMillis(ACP_HELD_TURN_SETTLE); @@ -1302,7 +1386,10 @@ export function makeAcpAdapter( return Effect.succeed(ctx); }; - const stopSessionInternal = (ctx: AcpSessionContext) => + const stopSessionInternal = ( + ctx: AcpSessionContext, + exitKind: "graceful" | "error" = "graceful", + ) => Effect.gen(function* () { if (ctx.stopped) return; ctx.stopped = true; @@ -1322,10 +1409,36 @@ export function makeAcpAdapter( ...(yield* makeEventStamp()), provider: PROVIDER, threadId: ctx.threadId, - payload: { exitKind: "graceful" }, + payload: { exitKind }, }); }); + /** + * The agent process ended by itself (`heldTurns`). A prompt in flight + * fails on its own and settles first; a turn held open for the agent's + * work has no request left to fail, so it ends failed here. The session + * stops, and the next message starts the agent again. + */ + const onAgentExited = (ctx: AcpSessionContext) => + Effect.gen(function* () { + yield* awaitPrompt(ctx).pipe(Effect.timeoutOption(ACP_CANCEL_DEADLINE)); + yield* ctx.turnStartLock.withPermit( + Effect.suspend(() => + ctx.held === undefined || ctx.stopped + ? Effect.void + : closeHeldTurn(ctx, ctx.held, { + failed: `${descriptor.presentation.displayName} stopped before its work finished.`, + }), + ), + ); + yield* withThreadLock( + ctx.threadId, + Effect.suspend(() => + sessions.get(ctx.threadId) === ctx ? stopSessionInternal(ctx, "error") : Effect.void, + ), + ); + }); + /** * Tells the descriptor when the agent answered `auth_required`, given the * ACP error or the adapter error that wraps it. Never fails or dies: a @@ -1653,6 +1766,7 @@ export function makeAcpAdapter( mcpServers, runtimeMode: input.runtimeMode, ...(descriptor.agentTurns ? { liveOutsidePrompt: true } : {}), + ...(descriptor.heldTurns ? { trackSilentToolCalls: true } : {}), ...acpNativeLoggers, }).pipe( Effect.provideService(Scope.Scope, sessionScope), @@ -2013,7 +2127,7 @@ export function makeAcpAdapter( (lostSession !== undefined ? `${descriptor.presentation.displayName} can no longer continue its earlier conversation.` : undefined); - if (lostSession !== undefined) lostSessions.delete(lostSession); + if (lostSession !== undefined) yield* forgetLostSession(lostSession); // A resumed conversation keeps the turn history its cursor carried. const keepsHistory = resumed !== undefined && @@ -2088,7 +2202,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.) @@ -2116,6 +2229,7 @@ export function makeAcpAdapter( subagentLaunches: new Set(), subagentsOut: 0, replyOpen: false, + workEndedSinceReply: false, lastAgentActivityMs: 0, stopped: false, }; @@ -2185,6 +2299,14 @@ export function makeAcpAdapter( return; case "ModeChanged": return; + case "ToolCallTracked": + // A held turn counts work whose updates show nothing new + // (a timer's "Running schedule" stays as it started). + if (descriptor.heldTurns !== undefined) { + ctx.lastAgentActivityMs = Date.now(); + trackWorkAfterPrompt(ctx, event.toolCall); + } + return; case "ReasoningDelta": yield* logNative(ctx.threadId, "session/update", event.rawPayload); yield* turnForOutput(ctx); @@ -2262,16 +2384,6 @@ export function makeAcpAdapter( return; } case "ContentDelta": - if ( - descriptor.cancellationNotice !== undefined && - ctx.cancelledTurnId !== undefined && - // A held turn stopped already: the notice would open another. - (ctx.cancelledTurnId === ctx.activeTurnId || - (descriptor.heldTurns !== undefined && ctx.activeTurnId === undefined)) && - event.text.trim() === descriptor.cancellationNotice - ) { - return; - } yield* turnForOutput(ctx); yield* closeReasoning(ctx); if (ctx.activeTurnText.length < PLAN_GATE_SCAN_MAX_CHARS) { @@ -2300,6 +2412,20 @@ export function makeAcpAdapter( ctx.notificationFiber = notificationFiber; sessions.set(input.threadId, ctx); + // Held turns wait on no request the exit would fail (`onAgentExited`). + if (descriptor.heldTurns !== undefined && acp.process !== undefined) { + const session = ctx; + yield* acp.process.exited.pipe( + Effect.andThen( + Effect.suspend(() => + session.stopped + ? Effect.void + : onAgentExited(session).pipe(Effect.forkIn(adapterScope), Effect.asVoid), + ), + ), + Effect.forkIn(sessionScope), + ); + } sessionScopeTransferred = true; recordHistory(ctx); @@ -2405,21 +2531,56 @@ export function makeAcpAdapter( // 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)), + Effect.gen(function* () { + // ACP serializes prompts per session; a turn sent while one is in + // flight starts after it, never interleaved with it (nor with a + // prompt a steer sent meanwhile). The wait is outside the lock: a + // Stop or a settling prompt that needs the lock must not queue + // behind a send that waits on them. + while (true) { + const awaited = yield* awaitPrompt(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. One that lost the race waits for the winner's. + const started = yield* ctx.turnStartLock.withPermit( + Effect.suspend(() => + ctx.promptFiber === awaited ? startTurn(ctx, input) : Effect.succeed(undefined), + ), + ); + if (started !== undefined) return started; + } + }), ); - const startTurn = (ctx: AcpSessionContext, input: Parameters[0]) => + /** Waits for the newest prompt (a steer may send another meanwhile); returns its fiber. */ + const awaitPrompt = (ctx: AcpSessionContext) => Effect.gen(function* () { - // ACP serializes prompts per session; a turn sent while one is in - // flight starts after it, never interleaved with it (nor with a prompt - // a steer sent meanwhile). while (ctx.promptFiber !== undefined) { const promptFiber = ctx.promptFiber; yield* Fiber.await(promptFiber); - if (ctx.promptFiber === promptFiber) break; + if (ctx.promptFiber === promptFiber) return promptFiber; + } + return undefined; + }); + + /** Waits for the turn's prompts: this one, and any a steer sent after it for the same turn. */ + const awaitTurnPrompts = ( + ctx: AcpSessionContext, + turnId: TurnId, + first: NonNullable, + ) => + Effect.gen(function* () { + let promptFiber = first; + while (true) { + yield* Fiber.await(promptFiber); + const next = ctx.promptFiber; + if (next === undefined || next === promptFiber || ctx.turnRun?.turnId !== turnId) return; + promptFiber = next; } + }); + + const startTurn = (ctx: AcpSessionContext, input: Parameters[0]) => + Effect.gen(function* () { // 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(); @@ -2502,7 +2663,6 @@ export function makeAcpAdapter( ), ); } - const checkOutcome = yield* watchPromptOutcome(ctx); ctx.activeTurnId = turnId; const run: AcpTurnRun = { turnId, @@ -2515,7 +2675,6 @@ export function makeAcpAdapter( phase: undefined, prompts: 0, usage: null, - checkOutcome, }; ctx.turnRun = run; yield* openPromptPhase(ctx, run); @@ -2566,12 +2725,12 @@ export function makeAcpAdapter( /** The turn's prompts' answer as the agent's own words tell it (`promptOutcome`). */ const checkPromptOutcome = ( - run: AcpTurnRun, + checkOutcome: AcpPromptOutcomeCheck | undefined, answer: Parameters[0], ): Effect.Effect => - run.checkOutcome === undefined + checkOutcome === undefined ? Effect.succeed(undefined) - : run.checkOutcome(answer).pipe( + : checkOutcome(answer).pipe( Effect.catchCause((cause) => Effect.logWarning("acp.prompt-outcome.check-failed", { provider: PROVIDER, @@ -2593,6 +2752,7 @@ export function makeAcpAdapter( ctx.openPrompt = phase; // What the agent did by itself is over: this prompt carries the turn on. ctx.replyOpen = false; + ctx.workEndedSinceReply = false; return phase; }); @@ -2607,228 +2767,261 @@ export function makeAcpAdapter( promptParts: ReadonlyArray, ) => Effect.gen(function* () { + // Each prompt reads its own outcome from where the agent's records + // stand as it goes out, not where the turn's first prompt found them. + const checkOutcome = yield* watchPromptOutcome(ctx); run.prompts += 1; const promptNumber = run.prompts; const phase = yield* openPromptPhase(ctx, run); + const answered = yield* Deferred.make(); ctx.promptFiber = yield* Effect.forkIn( - runTurnPrompt(ctx, run, phase, promptNumber, promptParts), + runTurnPrompt(ctx, run, { phase, answered, promptNumber, promptParts, checkOutcome }), ctx.scope, ); }); + /** + * One prompt of a turn, from its answer to the turn's end. `phase` is the + * turn's open prompt, shared with a steer's; `answered` is this prompt's + * own: the reader holds what follows its answer until it is settled, and + * a superseded prompt releases it at once, so its successor's output (a + * permission request included) is never stuck behind it. + */ const runTurnPrompt = ( ctx: AcpSessionContext, run: AcpTurnRun, - prompt: NonNullable, - promptNumber: number, - promptParts: ReadonlyArray, + input: { + readonly phase: NonNullable; + readonly answered: Deferred.Deferred; + readonly promptNumber: number; + readonly promptParts: ReadonlyArray; + readonly checkOutcome: AcpPromptOutcomeCheck | undefined; + }, ) => { + const { phase: prompt, answered, promptNumber, promptParts, checkOutcome } = input; const turnId = run.turnId; const threadId = ctx.threadId; const { planMode, resolvedModel, promptText, newestBefore } = run; const usageTotals = descriptor.turnUsageTotals ?? acpTurnUsageTotals; /** A newer prompt took the turn over (a steer): this one's answer settles nothing. */ const superseded = () => promptNumber !== run.prompts; + /** + * Settling runs under the turn lock when a steer sends a prompt, so a + * steer lands before the settle starts (and supersedes it) or after + * it ended (and finds the turn over, or held). + */ + const settleLocked = (settle: Effect.Effect) => + descriptor.steerWithPrompt === true ? ctx.turnStartLock.withPermit(settle) : settle; let lostSession = false; - return Effect.gen(function* () { - const promptMeta = descriptor.promptMeta?.(turnId); - const exit = yield* Effect.exit( - ctx.acp.prompt({ - prompt: [...promptParts], - ...(promptMeta ? { _meta: { ...promptMeta } } : {}), - }), - ); - if (Exit.isSuccess(exit)) { - const totals = usageTotals(exit.value.usage); - if (totals !== null) run.usage = addUsageTotals(run.usage, totals); + let finalized = false; + const finalize = Effect.gen(function* () { + if (finalized || superseded()) return; + finalized = true; + if (run.phase === prompt) run.phase = undefined; + if (ctx.held?.turnId !== turnId) { + if (ctx.activeTurnId === turnId) { + ctx.activeTurnId = undefined; + ctx.session = { ...ctx.session, activeTurnId: undefined, updatedAt: yield* nowIso }; + } + if (ctx.turnRun === run) ctx.turnRun = undefined; } - if (superseded()) return; - // Deltas travel through the notification fiber; make sure every one - // queued before the prompt returned is out before the turn closes. - // The reader may be past them already, held at a turn the agent - // began after them (`beginAgentTurnInOrder`). - yield* Effect.raceFirst(ctx.acp.flushEvents(prompt.closed), Deferred.await(prompt.drained)); - // A steer sent while the reader caught up carries the turn on. - if (superseded()) return; - // A turn that ends mid-thought (or on one) still settles its row. - yield* closeReasoning(ctx); - // Where the prompt landed, known before the turn reads as ended, - // so a revert or a stop right after it keeps it. - if (Exit.isSuccess(exit) || !Cause.hasInterruptsOnly(exit.cause)) { - yield* recordPromptPosition(ctx, turnId, promptText, newestBefore); + if (ctx.openPrompt === prompt) ctx.openPrompt = undefined; + yield* Deferred.succeed(prompt.closed, undefined); + // The agent can't go on with this session: it is stopped, and + // the next message opens a new one with the thread's history. + if (lostSession) { + yield* markSessionLost(ctx.acpSessionId); + yield* withThreadLock( + ctx.threadId, + Effect.suspend(() => + sessions.get(ctx.threadId) === ctx ? stopSessionInternal(ctx) : Effect.void, + ), + ).pipe(Effect.forkIn(adapterScope)); } - if (Exit.isSuccess(exit)) { - const result = exit.value; - ctx.turns.push({ id: turnId, items: [{ prompt: promptParts, result }] }); - const planMarkdown = planMode ? ctx.planMarkdown?.trim() : undefined; - if (planMarkdown && result.stopReason !== "cancelled") { + }); + const settle = (exit: Exit.Exit) => + Effect.gen(function* () { + // A turn that ends mid-thought (or on one) still settles its row. + yield* closeReasoning(ctx); + // Where the prompt landed, known before the turn reads as ended, + // so a revert or a stop right after it keeps it. + if (Exit.isSuccess(exit) || !Cause.hasInterruptsOnly(exit.cause)) { + yield* recordPromptPosition(ctx, turnId, promptText, newestBefore); + } + if (Exit.isSuccess(exit)) { + const result = exit.value; + ctx.turns.push({ id: turnId, items: [{ prompt: promptParts, result }] }); + const planMarkdown = planMode ? ctx.planMarkdown?.trim() : undefined; + if (planMarkdown && result.stopReason !== "cancelled") { + yield* offerRuntimeEvent({ + type: "turn.proposed.completed", + ...(yield* makeEventStamp()), + provider: PROVIDER, + threadId, + turnId, + payload: { planMarkdown }, + }); + } + ctx.session = { + ...ctx.session, + updatedAt: yield* nowIso, + ...(resolvedModel !== undefined ? { model: resolvedModel } : {}), + }; + // An agent that ends a turn normally on an upstream error says so + // in its own records (`promptOutcome`). + const hidden = + result.stopReason === "cancelled" + ? undefined + : yield* checkPromptOutcome(checkOutcome, { response: result }); + // 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; + const payload: AcpTurnCompletedPayload = hidden + ? failedTurnPayload(hidden, result.stopReason ?? null) + : 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, + }; + lostSession = hidden?.sessionLost === true; + // The agent goes on with work it started (`heldTurns`): the turn + // stays open, working and stoppable, until that work is done. + if ( + payload.state === "completed" && + descriptor.heldTurns !== undefined && + (ctx.workAfterPrompt.size > 0 || ctx.subagentsOut > 0) + ) { + const held: AcpHeldTurn = { + turnId, + completion: { payload, model: resolvedModel, usage: run.usage }, + }; + ctx.held = held; + ctx.replyOpen = false; + ctx.lastAgentActivityMs = Date.now(); + yield* watchHeldTurn(ctx, held).pipe(Effect.forkIn(ctx.scope)); + return; + } + if (payload.state !== "completed") clearWorkAfterPrompt(ctx); yield* offerRuntimeEvent({ - type: "turn.proposed.completed", + type: "turn.completed", ...(yield* makeEventStamp()), provider: PROVIDER, threadId, turnId, - payload: { planMarkdown }, + payload, }); + yield* settleTurnUsage(ctx, turnId, resolvedModel, run.usage); + return; } - ctx.session = { - ...ctx.session, - updatedAt: yield* nowIso, - ...(resolvedModel !== undefined ? { model: resolvedModel } : {}), - }; - // An agent that ends a turn normally on an upstream error says so - // in its own records (`promptOutcome`). - const hidden = - result.stopReason === "cancelled" - ? undefined - : yield* checkPromptOutcome(run, { response: result }); - // 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; - const payload: AcpTurnCompletedPayload = hidden - ? failedTurnPayload(hidden, result.stopReason ?? null) - : 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, - }; - lostSession = hidden?.sessionLost === true; - // The agent goes on with work it started (`heldTurns`): the turn - // stays open, working and stoppable, until that work is done. - if ( - payload.state === "completed" && - descriptor.heldTurns !== undefined && - (ctx.workAfterPrompt.size > 0 || ctx.subagentsOut > 0) - ) { - const held: AcpHeldTurn = { + if (Cause.hasInterruptsOnly(exit.cause)) { + return; + } + clearWorkAfterPrompt(ctx); + // The agent may never have taken the prompt: the brief goes again. + if (ctx.projectBriefCarrier?.turnId === turnId) requeueProjectBrief(ctx); + const failure = Cause.squash(exit.cause); + yield* notifyAuthRequired(failure); + const reported = yield* checkPromptOutcome(checkOutcome, { error: failure }); + if (reported !== undefined) { + lostSession = reported.sessionLost === true; + yield* offerRuntimeEvent({ + type: "turn.completed", + ...(yield* makeEventStamp()), + provider: PROVIDER, + threadId, turnId, - completion: { payload, model: resolvedModel, usage: run.usage }, - }; - ctx.held = held; - ctx.replyOpen = false; - ctx.lastAgentActivityMs = Date.now(); - yield* watchHeldTurn(ctx, held).pipe(Effect.forkIn(ctx.scope)); + payload: failedTurnPayload(reported, null), + }); + yield* settleTurnUsage(ctx, turnId, resolvedModel, run.usage); return; } - if (payload.state !== "completed") clearWorkAfterPrompt(ctx); - yield* offerRuntimeEvent({ - type: "turn.completed", - ...(yield* makeEventStamp()), - provider: PROVIDER, - threadId, - turnId, - payload, - }); - yield* settleTurnUsage(ctx, turnId, resolvedModel, run.usage); - return; - } - if (Cause.hasInterruptsOnly(exit.cause)) { - return; - } - clearWorkAfterPrompt(ctx); - // The agent may never have taken the prompt: the brief goes again. - if (ctx.projectBriefCarrier?.turnId === turnId) requeueProjectBrief(ctx); - const failure = Cause.squash(exit.cause); - yield* notifyAuthRequired(failure); - const reported = yield* checkPromptOutcome(run, { error: failure }); - if (reported !== undefined) { - lostSession = reported.sessionLost === true; + 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, + threadId, + "session/prompt", + failure as EffectAcpErrors.AcpError, + ).message + : String(failure); yield* offerRuntimeEvent({ type: "turn.completed", ...(yield* makeEventStamp()), provider: PROVIDER, threadId, turnId, - payload: failedTurnPayload(reported, null), + payload: { + state: "failed", + stopReason: isProviderPlanGateMessage(detail) ? "plan_gated" : null, + errorMessage: ctx.lastProviderStatus + ? `${detail} Provider status: ${ctx.lastProviderStatus}` + : detail, + ...withFailureCategory(failureCategory), + }, }); + // No result, so no tokens (but what a steered prompt before it + // reported); a running cost the agent reported still counts. yield* settleTurnUsage(ctx, turnId, resolvedModel, run.usage); - return; + }).pipe(Effect.ensuring(finalize)); + return Effect.gen(function* () { + const promptMeta = descriptor.promptMeta?.(turnId); + const exit = yield* Effect.exit( + ctx.acp.prompt({ + prompt: [...promptParts], + ...(promptMeta ? { _meta: { ...promptMeta } } : {}), + }), + ); + if (Exit.isSuccess(exit)) { + const totals = usageTotals(exit.value.usage); + if (totals !== null) { + // Written as the prompt answers, so a turn held open (or + // stopped, or outlived by a restart) never loses it, and it is + // dated when it was spent. + if (recordsEachPrompt) yield* recordPromptUsage(ctx, run, promptNumber, totals); + else run.usage = addUsageTotals(run.usage, totals); + } } - 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, - threadId, - "session/prompt", - failure as EffectAcpErrors.AcpError, - ).message - : String(failure); - yield* offerRuntimeEvent({ - type: "turn.completed", - ...(yield* makeEventStamp()), - provider: PROVIDER, - threadId, - turnId, - payload: { - state: "failed", - stopReason: isProviderPlanGateMessage(detail) ? "plan_gated" : null, - errorMessage: ctx.lastProviderStatus - ? `${detail} Provider status: ${ctx.lastProviderStatus}` - : detail, - ...withFailureCategory(failureCategory), - }, - }); - // No result, so no tokens (but what a steered prompt before it - // reported); a running cost the agent reported still counts. - yield* settleTurnUsage(ctx, turnId, resolvedModel, run.usage); + if (superseded()) return; + // Deltas travel through the notification fiber; make sure every one + // queued before the prompt returned is out before the turn closes. + // The reader may be past them already, held at a turn the agent + // began after them (`beginAgentTurnInOrder`). + yield* Effect.raceFirst(ctx.acp.flushEvents(answered), Deferred.await(prompt.drained)); + // A steer sent while the reader caught up carries the turn on. + yield* settleLocked(Effect.suspend(() => (superseded() ? Effect.void : settle(exit)))); }).pipe( - Effect.ensuring( - Effect.gen(function* () { - if (superseded()) return; - if (run.phase === prompt) run.phase = undefined; - if (ctx.held?.turnId !== turnId) { - if (ctx.activeTurnId === turnId) { - ctx.activeTurnId = undefined; - ctx.session = { ...ctx.session, activeTurnId: undefined, updatedAt: yield* nowIso }; - } - if (ctx.turnRun === run) ctx.turnRun = undefined; - } - if (ctx.openPrompt === prompt) ctx.openPrompt = undefined; - yield* Deferred.succeed(prompt.closed, undefined); - // The agent can't go on with this session: it is stopped, and - // the next message opens a new one with the thread's history. - if (lostSession) { - lostSessions.add(ctx.acpSessionId); - yield* withThreadLock( - ctx.threadId, - Effect.suspend(() => - sessions.get(ctx.threadId) === ctx ? stopSessionInternal(ctx) : Effect.void, - ), - ).pipe(Effect.forkIn(adapterScope)); - } - }), - ), + Effect.ensuring(finalize.pipe(Effect.andThen(Deferred.succeed(answered, undefined)))), ); }; @@ -2870,7 +3063,6 @@ 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); yield* Effect.ignore( @@ -2880,29 +3072,38 @@ export function makeAcpAdapter( ), ), ); + if (turnId === undefined) return; // A turn waiting on the agent's work (`heldTurns`) has no prompt to - // wait on: the cancel stopped that work, and the turn ends here. - if (descriptor.heldTurns !== undefined && turnId !== undefined) { - const closedHeld = yield* ctx.turnStartLock.withPermit( - Effect.suspend(() => { - const held = ctx.held; - return held?.turnId === turnId - ? closeHeldTurn(ctx, held, "cancelled").pipe(Effect.as(true)) - : Effect.succeed(false); - }), - ); - if (closedHeld) return; - } + // wait on: the cancel stopped that work, and the turn ends here. Taken + // under the turn lock, inside the deadline: a stuck holder of the lock + // must not keep Stop from recycling the agent. + const closeHeld = + descriptor.heldTurns === undefined + ? Effect.succeed(false) + : ctx.turnStartLock.withPermit( + Effect.suspend(() => { + const held = ctx.held; + return held?.turnId === turnId + ? closeHeldTurn(ctx, held, "cancelled").pipe(Effect.as(true)) + : Effect.succeed(false); + }), + ); // The agent's own turn has no prompt to wait on; its end notice // settles it, and the same deadline applies. const agentTurn = ctx.agentTurn?.turnId === turnId ? ctx.agentTurn : undefined; - const settled = + const awaitTurn = agentTurn !== undefined ? Deferred.await(agentTurn.ended) : promptFiber !== undefined - ? Fiber.await(promptFiber).pipe(Effect.asVoid) + ? awaitTurnPrompts(ctx, turnId, promptFiber) : undefined; - if (turnId !== undefined && settled !== undefined) { + const settled = + descriptor.heldTurns === undefined + ? awaitTurn + : closeHeld.pipe( + Effect.flatMap((closed) => (closed ? Effect.void : (awaitTurn ?? Effect.void))), + ); + if (settled !== undefined) { yield* settled.pipe( Effect.timeoutOption(ACP_CANCEL_DEADLINE), Effect.flatMap((outcome) => @@ -3004,7 +3205,6 @@ export function makeAcpAdapter( phase: undefined, prompts: 0, usage: null, - checkOutcome: yield* watchPromptOutcome(ctx), }; ctx.turnRun = run; } @@ -3114,7 +3314,10 @@ export function makeAcpAdapter( }); 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 @@ -3139,11 +3342,13 @@ 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, + }), ); 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), ), diff --git a/apps/server/src/provider/acp/AcpProviderDescriptor.ts b/apps/server/src/provider/acp/AcpProviderDescriptor.ts index 4cd40b756..217ab989f 100644 --- a/apps/server/src/provider/acp/AcpProviderDescriptor.ts +++ b/apps/server/src/provider/acp/AcpProviderDescriptor.ts @@ -201,6 +201,12 @@ export interface AcpHeldTurns { * wake-up 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 may go without output + * before it counts as ended when its closing `usage_update` never comes + * (default 2 minutes). + */ + readonly replyQuietLimit?: Duration.Duration; } /** Runtime hooks handed to a vendor's extension registration. */ diff --git a/apps/server/src/provider/acp/AcpProviderRuntime.ts b/apps/server/src/provider/acp/AcpProviderRuntime.ts index 2d2f24c50..4b11bb735 100644 --- a/apps/server/src/provider/acp/AcpProviderRuntime.ts +++ b/apps/server/src/provider/acp/AcpProviderRuntime.ts @@ -38,6 +38,7 @@ export interface AcpProviderRuntimeInput e AcpSessionRuntimeOptions, | "authMethodId" | "authenticateTimeoutMs" + | "cancellationNotice" | "cancelMeta" | "clientCapabilities" | "contextUsage" @@ -125,6 +126,9 @@ export const makeAcpProviderRuntime = ( ...(descriptor.initializeMeta ? { initializeMeta: descriptor.initializeMeta } : {}), ...(descriptor.cancelMeta ? { cancelMeta: descriptor.cancelMeta } : {}), ...(descriptor.contextUsage ? { contextUsage: descriptor.contextUsage } : {}), + ...(descriptor.cancellationNotice !== undefined + ? { cancellationNotice: descriptor.cancellationNotice } + : {}), ...(descriptor.verifyAgent ? { verifyInitialize: (response: EffectAcpSchema.InitializeResponse) => diff --git a/apps/server/src/provider/acp/AcpSessionRuntime.ts b/apps/server/src/provider/acp/AcpSessionRuntime.ts index 0f15fe67d..59eba6c91 100644 --- a/apps/server/src/provider/acp/AcpSessionRuntime.ts +++ b/apps/server/src/provider/acp/AcpSessionRuntime.ts @@ -150,6 +150,18 @@ export interface AcpSessionRuntimeOptions { * that starts turns of its own), not replayed history to drop. */ readonly liveOutsidePrompt?: boolean; + /** + * 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.heldTurns`). + */ + readonly trackSilentToolCalls?: boolean; + /** + * Text the agent appends when a prompt is cancelled. After a cancel and + * until the next prompt, a reply chunk that is just this text is dropped + * before it starts a message. + */ + readonly cancellationNotice?: string; /** Context fill carried on the agent's own updates (see `AcpProviderDescriptor.contextUsage`). */ readonly contextUsage?: { readonly usedTokens: (notification: EffectAcpSchema.SessionNotification) => number | undefined; @@ -279,6 +291,12 @@ 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; +} + /** Work for the reader to run where it was queued (see `inOrder`). */ export interface AcpSessionInOrderWork { readonly _tag: "InOrder"; @@ -288,7 +306,8 @@ export interface AcpSessionInOrderWork { export type AcpSessionRuntimeEvent = | AcpParsedSessionEvent | AcpSessionEventStreamBarrier - | AcpSessionInOrderWork; + | AcpSessionInOrderWork + | AcpSessionToolCallTracked; /** Upper bound on waiting for the reader; a dead consumer must not wedge a turn. */ const EVENT_FLUSH_TIMEOUT = "5 seconds"; @@ -498,6 +517,8 @@ const makeAcpSessionRuntime = ( // 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); + /** A cancel was sent and no prompt since: the agent's cancellation notice is dropped. */ + const cancelledRef = yield* Ref.make(false); /** Turns the agent started or ended itself so far (`markAgentTurnBoundary`). */ const agentTurnBoundariesRef = yield* Ref.make(0); const liveOutsidePromptRef = yield* Ref.make(false); @@ -538,6 +559,10 @@ const makeAcpSessionRuntime = ( itemIdScope, params: notification, ...(nativeControls ? { configOptionsRef } : {}), + ...(options.trackSilentToolCalls ? { trackSilentToolCalls: true } : {}), + ...(options.cancellationNotice !== undefined + ? { cancellationNotice: { text: options.cancellationNotice, cancelledRef } } + : {}), }); }), ); @@ -976,6 +1001,7 @@ const makeAcpSessionRuntime = ( return Effect.gen(function* () { yield* closeActiveAssistantSegment({ queue: eventQueue, assistantSegmentRef }); const boundariesBefore = yield* Ref.get(agentTurnBoundariesRef); + yield* Ref.set(cancelledRef, false); yield* Ref.update(promptsInFlightRef, (count) => count + 1); const response = yield* runLoggedRequest( "session/prompt", @@ -997,6 +1023,7 @@ const makeAcpSessionRuntime = ( }), ), cancel: getStartedState.pipe( + Effect.tap(() => Ref.set(cancelledRef, true)), Effect.flatMap((started) => acp.agent.cancel({ sessionId: started.sessionId, @@ -1092,6 +1119,8 @@ const handleSessionUpdate = ({ itemIdScope, params, configOptionsRef, + trackSilentToolCalls, + cancellationNotice, }: { readonly queue: Queue.Queue; readonly modeStateRef: Ref.Ref; @@ -1104,6 +1133,8 @@ const handleSessionUpdate = ({ readonly params: EffectAcpSchema.SessionNotification; /** Given for native controls only: the agent's own option updates land here. */ readonly configOptionsRef?: Ref.Ref>; + readonly trackSilentToolCalls?: boolean; + readonly cancellationNotice?: { readonly text: string; readonly cancelledRef: Ref.Ref }; }): Effect.Effect => Effect.gen(function* () { if (configOptionsRef && params.update.sessionUpdate === "config_option_update") { @@ -1149,6 +1180,9 @@ const handleSessionUpdate = ({ return [{ previous, merged: nextToolCall }, next] as const; }); if (!shouldEmitToolCallUpdate(previous, merged)) { + if (trackSilentToolCalls) { + yield* Queue.offer(queue, { _tag: "ToolCallTracked", toolCall: merged }); + } continue; } yield* Queue.offer(queue, { @@ -1159,6 +1193,13 @@ const handleSessionUpdate = ({ continue; } if (event._tag === "ContentDelta") { + if ( + cancellationNotice !== undefined && + event.text.trim() === cancellationNotice.text && + (yield* Ref.get(cancellationNotice.cancelledRef)) + ) { + continue; + } if (event.text.trim().length === 0) { const assistantSegmentState = yield* Ref.get(assistantSegmentRef); if (!assistantSegmentState.activeItemId) { diff --git a/apps/server/src/provider/antigravity/AntigravityTurns.test.ts b/apps/server/src/provider/antigravity/AntigravityTurns.test.ts index 2635e974c..68f4e8055 100644 --- a/apps/server/src/provider/antigravity/AntigravityTurns.test.ts +++ b/apps/server/src/provider/antigravity/AntigravityTurns.test.ts @@ -13,7 +13,11 @@ import { 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"; @@ -61,37 +65,56 @@ async function readFrames(file: string): Promise JSON.parse(line) as Record); } -/** Starts an Antigravity session on the stand-in, collecting every runtime event. */ -const startAgy = (scenario: string) => +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" = "full-access", +) => Effect.gen(function* () { const mock = yield* Effect.promise(() => makeAgyMock(scenario)); - const descriptor = makeAntigravityDescriptor({ + 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 adapter = yield* makeAcpAdapter( - descriptor, - decodeSettings({ enabled: true, binaryPath: mock.wrapper }), - { recordTurnUsage: (entry) => Effect.sync(() => void usage.push(entry)) }, - ); const events: Array = []; - yield* adapter.streamEvents.pipe( - Stream.runForEach((event) => Effect.sync(() => void events.push(event))), - Effect.forkScoped, - ); + const newAdapter = Effect.gen(function* () { + const made = yield* makeAcpAdapter( + descriptor, + decodeSettings({ enabled: true, binaryPath: mock.wrapper }), + { recordTurnUsage: (entry) => Effect.sync(() => void usage.push(entry)) }, + ); + 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: "full-access", + runtimeMode, }); - const waitFor = (predicate: (events: ReadonlyArray) => boolean) => + const waitFor = ( + predicate: (events: ReadonlyArray) => boolean, + attempts = 1_000, + ) => Effect.gen(function* () { - for (let attempt = 0; attempt < 1_000; attempt += 1) { + for (let attempt = 0; attempt < attempts; attempt += 1) { if (predicate(events)) return; yield* Effect.sleep("10 millis"); } @@ -104,6 +127,7 @@ const startAgy = (scenario: string) => threadId, session, waitFor, + newAdapter, frames: () => Effect.promise(() => readFrames(mock.log)), }; }); @@ -140,6 +164,8 @@ describe("Antigravity turns", () => { 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."); @@ -191,6 +217,9 @@ describe("Antigravity turns", () => { 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(); @@ -257,7 +286,13 @@ describe("Antigravity turns", () => { 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); - expect(agy.usage.map((entry) => entry.totals.uncachedInputTokens)).toEqual([300]); + // 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)), ); @@ -298,7 +333,9 @@ describe("Antigravity turns", () => { expect(completedTurns(agy.events)[0]?.payload).toMatchObject({ state: "failed" }); yield* agy.waitFor((events) => events.some((event) => event.type === "session.exited")); - const restarted = yield* agy.adapter.startSession({ + // A server restart before the next message: a new adapter. + const restartedAdapter = yield* agy.newAdapter; + const restarted = yield* restartedAdapter.startSession({ threadId: agy.threadId, provider: ProviderDriverKind.make("antigravity"), cwd: process.cwd(), @@ -313,6 +350,177 @@ describe("Antigravity turns", () => { ); }); +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("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("settles a turn once when a steer comes while its answer is read", () => + 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) => ({ + ...descriptor, + promptOutcome: { + watch: (sessionId) => + descriptor.promptOutcome!.watch(sessionId).pipe( + Effect.map((check) => (answer: Parameters[0]) => { + if (!first) return check(answer); + first = false; + return Deferred.succeed(reading, undefined).pipe( + Effect.andThen(Deferred.await(release)), + Effect.andThen(check(answer)), + ); + }), + ), + }, + }), + "approval-required", + ); + const { turnId } = yield* agy.adapter.sendTurn({ + threadId: agy.threadId, + input: "first", + attachments: [], + }); + yield* Deferred.await(reading); + const steer = yield* agy.adapter.steerTurn!({ + threadId: agy.threadId, + expectedTurnId: turnId, + input: "second", + }).pipe(Effect.exit, Effect.forkScoped); + yield* Effect.sleep("200 millis"); + yield* Deferred.succeed(release, undefined); + // The turn had ended: the steer is turned down, to be sent as a turn of its own. + expect(Exit.isFailure(yield* Fiber.join(steer))).toBe(true); + expect(completedTurns(agy.events)).toEqual([ + expect.objectContaining({ + turnId, + payload: expect.objectContaining({ state: "completed" }), + }), + ]); + const next = yield* agy.adapter.sendTurn({ + threadId: agy.threadId, + input: "second", + attachments: [], + }); + yield* agy.waitFor((events) => events.some((event) => event.type === "request.opened")); + expect(agy.events.find((event) => event.type === "request.opened")?.turnId).toBe(next.turnId); + }).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"); + 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("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("frees a subagent whose report never sends its closing usage update", () => + Effect.gen(function* () { + const agy = yield* startAgy("subagent-quiet", (descriptor) => ({ + ...descriptor, + heldTurns: { ...descriptor.heldTurns!, 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)), + ); +}); + describe("Antigravity turn reading", () => { const tool = (fields: Partial): AcpToolCallState => ({ toolCallId: "call", diff --git a/apps/server/src/usage/usagePricing.test.ts b/apps/server/src/usage/usagePricing.test.ts index a4a33ebaa..93ffe77ca 100644 --- a/apps/server/src/usage/usagePricing.test.ts +++ b/apps/server/src/usage/usagePricing.test.ts @@ -125,5 +125,19 @@ describe("priceUsage", () => { 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 84083c8da..3f18ae4d0 100644 --- a/apps/server/src/usage/usagePricing.ts +++ b/apps/server/src/usage/usagePricing.ts @@ -209,13 +209,27 @@ export function lookupRate(table: RateTable, model: string, atMs?: number): Mode const normalized = normalizeModelName(model); if (normalized.length === 0 || UNPRICEABLE_MODELS.has(normalized)) return null; const family = GEMINI_4_FAMILY.exec(normalized)?.[1]; - for (const name of family === undefined ? [normalized] : [normalized, family]) { + 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; From 81d6dc5dde2c1b2647c8c21a7f0bb85bdadf37d8 Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Mon, 23 Nov 2026 03:22:31 -0500 Subject: [PATCH 27/59] docs(antigravity): say how subagent reports and an agent exit end a held turn --- docs/providers/antigravity.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/providers/antigravity.md b/docs/providers/antigravity.md index a6ddda46b..0b8ce3b5c 100644 --- a/docs/providers/antigravity.md +++ b/docs/providers/antigravity.md @@ -105,7 +105,9 @@ Two limits keep a lost wake from leaving the thread working forever: a turn held 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. A timer holds the turn until it fires. Subagents are only known to finish by the report the agent gives when -one ends, so the first report frees the turn; a later subagent's report opens a turn of its own. +one ends, so each report (a reply no finished command or timer woke) frees one subagent. If the CLI +sends several reports in one reply, the turn holds until the 30-minute limit or Stop. 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 works steers the turn instead of waiting: Threadlines sends it as another prompt, which the CLI takes into the running turn (1.5.0+), leaving its commands and From ea08236a27993b11aefbc532899743ab562e920d Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Mon, 23 Nov 2026 03:31:37 -0500 Subject: [PATCH 28/59] feat(antigravity): its own slash commands and skills fill the composer's / list Antigravity lists its session's commands with ACP available_commands_update, which the ACP core ignored, and runs a skill when a message starts with /, while the composer only showed Codex's skills (as $ chips). The ACP core now reads the list, and for descriptors that opt in (agentCommands, Antigravity only) reports it as session.commands.updated. Ingestion records a changed list on the thread (thread.agent-commands.set, stored in projection_threads.agent_commands, migration 124, sent with the thread detail only), so each thread keeps its session's list, also across a restart. The composer lists those commands plus the status's skills (ServerProvider.slashSkills), the session's entry winning, and inserts skills as /name. Antigravity's /plan, /login and /logout stay Threadlines' own. A message starting with / goes as typed for such agents: no /plan prefix in plan mode, and the project brief or a switch preamble waits for the next message. --- apps/server/scripts/antigravity-mock-agent.ts | 23 ++++- apps/server/src/guide/topics.ts | 2 +- .../Layers/ProjectionPipeline.ts | 20 +++++ .../Layers/ProjectionSnapshotQuery.ts | 11 +++ .../Layers/ProviderRuntimeIngestion.test.ts | 41 +++++++++ .../Layers/ProviderRuntimeIngestion.ts | 47 ++++++++++- apps/server/src/orchestration/Schemas.ts | 2 + apps/server/src/orchestration/decider.ts | 25 ++++++ apps/server/src/orchestration/projector.ts | 22 +++++ .../src/orchestration/threadMoveDecisions.ts | 1 + .../persistence/Layers/ProjectionThreads.ts | 15 ++++ apps/server/src/persistence/Migrations.ts | 2 + .../124_ProjectionThreadsAgentCommands.ts | 17 ++++ .../persistence/Services/ProjectionThreads.ts | 9 ++ apps/server/src/provider/acp/AcpAdapter.ts | 47 +++++++++-- .../src/provider/acp/AcpProviderDescriptor.ts | 21 +++++ .../src/provider/acp/AcpProviderDriver.ts | 1 + .../src/provider/acp/AcpRuntimeModel.test.ts | 24 ++++++ .../src/provider/acp/AcpRuntimeModel.ts | 43 +++++++++- .../src/provider/acp/AntigravityAcpSupport.ts | 14 ++++ .../antigravity/AntigravityTurns.test.ts | 51 +++++++++++ apps/server/src/ws.ts | 8 +- apps/web/src/components/chat/ChatComposer.tsx | 59 ++++++++++--- .../components/chat/ComposerCommandMenu.tsx | 2 + .../chat/composerAgentCommands.test.ts | 84 +++++++++++++++++++ .../components/chat/composerAgentCommands.ts | 54 ++++++++++++ apps/web/src/store.test.ts | 27 ++++++ apps/web/src/store.ts | 33 ++++++++ apps/web/src/threadDerivation.ts | 7 +- apps/web/src/types.ts | 6 ++ docs/providers/antigravity.md | 31 ++++++- packages/contracts/src/orchestration.ts | 50 +++++++++++ packages/contracts/src/providerRuntime.ts | 23 +++++ packages/contracts/src/server.ts | 20 ++--- packages/contracts/src/slashCommands.ts | 22 +++++ packages/shared/package.json | 4 + packages/shared/src/agentCommands.ts | 54 ++++++++++++ 37 files changed, 886 insertions(+), 36 deletions(-) create mode 100644 apps/server/src/persistence/Migrations/124_ProjectionThreadsAgentCommands.ts create mode 100644 apps/web/src/components/chat/composerAgentCommands.test.ts create mode 100644 apps/web/src/components/chat/composerAgentCommands.ts create mode 100644 packages/contracts/src/slashCommands.ts create mode 100644 packages/shared/src/agentCommands.ts diff --git a/apps/server/scripts/antigravity-mock-agent.ts b/apps/server/scripts/antigravity-mock-agent.ts index 70997fc7f..c6f6d35f6 100644 --- a/apps/server/scripts/antigravity-mock-agent.ts +++ b/apps/server/scripts/antigravity-mock-agent.ts @@ -20,6 +20,9 @@ * - `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. */ import { appendFileSync, mkdirSync } from "node:fs"; import { join } from "node:path"; @@ -91,10 +94,26 @@ const program = Effect.gen(function* () { }), ); yield* agent.handleCreateSession(() => - Effect.sync(() => { + Effect.gen(function* () { sessionCount += 1; + const sessionId = `agy-session-${sessionCount}`; + // 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.forkDetach, + ); return { - sessionId: `agy-session-${sessionCount}`, + sessionId, modes: { currentModeId: "default", availableModes: [ diff --git a/apps/server/src/guide/topics.ts b/apps/server/src/guide/topics.ts index 9f75de9c4..8ab4d0692 100644 --- a/apps/server/src/guide/topics.ts +++ b/apps/server/src/guide/topics.ts @@ -313,7 +313,7 @@ Claude's models come from Claude Code itself, so a new one shows up without a Th 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 meanwhile steers the turn. 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 when a message starts with / and its name. +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 once a chat has started, the commands that chat's Antigravity offers. Such a message goes as typed, even in plan mode. 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, 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. 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. diff --git a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts index 12a0a1735..8c794ad40 100644 --- a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts +++ b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts @@ -1,4 +1,5 @@ import { replaceAgentCheckBacks } from "@threadlines/shared/checkBacks"; +import { applyAgentCommands } from "@threadlines/shared/agentCommands"; import { applyLinkedPullRequestSwitches, applyPullRequestLinked, @@ -1305,6 +1306,25 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti return; } + case "thread.agent-commands-set": { + const existingRow = yield* projectionThreadRepository.getById({ + threadId: event.payload.threadId, + }); + if (Option.isNone(existingRow)) { + return; + } + // Not the thread's updatedAt: an agent listing its commands is not + // activity in the thread. + yield* projectionThreadRepository.upsert({ + ...existingRow.value, + agentCommands: applyAgentCommands( + existingRow.value.agentCommands ?? undefined, + event.payload, + ), + }); + return; + } + case "thread.goal-state-set": { const existingRow = yield* projectionThreadRepository.getById({ threadId: event.payload.threadId, diff --git a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts index 9020410c7..2a1519e1a 100644 --- a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts +++ b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts @@ -35,6 +35,7 @@ import { MessageSentFrom, MessageTrigger, ModelSelection, + OrchestrationAgentCommands, OrchestrationCheckBack, OrchestrationThreadGoal, OrchestrationQueuedFollowUp, @@ -311,6 +312,12 @@ const ProjectionThreadDbRowSchema = ProjectionThread.mapFields( sentModels: Schema.optional( Schema.fromJsonString(Schema.Record(Schema.String, ModelSelection)), ), + // Read by the thread detail only: a thread shell never carries it. + agentCommands: Schema.optional( + Schema.NullOr( + Schema.fromJsonString(Schema.Record(Schema.String, OrchestrationAgentCommands)), + ), + ), agentRequests: Schema.optional( Schema.NullOr(Schema.fromJsonString(OrchestrationAgentRequestState)), ), @@ -1990,6 +1997,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { agent_role AS "agentRole", room_context AS "roomContext", sent_models AS "sentModels", + agent_commands AS "agentCommands", agent_requests AS "agentRequests", parent_thread_id AS "parentThreadId", parent_turn_id AS "parentTurnId", @@ -4236,6 +4244,9 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { ...(threadRow.value.sentModels && Object.keys(threadRow.value.sentModels).length > 0 ? { sentModels: threadRow.value.sentModels } : {}), + ...(threadRow.value.agentCommands && Object.keys(threadRow.value.agentCommands).length > 0 + ? { agentCommands: threadRow.value.agentCommands } + : {}), doneOverride: mapThreadDoneOverride(threadRow.value), lastSeenAt: threadRow.value.lastSeenAt ?? null, deletedAt: null, diff --git a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts index 48de77782..5da8a7c13 100644 --- a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts +++ b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts @@ -414,6 +414,8 @@ describe("ProviderRuntimeIngestion", () => { engine, workspaceRoot, readModel: () => Effect.runPromise(snapshotQuery.getSnapshot()), + threadDetail: (threadId: ThreadId) => + Effect.runPromise(snapshotQuery.getThreadDetailById(threadId)).then(Option.getOrUndefined), emit: provider.emit, setProviderSession: provider.setSession, interruptedThreadIds: provider.interruptedThreadIds, @@ -1205,6 +1207,45 @@ describe("ProviderRuntimeIngestion", () => { expect(Option.getOrThrow(side).providerThreadId).toBeNull(); }); + it("records the slash commands a session lists on its thread, once per change", async () => { + const harness = await createHarness(); + const now = "2026-01-01T00:00:00.000Z"; + const threadId = asThreadId("thread-1"); + const listed = (eventId: string, commands: ReadonlyArray<{ name: string }>) => { + harness.emit({ + type: "session.commands.updated", + eventId: asEventId(eventId), + provider: ProviderDriverKind.make("antigravity"), + providerInstanceId: ProviderInstanceId.make("antigravity"), + threadId, + createdAt: now, + payload: { commands }, + }); + }; + listed("evt-commands-1", [{ name: "goal" }, { name: "compact" }]); + // The session lists them again as it reopens: nothing changed. + listed("evt-commands-2", [{ name: "goal" }, { name: "compact" }]); + listed("evt-commands-3", [{ name: "goal" }]); + await harness.drain(); + + const recorded = await Effect.runPromise( + Stream.runCollect(harness.engine.readEvents(0)).pipe( + Effect.map((events) => + Array.from(events).filter((event) => event.type === "thread.agent-commands-set"), + ), + ), + ); + expect(recorded).toHaveLength(2); + const detail = await harness.threadDetail(threadId); + expect(detail?.agentCommands).toEqual({ + primary: { + providerInstanceId: ProviderInstanceId.make("antigravity"), + commands: [{ name: "goal" }], + updatedAt: now, + }, + }); + }); + it("keeps a room agent's check-backs while another agent works, and notes one it had to skip", async () => { const harness = await createHarness(); const now = "2026-01-01T00:00:00.000Z"; diff --git a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts index dbe3b4490..5242dee37 100644 --- a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts +++ b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts @@ -44,10 +44,12 @@ import * as Stream from "effect/Stream"; import { countUnifiedDiffStats, type DiffLineStats } from "@threadlines/shared/diffStats"; import { makeDrainableWorker } from "@threadlines/shared/DrainableWorker"; import { sameCheckBacks } from "@threadlines/shared/checkBacks"; +import { sameSlashCommands } from "@threadlines/shared/agentCommands"; import { areFilesystemPathsEqual } from "@threadlines/shared/path"; import { ASSISTANT_STREAM_FLUSH_INTERVAL_MS } from "@threadlines/shared/threadLimits"; import { participantSessionKey, + roomAgentKey, sessionSlotParticipantId, } from "@threadlines/shared/threadParticipants"; import { turnAdmission } from "../turnAdmission.ts"; @@ -64,6 +66,8 @@ import { ProviderService } from "../../provider/Services/ProviderService.ts"; import { isCarriedSessionRejection } from "../../provider/nativeSession.ts"; import { ProjectionTurnRepository } from "../../persistence/Services/ProjectionTurns.ts"; import { ProjectionTurnRepositoryLive } from "../../persistence/Layers/ProjectionTurns.ts"; +import { ProjectionThreadRepository } from "../../persistence/Services/ProjectionThreads.ts"; +import { ProjectionThreadRepositoryLive } from "../../persistence/Layers/ProjectionThreads.ts"; import { checkoutEndsTurnsWithCheckpoints, turnEndStateFromRuntime } from "../turnEnd.ts"; import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts"; import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts"; @@ -944,6 +948,7 @@ const make = Effect.gen(function* () { const providerService = yield* ProviderService; const projectionTurnRepository = yield* ProjectionTurnRepository; + const projectionThreadRepository = yield* ProjectionThreadRepository; // Computer links, when this server has them: see RemoteRequestTurnEnds. const remoteRequestTurnEnds = yield* Effect.serviceOption(RemoteRequestTurnEnds); // Scheduled tasks, when this server has them: see ScheduledRunTurnEnds. @@ -2983,6 +2988,42 @@ const make = Effect.gen(function* () { } }); + /** + * The slash commands an agent's session listed, recorded on the thread for + * the composer's `/` list. Like check-backs they belong to the agent, so + * they are recorded whoever holds the session slot. A session lists them + * each time it opens; only a changed list is recorded. + */ + const recordAgentCommands = ( + event: Extract, + thread: NonNullable>>, + ) => + Effect.gen(function* () { + const providerInstanceId = event.providerInstanceId; + if (providerInstanceId === undefined) return; + const participantId = event.participantId ?? null; + const row = yield* projectionThreadRepository.getById({ threadId: thread.id }); + const current = Option.isSome(row) + ? row.value.agentCommands?.[roomAgentKey(participantId)] + : undefined; + if ( + current !== undefined && + current.providerInstanceId === providerInstanceId && + sameSlashCommands(current.commands, event.payload.commands) + ) { + return; + } + yield* orchestrationEngine.dispatch({ + type: "thread.agent-commands.set", + commandId: providerCommandId(event, "agent-commands-set"), + threadId: thread.id, + participantId, + providerInstanceId, + commands: event.payload.commands, + createdAt: event.createdAt, + }); + }); + const processRuntimeEvent = (event: ProviderRuntimeEvent) => Effect.gen(function* () { // Realtime audio/item traffic is intentionally in-memory only. Keep this @@ -3022,6 +3063,10 @@ const make = Effect.gen(function* () { yield* recordCheckBacks(event, thread); return; } + if (event.type === "session.commands.updated") { + yield* recordAgentCommands(event, thread); + return; + } // A thread moving or moved to another computer is frozen here: its // runtime was stopped at the freeze, and a turn one starts by itself // anyway is refused and stopped. @@ -4513,4 +4558,4 @@ const make = Effect.gen(function* () { export const ProviderRuntimeIngestionLive = Layer.effect( ProviderRuntimeIngestionService, make, -).pipe(Layer.provide(ProjectionTurnRepositoryLive)); +).pipe(Layer.provide(Layer.mergeAll(ProjectionTurnRepositoryLive, ProjectionThreadRepositoryLive))); diff --git a/apps/server/src/orchestration/Schemas.ts b/apps/server/src/orchestration/Schemas.ts index ac32fe97b..08190829f 100644 --- a/apps/server/src/orchestration/Schemas.ts +++ b/apps/server/src/orchestration/Schemas.ts @@ -75,6 +75,7 @@ import { ThreadEffectiveCwdSetPayload as ContractsThreadEffectiveCwdSetPayloadSchema, ThreadGoalStateSetPayload as ContractsThreadGoalStateSetPayloadSchema, ThreadCheckBacksSetPayload as ContractsThreadCheckBacksSetPayloadSchema, + ThreadAgentCommandsSetPayload as ContractsThreadAgentCommandsSetPayloadSchema, ThreadTurnDiffCompletedPayload as ContractsThreadTurnDiffCompletedPayloadSchema, ThreadTurnDiffSummaryUpdatedPayload as ContractsThreadTurnDiffSummaryUpdatedPayloadSchema, ThreadTurnCompletedPayload as ContractsThreadTurnCompletedPayloadSchema, @@ -186,6 +187,7 @@ export const ThreadRealtimeStateSetPayload = ContractsThreadRealtimeStateSetPayl export const ThreadEffectiveCwdSetPayload = ContractsThreadEffectiveCwdSetPayloadSchema; export const ThreadGoalStateSetPayload = ContractsThreadGoalStateSetPayloadSchema; export const ThreadCheckBacksSetPayload = ContractsThreadCheckBacksSetPayloadSchema; +export const ThreadAgentCommandsSetPayload = ContractsThreadAgentCommandsSetPayloadSchema; export const ThreadTurnDiffCompletedPayload = ContractsThreadTurnDiffCompletedPayloadSchema; export const ThreadTurnDiffSummaryUpdatedPayload = ContractsThreadTurnDiffSummaryUpdatedPayloadSchema; diff --git a/apps/server/src/orchestration/decider.ts b/apps/server/src/orchestration/decider.ts index d8e5264a9..8a582bc11 100644 --- a/apps/server/src/orchestration/decider.ts +++ b/apps/server/src/orchestration/decider.ts @@ -5755,6 +5755,31 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" }; } + case "thread.agent-commands.set": { + yield* requireThread({ + readModel, + command, + threadId: command.threadId, + }); + return { + ...withEventBase({ + aggregateKind: "thread", + aggregateId: command.threadId, + occurredAt: command.createdAt, + commandId: command.commandId, + metadata: {}, + }), + type: "thread.agent-commands-set", + payload: { + threadId: command.threadId, + participantId: command.participantId, + providerInstanceId: command.providerInstanceId, + commands: command.commands, + updatedAt: command.createdAt, + }, + }; + } + case "thread.check-back.cancel": { const thread = yield* requireThread({ readModel, diff --git a/apps/server/src/orchestration/projector.ts b/apps/server/src/orchestration/projector.ts index ec8dc6cb9..e75a0a9fa 100644 --- a/apps/server/src/orchestration/projector.ts +++ b/apps/server/src/orchestration/projector.ts @@ -25,6 +25,7 @@ import { retainThreadActivities } from "@threadlines/shared/threadActivityRetent import { applyRoomAgentUpdate, recordTurnModel } from "@threadlines/shared/threadParticipants"; import { effectiveCwdOf } from "@threadlines/shared/threadCwd"; import { replaceAgentCheckBacks } from "@threadlines/shared/checkBacks"; +import { applyAgentCommands } from "@threadlines/shared/agentCommands"; import { applyPullRequestDismissed } from "@threadlines/shared/pullRequestDismissals"; import { applyLinkedPullRequestSwitches, @@ -141,6 +142,7 @@ import { ThreadEffectiveCwdSetPayload, ThreadGoalStateSetPayload, ThreadCheckBacksSetPayload, + ThreadAgentCommandsSetPayload, ThreadFollowUpSubmittedPayload, ThreadTurnStartRequestedPayload, ThreadFollowUpAcceptedPayload, @@ -1872,6 +1874,26 @@ export function projectEvent( }; }); + case "thread.agent-commands-set": + return Effect.gen(function* () { + const payload = yield* decodeForEvent( + ThreadAgentCommandsSetPayload, + event.payload, + event.type, + "payload", + ); + const thread = nextBase.threads.find((entry) => entry.id === payload.threadId); + if (!thread) { + return nextBase; + } + return { + ...nextBase, + threads: updateThread(nextBase.threads, payload.threadId, { + agentCommands: applyAgentCommands(thread.agentCommands, payload), + }), + }; + }); + case "thread.goal-state-set": return Effect.gen(function* () { const payload = yield* decodeForEvent( diff --git a/apps/server/src/orchestration/threadMoveDecisions.ts b/apps/server/src/orchestration/threadMoveDecisions.ts index 670d73050..b0f683365 100644 --- a/apps/server/src/orchestration/threadMoveDecisions.ts +++ b/apps/server/src/orchestration/threadMoveDecisions.ts @@ -705,6 +705,7 @@ const FROZEN_THREAD_COMMANDS: ReadonlySet = new Se "thread.activity.append", "thread.effective-cwd.set", "thread.check-backs.set", + "thread.agent-commands.set", // What the provider reports of its goal as the move's stop pauses it: the // goal bar must say what the provider holds, should the move be dropped. "thread.goal.state.set", diff --git a/apps/server/src/persistence/Layers/ProjectionThreads.ts b/apps/server/src/persistence/Layers/ProjectionThreads.ts index 6c56c6a8c..668be8007 100644 --- a/apps/server/src/persistence/Layers/ProjectionThreads.ts +++ b/apps/server/src/persistence/Layers/ProjectionThreads.ts @@ -20,6 +20,7 @@ import { } from "../Services/ProjectionThreads.ts"; import { ModelSelection, + OrchestrationAgentCommands, OrchestrationCheckBack, OrchestrationThreadGoal, OrchestrationQueuedFollowUp, @@ -82,6 +83,11 @@ const ProjectionThreadDbRow = ProjectionThread.mapFields( Schema.Record(Schema.String, OrchestrationRoomContextCursor), ), sentModels: Schema.fromJsonString(Schema.Record(Schema.String, ModelSelection)), + agentCommands: Schema.optional( + Schema.NullOr( + Schema.fromJsonString(Schema.Record(Schema.String, OrchestrationAgentCommands)), + ), + ), }), ); type ProjectionThreadDbRow = typeof ProjectionThreadDbRow.Type; @@ -122,6 +128,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () { side_turn, room_context, sent_models, + agent_commands, agent_role, agent_requests, parent_thread_id, @@ -191,6 +198,11 @@ const makeProjectionThreadRepository = Effect.gen(function* () { ${sideTurnsColumnValue(row.sideTurns)}, ${JSON.stringify(row.roomContext ?? {})}, ${JSON.stringify(row.sentModels ?? {})}, + ${ + row.agentCommands && Object.keys(row.agentCommands).length > 0 + ? JSON.stringify(row.agentCommands) + : null + }, ${row.agentRole ?? null}, ${row.agentRequests ? JSON.stringify(row.agentRequests) : null}, ${row.parentThreadId ?? null}, @@ -264,6 +276,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () { side_turn = excluded.side_turn, room_context = excluded.room_context, sent_models = excluded.sent_models, + agent_commands = excluded.agent_commands, agent_role = excluded.agent_role, agent_requests = excluded.agent_requests, parent_thread_id = excluded.parent_thread_id, @@ -336,6 +349,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () { side_turn AS "sideTurns", room_context AS "roomContext", sent_models AS "sentModels", + agent_commands AS "agentCommands", agent_role AS "agentRole", agent_requests AS "agentRequests", parent_thread_id AS "parentThreadId", @@ -410,6 +424,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () { side_turn AS "sideTurns", room_context AS "roomContext", sent_models AS "sentModels", + agent_commands AS "agentCommands", agent_role AS "agentRole", agent_requests AS "agentRequests", parent_thread_id AS "parentThreadId", diff --git a/apps/server/src/persistence/Migrations.ts b/apps/server/src/persistence/Migrations.ts index a3a3473a3..fe60e5b6a 100644 --- a/apps/server/src/persistence/Migrations.ts +++ b/apps/server/src/persistence/Migrations.ts @@ -143,6 +143,7 @@ import Migration0120 from "./Migrations/120_ThreadAdoptedFromLink.ts"; import Migration0121 from "./Migrations/121_ProjectionThreadSecretRequests.ts"; import Migration0122 from "./Migrations/122_ProjectBriefs.ts"; import Migration0123 from "./Migrations/123_ProjectNotes.ts"; +import Migration0124 from "./Migrations/124_ProjectionThreadsAgentCommands.ts"; /** * Migration loader with all migrations defined inline. @@ -278,6 +279,7 @@ export const migrationEntries = [ [121, "ProjectionThreadSecretRequests", Migration0121], [122, "ProjectBriefs", Migration0122], [123, "ProjectNotes", Migration0123], + [124, "ProjectionThreadsAgentCommands", Migration0124], ] as const; /** Highest id in the full registry, so the "n of total" count is the real total. */ diff --git a/apps/server/src/persistence/Migrations/124_ProjectionThreadsAgentCommands.ts b/apps/server/src/persistence/Migrations/124_ProjectionThreadsAgentCommands.ts new file mode 100644 index 000000000..bf8427e53 --- /dev/null +++ b/apps/server/src/persistence/Migrations/124_ProjectionThreadsAgentCommands.ts @@ -0,0 +1,17 @@ +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/sql/SqlClient"; + +/** Adds `agent_commands`: per agent, the slash commands its session last listed. */ +export default Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + const columns = yield* sql<{ readonly name: string }>` + PRAGMA table_info(projection_threads) + `; + if (!columns.some((column) => column.name === "agent_commands")) { + yield* sql` + ALTER TABLE projection_threads + ADD COLUMN agent_commands TEXT + `; + } +}); diff --git a/apps/server/src/persistence/Services/ProjectionThreads.ts b/apps/server/src/persistence/Services/ProjectionThreads.ts index 026c1110e..d89b0dc76 100644 --- a/apps/server/src/persistence/Services/ProjectionThreads.ts +++ b/apps/server/src/persistence/Services/ProjectionThreads.ts @@ -11,6 +11,7 @@ import { MessageId, ModelSelection, NonNegativeInt, + OrchestrationAgentCommands, OrchestrationCheckBack, OrchestrationThreadGoal, OrchestrationQueuedFollowUp, @@ -167,6 +168,14 @@ export const ProjectionThread = Schema.Struct({ * migration 063 decode; absent reads as nothing recorded yet. */ sentModels: Schema.optional(Schema.Record(Schema.String, ModelSelection)), + /** + * Per agent, the slash commands its session last listed; see + * `OrchestrationThread.agentCommands`. Optional so rows written before + * migration 124 decode; absent reads as none reported. + */ + agentCommands: Schema.optional( + Schema.NullOr(Schema.Record(Schema.String, OrchestrationAgentCommands)), + ), /** * The user's name for the thread's own agent; see * `OrchestrationThreadShell.agentRole`. Optional so rows written before diff --git a/apps/server/src/provider/acp/AcpAdapter.ts b/apps/server/src/provider/acp/AcpAdapter.ts index c00a2435a..e9552d3ae 100644 --- a/apps/server/src/provider/acp/AcpAdapter.ts +++ b/apps/server/src/provider/acp/AcpAdapter.ts @@ -549,6 +549,16 @@ function findModeByAliases( return undefined; } +/** + * Whether a message starts with a slash command, as an agent with + * `agentCommands` reads it: `/` and a name, then whitespace or the end. A + * path (`/tmp/out.log is empty`) has a second `/` in its first word and is + * not one. + */ +export function startsWithAgentCommand(text: string): boolean { + return /^\/[\p{L}\p{N}_][\p{L}\p{N}_.:-]*(?:\s|$)/u.test(text); +} + function isPlanMode(mode: AcpSessionMode): boolean { return findModeByAliases([mode], ACP_PLAN_MODE_ALIASES) !== undefined; } @@ -2177,6 +2187,24 @@ export function makeAcpAdapter( }); return; } + case "AvailableCommandsUpdated": { + // The composer's `/` list for this thread; a side runtime + // answers no messages of its own, so it lists none. + const agentCommands = descriptor.agentCommands; + if (agentCommands === undefined || ctx.lockdown !== undefined) return; + yield* offerRuntimeEvent({ + type: "session.commands.updated", + ...(yield* makeEventStamp()), + provider: PROVIDER, + threadId: ctx.threadId, + payload: { + commands: event.commands.filter( + (command) => !agentCommands.hidden.has(command.name), + ), + }, + }); + return; + } case "SessionCost": ctx.latestCostUsd = event.totalUsd; // A report between turns marks the boundary exactly. @@ -2444,13 +2472,22 @@ export function makeAcpAdapter( const model = turnModelSelection?.model ?? ctx.session.model; const resolvedModel = resolveModelId(model); + const userText = input.input?.trim() ?? ""; + // The agent runs a command (or a skill) only when the message starts + // with it, so one goes as typed: no plan prefix, and the earlier + // context and the project brief wait for the next message. + const sendsAgentCommand = + descriptor.agentCommands !== undefined && startsWithAgentCommand(userText); // 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) @@ -2520,7 +2557,7 @@ export function makeAcpAdapter( ctx.turnRun = run; yield* openPromptPhase(ctx, run); resetTurnState(ctx); - ctx.pendingContextPreamble = undefined; + if (!sendsAgentCommand) ctx.pendingContextPreamble = undefined; if (projectBrief.text !== undefined) { ctx.projectBriefCarrier = { turnId, diff --git a/apps/server/src/provider/acp/AcpProviderDescriptor.ts b/apps/server/src/provider/acp/AcpProviderDescriptor.ts index 4cd40b756..ce8f7320b 100644 --- a/apps/server/src/provider/acp/AcpProviderDescriptor.ts +++ b/apps/server/src/provider/acp/AcpProviderDescriptor.ts @@ -98,6 +98,21 @@ export interface AcpPromptPlanMode { 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; @@ -480,6 +495,12 @@ export interface AcpProviderDescriptor { * a revert trims only Threadlines' turn list, and the agent remembers. */ readonly conversationHistory?: AcpConversationHistory; + /** + * The agent's slash commands (ACP `available_commands_update`) reach the + * composer's `/` list for the session's thread. Absent: the list is + * ignored, as for agents whose lists were never checked in Threadlines. + */ + 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`). diff --git a/apps/server/src/provider/acp/AcpProviderDriver.ts b/apps/server/src/provider/acp/AcpProviderDriver.ts index 3c594ea99..b49c8c293 100644 --- a/apps/server/src/provider/acp/AcpProviderDriver.ts +++ b/apps/server/src/provider/acp/AcpProviderDriver.ts @@ -178,6 +178,7 @@ export function makeAcpProviderDriver( ...(displayName ? { displayName } : {}), ...(accentColor ? { accentColor } : {}), continuation: { groupKey: continuationIdentity.continuationKey }, + ...(descriptor.agentCommands?.slashSkills === true ? { slashSkills: true } : {}), ...descriptor.snapshotExtras?.(), }); // A bare binary name is resolved once against the server's PATH plus 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..c333904b8 100644 --- a/apps/server/src/provider/acp/AcpRuntimeModel.ts +++ b/apps/server/src/provider/acp/AcpRuntimeModel.ts @@ -1,6 +1,10 @@ import type * as EffectAcpSchema from "effect-acp/schema"; 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); @@ -96,6 +100,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 = @@ -604,6 +613,31 @@ function sessionInfoStatusMessage(update: { readonly _meta?: unknown }): string return typeof message === "string" && message.trim().length > 0 ? message.trim() : undefined; } +/** + * An agent's command list in the composer's terms: names without a leading + * `/`, each once (the first wins), and none a message could not start with + * (empty, or with whitespace inside). + */ +export function acpSlashCommands( + commands: ReadonlyArray, +): ReadonlyArray { + const seen = new Set(); + return commands.flatMap((command): Array => { + const name = command.name.trim().replace(/^\//u, ""); + if (name.length === 0 || /\s/u.test(name) || seen.has(name)) return []; + seen.add(name); + const description = command.description.trim(); + const hint = command.input?.hint.trim(); + return [ + { + name, + ...(description ? { description } : {}), + ...(hint ? { input: { hint } } : {}), + }, + ]; + }); +} + export function parseSessionUpdateEvent(params: EffectAcpSchema.SessionNotification): { readonly modeId?: string; readonly events: ReadonlyArray; @@ -714,6 +748,13 @@ export function parseSessionUpdateEvent(params: EffectAcpSchema.SessionNotificat } break; } + case "available_commands_update": { + events.push({ + _tag: "AvailableCommandsUpdated", + commands: acpSlashCommands(upd.availableCommands), + }); + break; + } default: break; } diff --git a/apps/server/src/provider/acp/AntigravityAcpSupport.ts b/apps/server/src/provider/acp/AntigravityAcpSupport.ts index 905f6a689..3aad651f8 100644 --- a/apps/server/src/provider/acp/AntigravityAcpSupport.ts +++ b/apps/server/src/provider/acp/AntigravityAcpSupport.ts @@ -21,6 +21,8 @@ * (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. * - Edits carry exact ACP `diff` content, and the agent writes the files * itself, so no client file system is offered. * @@ -153,6 +155,16 @@ export function antigravityAgentMode( * 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( @@ -838,6 +850,8 @@ export function makeAntigravityDescriptor( return undefined; }, }, + // The session's own `/` commands and skills reach the composer. + agentCommands: ANTIGRAVITY_AGENT_COMMANDS, diffEvidence: true, isolateTextGeneration: true, onSessionConfigOptions: (settings, configOptions) => diff --git a/apps/server/src/provider/antigravity/AntigravityTurns.test.ts b/apps/server/src/provider/antigravity/AntigravityTurns.test.ts index 2635e974c..6d28a16b3 100644 --- a/apps/server/src/provider/antigravity/AntigravityTurns.test.ts +++ b/apps/server/src/provider/antigravity/AntigravityTurns.test.ts @@ -313,6 +313,57 @@ describe("Antigravity turns", () => { ); }); +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("lists the session's own slash commands for its thread, less Threadlines' own", () => + Effect.gen(function* () { + const agy = yield* startAgy("simple"); + yield* agy.waitFor((events) => + events.some((event) => event.type === "session.commands.updated"), + ); + const listed = agy.events.find((event) => event.type === "session.commands.updated"); + expect(listed).toMatchObject({ + threadId: agy.threadId, + payload: { + commands: [ + { name: "goal", description: "Work toward a goal", input: { hint: "objective" } }, + { name: "compact", description: "Summarize the conversation" }, + ], + }, + }); + }).pipe(Effect.scoped, Effect.provide(testServices)), + ); + + it.live("sends a command as typed in plan mode, and plans the next message", () => + Effect.gen(function* () { + const agy = yield* startAgy("simple"); + yield* agy.adapter.sendTurn({ + threadId: agy.threadId, + input: "/compact", + interactionMode: "plan", + attachments: [], + }); + yield* agy.waitFor((events) => completedTurns(events).length === 1); + yield* agy.adapter.sendTurn({ + threadId: agy.threadId, + input: "/tmp/out.log is empty", + interactionMode: "plan", + attachments: [], + }); + yield* agy.waitFor((events) => completedTurns(events).length === 2); + expect(promptTexts(yield* agy.frames())).toEqual(["/compact", "/plan /tmp/out.log is empty"]); + }).pipe(Effect.scoped, Effect.provide(testServices)), + ); + +}); + describe("Antigravity turn reading", () => { const tool = (fields: Partial): AcpToolCallState => ({ toolCallId: "call", diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index c875b714b..60c6e2995 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -296,7 +296,8 @@ export function isThreadDetailEvent(event: OrchestrationEvent): event is Extract | "thread.secret-request-notes-delivered" | "thread.handed-back" | "thread.parent-attachment-set" - | "thread.pull-request-dismissed"; + | "thread.pull-request-dismissed" + | "thread.agent-commands-set"; } > { return ( @@ -338,6 +339,8 @@ export function isThreadDetailEvent(event: OrchestrationEvent): event is Extract // snapshot writes the shell too: one read before a close and delivered // after it would undo the close, so the change follows the snapshot here. event.type === "thread.pull-request-dismissed" || + // The slash commands an agent's session listed: the open chat's `/` list. + event.type === "thread.agent-commands-set" || event.type === "thread.message-sent" || event.type === "thread.follow-up-submitted" || event.type === "thread.follow-up-accepted" || @@ -1146,6 +1149,9 @@ const makeCoreRpcLayer = ( threadId: event.payload.threadId, }), ); + // Detail only: nothing on the thread's shell changed. + case "thread.agent-commands-set": + return Effect.succeed(Option.none()); case "thread.unarchived": return projectionSnapshotQuery.getThreadShellById(event.payload.threadId).pipe( Effect.map((thread) => diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index 4142f4193..8aad0d03f 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -208,6 +208,7 @@ import { useRoomRecipientStore, } from "../../rooms"; import { getPickerModelName } from "./providerIconUtils"; +import { composerProviderSlashList } from "./composerAgentCommands"; import { awaitingInvite } from "@threadlines/shared/roomAgentRequests"; import { shownSettingsChange } from "@threadlines/shared/settingsChangeState"; import { activeParticipants, hasAgentRecords } from "@threadlines/shared/threadParticipants"; @@ -264,6 +265,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 +287,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 +1329,31 @@ 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: for an agent that lists its own + // commands per session (Antigravity), the list this thread's session sent. + const sessionCommandsKey = roomAgentKey(addressingRoomAgent ? roomRecipientId : null); + const sessionCommands = activeThread?.agentCommands?.[sessionCommandsKey]; + const providerSlashList = useMemo( + () => + composerProviderSlashList({ + provider: selectedProviderStatus, + instanceId: selectedInstanceId, + sessionCommands, + threadlinesCommands: goalSupported + ? THREADLINES_SLASH_COMMANDS_WITH_GOAL + : THREADLINES_SLASH_COMMANDS, + }), + [goalSupported, selectedInstanceId, selectedProviderStatus, sessionCommands], + ); 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,7 +1501,7 @@ 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) => ({ @@ -1488,10 +1520,14 @@ 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(composerSkills, query), selectedProvider), + ...buildComposerSkillItems( + searchProviderSkills(providerSlashList.slashSkills, query), + selectedProvider, + "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 +1555,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) composerSkills, composerTrigger, goalSupported, + providerSlashList, selectedProvider, - selectedProviderStatus, threadGoal, workspaceEntries, ]); @@ -3038,7 +3074,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, 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..48b0da12e --- /dev/null +++ b/apps/web/src/components/chat/composerAgentCommands.test.ts @@ -0,0 +1,84 @@ +import { ProviderInstanceId, type ServerProviderSkill } from "@threadlines/contracts"; +import { describe, expect, it } from "vite-plus/test"; + +import { composerProviderSlashList } from "./composerAgentCommands"; + +const instanceId = ProviderInstanceId.make("antigravity"); +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, + instanceId, + sessionCommands: { + providerInstanceId: instanceId, + commands: [{ name: "other" }], + updatedAt: "2026-11-23T00:00:00.000Z", + }, + 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")], + slashSkills: true, + }; + // Before a session has opened: the skills alone. + expect( + composerProviderSlashList({ + provider, + instanceId, + sessionCommands: undefined, + threadlinesCommands: THREADLINES, + }), + ).toEqual({ commands: [], slashSkills: [skill("review"), skill("compact")] }); + + const session = { + providerInstanceId: instanceId, + commands: [ + { name: "goal", input: { hint: "objective" } }, + { name: "compact", description: "Summarize the conversation" }, + { name: "model" }, + ], + updatedAt: "2026-11-23T00:00:00.000Z", + }; + expect( + composerProviderSlashList({ + provider, + instanceId, + sessionCommands: session, + threadlinesCommands: THREADLINES, + }), + ).toEqual({ + commands: [ + { name: "goal", input: { hint: "objective" } }, + { name: "compact", description: "Summarize the conversation" }, + ], + slashSkills: [skill("review")], + }); + + // A list another account's session sent doesn't describe this one. + expect( + composerProviderSlashList({ + provider, + instanceId: ProviderInstanceId.make("antigravity_work"), + sessionCommands: session, + threadlinesCommands: THREADLINES, + }).commands, + ).toEqual([]); + }); +}); diff --git a/apps/web/src/components/chat/composerAgentCommands.ts b/apps/web/src/components/chat/composerAgentCommands.ts new file mode 100644 index 000000000..9a0a1cfe6 --- /dev/null +++ b/apps/web/src/components/chat/composerAgentCommands.ts @@ -0,0 +1,54 @@ +import type { + OrchestrationAgentCommands, + ProviderInstanceId, + ServerProvider, + ServerProviderSkill, + ServerProviderSlashCommand, +} from "@threadlines/contracts"; + +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 = []; + +/** + * What the composer's `/` list offers from the agent. A provider whose agent + * runs skills on `/` (`ServerProvider.slashSkills`, Antigravity) lists + * the commands its session reported for this thread, once there is such a + * list from this provider instance, else the status's; 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; + readonly instanceId: ProviderInstanceId; + /** The list the agent's session last reported for this thread, if any. */ + readonly sessionCommands: OrchestrationAgentCommands | undefined; + readonly threadlinesCommands: ReadonlySet; +}): ComposerProviderSlashList { + const provider = input.provider; + if (provider?.slashSkills !== true) { + return { commands: provider?.slashCommands ?? [], slashSkills: NO_SKILLS }; + } + const sessionCommands = + input.sessionCommands?.providerInstanceId === input.instanceId + ? input.sessionCommands.commands + : undefined; + const commands = (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) && + !/\s/u.test(skill.name), + ); + return { commands, slashSkills }; +} diff --git a/apps/web/src/store.test.ts b/apps/web/src/store.test.ts index fbc1b10cb..4bcad493a 100644 --- a/apps/web/src/store.test.ts +++ b/apps/web/src/store.test.ts @@ -1031,6 +1031,33 @@ describe("incremental orchestration updates", () => { expect(threadsOf(reverted)[0]?.workflowRuns?.map((run) => run.taskId)).toEqual(["task-a"]); }); + it("keeps each agent's slash command list from its session's latest report", () => { + const threadId = ThreadId.make("thread-1"); + const instanceId = ProviderInstanceId.make("antigravity"); + const listed = (sequence: number, names: ReadonlyArray) => + makeEvent( + "thread.agent-commands-set", + { + threadId, + participantId: null, + providerInstanceId: instanceId, + commands: names.map((name) => ({ name })), + updatedAt: "2026-02-27T00:00:01.000Z", + }, + { sequence }, + ); + let state = makeState(makeThread()); + state = applyOrchestrationEvent(state, listed(1, ["goal", "compact"]), localEnvironmentId); + state = applyOrchestrationEvent(state, listed(2, ["goal"]), localEnvironmentId); + expect(threadsOf(state)[0]?.agentCommands).toEqual({ + primary: { + providerInstanceId: instanceId, + commands: [{ name: "goal" }], + updatedAt: "2026-02-27T00:00:01.000Z", + }, + }); + }); + it("projects realtime voice state into thread detail and shell state", () => { const state = makeState(makeThread()); diff --git a/apps/web/src/store.ts b/apps/web/src/store.ts index 206d0da75..1807fbb0f 100644 --- a/apps/web/src/store.ts +++ b/apps/web/src/store.ts @@ -1,5 +1,6 @@ import { hasLiveSideTurn, liveSideTurns } from "@threadlines/shared/sideTurns"; import { replaceAgentCheckBacks, sameCheckBacks } from "@threadlines/shared/checkBacks"; +import { applyAgentCommands } from "@threadlines/shared/agentCommands"; import { applyLinkedPullRequestSwitches, applyPullRequestLinked, @@ -19,6 +20,7 @@ import type { OrchestrationAgentPage, OrchestrationCommandRequest, OrchestrationCommandRun, + OrchestrationAgentCommands, OrchestrationReadModel, OrchestrationSecretRequest, OrchestrationSettingsChangeRequest, @@ -213,6 +215,8 @@ export interface EnvironmentState { /** Suggested commands per thread (docs/terminal-command-runs.md); absent until a thread's detail loads. */ commandRequestsByThreadId?: Record>; commandRunsByThreadId?: Record>; + /** The slash commands each thread's agents' sessions listed; absent until a thread's detail loads. */ + agentCommandsByThreadId?: Record>>; /** * Threads whose detail snapshot has landed (syncServerThreadDetail). Events * and optimistic writes fill the detail slices too, so only this says a @@ -277,6 +281,7 @@ const initialEnvironmentState: EnvironmentState = { subagentsByThreadId: {}, commandRequestsByThreadId: {}, commandRunsByThreadId: {}, + agentCommandsByThreadId: {}, threadDetailLoadedById: {}, childRequestsByThreadId: {}, settingsRequestsByThreadId: {}, @@ -292,6 +297,7 @@ const initialState: AppState = { const EMPTY_THREAD_IDS: ThreadId[] = []; const EMPTY_SUBAGENTS: ReadonlyArray = []; +const EMPTY_AGENT_COMMANDS: Readonly> = {}; function arraysEqual(left: readonly T[], right: readonly T[]): boolean { return left.length === right.length && left.every((value, index) => value === right[index]); @@ -875,6 +881,7 @@ function mapThread(thread: OrchestrationThread, environmentId: EnvironmentId): T pages: thread.pages ?? [], commandRequests: thread.commandRequests ?? [], commandRuns: thread.commandRuns ?? [], + agentCommands: thread.agentCommands ?? EMPTY_AGENT_COMMANDS, error: sessionNoticeError(thread.session), createdAt: thread.createdAt, archivedAt: thread.archivedAt, @@ -1865,6 +1872,19 @@ function writeThreadState( }; } + if ( + nextThread.agentCommands !== undefined && + previousThread?.agentCommands !== nextThread.agentCommands + ) { + nextState = { + ...nextState, + agentCommandsByThreadId: { + ...nextState.agentCommandsByThreadId, + [nextThread.id]: nextThread.agentCommands, + }, + }; + } + if ( nextThread.commandRuns !== undefined && previousThread?.commandRuns !== nextThread.commandRuns @@ -2079,6 +2099,8 @@ function removeThreadState(state: EnvironmentState, threadId: ThreadId): Environ state.commandRequestsByThreadId ?? {}; const { [threadId]: _removedCommandRuns, ...commandRunsByThreadId } = state.commandRunsByThreadId ?? {}; + const { [threadId]: _removedAgentCommands, ...agentCommandsByThreadId } = + state.agentCommandsByThreadId ?? {}; const { [threadId]: _removedDetailLoaded, ...threadDetailLoadedById } = state.threadDetailLoadedById ?? {}; const { [threadId]: _removedChildRequests, ...childRequestsByThreadId } = @@ -2109,6 +2131,7 @@ function removeThreadState(state: EnvironmentState, threadId: ThreadId): Environ subagentsByThreadId, commandRequestsByThreadId, commandRunsByThreadId, + agentCommandsByThreadId, threadDetailLoadedById, childRequestsByThreadId, settingsRequestsByThreadId, @@ -2550,6 +2573,10 @@ function syncEnvironmentShellSnapshot( state.commandRunsByThreadId ?? {}, nextThreadIds, ), + agentCommandsByThreadId: retainThreadScopedRecord( + state.agentCommandsByThreadId ?? {}, + nextThreadIds, + ), threadDetailLoadedById: retainThreadScopedRecord( state.threadDetailLoadedById ?? {}, nextThreadIds, @@ -2986,6 +3013,12 @@ function applyEnvironmentOrchestrationEvent( updatedAt: event.payload.updatedAt, })); + case "thread.agent-commands-set": + return updateThreadState(state, event.payload.threadId, (thread) => ({ + ...thread, + agentCommands: applyAgentCommands(thread.agentCommands, event.payload), + })); + case "thread.check-backs-set": return updateThreadState(state, event.payload.threadId, (thread) => ({ ...thread, diff --git a/apps/web/src/threadDerivation.ts b/apps/web/src/threadDerivation.ts index 04a59f0b1..5791dad3f 100644 --- a/apps/web/src/threadDerivation.ts +++ b/apps/web/src/threadDerivation.ts @@ -36,6 +36,7 @@ const threadCache = new WeakMap< subagents: Thread["subagents"]; commandRequests: Thread["commandRequests"]; commandRuns: Thread["commandRuns"]; + agentCommands: Thread["agentCommands"]; thread: Thread; } >(); @@ -124,6 +125,7 @@ export function getThreadFromEnvironmentState( const subagents = state.subagentsByThreadId?.[threadId]; const commandRequests = state.commandRequestsByThreadId?.[threadId]; const commandRuns = state.commandRunsByThreadId?.[threadId]; + const agentCommands = state.agentCommandsByThreadId?.[threadId]; const cached = threadCache.get(shell); if ( @@ -142,7 +144,8 @@ export function getThreadFromEnvironmentState( cached.workflowRuns === workflowRuns && cached.subagents === subagents && cached.commandRequests === commandRequests && - cached.commandRuns === commandRuns + cached.commandRuns === commandRuns && + cached.agentCommands === agentCommands ) { return cached.thread; } @@ -165,6 +168,7 @@ export function getThreadFromEnvironmentState( ...(subagents !== undefined ? { subagents } : {}), ...(commandRequests !== undefined ? { commandRequests } : {}), ...(commandRuns !== undefined ? { commandRuns } : {}), + ...(agentCommands !== undefined ? { agentCommands } : {}), }; threadCache.set(shell, { @@ -183,6 +187,7 @@ export function getThreadFromEnvironmentState( subagents, commandRequests, commandRuns, + agentCommands, thread, }); diff --git a/apps/web/src/types.ts b/apps/web/src/types.ts index bc5bbd164..c30ef72f5 100644 --- a/apps/web/src/types.ts +++ b/apps/web/src/types.ts @@ -8,6 +8,7 @@ import type { OrchestrationCheckBack, OrchestrationCommandRequest, OrchestrationCommandRun, + OrchestrationAgentCommands, OrchestrationSecretRequest, OrchestrationSettingsChangeRequest, PullRequestMergeMethod, @@ -230,6 +231,11 @@ export interface Thread { commandRequests?: ReadonlyArray; /** Runs the user started from a request card or a code block. Absent until the detail loads. */ commandRuns?: ReadonlyArray; + /** + * Per agent (`primary` or a participant id), the slash commands its session + * last listed (OrchestrationThread.agentCommands). Absent until the detail loads. + */ + agentCommands?: Readonly>; error: string | null; createdAt: string; archivedAt: string | null; diff --git a/docs/providers/antigravity.md b/docs/providers/antigravity.md index a6ddda46b..2dd9f0569 100644 --- a/docs/providers/antigravity.md +++ b/docs/providers/antigravity.md @@ -55,7 +55,9 @@ has them. The reasoning level is its own choice next to the model. | 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. +Plan mode sends the task as `/plan`, and the plan shows on the plan card for review. 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 @@ -90,7 +92,32 @@ other agents' lists, so a project's own skills show only when Threadlines runs i 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. +`$` 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. + +- Before a chat has started, the list has the skills Threadlines found (above). +- Once Antigravity has started in a thread, 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. Each thread keeps its own list, + saved with the thread, so it is there again after a restart, before Antigravity starts again; a + new list from the agent replaces it. +- 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. + +A message that starts with `/` and a name goes to Antigravity exactly as typed, since Antigravity +only runs a command at the very start of the message. In plan mode it goes without the `/plan` +prefix, and the project's instructions Threadlines sends with a new chat's first message wait for +the next message. A message that starts with a path (`/tmp/out.log is empty`) is plain text. + +The first message after Threadlines starts Antigravity over with the thread's history (a moved +thread, a conversation Google can't continue) carries that history in +front of the words, so a command there arrives as text. Send it again on its own. ## Turns diff --git a/packages/contracts/src/orchestration.ts b/packages/contracts/src/orchestration.ts index 607cae2bd..f0c083cd8 100644 --- a/packages/contracts/src/orchestration.ts +++ b/packages/contracts/src/orchestration.ts @@ -42,6 +42,7 @@ import { TurnId, } from "./baseSchemas.ts"; import { ProviderDriverKind, ProviderInstanceId } from "./providerInstance.ts"; +import { ServerProviderSlashCommand } from "./slashCommands.ts"; import { PullRequestMergeMethod } from "./pullRequest.ts"; import { ProjectRevisionFileResult } from "./project.ts"; import { TerminalReuseIds } from "./terminal.ts"; @@ -844,6 +845,21 @@ export type ThreadMoveTarget = typeof ThreadMoveTarget.Type; /** A check-back's prompt is kept up to this many characters (OrchestrationCheckBack.prompt). */ export const CHECK_BACK_PROMPT_MAX_CHARS = 2_000; +/** + * The commands an agent's session last listed for this thread (ACP + * `available_commands_update`): what the composer's `/` list offers while + * that agent and provider instance answer the thread. Kept across restarts, + * so the list is there before the session opens again; a new list from the + * session replaces it. + */ +export const OrchestrationAgentCommands = Schema.Struct({ + /** The provider instance whose session listed them. */ + providerInstanceId: ProviderInstanceId, + commands: Schema.Array(ServerProviderSlashCommand), + updatedAt: IsoDateTime, +}); +export type OrchestrationAgentCommands = typeof OrchestrationAgentCommands.Type; + /** * A time an agent set itself to come back to the thread (Claude's * ScheduleWakeup and CronCreate). It belongs to the agent that set it, not @@ -3229,6 +3245,12 @@ export const OrchestrationThread = Schema.Struct({ * OrchestrationMessage.agentModels). Absent: nothing recorded yet. */ sentModels: Schema.optional(Schema.Record(Schema.String, ModelSelection)), + /** + * Per agent (`primary` or a participant id), the slash commands its + * session last listed; see OrchestrationAgentCommands. Only providers that + * report them fill it. Absent: none reported. + */ + agentCommands: Schema.optional(Schema.Record(Schema.String, OrchestrationAgentCommands)), /** See OrchestrationThreadShell.doneOverride. */ doneOverride: Schema.NullOr(OrchestrationThreadDoneOverride).pipe( Schema.withDecodingDefault(Effect.succeed(null)), @@ -4495,6 +4517,19 @@ const ThreadCheckBacksSetCommand = Schema.Struct({ createdAt: IsoDateTime, }); +/** Provider-internal: the slash commands an agent's session listed; replaces + * that agent's list. Emitted by runtime ingestion off + * `session.commands.updated`, only when the list changed. */ +const ThreadAgentCommandsSetCommand = Schema.Struct({ + type: Schema.Literal("thread.agent-commands.set"), + commandId: CommandId, + threadId: ThreadId, + participantId: Schema.NullOr(ThreadParticipantId), + providerInstanceId: ProviderInstanceId, + commands: Schema.Array(ServerProviderSlashCommand), + createdAt: IsoDateTime, +}); + /** * Server-internal: bring the thread's goal in line with what the thread waits * on (docs/design/goal-wait-pause.md). The decider pauses an active goal while @@ -6078,6 +6113,7 @@ const InternalOrchestrationCommand = Schema.Union([ ThreadRealtimeStateSetCommand, ThreadEffectiveCwdSetCommand, ThreadCheckBacksSetCommand, + ThreadAgentCommandsSetCommand, ThreadGoalSetCommand, ThreadGoalClearCommand, ThreadGoalStateSetCommand, @@ -6209,6 +6245,7 @@ export const OrchestrationEventType = Schema.Literals([ "thread.continue-at-reset-skipped", "thread.effective-cwd-set", "thread.check-backs-set", + "thread.agent-commands-set", "thread.goal-set-requested", "thread.goal-clear-requested", "thread.goal-state-set", @@ -7091,6 +7128,14 @@ export const ThreadCheckBacksSetPayload = Schema.Struct({ updatedAt: IsoDateTime, }); +export const ThreadAgentCommandsSetPayload = Schema.Struct({ + threadId: ThreadId, + participantId: Schema.NullOr(ThreadParticipantId), + providerInstanceId: ProviderInstanceId, + commands: Schema.Array(ServerProviderSlashCommand), + updatedAt: IsoDateTime, +}); + export const ThreadCheckBackCancelRequestedPayload = Schema.Struct({ threadId: ThreadId, participantId: Schema.NullOr(ThreadParticipantId), @@ -7684,6 +7729,11 @@ export const OrchestrationEvent = Schema.Union([ type: Schema.Literal("thread.check-backs-set"), payload: ThreadCheckBacksSetPayload, }), + Schema.Struct({ + ...EventBaseFields, + type: Schema.Literal("thread.agent-commands-set"), + payload: ThreadAgentCommandsSetPayload, + }), Schema.Struct({ ...EventBaseFields, type: Schema.Literal("thread.check-back-cancel-requested"), diff --git a/packages/contracts/src/providerRuntime.ts b/packages/contracts/src/providerRuntime.ts index fc8f986a9..ce61aa618 100644 --- a/packages/contracts/src/providerRuntime.ts +++ b/packages/contracts/src/providerRuntime.ts @@ -23,6 +23,7 @@ import { ProviderApprovalDecision, } from "./orchestration.ts"; import { RuntimeMcpAppCall } from "./mcpApps.ts"; +import { ServerProviderSlashCommand } from "./slashCommands.ts"; import { AwaitedWorkflowProgress, WorkflowRunUpdate } from "./workflow.ts"; const TrimmedNonEmptyStringSchema = TrimmedNonEmptyString; @@ -207,6 +208,7 @@ const ProviderRuntimeEventType = Schema.Literals([ "goal.updated", "goal.cleared", "session.check-backs.updated", + "session.commands.updated", "thread.realtime.started", "thread.realtime.item-added", "thread.realtime.audio.delta", @@ -270,6 +272,7 @@ const ThreadTokenUsageUpdatedType = Schema.Literal("thread.token-usage.updated") const GoalUpdatedType = Schema.Literal("goal.updated"); const GoalClearedType = Schema.Literal("goal.cleared"); const SessionCheckBacksUpdatedType = Schema.Literal("session.check-backs.updated"); +const SessionCommandsUpdatedType = Schema.Literal("session.commands.updated"); const ThreadRealtimeStartedType = Schema.Literal("thread.realtime.started"); const ThreadRealtimeItemAddedType = Schema.Literal("thread.realtime.item-added"); const ThreadRealtimeAudioDeltaType = Schema.Literal("thread.realtime.audio.delta"); @@ -574,6 +577,17 @@ const SessionCheckBacksUpdatedPayload = Schema.Struct({ }); export type SessionCheckBacksUpdatedPayload = typeof SessionCheckBacksUpdatedPayload.Type; +/** + * The commands the session's agent runs when a message starts with + * `/`, as it last listed them (ACP `available_commands_update`). Each + * report replaces the earlier list. Only drivers that let these reach the + * composer send it. + */ +const SessionCommandsUpdatedPayload = Schema.Struct({ + commands: Schema.Array(ServerProviderSlashCommand), +}); +export type SessionCommandsUpdatedPayload = typeof SessionCommandsUpdatedPayload.Type; + const ThreadRealtimeStartedPayload = Schema.Struct({ realtimeSessionId: Schema.optional(TrimmedNonEmptyStringSchema), }); @@ -1188,6 +1202,14 @@ const ProviderRuntimeSessionCheckBacksUpdatedEvent = Schema.Struct({ export type ProviderRuntimeSessionCheckBacksUpdatedEvent = typeof ProviderRuntimeSessionCheckBacksUpdatedEvent.Type; +const ProviderRuntimeSessionCommandsUpdatedEvent = Schema.Struct({ + ...ProviderRuntimeEventBase.fields, + type: SessionCommandsUpdatedType, + payload: SessionCommandsUpdatedPayload, +}); +export type ProviderRuntimeSessionCommandsUpdatedEvent = + typeof ProviderRuntimeSessionCommandsUpdatedEvent.Type; + const ProviderRuntimeGoalClearedEvent = Schema.Struct({ ...ProviderRuntimeEventBase.fields, type: GoalClearedType, @@ -1552,6 +1574,7 @@ export const ProviderRuntimeEventV2 = Schema.Union([ ProviderRuntimeGoalUpdatedEvent, ProviderRuntimeGoalClearedEvent, ProviderRuntimeSessionCheckBacksUpdatedEvent, + ProviderRuntimeSessionCommandsUpdatedEvent, ProviderRuntimeThreadRealtimeStartedEvent, ProviderRuntimeThreadRealtimeItemAddedEvent, ProviderRuntimeThreadRealtimeAudioDeltaEvent, diff --git a/packages/contracts/src/server.ts b/packages/contracts/src/server.ts index 361b7ba27..9ff54ce86 100644 --- a/packages/contracts/src/server.ts +++ b/packages/contracts/src/server.ts @@ -26,6 +26,7 @@ import { ModelCapabilities, ModelUpgradeInfo } from "./model.ts"; import { RuntimeMode } from "./orchestration.ts"; import { ProviderDriverKind, ProviderInstanceId } from "./providerInstance.ts"; import { ServerSettings } from "./settings.ts"; +import { ServerProviderSlashCommand, ServerProviderSlashCommandInput } from "./slashCommands.ts"; const KeybindingsMalformedConfigIssue = Schema.Struct({ kind: Schema.Literal("keybindings.malformed-config"), @@ -365,17 +366,7 @@ export const ServerProviderModel = Schema.Struct({ }); export type ServerProviderModel = typeof ServerProviderModel.Type; -export const ServerProviderSlashCommandInput = Schema.Struct({ - hint: TrimmedNonEmptyString, -}); -export type ServerProviderSlashCommandInput = typeof ServerProviderSlashCommandInput.Type; - -export const ServerProviderSlashCommand = Schema.Struct({ - name: TrimmedNonEmptyString, - description: Schema.optional(TrimmedNonEmptyString), - input: Schema.optional(ServerProviderSlashCommandInput), -}); -export type ServerProviderSlashCommand = typeof ServerProviderSlashCommand.Type; +export { ServerProviderSlashCommand, ServerProviderSlashCommandInput }; export const ServerProviderSkill = Schema.Struct({ name: TrimmedNonEmptyString, @@ -555,6 +546,13 @@ 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), versionAdvisory: Schema.optionalKey(ServerProviderVersionAdvisory), updateState: Schema.optionalKey(ServerProviderUpdateState), detection: Schema.optionalKey(ServerProviderDetection), diff --git a/packages/contracts/src/slashCommands.ts b/packages/contracts/src/slashCommands.ts new file mode 100644 index 000000000..d4b370452 --- /dev/null +++ b/packages/contracts/src/slashCommands.ts @@ -0,0 +1,22 @@ +import * as Schema from "effect/Schema"; + +import { TrimmedNonEmptyString } from "./baseSchemas.ts"; + +/** + * A command an agent runs when a message starts with `/`: a provider's + * own commands on its status (`ServerProvider.slashCommands`), and the list + * a running session reported for its thread (`OrchestrationThread.agentCommands`). + * Re-exported from `server.ts`; its own module so orchestration contracts can + * use it without importing the server contracts. + */ +export const ServerProviderSlashCommandInput = Schema.Struct({ + hint: TrimmedNonEmptyString, +}); +export type ServerProviderSlashCommandInput = typeof ServerProviderSlashCommandInput.Type; + +export const ServerProviderSlashCommand = Schema.Struct({ + name: TrimmedNonEmptyString, + description: Schema.optional(TrimmedNonEmptyString), + input: Schema.optional(ServerProviderSlashCommandInput), +}); +export type ServerProviderSlashCommand = typeof ServerProviderSlashCommand.Type; diff --git a/packages/shared/package.json b/packages/shared/package.json index c51910aac..d85a0d94b 100644 --- a/packages/shared/package.json +++ b/packages/shared/package.json @@ -239,6 +239,10 @@ "types": "./src/queuedFollowUps.ts", "import": "./src/queuedFollowUps.ts" }, + "./agentCommands": { + "types": "./src/agentCommands.ts", + "import": "./src/agentCommands.ts" + }, "./checkBacks": { "types": "./src/checkBacks.ts", "import": "./src/checkBacks.ts" diff --git a/packages/shared/src/agentCommands.ts b/packages/shared/src/agentCommands.ts new file mode 100644 index 000000000..7f78a0bc4 --- /dev/null +++ b/packages/shared/src/agentCommands.ts @@ -0,0 +1,54 @@ +import type { + OrchestrationAgentCommands, + ProviderInstanceId, + ServerProviderSlashCommand, + ThreadParticipantId, +} from "@threadlines/contracts"; + +import { roomAgentKey } from "./threadParticipants.ts"; + +type AgentCommandsByAgent = Readonly>; + +/** + * A thread's agent commands after one agent's session listed its commands: + * that agent's entry is replaced, every other agent's kept. Every reader of + * `thread.agent-commands-set` (server read models, clients) applies it. + */ +export function applyAgentCommands( + current: AgentCommandsByAgent | undefined, + update: { + readonly participantId: ThreadParticipantId | null; + readonly providerInstanceId: ProviderInstanceId; + readonly commands: ReadonlyArray; + readonly updatedAt: string; + }, +): AgentCommandsByAgent { + return { + ...current, + [roomAgentKey(update.participantId)]: { + providerInstanceId: update.providerInstanceId, + commands: update.commands, + updatedAt: update.updatedAt, + }, + }; +} + +/** Whether two command lists say the same thing, in the same order (a + * session lists its commands each time it opens; only a change is recorded). */ +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 + ); + }) + ); +} From 61b0e77049a584bfcb26b059e4b04f2ced6625c5 Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Mon, 23 Nov 2026 03:31:44 -0500 Subject: [PATCH 29/59] feat(antigravity): editing an earlier message starts the agent over without the removed turns Antigravity can't rewind its conversation, so a revert only trimmed our turn list and the agent kept remembering the removed turns. Descriptors with rollbackByNewSession (Antigravity) now end the session on a revert: work still running is stopped as Stop does, then the session closes and is marked lost, so the next message opens a new one that the thread seeds with the turns kept (resumeFailed). The adapter reports this as conversationRollback "new-session", which the checkpoint reactor also uses to reach the agent when no runtime is live, since the next turn would otherwise reopen the saved conversation as it was. --- apps/server/src/guide/topics.ts | 2 +- .../Layers/CheckpointReactor.test.ts | 52 ++++++++++++++++++- .../orchestration/Layers/CheckpointReactor.ts | 28 +++++++++- .../src/provider/Services/ProviderAdapter.ts | 6 ++- apps/server/src/provider/acp/AcpAdapter.ts | 39 +++++++++++++- .../src/provider/acp/AcpProviderDescriptor.ts | 8 +++ .../src/provider/acp/AntigravityAcpSupport.ts | 4 ++ .../antigravity/AntigravityTurns.test.ts | 51 ++++++++++++++++++ docs/providers/antigravity.md | 12 ++++- 9 files changed, 194 insertions(+), 8 deletions(-) diff --git a/apps/server/src/guide/topics.ts b/apps/server/src/guide/topics.ts index 8ab4d0692..027ed0710 100644 --- a/apps/server/src/guide/topics.ts +++ b/apps/server/src/guide/topics.ts @@ -313,7 +313,7 @@ Claude's models come from Claude Code itself, so a new one shows up without a Th 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 meanwhile steers the turn. 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 once a chat has started, the commands that chat's Antigravity offers. Such a message goes as typed, even in plan mode. +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 once a chat has started, the commands that chat's Antigravity offers. Such a message goes as typed, even in plan mode. Editing an earlier message starts Antigravity over with only the turns before it, since it can't rewind its own conversation; anything it still ran stops first. 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, 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. 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. diff --git a/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts b/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts index a1daa1a74..8bfb4157c 100644 --- a/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts +++ b/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts @@ -94,6 +94,7 @@ function createProviderServiceHarness( sessionCwd = cwd, providerName: ProviderSession["provider"] = ProviderDriverKind.make("codex"), extraSessions: ReadonlyArray = [], + conversationRollback?: "native" | "none" | "new-session", ) { const now = "2026-01-01T00:00:00.000Z"; const runtimeEventPubSub = Effect.runSync(PubSub.unbounded()); @@ -161,7 +162,11 @@ function createProviderServiceHarness( adoptNativeSession: () => Effect.void, forgetNativeSession: () => Effect.void, dropResumeCursor: () => Effect.void, - getCapabilities: () => Effect.succeed({ sessionModelSwitch: "in-session" }), + getCapabilities: () => + Effect.succeed({ + sessionModelSwitch: "in-session", + ...(conversationRollback !== undefined ? { conversationRollback } : {}), + }), getInstanceInfo: (instanceId) => Effect.succeed({ instanceId, @@ -366,6 +371,7 @@ describe("CheckpointReactor", () => { readonly includeConcurrentSession?: boolean; readonly extraProviderSessions?: ReadonlyArray; readonly gitStatusRefreshCalls?: Array; + readonly conversationRollback?: "native" | "none" | "new-session"; }) { const cwd = createGitRepository(); tempDirs.push(cwd); @@ -393,6 +399,7 @@ describe("CheckpointReactor", () => { options?.providerSessionCwd ?? cwd, options?.providerName ?? ProviderDriverKind.make("codex"), extraProviderSessions, + options?.conversationRollback, ); const orchestrationLayer = OrchestrationEngineLive.pipe( Layer.provide(OrchestrationProjectionSnapshotQueryLive), @@ -3111,6 +3118,49 @@ describe("CheckpointReactor", () => { ); }); + it("still reaches an agent that forgets by starting over when no session runs", async () => { + const harness = await createHarness({ hasSession: false, conversationRollback: "new-session" }); + 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-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"); + // The service reopens the saved session to end it, or the next turn would + // pick the conversation up as it was. + expect(harness.provider.rollbackConversation).toHaveBeenCalledTimes(1); + const thread = (await harness.readModel()).threads.find((entry) => entry.id === threadId); + expect( + thread?.activities.some((activity) => activity.kind.startsWith("checkpoint.revert.rollback")), + ).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..d0ba797b9 100644 --- a/apps/server/src/orchestration/Layers/CheckpointReactor.ts +++ b/apps/server/src/orchestration/Layers/CheckpointReactor.ts @@ -1243,16 +1243,40 @@ const make = Effect.gen(function* () { const rolledBackTurns = Math.max(0, context.currentTurnCount - event.payload.turnCount); if (rolledBackTurns > 0) { - if (context.hasProviderSession) { + // An agent that forgets by starting over (Antigravity) is reached with + // no runtime live too: the service reopens its session to end it, or + // the next turn would reopen the conversation as it was. + const startsOver = + !context.hasProviderSession && + (yield* providerService + .getCapabilities( + context.thread.session?.providerInstanceId ?? context.thread.modelSelection.instanceId, + ) + .pipe( + Effect.map((capabilities) => capabilities.conversationRollback === "new-session"), + Effect.orElseSucceed(() => false), + )); + if (context.hasProviderSession || startsOver) { const targetUserMessageId = targetUserMessageIdForCheckpointRewind({ thread: context.thread, targetTurnCount: event.payload.turnCount, }); - const rollback = yield* providerService.rollbackConversation({ + const rollbackRequest = providerService.rollbackConversation({ threadId: event.payload.threadId, numTurns: rolledBackTurns, ...(targetUserMessageId !== undefined ? { targetUserMessageId } : {}), }); + // A session that can't be reopened to end it is said to remember. + const rollback = yield* startsOver + ? rollbackRequest.pipe( + Effect.catch((cause) => + Effect.logWarning("checkpoint revert could not reopen the session to end it", { + threadId: event.payload.threadId, + cause, + }).pipe(Effect.as({ conversationRolledBack: false })), + ), + ) + : rollbackRequest; if (!rollback.conversationRolledBack) { yield* orchestrationEngine .dispatch({ diff --git a/apps/server/src/provider/Services/ProviderAdapter.ts b/apps/server/src/provider/Services/ProviderAdapter.ts index d98f2bfbe..2cb9a5ce1 100644 --- a/apps/server/src/provider/Services/ProviderAdapter.ts +++ b/apps/server/src/provider/Services/ProviderAdapter.ts @@ -159,8 +159,12 @@ 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) ends the session instead, and the next turn + * opens a new one seeded with the turns kept; a revert reaches it even + * with no runtime live, since the saved conversation would otherwise be + * reopened as it was. */ - readonly conversationRollback?: "native" | "none"; + readonly conversationRollback?: "native" | "none" | "new-session"; /** * Whether a session may be started before its first message, while the user diff --git a/apps/server/src/provider/acp/AcpAdapter.ts b/apps/server/src/provider/acp/AcpAdapter.ts index e9552d3ae..e819c6f6d 100644 --- a/apps/server/src/provider/acp/AcpAdapter.ts +++ b/apps/server/src/provider/acp/AcpAdapter.ts @@ -143,6 +143,8 @@ const ACP_RESUME_VERSION = 1 as const; * 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 @@ -3088,7 +3090,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* () { @@ -3102,6 +3105,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( @@ -3150,6 +3162,29 @@ export function makeAcpAdapter( return { threadId, turns: ctx.turns, conversationRolledBack: rewound }; }); + /** + * For an agent that can't rewind (`rollbackByNewSession`): the session + * ends and is marked lost, so it is never reopened. The next message + * starts a new one, which the thread seeds with the turns it kept + * (`resumeFailed`), and the agent forgets the reverted ones. 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* () { + lostSessions.add(ctx.acpSessionId); + const working = () => + ctx.activeTurnId !== undefined || ctx.workAfterPrompt.size > 0 || ctx.subagentsOut > 0; + 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)); @@ -3190,7 +3225,7 @@ export function makeAcpAdapter( provider: PROVIDER, capabilities: { sessionModelSwitch: "in-session", - conversationRollback: "none", + conversationRollback: descriptor.rollbackByNewSession ? "new-session" : "none", ...(descriptor.steer || descriptor.steerWithPrompt ? { activeTurnSteering: "supported" as const } : {}), diff --git a/apps/server/src/provider/acp/AcpProviderDescriptor.ts b/apps/server/src/provider/acp/AcpProviderDescriptor.ts index ce8f7320b..95ed62c8f 100644 --- a/apps/server/src/provider/acp/AcpProviderDescriptor.ts +++ b/apps/server/src/provider/acp/AcpProviderDescriptor.ts @@ -495,6 +495,14 @@ 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 the session + * (closing it stops what it runs) and the next message opens a new one + * seeded with the turns kept, as after a failed resume, so the agent + * forgets the reverted ones (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. Absent: the list is diff --git a/apps/server/src/provider/acp/AntigravityAcpSupport.ts b/apps/server/src/provider/acp/AntigravityAcpSupport.ts index 3aad651f8..ed6322437 100644 --- a/apps/server/src/provider/acp/AntigravityAcpSupport.ts +++ b/apps/server/src/provider/acp/AntigravityAcpSupport.ts @@ -23,6 +23,8 @@ * 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. * @@ -852,6 +854,8 @@ export function makeAntigravityDescriptor( }, // 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) => diff --git a/apps/server/src/provider/antigravity/AntigravityTurns.test.ts b/apps/server/src/provider/antigravity/AntigravityTurns.test.ts index 6d28a16b3..e76f1fe53 100644 --- a/apps/server/src/provider/antigravity/AntigravityTurns.test.ts +++ b/apps/server/src/provider/antigravity/AntigravityTurns.test.ts @@ -362,6 +362,57 @@ describe("Antigravity commands and edits", () => { }).pipe(Effect.scoped, Effect.provide(testServices)), ); + it.live("forgets reverted turns by ending the session and starting a new one", () => + Effect.gen(function* () { + const agy = yield* startAgy("simple"); + expect(agy.adapter.capabilities.conversationRollback).toBe("new-session"); + yield* agy.adapter.sendTurn({ threadId: agy.threadId, input: "first", attachments: [] }); + yield* agy.waitFor((events) => completedTurns(events).length === 1); + const [beforeRevert] = yield* agy.adapter.listSessions(); + + const rolledBack = yield* agy.adapter.rollbackThread(agy.threadId, 1); + expect(rolledBack.conversationRolledBack).toBe(true); + expect(agy.events.some((event) => event.type === "session.exited")).toBe(true); + expect(yield* agy.adapter.hasSession(agy.threadId)).toBe(false); + + // The next message opens a new conversation the thread seeds. + const restarted = yield* agy.adapter.startSession({ + threadId: agy.threadId, + provider: ProviderDriverKind.make("antigravity"), + cwd: process.cwd(), + runtimeMode: "full-access", + resumeCursor: beforeRevert?.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("stops the agent's running work, and its turn once, before a revert ends it", () => + 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.rollbackThread(agy.threadId, 1); + 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); + }).pipe(Effect.scoped, Effect.provide(testServices)), + ); }); describe("Antigravity turn reading", () => { diff --git a/docs/providers/antigravity.md b/docs/providers/antigravity.md index 2dd9f0569..5b2196384 100644 --- a/docs/providers/antigravity.md +++ b/docs/providers/antigravity.md @@ -116,7 +116,7 @@ prefix, and the project's instructions Threadlines sends with a new chat's first the next message. A message that starts with a path (`/tmp/out.log is empty`) is plain text. The first message after Threadlines starts Antigravity over with the thread's history (a moved -thread, a conversation Google can't continue) carries that history in +thread, a conversation Google can't continue, an edited earlier message) carries that history in front of the words, so a command there arrives as text. Send it again on its own. ## Turns @@ -149,6 +149,16 @@ it resets and can continue then. A conversation Google can no longer continue (a saved thinking block) stops its session, and the next message starts a new one with the thread's history. +### Editing an Earlier Message + +Antigravity can't rewind its own conversation. When you edit an earlier message (or undo back to +one), Threadlines restores the files, 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. The next message starts a new Antigravity session and sends it the turns that are left, +so Antigravity no longer remembers the removed ones. This also works when no Antigravity was +running for the thread: Threadlines opens the saved session just to end it, since the next message +would otherwise continue it as it was. + ### Tokens Each turn's tokens come from the CLI's answer to the prompt: input is its input plus cached reads, From f89459555c5dd95d49204aeea2e284a12ca48bc6 Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Mon, 23 Nov 2026 03:34:34 -0500 Subject: [PATCH 30/59] fix(antigravity): a revert marks the session lost on disk, so a restart before the next message still starts over --- apps/server/src/provider/acp/AcpAdapter.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/server/src/provider/acp/AcpAdapter.ts b/apps/server/src/provider/acp/AcpAdapter.ts index b763f4642..6c9e8af54 100644 --- a/apps/server/src/provider/acp/AcpAdapter.ts +++ b/apps/server/src/provider/acp/AcpAdapter.ts @@ -3377,7 +3377,7 @@ export function makeAcpAdapter( */ const forgetByNewSession = (ctx: AcpSessionContext) => Effect.gen(function* () { - lostSessions.add(ctx.acpSessionId); + yield* markSessionLost(ctx.acpSessionId); const working = () => ctx.activeTurnId !== undefined || ctx.workAfterPrompt.size > 0 || ctx.subagentsOut > 0; if (working()) { From ed9e75ce61d33f13a9984bd5ad74d5ec41044660 Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Mon, 23 Nov 2026 03:38:30 -0500 Subject: [PATCH 31/59] docs(antigravity): an edited earlier message starts over also across a restart --- docs/providers/antigravity.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/providers/antigravity.md b/docs/providers/antigravity.md index e41d88f84..e6f25ed8f 100644 --- a/docs/providers/antigravity.md +++ b/docs/providers/antigravity.md @@ -170,9 +170,9 @@ Antigravity can't rewind its own conversation. When you edit an earlier message one), Threadlines restores the files, 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. The next message starts a new Antigravity session and sends it the turns that are left, -so Antigravity no longer remembers the removed ones. This also works when no Antigravity was -running for the thread: Threadlines opens the saved session just to end it, since the next message -would otherwise continue it as it was. +so Antigravity no longer remembers the removed ones, also when Threadlines restarts before that +message. This also works when no Antigravity was running for the thread: Threadlines opens the +saved session just to end it, since the next message would otherwise continue it as it was. ### Tokens From 77b65e0ba034b269221b2361b21fcc6d3128fd2f Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Mon, 23 Nov 2026 03:52:07 -0500 Subject: [PATCH 32/59] feat(acp): a pure turn machine for agents whose turns outlive their prompt One reducer decides what a turn is and what the adapter does next, from every event that can happen to it: a send, a steer, a prompt going out and answering, its outcome read, work the agent goes on with, its output and reply ends, approvals, Stop, timers, the process exiting, the session stopping. Timers follow the state, so a state that needs a deadline always has one armed. A breadth-first explorer walks every event sequence up to depth 10 (about a million states) and checks each: one terminal event per turn, a deadline whenever Stop is pending, no completion while a newer prompt is unanswered, every turn ended when the session ends, counts never negative, a hold with nothing left always settles, every send and steer answered once. --- .../src/provider/acp/AcpTurnMachine.test.ts | 516 ++++++++++++++++ .../server/src/provider/acp/AcpTurnMachine.ts | 573 ++++++++++++++++++ 2 files changed, 1089 insertions(+) create mode 100644 apps/server/src/provider/acp/AcpTurnMachine.test.ts create mode 100644 apps/server/src/provider/acp/AcpTurnMachine.ts 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..38b1bd6c6 --- /dev/null +++ b/apps/server/src/provider/acp/AcpTurnMachine.test.ts @@ -0,0 +1,516 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { + type AcpPromptOutcomeRead, + type AcpTurnCommand, + type AcpTurnEvent, + type AcpTurnMachineState, + 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; + readonly workUsed: ReadonlyArray; + readonly launched: boolean; + readonly childrenReported: boolean; +} + +interface World { + readonly state: State; + readonly monitor: Monitor; +} + +const initialWorld: World = { + state: initialTurnMachineState(), + monitor: { + sends: 0, + steers: 0, + agentTurns: 0, + open: [], + closed: [], + unansweredCallers: [], + reads: [], + workUsed: [], + launched: false, + childrenReported: false, + }, +}; + +/** Every event the adapter could produce next, with small bounded domains. */ +function possibleEvents(world: World): 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 (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) }, + ); + } + if (!monitor.workUsed.includes("c1")) + events.push({ type: "workStarted", id: "c1", kind: "command" }); + if (!monitor.workUsed.includes("w1")) + events.push({ type: "workStarted", id: "w1", kind: "timer" }); + for (const [id] of state.running) events.push({ type: "workEnded", id }); + if (!monitor.launched) events.push({ type: "subagentsLaunched", id: "l1", count: 2 }); + if (monitor.launched && !monitor.childrenReported) { + events.push({ type: "childrenAtWork", count: 0 }); + } + const newTurnId = `a${monitor.agentTurns + 1}`; + if (monitor.agentTurns < 2) { + events.push( + { type: "agentOutput", newTurnId }, + { type: "cancellationNotice", newTurnId }, + ...(state.requestsOpen === 0 ? [{ 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" }); + for (const [timer, generation] of state.timers) { + events.push({ type: "timerFired", timer, generation }); + } + 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 ")}`, + ); + } +} + +/** 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, workUsed: [...monitor.workUsed, event.id] }; + if (event.type === "subagentsLaunched") monitor = { ...monitor, launched: true }; + if (event.type === "childrenAtWork") monitor = { ...monitor, childrenReported: true }; + if (event.type === "outcomeRead") { + monitor = { ...monitor, reads: monitor.reads.filter((prompt) => prompt !== event.prompt) }; + } + + 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); + 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 "sendPrompt": + // 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. + if (state.turn?.stopRequested === true) { + check( + state.timers.some(([timer]) => timer === "cancelDeadline"), + "Stop is pending with no deadline armed", + 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); + } + } + // 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); + } + 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)); +} + +/** Breadth-first over every event sequence up to `depth`, skipping states already seen. */ +function explore(depth: number): { + readonly states: number; + readonly worlds: ReadonlyArray; +} { + const seen = new Set(); + let frontier: Array<{ world: World; trail: ReadonlyArray }> = [ + { world: initialWorld, trail: [] }, + ]; + const all: Array = [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)) { + const nextTrail = [...trail, event]; + const advanced = advance(world, event, nextTrail); + check(callersSettled(advanced), "a send or steer was left without an answer", nextTrail); + const key = JSON.stringify(advanced); + if (seen.has(key)) continue; + seen.add(key); + all.push(advanced); + next.push({ world: advanced, trail: nextTrail }); + } + } + frontier = next; + } + return { states: seen.size, worlds: all }; +} + +/** 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: "cancelDeadline" | "settle" | "replyQuiet" | "silent", +): 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] : [])); + +describe("AcpTurnMachine, every reachable state", () => { + // Depth 10 reaches every race below (the longest takes 10 events): about a + // million distinct states, 20 seconds; depth 11 (2.2 million) passes too. + // The alphabet is bounded to two sends, two steers, one command, one timer, + // one batch of two subagents and two turns of the agent's own. + const { states, worlds } = explore(10); + + it("explores a state space large enough to mean something", () => { + expect(states).toBeGreaterThan(1_000_000); + }); + + it("reaches a terminal event from every Stop through the deadline alone", () => { + for (const world of worlds) { + const turn = world.state.turn; + if (turn?.stopRequested !== true) continue; + const step = stepTurnMachine(world.state, fire(world.state, "cancelDeadline")); + expect(ends(step.commands).map((end) => end.turnId)).toEqual([turn.id]); + expect(step.commands.some((command) => command.type === "recycleAgent")).toBe(true); + } + }); + + it("ends every open turn exactly once when the session stops or the agent exits", () => { + for (const world of worlds) { + for (const type of ["sessionStopping", "processExited"] as const) { + if (type === "processExited" && world.state.ended) continue; + const step = stepTurnMachine(world.state, { type }); + const ended = ends(step.commands).map((end) => end.turnId); + expect(ended).toEqual(world.state.turn === undefined ? [] : [world.state.turn.id]); + expect(step.state.turn).toBeUndefined(); + expect(step.commands.some((command) => command.type === "startTurn")).toBe(false); + } + } + }); + + it("ends a hold through timers alone once the agent's work is done", () => { + for (const world of worlds) { + const state = world.state; + if (state.turn?.phase.tag !== "waiting" || state.requestsOpen > 0) continue; + // Each quiet limit that can run, run in turn, ends the hold unless a timer the agent set still runs. + const heldId = state.turn.id; + let current = state; + for (let round = 0; round < 6 && current.turn?.id === heldId; round += 1) { + const armed = current.timers.find(([timer]) => timer !== "cancelDeadline"); + 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); + } + }); +}); + +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 stayed armed from Stop until the turn ended. + expect(commands.filter((command) => command.type === "armTimer")).toEqual([ + { type: "armTimer", timer: "cancelDeadline", generation: 1 }, + ]); + }); + + 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"]); + }); + + it("the agent's own count of children, once reported, decides (wiring for the child records)", () => { + const { state } = run([ + { type: "send", sendId: "s1", turnId: "u1" }, + { type: "subagentsLaunched", id: "l1", count: 2 }, + { type: "promptAnswered", prompt: 1 }, + { type: "outcomeRead", prompt: 1, outcome: outcome("completed") }, + { type: "childrenAtWork", count: 0 }, + ]); + expect(state.timers.map(([timer]) => timer)).toEqual(["settle"]); + }); + + 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.at(-1)).toEqual({ 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"); + }); + + it("an older prompt answering after a steer moves the newer one's outcome reading on", () => { + const { commands } = run([ + { type: "send", sendId: "s1", turnId: "u1" }, + { type: "steer", steerId: "t1", expectedTurnId: "u1" }, + { type: "promptAnswered", prompt: 1 }, + ]); + expect(commands).toContainEqual({ type: "rebaseOutcome", prompt: 2 }); + }); +}); diff --git a/apps/server/src/provider/acp/AcpTurnMachine.ts b/apps/server/src/provider/acp/AcpTurnMachine.ts new file mode 100644 index 000000000..63035dae0 --- /dev/null +++ b/apps/server/src/provider/acp/AcpTurnMachine.ts @@ -0,0 +1,573 @@ +/** + * 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") restart on the + * agent's activity in the adapter; the machine only arms, disarms and hears + * them fire. + * + * @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"; + +export const ACP_TURN_TIMERS: ReadonlyArray = [ + "cancelDeadline", + "settle", + "replyQuiet", + "silent", +]; + +/** 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 whose fiber hasn't reported sending them yet. */ + 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. */ + readonly launches: ReadonlyArray; + /** Subagents launched and not yet heard back from (protocol counting). */ + readonly subagents: number; + /** The children at work by the agent's own records, once a reader reports them; wins over `subagents`. */ + readonly childrenAtWork: number | 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's fiber is sending it now. */ + | { readonly type: "promptDispatched"; readonly prompt: number } + /** A prompt answered or failed. Placed after every update it produced. */ + | { 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 } + | { readonly type: "subagentsLaunched"; readonly id: string; readonly count: number } + /** The agent's own records say this many children are still at work. */ + | { readonly type: "childrenAtWork"; readonly count: number } + /** 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 } + | { 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 } + /** An older prompt answered after this one went out: its outcome reads only from here on. */ + | { readonly type: "rebaseOutcome"; readonly prompt: number } + | { 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. */ + | { 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: [], + subagents: 0, + childrenAtWork: undefined, + replyOpen: false, + wakesOwed: 0, + requestsOpen: 0, + noticesExpected: 0, + timers: [], + timerGeneration: 0, + }; +} + +/** Subagents still out: the agent's own count when known, else the protocol count. */ +export function subagentsOut(state: AcpTurnMachineState): number { + return state.childrenAtWork ?? state.subagents; +} + +/** 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 { + const turn = state.turn; + if (turn === undefined || state.ended) return []; + const timers: Array = []; + if (turn.stopRequested) timers.push("cancelDeadline"); + 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.subagents = 0; + state.replyOpen = false; + state.wakesOwed = 0; + }; + + 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) 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(); + rejectQueue(); + }; + + /** 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. */ + const endReply = () => { + state.replyOpen = false; + if (state.wakesOwed > 0) state.wakesOwed -= 1; + else if (state.childrenAtWork === undefined && state.subagents > 0) state.subagents -= 1; + }; + + /** 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); + // 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); + state.undispatched = state.undispatched.filter((prompt) => prompt !== event.prompt); + 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 }); + } else if ( + turn.prompts.includes(event.prompt) && + turn.newest !== undefined && + state.unanswered.includes(turn.newest) + ) { + // What the older prompt left in the agent's records is its own. + commands.push({ type: "rebaseOutcome", prompt: turn.newest }); + } + } + 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) { + clearWork(); + 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": { + 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 "subagentsLaunched": { + if (state.launches.includes(event.id) || event.count <= 0) break; + state.launches = [...state.launches, event.id]; + state.subagents += event.count; + break; + } + case "childrenAtWork": { + state.childrenAtWork = Math.max(0, event.count); + 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; + if (state.ended || turn === undefined || turn.stopRequested) break; + commands.push({ type: "sendCancel" }); + if (turn.phase.tag === "waiting") { + // Nothing to answer: the cancel stops the agent's work, and the turn ends now. + clearWork(); + endTurn({ kind: "stopped" }); + break; + } + state.turn = { ...turn, stopRequested: true }; + // A cancelled prompt is followed by the agent's notice. + if (turn.phase.tag === "prompting") state.noticesExpected += 1; + 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) { + commands.push({ type: "recycleAgent" }); + endSession(); + endTurn({ kind: "stopped" }); + } + 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; + } + 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 }; +} From 400b20744503cc796c644fe7352982addb1fdd2e Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Mon, 23 Nov 2026 03:54:26 -0500 Subject: [PATCH 33/59] refactor(antigravity): subagent records answer one question, and the turn's hold is left alone The turn-lifecycle work is replacing the adapter's hold state with a state machine, so the subagent records no longer change how long a turn is held. This takes that part back out: AcpAdapter's hold code and AntigravityTurns.ts are as on the base branch. What stays is the reading side. readAntigravityChildren says, for a session, which children are running, which reported and which were killed, each with the launching tool call where the records tie it to exactly one, or that the records are not available ("no-records" or "unreadable"). The turn builder can feed it to the machine as an event. The subagent view moves into AcpSubagentRoster, outside the hold code. It reads the records when a reply message or a context update ends and when a turn completes, marks every running subagent stopped on a cancelled turn or when the session ends, and shows a launch the records don't name as done once its turn has completed. The stand-in's context size now grows with each model call, as agy's does. --- apps/server/scripts/antigravity-mock-agent.ts | 55 ++--- apps/server/src/guide/topics.ts | 2 +- apps/server/src/provider/acp/AcpAdapter.ts | 221 ++++-------------- .../src/provider/acp/AcpProviderDescriptor.ts | 5 +- .../src/provider/acp/AcpSubagentRoster.ts | 169 ++++++++++++++ .../src/provider/acp/AntigravityAcpSupport.ts | 3 + .../AntigravityChildRecords.test.ts | 214 +++++++++++------ .../antigravity/AntigravityChildRecords.ts | 122 ++++++---- .../antigravity/AntigravitySubagents.ts | 31 +-- .../antigravity/AntigravityTurns.test.ts | 41 +--- .../provider/antigravity/AntigravityTurns.ts | 30 ++- docs/providers/antigravity.md | 19 +- 12 files changed, 505 insertions(+), 407 deletions(-) create mode 100644 apps/server/src/provider/acp/AcpSubagentRoster.ts diff --git a/apps/server/scripts/antigravity-mock-agent.ts b/apps/server/scripts/antigravity-mock-agent.ts index 7a24964d5..6772487b9 100644 --- a/apps/server/scripts/antigravity-mock-agent.ts +++ b/apps/server/scripts/antigravity-mock-agent.ts @@ -28,8 +28,6 @@ * 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. - * - `subagent-records-together`: both children report before one reply. - * - `subagent-killed`: launches a subagent and kills it within the prompt. * - `tools`: an MCP call through `call_mcp_tool`, a long command line, and * a screenshot in a tool's content. It writes no subagent records. * - `subagents`: launches two subagents with their records (as 1.5.12+ @@ -169,8 +167,17 @@ const program = Effect.gen(function* () { 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) => - update(sessionId, { sessionUpdate: "usage_update", used: 9_000, size: 1_048_576 }); + 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", @@ -406,7 +413,7 @@ const program = Effect.gen(function* () { }).pipe(Effect.forkDetach); return { stopReason: "end_turn" as const }; } - if (scenario === "subagent-records" || scenario === "subagent-records-together") { + if (scenario === "subagent-records") { const launch = (callId: string, child: string, role: string, prompt: string) => Effect.gen(function* () { recordChild({ @@ -421,7 +428,8 @@ const program = Effect.gen(function* () { sessionUpdate: "tool_call", toolCallId: callId, kind: "other", - title: "Run invoke_subagent", + // 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 }, }); @@ -433,13 +441,6 @@ const program = Effect.gen(function* () { yield* Effect.gen(function* () { yield* Effect.sleep("400 millis"); recordReport(sessionId, "child-research", "The flaky test is api.test.ts."); - if (scenario === "subagent-records-together") { - // Both reports wake one reply. - recordReport(sessionId, "child-review", "The fix looks right."); - yield* say(sessionId, " Both reported."); - yield* modelCallEnds(sessionId); - return; - } yield* say(sessionId, " The researcher found it."); yield* modelCallEnds(sessionId); // Longer than a held turn's settle: only the records hold it. @@ -450,36 +451,6 @@ const program = Effect.gen(function* () { }).pipe(Effect.forkDetach); return { stopReason: "end_turn" as const }; } - if (scenario === "subagent-killed") { - recordChild({ - parent: sessionId, - child: "child-stray", - callId: "call_stray", - role: "Explorer", - prompt: "Look around", - state: "SUBAGENT_STATE_ALIVE", - }); - yield* update(sessionId, { - sessionUpdate: "tool_call", - toolCallId: "call_stray", - kind: "other", - title: "Run invoke_subagent", - status: "completed", - rawInput: { Role: "Explorer", Prompt: "Look around" }, - }); - // `manage_subagents` kill only rewrites the record's state. - recordChild({ - parent: sessionId, - child: "child-stray", - callId: "call_stray", - role: "Explorer", - prompt: "Look around", - state: "SUBAGENT_STATE_KILLED", - }); - yield* say(sessionId, "Stopped the explorer."); - yield* modelCallEnds(sessionId); - return { stopReason: "end_turn" as const }; - } if (scenario === "tools") { yield* update(sessionId, { sessionUpdate: "tool_call", diff --git a/apps/server/src/guide/topics.ts b/apps/server/src/guide/topics.ts index 7d8e38e4b..63d1cbbce 100644 --- a/apps/server/src/guide/topics.ts +++ b/apps/server/src/guide/topics.ts @@ -311,7 +311,7 @@ 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. -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 meanwhile steers the turn. Each subagent Antigravity launches shows like other agents' subagents, with its role, prompt, report and recent steps, and holds the turn until it reports or the agent stops it. Images and audio go to Antigravity inline, PDFs and text files as documents, other files as a path. Its turns count on {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 meanwhile steers the turn. 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 once a chat has started, the commands that chat's Antigravity offers. Such a message goes as typed, even in plan mode. Editing an earlier message starts Antigravity over with only the turns before it, since it can't rewind its own conversation; anything it still ran stops first. diff --git a/apps/server/src/provider/acp/AcpAdapter.ts b/apps/server/src/provider/acp/AcpAdapter.ts index 81ada6011..ec561bdb5 100644 --- a/apps/server/src/provider/acp/AcpAdapter.ts +++ b/apps/server/src/provider/acp/AcpAdapter.ts @@ -110,25 +110,17 @@ import { import { makeAcpNativeLoggers } from "./AcpNativeLogging.ts"; import type { AcpExtensionContext, - AcpExtensionRuntimeEvent, AcpPromptFailure, AcpPromptOutcome, AcpPromptPlanMode, AcpProviderDescriptor, AcpProviderSettings, - AcpSubagentLaunch, AcpSubagents, AcpTurnOutcome, AcpWorkAfterPrompt, } from "./AcpProviderDescriptor.ts"; import { type AcpAttachmentBudget, acpAttachmentContent } from "./AcpPromptAttachments.ts"; -import { - type AcpSubagentStatus, - acpSubagentSettledEvents, - acpSubagentSnapshotEvent, - acpSubagentStartedEvents, - describeAcpSubagentLaunches, -} from "./AcpSubagentEvents.ts"; +import { type AcpSubagentRoster, makeAcpSubagentRoster } from "./AcpSubagentRoster.ts"; import { applyAcpModelSelection, defaultResolveAcpModelId, @@ -247,6 +239,8 @@ interface AcpSessionContext { 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 @@ -329,23 +323,8 @@ interface AcpSessionContext { readonly workAfterPrompt: Map; /** Subagent launches counted so far, by tool call id, so a repeated update counts once. */ readonly subagentLaunches: Set; - /** - * Subagents launched and not heard back from. Counted down by the replies - * the agent starts by itself; set exactly from the agent's records - * (`subagents`) when they name every child still out. - */ + /** Subagents launched and not heard back from (a reply the agent started by itself ended since). */ subagentsOut: number; - /** The launching calls of the subagents still out, for the records (`subagents`). */ - readonly subagentsPending: Set; - /** Subagents shown for this session's launches (`subagents`), by launching call id. */ - readonly subagentRoster: Map< - string, - { - readonly turnId: TurnId | undefined; - readonly launch: AcpSubagentLaunch; - status: AcpSubagentStatus; - } - >; /** A reply the agent started by itself has output and no closing `usage_update` yet. */ replyOpen: boolean; /** A held command or timer ended since the last reply: the next reply is its wake. */ @@ -805,7 +784,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) => { @@ -1263,17 +1249,13 @@ export function makeAcpAdapter( /** * The `usage_update` that ends each model call (`heldTurns`): a reply the - * agent started by itself is over. The agent's records then say which - * subagents are done (`subagents`); the reader moves on meanwhile. + * agent started by itself is over. */ - const noteReplyEnd = (ctx: AcpSessionContext) => - Effect.gen(function* () { - if (descriptor.heldTurns === undefined) return; - ctx.lastAgentActivityMs = Date.now(); - if (!ctx.replyOpen) return; - endReply(ctx); - yield* checkSubagents(ctx, "reply").pipe(Effect.forkIn(ctx.scope)); - }); + const noteReplyEnd = (ctx: AcpSessionContext) => { + if (descriptor.heldTurns === undefined) return; + ctx.lastAgentActivityMs = Date.now(); + if (ctx.replyOpen) endReply(ctx); + }; /** * A reply the agent started by itself ended (its `usage_update`, or a @@ -1287,122 +1269,6 @@ export function makeAcpAdapter( else if (ctx.subagentsOut > 0) ctx.subagentsOut -= 1; }; - /** - * Reads which launched subagents are done (`subagents`). One that - * reported or was killed shows as ended and leaves the pending set. When - * the records name every child still pending, the hold is exactly those - * children (several reports in one reply free them all; a kill frees - * one). Otherwise the count the replies keep stands, and once it reaches - * zero after a reply, the children the records don't name show as done. - */ - const checkSubagents = (ctx: AcpSessionContext, moment: "prompt" | "reply") => - Effect.gen(function* () { - const subagents = descriptor.subagents; - if (subagents === undefined) return; - const running = [...ctx.subagentRoster].flatMap(([id, entry]) => - entry.status === "running" ? [id] : [], - ); - const ids = [...new Set([...running, ...ctx.subagentsPending])]; - if (ids.length === 0) return; - const states = yield* subagents.states({ - sessionId: ctx.acpSessionId, - launchCallIds: ids, - }); - for (const [id, state] of states ?? []) { - if (state.state === "working") continue; - ctx.subagentsPending.delete(id); - yield* settleSubagent( - ctx, - id, - state.state === "killed" ? "interrupted" : "completed", - state.report, - ); - } - if (states !== undefined && [...ctx.subagentsPending].every((id) => states.has(id))) { - ctx.subagentsOut = ctx.subagentsPending.size; - return; - } - if (moment === "reply" && ctx.subagentsOut === 0) { - for (const id of ids) { - ctx.subagentsPending.delete(id); - yield* settleSubagent(ctx, id, "completed", undefined); - } - } - }); - - /** Emits a subagent's events on the turn that launched it. */ - const emitSubagentEvents = ( - ctx: AcpSessionContext, - turnId: TurnId | undefined, - events: ReadonlyArray, - ) => - Effect.forEach( - events, - (event) => - Effect.gen(function* () { - yield* offerRuntimeEvent({ - ...event, - ...(yield* makeEventStamp()), - provider: PROVIDER, - threadId: ctx.threadId, - ...(turnId ? { turnId } : {}), - } as ProviderRuntimeEvent); - }), - { discard: true }, - ); - - /** The snapshot of the subagents still running (`subagents`). */ - const emitSubagentSnapshot = (ctx: AcpSessionContext) => - emitSubagentEvents(ctx, undefined, [ - acpSubagentSnapshotEvent( - [...ctx.subagentRoster].flatMap(([launchCallId, entry]) => - entry.status === "running" ? [{ launchCallId, launch: entry.launch }] : [], - ), - ), - ]); - - /** Shows a launch as a running subagent, once (`subagents`). */ - const noteSubagentLaunch = ( - ctx: AcpSessionContext, - toolCall: AcpToolCallState, - turnId: TurnId | undefined, - ) => - Effect.gen(function* () { - const subagents = descriptor.subagents; - if (subagents === undefined || toolCall.status !== "completed") return; - const id = toolCall.toolCallId; - if (ctx.subagentRoster.has(id)) return; - const launches = subagents.launches(toolCall); - if (launches === undefined) return; - const launch = describeAcpSubagentLaunches(launches); - ctx.subagentRoster.set(id, { turnId, launch, status: "running" }); - yield* emitSubagentEvents(ctx, turnId, acpSubagentStartedEvents(id, launch)); - yield* emitSubagentSnapshot(ctx); - }); - - /** A shown subagent ended, once. */ - const settleSubagent = ( - ctx: AcpSessionContext, - id: string, - status: Exclude, - report: string | undefined, - ) => - Effect.gen(function* () { - const entry = ctx.subagentRoster.get(id); - if (entry === undefined || entry.status !== "running") return; - entry.status = status; - yield* emitSubagentEvents(ctx, entry.turnId, acpSubagentSettledEvents(id, status, report)); - yield* emitSubagentSnapshot(ctx); - }); - - /** Stop ends the session's subagents with its turn (Antigravity 1.5.10 cancels them). */ - const interruptSubagents = (ctx: AcpSessionContext) => - Effect.forEach( - [...ctx.subagentRoster].flatMap(([id, entry]) => (entry.status === "running" ? [id] : [])), - (id) => settleSubagent(ctx, id, "interrupted", undefined), - { discard: true }, - ); - /** Keeps count of the work a tool call goes on with after its prompt (`heldTurns`). */ const trackWorkAfterPrompt = (ctx: AcpSessionContext, toolCall: AcpToolCallState) => { const kind = descriptor.heldTurns?.workAfterPrompt(toolCall); @@ -1416,7 +1282,6 @@ export function makeAcpAdapter( if (toolCall.status === "completed" && !ctx.subagentLaunches.has(id)) { ctx.subagentLaunches.add(id); ctx.subagentsOut += 1; - ctx.subagentsPending.add(id); } return; } @@ -1435,7 +1300,6 @@ export function makeAcpAdapter( const clearWorkAfterPrompt = (ctx: AcpSessionContext) => { ctx.workAfterPrompt.clear(); ctx.subagentsOut = 0; - ctx.subagentsPending.clear(); ctx.replyOpen = false; ctx.workEndedSinceReply = false; }; @@ -1515,10 +1379,7 @@ export function makeAcpAdapter( continue; } const quietMs = now - ctx.lastAgentActivityMs; - if (ctx.replyOpen && quietMs >= replyQuietMs) { - endReply(ctx); - yield* checkSubagents(ctx, "reply").pipe(Effect.forkIn(ctx.scope)); - } + if (ctx.replyOpen && quietMs >= replyQuietMs) endReply(ctx); const work = [...ctx.workAfterPrompt.values()]; const waiting = work.length > 0 || ctx.subagentsOut > 0 || ctx.replyOpen; const settled = !waiting && quietMs >= Duration.toMillis(ACP_HELD_TURN_SETTLE); @@ -1582,7 +1443,7 @@ export function makeAcpAdapter( yield* settlePendingApprovalsAsCancelled(ctx.pendingApprovals); yield* settlePendingUserInputsAsEmptyAnswers(ctx.pendingUserInputs); // The agent's process takes its subagents with it. - yield* interruptSubagents(ctx); + if (ctx.subagentRoster !== undefined) yield* ctx.subagentRoster.end; if (ctx.promptFiber) { yield* Fiber.interrupt(ctx.promptFiber); } @@ -2382,6 +2243,24 @@ export function makeAcpAdapter( 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) && @@ -2419,8 +2298,6 @@ export function makeAcpAdapter( workAfterPrompt: new Map(), subagentLaunches: new Set(), subagentsOut: 0, - subagentsPending: new Set(), - subagentRoster: new Map(), replyOpen: false, workEndedSinceReply: false, lastAgentActivityMs: 0, @@ -2460,7 +2337,7 @@ export function makeAcpAdapter( } return; case "ContextUsage": { - yield* noteReplyEnd(ctx); + noteReplyEnd(ctx); // 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. @@ -2518,11 +2395,12 @@ export function makeAcpAdapter( trackWorkAfterPrompt(ctx, event.toolCall); } // A launch approved earlier completes with nothing new to show. - yield* noteSubagentLaunch( - ctx, - event.toolCall, - ctx.toolCallTurns.get(event.toolCall.toolCallId) ?? ctx.activeTurnId, - ); + if (ctx.subagentRoster !== undefined) { + yield* ctx.subagentRoster.noteToolCall( + event.toolCall, + ctx.toolCallTurns.get(event.toolCall.toolCallId) ?? ctx.activeTurnId, + ); + } return; case "ReasoningDelta": yield* logNative(ctx.threadId, "session/update", event.rawPayload); @@ -2577,7 +2455,9 @@ export function makeAcpAdapter( const turnId = yield* turnForOutput(ctx, toolCallId); if (descriptor.heldTurns !== undefined) trackWorkAfterPrompt(ctx, event.toolCall); - yield* noteSubagentLaunch(ctx, event.toolCall, turnId); + if (ctx.subagentRoster !== undefined) { + yield* ctx.subagentRoster.noteToolCall(event.toolCall, turnId); + } if ( event.toolCall.status === "completed" || event.toolCall.status === "failed" @@ -3162,10 +3042,6 @@ export function makeAcpAdapter( stopReason: result.stopReason ?? null, }; lostSession = hidden?.sessionLost === true; - // A child killed or done within the prompt holds nothing (`subagents`). - if (payload.state === "completed" && ctx.subagentsPending.size > 0) { - yield* checkSubagents(ctx, "prompt"); - } // The agent goes on with work it started (`heldTurns`): the turn // stays open, working and stoppable, until that work is done. if ( @@ -3330,7 +3206,6 @@ export function makeAcpAdapter( ), ), ); - yield* interruptSubagents(ctx); if (turnId === undefined) return; // A turn waiting on the agent's work (`heldTurns`) has no prompt to // wait on: the cancel stopped that work, and the turn ends here. Taken diff --git a/apps/server/src/provider/acp/AcpProviderDescriptor.ts b/apps/server/src/provider/acp/AcpProviderDescriptor.ts index 4285637a4..062901b99 100644 --- a/apps/server/src/provider/acp/AcpProviderDescriptor.ts +++ b/apps/server/src/provider/acp/AcpProviderDescriptor.ts @@ -249,9 +249,8 @@ export interface AcpSubagentState { * 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, and a turn held for - * subagents (`heldTurns`) lasts until every child has reported or been - * killed, as far as the records tell. + * did. With it, each launch shows as a subagent (`AcpSubagentRoster`). It + * plays no part in how long a turn is held (`heldTurns`). */ export interface AcpSubagents { /** The subagents this tool call launches; `undefined` for any other call. */ diff --git a/apps/server/src/provider/acp/AcpSubagentRoster.ts b/apps/server/src/provider/acp/AcpSubagentRoster.ts new file mode 100644 index 000000000..ee0189039 --- /dev/null +++ b/apps/server/src/provider/acp/AcpSubagentRoster.ts @@ -0,0 +1,169 @@ +/** + * 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 the records don't name + * show as done; + * - 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. + * + * @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 { + type AcpSubagentStatus, + acpSubagentSettledEvents, + acpSubagentSnapshotEvent, + acpSubagentStartedEvents, + describeAcpSubagentLaunches, +} from "./AcpSubagentEvents.ts"; + +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; +} + +interface Entry { + readonly turnId: TurnId | undefined; + readonly launch: AcpSubagentLaunch; + status: AcpSubagentStatus; +} + +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 running = () => + [...entries].flatMap(([id, entry]) => (entry.status === "running" ? [id] : [])); + + const emitSnapshot = Effect.suspend(() => + input.emit( + acpSubagentSnapshotEvent( + [...entries].flatMap(([launchCallId, entry]) => + entry.status === "running" ? [{ launchCallId, launch: entry.launch }] : [], + ), + ), + undefined, + ), + ); + + const settle = (id: string, status: Exclude, report?: string) => + Effect.gen(function* () { + const entry = entries.get(id); + if (entry === undefined || entry.status !== "running") return; + entry.status = status; + for (const event of acpSubagentSettledEvents(id, status, report)) { + yield* input.emit(event, entry.turnId); + } + yield* emitSnapshot; + }); + + /** + * Settles the running subagents the records say are done. With `ended`, + * the launches of that turn the records don't name show as done too. + */ + const read = (ended: TurnId | undefined) => + Effect.gen(function* () { + const ids = running(); + if (ids.length === 0) return; + const states = yield* input.subagents.states({ + sessionId: input.sessionId, + launchCallIds: ids, + }); + for (const id of ids) { + const state = states?.get(id); + if (state === undefined) { + if (ended !== undefined && entries.get(id)?.turnId === ended) + yield* settle(id, "completed"); + continue; + } + if (state.state === "working") continue; + 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: { ended: TurnId | undefined } | undefined; + const requestRead = (ended: TurnId | undefined): Effect.Effect => + Effect.suspend(() => { + if (running().length === 0) return Effect.void; + if (reading) { + again = { ended: ended ?? again?.ended }; + return Effect.void; + } + reading = true; + const loop: Effect.Effect = read(ended).pipe( + Effect.ensuring(Effect.sync(() => (reading = false))), + Effect.andThen( + Effect.suspend(() => { + const next = again; + again = undefined; + return next === undefined ? Effect.void : requestRead(next.ended); + }), + ), + ); + return input.fork(loop); + }); + + const stopAll = Effect.suspend(() => + Effect.forEach(running(), (id) => settle(id, "interrupted"), { discard: true }), + ); + + return { + noteToolCall: (toolCall, turnId) => + Effect.gen(function* () { + if (toolCall.status !== "completed" || entries.has(toolCall.toolCallId)) return; + const launches = input.subagents.launches(toolCall); + if (launches === undefined) return; + const launch = describeAcpSubagentLaunches(launches); + entries.set(toolCall.toolCallId, { turnId, launch, status: "running" }); + for (const event of acpSubagentStartedEvents(toolCall.toolCallId, launch)) { + yield* input.emit(event, turnId); + } + yield* emitSnapshot; + }), + observe: (event) => { + if ( + event.type === "thread.token-usage.updated" || + (event.type === "item.completed" && event.payload.itemType === "assistant_message") + ) { + return requestRead(undefined); + } + if (event.type !== "turn.completed") return Effect.void; + if (event.payload.state === "cancelled") return stopAll; + return requestRead(event.payload.state === "completed" ? event.turnId : undefined); + }, + end: stopAll, + }; +} diff --git a/apps/server/src/provider/acp/AntigravityAcpSupport.ts b/apps/server/src/provider/acp/AntigravityAcpSupport.ts index a2d625d88..c858fc988 100644 --- a/apps/server/src/provider/acp/AntigravityAcpSupport.ts +++ b/apps/server/src/provider/acp/AntigravityAcpSupport.ts @@ -64,6 +64,7 @@ import { } 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, @@ -830,6 +831,8 @@ export function makeAntigravityDescriptor( 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: { diff --git a/apps/server/src/provider/antigravity/AntigravityChildRecords.test.ts b/apps/server/src/provider/antigravity/AntigravityChildRecords.test.ts index a72df4d88..4eb445393 100644 --- a/apps/server/src/provider/antigravity/AntigravityChildRecords.test.ts +++ b/apps/server/src/provider/antigravity/AntigravityChildRecords.test.ts @@ -7,7 +7,12 @@ import { it } from "@effect/vitest"; import * as Effect from "effect/Effect"; import { describe, expect } from "vite-plus/test"; -import { antigravityChildStates, antigravityChildTranscript } from "./AntigravityChildRecords.ts"; +import { + type AntigravityChildrenReading, + antigravityChildOf, + antigravityChildTranscript, + readAntigravityChildren, +} from "./AntigravityChildRecords.ts"; const PARENT = "7d40e54d-5977-4239-940b-246cdd81a12b"; @@ -35,87 +40,144 @@ async function makeProfile() { }); await write([id, ".system_generated", "messages", "read.json"], { launch: true }); }; - return { profile, brain, write, child }; + const report = (child: string, content: string) => + write([PARENT, ".system_generated", "messages", `${child}-report.json`], { + sender: child, + content, + }); + return { profile, brain, write, child, report }; } -describe("Antigravity child records", () => { - it.live("reads each child's state from its records, and leaves out what they don't prove", () => - Effect.gen(function* () { - const records = yield* Effect.promise(makeProfile); - 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"); - // Two children claiming one launch: neither is proven its child. - await records.child("child-twin-a", "call_twin"); - await records.child("child-twin-b", "call_twin"); - await records.write([PARENT, ".system_generated", "messages", "report.json"], { - sender: "child-reported", - content: "README.md has 42 lines.", +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" } } }, + }); }); - // 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"], }); - }); - const states = yield* antigravityChildStates(records.profile, PARENT, [ - "call_working", - "call_reported", - "call_killed", - "call_twin", - "call_followup", - ]); - expect( - Object.fromEntries([...states!].map(([id, child]) => [id, [child.state, child.report]])), - ).toEqual({ - call_working: ["working", undefined], - call_reported: ["reported", "README.md has 42 lines."], - call_killed: ["killed", undefined], - }); - // Without argumentsJson the role comes from the child's entry and the prompt from its launch. - expect(states!.get("call_working")?.launch).toEqual({ - role: "Line Counter", - prompt: "Count lines in README.md", - }); - // A child with no transcript yet is still named, with its instruction. - const transcript = yield* antigravityChildTranscript(records.profile, PARENT, "call_working"); - expect(transcript?.child.conversationId).toBe("child-working"); - expect(transcript?.entries).toEqual([ - { id: "launch", role: "user", text: "Count lines in README.md", toolUses: [] }, - ]); - yield* Effect.promise(() => rm(records.profile, { recursive: true, force: true })); - }), + 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("proves nothing through a link or an unreadable inbox", () => - Effect.gen(function* () { - const records = yield* Effect.promise(makeProfile); - 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"]); + 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(); + }), + ), + ); - // A message that isn't JSON could be the one that matters. - yield* Effect.promise(() => - records.write([PARENT, ".system_generated", "messages", "broken.json"], "{not json"), - ); - expect(yield* antigravityChildStates(records.profile, PARENT, ["call_a"])).toBeUndefined(); - // A session id that walks a path is refused outright. - expect(yield* antigravityChildStates(records.profile, "../x", ["call_a"])).toBeUndefined(); - yield* Effect.promise(async () => { - await rm(records.profile, { recursive: true, force: true }); - await rm(elsewhere, { recursive: true, force: true }); - }); - }), + 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); + // A message that isn't JSON could be the report that matters. + yield* Effect.promise(() => + records.write([PARENT, ".system_generated", "messages", "broken.json"], "{not json"), + ); + expect(yield* readAntigravityChildren(records.profile, PARENT)).toEqual({ + available: false, + reason: "unreadable", + }); + }), + ), + ); + + 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 })); + }), + ), ); }); diff --git a/apps/server/src/provider/antigravity/AntigravityChildRecords.ts b/apps/server/src/provider/antigravity/AntigravityChildRecords.ts index dc91f05d8..c2b30b91c 100644 --- a/apps/server/src/provider/antigravity/AntigravityChildRecords.ts +++ b/apps/server/src/provider/antigravity/AntigravityChildRecords.ts @@ -62,7 +62,10 @@ export interface AntigravityChildLaunch { /** One child the session started, as its records describe it. */ export interface AntigravityChild { readonly conversationId: string; - /** The parent's `invoke_subagent` tool call that started it. */ + /** + * 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. */ @@ -167,29 +170,51 @@ function launchCall(message: unknown, parentId: string) { } /** - * Every child the session started, with its launch and state, or - * `undefined` when the records can't be read whole. + * 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. */ +export type AntigravityChildrenReading = + | { readonly available: false; readonly reason: "no-records" | "unreadable" } + | { + readonly available: true; + readonly running: ReadonlyArray; + readonly reported: ReadonlyArray; + readonly killed: ReadonlyArray; + }; + +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 | undefined> { - if (!NATIVE_ID.test(parentId)) return undefined; +): Promise< + | { readonly children: ReadonlyArray } + | { readonly reason: "no-records" | "unreadable" } +> { + if (!NATIVE_ID.test(parentId)) return { reason: "unreadable" }; const folder = await antigravityProfileEntry( profileDir, generated(parentId, "subagents"), "directory", ); - if (folder === undefined) return []; + if (folder === undefined) return { reason: "no-records" }; const names = await NodeFSP.readdir(folder.path).catch(() => undefined); - if (names === undefined) return undefined; + 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)] : [], ); - if (childIds.length > MAX_CHILDREN) return undefined; + if (childIds.length > MAX_CHILDREN) return { reason: "unreadable" }; const budget: ReadBudget = { bytes: MAX_READ_BYTES }; const parentInbox = await readInbox(profileDir, parentId, budget); - if (parentInbox === undefined) return undefined; + if (parentInbox === undefined) return { reason: "unreadable" }; const children: Array = []; for (const childId of childIds) { const record = await readRecord( @@ -197,11 +222,11 @@ async function readChildren( generated(parentId, "subagents", `${childId}.json`), budget, ); - if (!isRecord(record)) return undefined; + if (!isRecord(record)) return { reason: "unreadable" }; const recordedId = stringField(record, "conversationId"); - if (recordedId !== undefined && recordedId !== childId) return undefined; + if (recordedId !== undefined && recordedId !== childId) return { reason: "unreadable" }; const inbox = await readInbox(profileDir, childId, budget); - if (inbox === undefined) return undefined; + if (inbox === undefined) return { reason: "unreadable" }; const launches = inbox.flatMap((message) => { const call = launchCall(message, parentId); return call === undefined ? [] : [{ call, content: stringField(message, "content") }]; @@ -229,35 +254,51 @@ async function readChildren( report: reports.length > 0 ? boundAntigravityText(reports.join("\n\n").trim()) : undefined, }); } - return children; -} - -/** The one child a launching call started, or `undefined` when none or several claim it. */ -function childOf(children: ReadonlyArray, launchCallId: string) { - const claimed = children.filter((child) => child.launchCallId === launchCallId); - return claimed.length === 1 ? claimed[0] : 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 { + children: children.map((child) => + child.launchCallId !== undefined && claims.get(child.launchCallId) !== 1 + ? { ...child, launchCallId: undefined } + : child, + ), + }; } /** - * What became of the children these launching calls started, by call id. - * A call the records don't tie to exactly one child is left out; `undefined` - * when the records can't be read. + * 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 antigravityChildStates = ( - profileDir: string, - parentId: string, - launchCallIds: ReadonlyArray, -) => - Effect.tryPromise(async () => { - const children = await readChildren(profileDir, parentId); - if (children === undefined) return undefined; - const states = new Map(); - for (const id of launchCallIds) { - const child = childOf(children, id); - if (child !== undefined) states.set(id, child); - } - return states as ReadonlyMap; - }).pipe(Effect.orElseSucceed(() => undefined)); +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"), + }; + }).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 ────────────────────────────────────────────────── @@ -407,8 +448,11 @@ export const antigravityChildTranscript = ( launchCallId: string, ) => Effect.tryPromise(async () => { - const children = await readChildren(profileDir, parentId); - const child = children === undefined ? undefined : childOf(children, launchCallId); + 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, diff --git a/apps/server/src/provider/antigravity/AntigravitySubagents.ts b/apps/server/src/provider/antigravity/AntigravitySubagents.ts index d2896b073..bd8525bb3 100644 --- a/apps/server/src/provider/antigravity/AntigravitySubagents.ts +++ b/apps/server/src/provider/antigravity/AntigravitySubagents.ts @@ -16,8 +16,9 @@ import type { AcpSubagentState, AcpSubagents } from "../acp/AcpProviderDescripto import type { AcpToolCallState } from "../acp/AcpRuntimeModel.ts"; import { antigravityChildLaunches, - antigravityChildStates, + antigravityChildOf, antigravityChildTranscript, + readAntigravityChildren, } from "./AntigravityChildRecords.ts"; /** The titles a subagent launch arrives under, asked or auto-approved. */ @@ -48,20 +49,20 @@ export function antigravitySubagents(profileDir: string): AcpSubagents { ? antigravityChildLaunches(toolCall.data.rawInput) : undefined, states: ({ sessionId, launchCallIds }) => - antigravityChildStates(profileDir, sessionId, launchCallIds).pipe( - Effect.map((children) => - children === undefined - ? undefined - : new Map( - [...children].map(([id, child]): [string, AcpSubagentState] => [ - id, - { - state: child.state, - ...(child.report !== undefined ? { report: child.report } : {}), - }, - ]), - ), - ), + 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 states; + }), ), transcript: ({ sessionId, launchCallId }) => antigravityChildTranscript(profileDir, sessionId, launchCallId).pipe( diff --git a/apps/server/src/provider/antigravity/AntigravityTurns.test.ts b/apps/server/src/provider/antigravity/AntigravityTurns.test.ts index 6859d1357..5d34efd25 100644 --- a/apps/server/src/provider/antigravity/AntigravityTurns.test.ts +++ b/apps/server/src/provider/antigravity/AntigravityTurns.test.ts @@ -256,7 +256,7 @@ describe("Antigravity turns", () => { }).pipe(Effect.scoped, Effect.provide(testServices)), ); - it.live("holds a turn until every subagent reported, and shows each with its steps", () => + 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({ @@ -344,45 +344,6 @@ describe("Antigravity turns", () => { }).pipe(Effect.scoped, Effect.provide(testServices)), ); - it.live("ends a held turn when several subagents report in one reply", () => - Effect.gen(function* () { - const agy = yield* startAgy("subagent-records-together"); - const { turnId } = yield* agy.adapter.sendTurn({ - threadId: agy.threadId, - input: "find and review the flaky test", - attachments: [], - }); - // Counting replies alone would hold this until the 30-minute limit. - yield* agy.waitFor((events) => completedTurns(events).length === 1); - expect(completedTurns(agy.events)[0]).toMatchObject({ - turnId, - payload: { state: "completed" }, - }); - expect(replyTo(agy.events, turnId)).toContain("Both reported."); - expect(subagentStatuses(agy.events)).toEqual({ - call_research: "completed", - call_review: "completed", - }); - }).pipe(Effect.scoped, Effect.provide(testServices)), - ); - - it.live("does not hold a turn for a subagent killed within it", () => - Effect.gen(function* () { - const agy = yield* startAgy("subagent-killed"); - const { turnId } = yield* agy.adapter.sendTurn({ - threadId: agy.threadId, - input: "explore, then stop", - attachments: [], - }); - yield* agy.waitFor((events) => completedTurns(events).length === 1); - expect(completedTurns(agy.events)[0]).toMatchObject({ - turnId, - payload: { state: "completed" }, - }); - expect(subagentStatuses(agy.events)).toEqual({ call_stray: "interrupted" }); - }).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"); diff --git a/apps/server/src/provider/antigravity/AntigravityTurns.ts b/apps/server/src/provider/antigravity/AntigravityTurns.ts index 75229ff74..5066ce3b8 100644 --- a/apps/server/src/provider/antigravity/AntigravityTurns.ts +++ b/apps/server/src/provider/antigravity/AntigravityTurns.ts @@ -32,10 +32,16 @@ import type { } from "../acp/AcpProviderDescriptor.ts"; import type { AcpToolCallState } from "../acp/AcpRuntimeModel.ts"; import { antigravityLogPosition, antigravityTurnSteps } from "./AntigravitySessionLog.ts"; -import { antigravitySubagents, 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 subagent launch: the call returns at once and the subagent works on. */ +const SUBAGENT_TITLES = new Set([ + "Running start_subagent", + "Run start_subagent?", + "Running invoke_subagent", + "Run invoke_subagent?", +]); /** * 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 @@ -46,6 +52,13 @@ export const ANTIGRAVITY_SILENT_WORK_LIMIT = Duration.minutes(30); const isRecord = (value: unknown): value is Record => typeof value === "object" && value !== null && !Array.isArray(value); +/** A launch's input: one subagent (`Role`, `Prompt`), or a batch (`Subagents`). */ +function isSubagentLaunch(input: unknown): boolean { + if (!isRecord(input)) return false; + if (typeof input.Role === "string" && typeof input.Prompt === "string") return true; + return Array.isArray(input.Subagents) && input.Subagents.length > 0; +} + /** * 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 @@ -59,9 +72,14 @@ export function antigravityWorkAfterPrompt( if (toolCall.kind === "execute") { return isRecord(input) && input.IsDaemon === true ? undefined : "command"; } - // Stage 3: one reading of a launch, shared with the subagent rows; it adds - // 1.5's auto-approved title ("Run invoke_subagent"). - if (isAntigravitySubagentLaunch(toolCall)) return "subagent"; + if ( + (toolCall.kind === undefined || toolCall.kind === "other") && + toolCall.title !== undefined && + SUBAGENT_TITLES.has(toolCall.title) && + isSubagentLaunch(input) + ) { + return "subagent"; + } return undefined; } @@ -225,7 +243,6 @@ export function antigravityTurnBehavior( AcpProviderDescriptor, | "agentTurns" | "heldTurns" - | "subagents" | "steerWithPrompt" | "promptOutcome" | "usageLedger" @@ -239,9 +256,6 @@ export function antigravityTurnBehavior( workAfterPrompt: antigravityWorkAfterPrompt, silentLimit: ANTIGRAVITY_SILENT_WORK_LIMIT, }, - // Stage 3: each launch shows as a subagent, and the hold on subagents - // lasts until the CLI's records say every child reported or was killed. - subagents: antigravitySubagents(profileDir), steerWithPrompt: true, promptOutcome: { watch: (sessionId, model) => diff --git a/docs/providers/antigravity.md b/docs/providers/antigravity.md index 7f9b8e33a..4f45cdef5 100644 --- a/docs/providers/antigravity.md +++ b/docs/providers/antigravity.md @@ -144,10 +144,8 @@ a cancel). A reply the agent starts after the turn ended opens a turn of its own 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. A timer -holds the turn until it fires. A subagent holds the turn until it has sent the agent its report or -the agent stopped it, as the CLI's records say (see Subagents), so several reports in one reply free -them all and a stopped subagent frees its hold. Where the records don't name every subagent still -out, each report (a reply no finished command or timer woke) frees one subagent; if the CLI then +holds the turn until it fires. Subagents are only known to finish by the report the agent gives when +one ends, so each report (a reply no finished command or timer woke) frees one subagent. If the CLI sends several reports in one reply, the turn holds until the 30-minute limit or Stop. If the agent exits while a turn is held, the turn fails with that reason and the next message starts it again. @@ -161,16 +159,17 @@ When Antigravity launches a subagent (its `invoke_subagent` tool), the subagent 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 checked -when the agent's prompt ends and when each reply it starts by itself ends: +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 and no longer keeps the turn running. +- One the agent stopped (`manage_subagents`) shows as stopped. - Stop ends every running subagent with the turn. -- When the records don't say which subagent a launch started, its view says "Antigravity did not - record which subagent this started", and the turn falls back to the rule above. +- 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". -The view is read-only: you can't message a subagent directly. +The view is read-only: you can't message a subagent directly. How long the turn stays open is the +rule above; the records don't change it. ### Tool rows From b958948a8af3433811417c8fdb727e7ea8ff5825 Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Mon, 23 Nov 2026 04:14:14 -0500 Subject: [PATCH 34/59] fix(antigravity): call_mcp_tool is only shown as an MCP tool when the call positively is one A call counted as call_mcp_tool whenever its input named ServerName and ToolName, so a command or an edit carrying those names could show as an unrelated MCP tool, and its approval lost the command being authorized. Now the update itself must say so: an execute call titled "MCP Tool " whose input is only ServerName, ToolName and object Arguments, with no command field, diff, terminal or file location. A later update with any command or edit evidence turns it back into what it says it is. The hook gets the report that just arrived (AcpToolCallReport), since the merged state has lost the agent's own title. An approval keeps its request kind, so every access mode asks and answers as before, and for a real MCP call its words name the server, the tool and the arguments. Tool text bounding now keeps content blocks valid ACP: each block is rebuilt in its own shape (a text block that starts with data:image/ stays text, binary resources and images are left out) and checked against the schema. Only an edit's diff block keeps its whole old and new text; output fields with those names are budgeted like any other. The 8,000-character limit includes the cut marker, and `cmd` keeps its start like the other command fields. --- apps/server/scripts/antigravity-mock-agent.ts | 34 +- apps/server/src/provider/acp/AcpAdapter.ts | 18 +- .../src/provider/acp/AcpProviderDescriptor.ts | 14 +- .../src/provider/acp/AcpRuntimeModel.ts | 14 + .../src/provider/acp/AcpSessionRuntime.ts | 14 +- .../antigravity/AntigravityToolCalls.test.ts | 164 +++++++++- .../antigravity/AntigravityToolCalls.ts | 292 +++++++++++++----- .../antigravity/AntigravityTurns.test.ts | 51 +++ 8 files changed, 506 insertions(+), 95 deletions(-) diff --git a/apps/server/scripts/antigravity-mock-agent.ts b/apps/server/scripts/antigravity-mock-agent.ts index 6772487b9..18b9e565e 100644 --- a/apps/server/scripts/antigravity-mock-agent.ts +++ b/apps/server/scripts/antigravity-mock-agent.ts @@ -29,7 +29,9 @@ * - `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. It writes no subagent records. + * 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. It writes no subagent records. * - `subagents`: launches two subagents with their records (as 1.5.12+ * keeps them under `brain/`); the first reports, the agent replies, and * the second reports a while later. @@ -256,6 +258,36 @@ const program = Effect.gen(function* () { yield* say(sessionId, "Thinking hard."); return yield* Effect.never; } + 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."); diff --git a/apps/server/src/provider/acp/AcpAdapter.ts b/apps/server/src/provider/acp/AcpAdapter.ts index ec561bdb5..1a38358c7 100644 --- a/apps/server/src/provider/acp/AcpAdapter.ts +++ b/apps/server/src/provider/acp/AcpAdapter.ts @@ -128,6 +128,7 @@ import { } from "./AcpProviderRuntime.ts"; import { type AcpPermissionRequest, + type AcpToolCallReport, type AcpPlanUpdate, type AcpSessionMode, type AcpSessionModeState, @@ -1221,17 +1222,21 @@ export function makeAcpAdapter( /** * A permission request as the descriptor describes its tool call - * (`normalizeToolCall`): an MCP call the agent runs as a command asks as - * a tool call, not a command. + * (`normalizeToolCall`): an MCP call the agent runs through a command + * shows the server, tool and arguments it runs, under the same kind. */ - const normalizedPermissionRequest = (request: AcpPermissionRequest): AcpPermissionRequest => { + 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); - // A call the descriptor retyped is named by its own detail, not the command's. + 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: toolCall.kind ?? request.kind, + kind: request.kind, ...(detail !== undefined ? { detail } : {}), toolCall, }; @@ -2063,6 +2068,7 @@ export function makeAcpAdapter( } const permissionRequest = normalizedPermissionRequest( parsePermissionRequest(params), + params.toolCall, ); const planFileWrite = permissionRequest.toolCall !== undefined && diff --git a/apps/server/src/provider/acp/AcpProviderDescriptor.ts b/apps/server/src/provider/acp/AcpProviderDescriptor.ts index 062901b99..dcc177e7b 100644 --- a/apps/server/src/provider/acp/AcpProviderDescriptor.ts +++ b/apps/server/src/provider/acp/AcpProviderDescriptor.ts @@ -48,7 +48,7 @@ import type { import type { UsageLedgerProvider } from "../../usage/usageLedger.ts"; import type { ProviderProbeResult, ServerProviderPresentation } from "../providerSnapshot.ts"; import type { AcpAttachmentDelivery } from "./AcpPromptAttachments.ts"; -import type { AcpPlanUpdate, AcpToolCallState } from "./AcpRuntimeModel.ts"; +import type { AcpPlanUpdate, AcpToolCallReport, AcpToolCallState } from "./AcpRuntimeModel.ts"; import type { AcpSessionRuntimeShape, AcpSpawnInput } from "./AcpSessionRuntime.ts"; /** Settings fields every ACP provider config must carry. */ @@ -656,9 +656,15 @@ export interface AcpProviderDescriptor { /** * 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`). - */ - readonly normalizeToolCall?: (toolCall: AcpToolCallState) => AcpToolCallState; + * 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 diff --git a/apps/server/src/provider/acp/AcpRuntimeModel.ts b/apps/server/src/provider/acp/AcpRuntimeModel.ts index da42db0f4..720e6c50e 100644 --- a/apps/server/src/provider/acp/AcpRuntimeModel.ts +++ b/apps/server/src/provider/acp/AcpRuntimeModel.ts @@ -42,6 +42,20 @@ export interface AcpToolCallState { 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<{ diff --git a/apps/server/src/provider/acp/AcpSessionRuntime.ts b/apps/server/src/provider/acp/AcpSessionRuntime.ts index 3c5669246..41770a608 100644 --- a/apps/server/src/provider/acp/AcpSessionRuntime.ts +++ b/apps/server/src/provider/acp/AcpSessionRuntime.ts @@ -31,6 +31,7 @@ import { parseSessionUpdateEvent, type AcpParsedSessionEvent, type AcpSessionModeState, + type AcpToolCallReport, type AcpToolCallState, } from "./AcpRuntimeModel.ts"; @@ -155,7 +156,10 @@ export interface AcpSessionRuntimeOptions { notification: EffectAcpSchema.SessionNotification, ) => EffectAcpSchema.SessionNotification; /** Rewrites each merged tool call (see `AcpProviderDescriptor.normalizeToolCall`). */ - readonly normalizeToolCall?: (toolCall: AcpToolCallState) => AcpToolCallState; + 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 @@ -1142,7 +1146,10 @@ const handleSessionUpdate = ({ readonly params: EffectAcpSchema.SessionNotification; /** Given for native controls only: the agent's own option updates land here. */ readonly configOptionsRef?: Ref.Ref>; - readonly normalizeToolCall?: (toolCall: AcpToolCallState) => AcpToolCallState; + readonly normalizeToolCall?: ( + toolCall: AcpToolCallState, + report: AcpToolCallReport, + ) => AcpToolCallState; readonly trackSilentToolCalls?: boolean; readonly cancellationNotice?: { readonly text: string; readonly cancelledRef: Ref.Ref }; }): Effect.Effect => @@ -1181,7 +1188,8 @@ const handleSessionUpdate = ({ const { previous, merged } = yield* Ref.modify(toolCallsRef, (current) => { const previous = current.get(event.toolCall.toolCallId); const mergedToolCall = mergeToolCallState(previous, event.toolCall); - const nextToolCall = normalizeToolCall?.(mergedToolCall) ?? mergedToolCall; + const report = 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); diff --git a/apps/server/src/provider/antigravity/AntigravityToolCalls.test.ts b/apps/server/src/provider/antigravity/AntigravityToolCalls.test.ts index d3d4e0b9d..b39d59acc 100644 --- a/apps/server/src/provider/antigravity/AntigravityToolCalls.test.ts +++ b/apps/server/src/provider/antigravity/AntigravityToolCalls.test.ts @@ -1,14 +1,166 @@ +import * as Schema from "effect/Schema"; +import * as EffectAcpSchema from "effect-acp/schema"; import { describe, expect, it } from "vite-plus/test"; -import { boundAntigravityCommandLine, boundAntigravityText } from "./AntigravityToolCalls.ts"; +import type { AcpToolCallState } 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("never cuts a character in half", () => { + 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(9)}`, 10); - expect(tail).toBe(`[Earlier output truncated]\n\n${"b".repeat(9)}`); - const head = boundAntigravityCommandLine(`${"c".repeat(9)}😀d`, 10); - expect(head).toBe(`${"c".repeat(9)}\n\n[Command truncated]`); + 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(); + }); }); diff --git a/apps/server/src/provider/antigravity/AntigravityToolCalls.ts b/apps/server/src/provider/antigravity/AntigravityToolCalls.ts index c55823e0f..a4f08a88c 100644 --- a/apps/server/src/provider/antigravity/AntigravityToolCalls.ts +++ b/apps/server/src/provider/antigravity/AntigravityToolCalls.ts @@ -6,36 +6,41 @@ * `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. An edit's old and new - * text are the exception: the core counts the edit's lines from them. 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. + * `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 type * as EffectAcpSchema from "effect-acp/schema"; +import * as Schema from "effect/Schema"; +import * as EffectAcpSchema from "effect-acp/schema"; import type { AcpToolCallState } from "../acp/AcpRuntimeModel.ts"; -/** The most characters one tool text field keeps. */ +/** 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 update, so a huge array or object can't flood it. */ -const UPDATE_NODE_BUDGET = 512; +/** 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. */ -const COMMAND_LINE_FIELDS = new Set(["CommandLine", "command_line", "commandLine", "command"]); -/** - * Diff text is the file's own content: the ACP core counts an edit's lines - * from it, and a cut copy would miscount them. - */ -const FILE_TEXT_FIELDS = new Set(["oldText", "newText"]); +/** 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); @@ -43,20 +48,22 @@ const isRecord = (value: unknown): value is Record => /** 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; a lone low surrogate at the cut is dropped. */ +/** 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 tail = text.slice(-limit).replace(/^[\uDC00-\uDFFF]/u, ""); + 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; a lone high surrogate at the cut is dropped. */ +/** 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 head = text.slice(0, limit).replace(/[\uD800-\uDBFF]$/u, ""); + const room = Math.max(0, limit - COMMAND_CUT.length); + const head = text.slice(0, room).replace(/[\uD800-\uDBFF]$/u, ""); return copyText(`${head}${COMMAND_CUT}`); } @@ -65,27 +72,31 @@ interface Budget { 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/")); /** - * One JSON value with its text bounded and inline image data left out. - * `undefined` means "drop it". + * 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; - if (field !== undefined && FILE_TEXT_FIELDS.has(field)) return value; - if (budget.text <= 0) return undefined; - const limit = Math.min(ANTIGRAVITY_TOOL_TEXT_LIMIT, budget.text); - const text = - field !== undefined && COMMAND_LINE_FIELDS.has(field) - ? boundAntigravityCommandLine(value, limit) - : boundAntigravityText(value, limit); - budget.text -= text.length; - return text; + return boundField(value, budget, field); } if (Array.isArray(value)) { const kept: Array = []; @@ -109,22 +120,74 @@ function boundValue(value: unknown, budget: Budget, depth: number, field?: strin } /** A tool payload (`rawInput`, `rawOutput`, `_meta`) with its text bounded and images left out. */ -export function boundAntigravityToolPayload(payload: unknown): unknown { - return boundValue(payload, { nodes: UPDATE_NODE_BUDGET, text: UPDATE_TEXT_BUDGET }, 0); +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; } -/** A tool content entry, or `undefined` for an inline image (its bytes are the only thing in it). */ +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: Budget, + budget: { text: number }, ): EffectAcpSchema.ToolCallContent | undefined { - if ( - entry.type === "content" && - (entry.content.type === "image" || entry.content.type === "audio") - ) - return undefined; - const bounded = boundValue(entry, budget, 0); - return isRecord(bounded) ? (bounded as EffectAcpSchema.ToolCallContent) : undefined; + 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": + bounded = { + type: "content", + content: { + type: "resource_link", + uri: block.uri, + 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)) return undefined; + bounded = { + type: "content", + content: { + type: "resource", + resource: { + uri: resource.uri, + text: boundField(resource.text, budget), + ...(typeof resource.mimeType === "string" ? { mimeType: resource.mimeType } : {}), + }, + }, + }; + break; + } + default: + return entry; + } + return isToolCallContent(bounded) ? bounded : entry; } /** @@ -138,64 +201,105 @@ export function normalizeAntigravitySessionUpdate( if (update.sessionUpdate !== "tool_call" && update.sessionUpdate !== "tool_call_update") { return notification; } - const budget: Budget = { nodes: UPDATE_NODE_BUDGET, text: UPDATE_TEXT_BUDGET }; + const budget = { text: UPDATE_TEXT_BUDGET }; 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: boundAntigravityToolPayload(update.rawInput) } + ? { rawInput: boundAntigravityToolPayload(update.rawInput, budget) } : {}), ...(update.rawOutput !== undefined - ? { rawOutput: boundAntigravityToolPayload(update.rawOutput) } + ? { rawOutput: boundAntigravityToolPayload(update.rawOutput, budget) } : {}), ...(update.content !== undefined && update.content !== null ? { content: content ?? [] } : {}), ...(update._meta !== undefined && update._meta !== null - ? { _meta: (boundAntigravityToolPayload(update._meta) ?? null) as Record } + ? { _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)) + ); +} + /** - * The MCP tool an Antigravity `call_mcp_tool` call runs. Antigravity reaches - * MCP tools its context budget left out through it: an `execute` call - * titled "MCP Tool " whose input names `ServerName`, `ToolName` and - * `Arguments` (T3 Code 7f928416b2). + * The MCP tool this update positively says it runs through `call_mcp_tool`: + * an `execute` call titled "MCP Tool " whose input is exactly + * `ServerName`, `ToolName` and optional object `Arguments` (agy 1.5.12, T3 + * Code 7f928416b2), with no command or edit about it. Anything else is + * `undefined` and stays what the agent called it. */ -export function antigravityProxiedMcpTool(rawInput: unknown): - | { - readonly server: string; - readonly tool: string; - readonly arguments?: Record; - } - | undefined { - if (!isRecord(rawInput)) return undefined; - const server = typeof rawInput.ServerName === "string" ? rawInput.ServerName.trim() : ""; - const tool = typeof rawInput.ToolName === "string" ? rawInput.ToolName.trim() : ""; +export function antigravityProxiedMcpTool( + update: AntigravityToolCallUpdate, +): AntigravityProxiedMcpTool | undefined { + const input = update.rawInput; + if (!isRecord(input) || commandOrEditEvidence(update)) return undefined; + if (update.kind !== "execute") return undefined; + if (!Object.keys(input).every((key) => WRAPPER_INPUT_KEYS.has(key))) return undefined; + const server = typeof input.ServerName === "string" ? input.ServerName.trim() : ""; + const tool = typeof input.ToolName === "string" ? input.ToolName.trim() : ""; if (!server || !tool) return undefined; - return { - server, - tool, - ...(isRecord(rawInput.Arguments) ? { arguments: rawInput.Arguments } : {}), - }; + if (input.Arguments !== undefined && !isRecord(input.Arguments)) return undefined; + if (update.title?.trim() !== `MCP Tool ${tool}`) return undefined; + return { server, tool, ...(isRecord(input.Arguments) ? { arguments: input.Arguments } : {}) }; } -/** - * A tool call as the timeline should show it. An MCP call through - * `call_mcp_tool` is an MCP tool call with its server and tool, not a - * command (and so never holds a turn as a command would). - */ -export function normalizeAntigravityToolCall(toolCall: AcpToolCallState): AcpToolCallState { - const mcp = antigravityProxiedMcpTool(toolCall.data.rawInput); - if (mcp === undefined) return toolCall; +/** What an approval for the call shows: the server, the tool and its arguments. */ +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): AntigravityProxiedMcpTool | undefined { + const { server, tool, arguments: args } = toolCall.data; + if (typeof server !== "string" || typeof tool !== "string") return undefined; + return { server, tool, ...(isRecord(args) ? { arguments: args } : {}) }; +} + +function asMcpToolCall(toolCall: AcpToolCallState, mcp: AntigravityProxiedMcpTool) { const { item: _item, command: _command, ...data } = toolCall.data; const { command: _shown, ...rest } = toolCall; return { @@ -204,7 +308,7 @@ export function normalizeAntigravityToolCall(toolCall: AcpToolCallState): AcpToo itemType: "mcp_tool_call", // The approval panel names a tool call by its title. title: mcp.tool, - detail: `${mcp.server} · ${mcp.tool}`, + detail: antigravityMcpToolLabel(mcp), data: { ...data, kind: "other", @@ -212,5 +316,43 @@ export function normalizeAntigravityToolCall(toolCall: AcpToolCallState): AcpToo tool: mcp.tool, ...(mcp.arguments !== undefined ? { arguments: mcp.arguments } : {}), }, - }; + } satisfies AcpToolCallState; +} + +/** + * The merged call without the MCP fields an earlier update gave it, back to + * the kind the agent gives it (a wrapper was an `execute` call). + */ +function withoutMcpTool(toolCall: AcpToolCallState, kind: string): AcpToolCallState { + const { server: _server, tool: _tool, arguments: _args, ...data } = toolCall.data; + const { itemType: _itemType, ...rest } = toolCall; + return { ...rest, kind, data: { ...data, kind } }; +} + +/** + * A tool call as the timeline should show it, given the update that just + * arrived. 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. Anything else stays as the agent + * described it. + */ +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") || + (restated !== undefined && + (!Object.keys(restated).every((key) => WRAPPER_INPUT_KEYS.has(key)) || + restated.ServerName !== shown.server || + restated.ToolName !== shown.tool)); + return conflicting + ? withoutMcpTool(toolCall, update.kind ?? "execute") + : asMcpToolCall(toolCall, shown); } diff --git a/apps/server/src/provider/antigravity/AntigravityTurns.test.ts b/apps/server/src/provider/antigravity/AntigravityTurns.test.ts index 5d34efd25..8154ff0ea 100644 --- a/apps/server/src/provider/antigravity/AntigravityTurns.test.ts +++ b/apps/server/src/provider/antigravity/AntigravityTurns.test.ts @@ -8,6 +8,7 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import { it } from "@effect/vitest"; import { AntigravitySettings, + ApprovalRequestId, type ChatAttachment, ProviderDriverKind, type ProviderRuntimeEvent, @@ -870,6 +871,56 @@ describe("Antigravity tool rows and attachments", () => { | 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)), + ); + 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"); From 3c2bb0fb0727268852b486d21ff20610251b2b79 Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Mon, 23 Nov 2026 04:16:50 -0500 Subject: [PATCH 35/59] fix(antigravity): the session's / list is live provider status, and only typed commands go raw The command list an Antigravity session advertises was written to the event log (thread.agent-commands-set, migration 124): replayed forever, floodable by the agent, an event type older builds can't decode, and missing from full snapshots. It is session information, so it now rides on the provider status the way other live session facts do (patchSnapshot): ServerProvider .sessionCommands, each distinct list once with the sessions that listed it, gone when the session ends. Older clients ignore the unknown field. The event, command, projection column and migration are removed. Lists are capped (200 commands, short descriptions and hints cut on whole characters), names must be typeable command names (no '/', spaces or invisible and bidi characters), and an unchanged list or one changing faster than every 5 seconds sends nothing new. A message is an agent command only when the person's own typed text (not the context the server put in front of it, not plain text or an agent's words, not text with leading whitespace) starts with /name of a command the session advertised or a skill the status lists. It then goes alone; the adapter reports contextDeferred so the server keeps every debt it would have paid. In a room the / list describes the addressed agent's own provider. The ACP lost-sessions file goes too: a lost conversation is reported on session.exited (conversationLost) and forgotten by the provider service. --- apps/server/scripts/antigravity-mock-agent.ts | 16 +- apps/server/src/guide/topics.ts | 2 +- .../Layers/ProjectionPipeline.ts | 20 -- .../Layers/ProjectionSnapshotQuery.ts | 11 - .../Layers/ProviderRuntimeIngestion.test.ts | 41 --- .../Layers/ProviderRuntimeIngestion.ts | 47 +--- apps/server/src/orchestration/Schemas.ts | 2 - apps/server/src/orchestration/decider.ts | 25 -- apps/server/src/orchestration/projector.ts | 22 -- .../src/orchestration/threadMoveDecisions.ts | 1 - .../persistence/Layers/ProjectionThreads.ts | 15 -- apps/server/src/persistence/Migrations.ts | 2 - .../124_ProjectionThreadsAgentCommands.ts | 17 -- .../persistence/Services/ProjectionThreads.ts | 9 - apps/server/src/provider/acp/AcpAdapter.ts | 243 ++++++++++-------- .../src/provider/acp/AcpProviderDescriptor.ts | 16 +- .../provider/acp/AcpProviderDriver.test.ts | 24 +- .../src/provider/acp/AcpProviderDriver.ts | 69 ++++- .../src/provider/acp/AcpRuntimeModel.ts | 28 +- .../antigravity/AntigravityTurns.test.ts | 169 ++++++------ apps/server/src/ws.ts | 8 +- apps/web/src/components/chat/ChatComposer.tsx | 59 ++++- .../chat/composerAgentCommands.test.ts | 116 ++++++--- .../components/chat/composerAgentCommands.ts | 90 +++++-- apps/web/src/store.test.ts | 27 -- apps/web/src/store.ts | 33 --- apps/web/src/threadDerivation.ts | 7 +- apps/web/src/types.ts | 6 - docs/providers/antigravity.md | 54 ++-- packages/contracts/src/orchestration.ts | 50 ---- packages/contracts/src/provider.ts | 12 + packages/contracts/src/providerRuntime.ts | 29 +-- packages/contracts/src/server.ts | 29 ++- packages/contracts/src/slashCommands.ts | 22 -- packages/shared/package.json | 6 +- packages/shared/src/agentCommands.ts | 54 ---- packages/shared/src/slashCommands.test.ts | 52 ++++ packages/shared/src/slashCommands.ts | 91 +++++++ 38 files changed, 770 insertions(+), 754 deletions(-) delete mode 100644 apps/server/src/persistence/Migrations/124_ProjectionThreadsAgentCommands.ts delete mode 100644 packages/contracts/src/slashCommands.ts delete mode 100644 packages/shared/src/agentCommands.ts create mode 100644 packages/shared/src/slashCommands.test.ts create mode 100644 packages/shared/src/slashCommands.ts diff --git a/apps/server/scripts/antigravity-mock-agent.ts b/apps/server/scripts/antigravity-mock-agent.ts index 5d2dfe45a..9cb7c15bd 100644 --- a/apps/server/scripts/antigravity-mock-agent.ts +++ b/apps/server/scripts/antigravity-mock-agent.ts @@ -34,7 +34,8 @@ * - `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. + * (`available_commands_update`), as the 1.5 CLI does. Under `flapping` it + * then changes the list ten times in a row. */ import { appendFileSync, mkdirSync } from "node:fs"; import { join } from "node:path"; @@ -122,6 +123,19 @@ const program = Effect.gen(function* () { ], }), ), + 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 { diff --git a/apps/server/src/guide/topics.ts b/apps/server/src/guide/topics.ts index 027ed0710..6d8b40168 100644 --- a/apps/server/src/guide/topics.ts +++ b/apps/server/src/guide/topics.ts @@ -313,7 +313,7 @@ Claude's models come from Claude Code itself, so a new one shows up without a Th 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 meanwhile steers the turn. 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 once a chat has started, the commands that chat's Antigravity offers. Such a message goes as typed, even in plan mode. Editing an earlier message starts Antigravity over with only the turns before it, since it can't rewind its own conversation; anything it still ran stops first. +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, 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. 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. diff --git a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts index 8c794ad40..12a0a1735 100644 --- a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts +++ b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts @@ -1,5 +1,4 @@ import { replaceAgentCheckBacks } from "@threadlines/shared/checkBacks"; -import { applyAgentCommands } from "@threadlines/shared/agentCommands"; import { applyLinkedPullRequestSwitches, applyPullRequestLinked, @@ -1306,25 +1305,6 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti return; } - case "thread.agent-commands-set": { - const existingRow = yield* projectionThreadRepository.getById({ - threadId: event.payload.threadId, - }); - if (Option.isNone(existingRow)) { - return; - } - // Not the thread's updatedAt: an agent listing its commands is not - // activity in the thread. - yield* projectionThreadRepository.upsert({ - ...existingRow.value, - agentCommands: applyAgentCommands( - existingRow.value.agentCommands ?? undefined, - event.payload, - ), - }); - return; - } - case "thread.goal-state-set": { const existingRow = yield* projectionThreadRepository.getById({ threadId: event.payload.threadId, diff --git a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts index 2a1519e1a..9020410c7 100644 --- a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts +++ b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts @@ -35,7 +35,6 @@ import { MessageSentFrom, MessageTrigger, ModelSelection, - OrchestrationAgentCommands, OrchestrationCheckBack, OrchestrationThreadGoal, OrchestrationQueuedFollowUp, @@ -312,12 +311,6 @@ const ProjectionThreadDbRowSchema = ProjectionThread.mapFields( sentModels: Schema.optional( Schema.fromJsonString(Schema.Record(Schema.String, ModelSelection)), ), - // Read by the thread detail only: a thread shell never carries it. - agentCommands: Schema.optional( - Schema.NullOr( - Schema.fromJsonString(Schema.Record(Schema.String, OrchestrationAgentCommands)), - ), - ), agentRequests: Schema.optional( Schema.NullOr(Schema.fromJsonString(OrchestrationAgentRequestState)), ), @@ -1997,7 +1990,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { agent_role AS "agentRole", room_context AS "roomContext", sent_models AS "sentModels", - agent_commands AS "agentCommands", agent_requests AS "agentRequests", parent_thread_id AS "parentThreadId", parent_turn_id AS "parentTurnId", @@ -4244,9 +4236,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { ...(threadRow.value.sentModels && Object.keys(threadRow.value.sentModels).length > 0 ? { sentModels: threadRow.value.sentModels } : {}), - ...(threadRow.value.agentCommands && Object.keys(threadRow.value.agentCommands).length > 0 - ? { agentCommands: threadRow.value.agentCommands } - : {}), doneOverride: mapThreadDoneOverride(threadRow.value), lastSeenAt: threadRow.value.lastSeenAt ?? null, deletedAt: null, diff --git a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts index 5da8a7c13..48de77782 100644 --- a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts +++ b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts @@ -414,8 +414,6 @@ describe("ProviderRuntimeIngestion", () => { engine, workspaceRoot, readModel: () => Effect.runPromise(snapshotQuery.getSnapshot()), - threadDetail: (threadId: ThreadId) => - Effect.runPromise(snapshotQuery.getThreadDetailById(threadId)).then(Option.getOrUndefined), emit: provider.emit, setProviderSession: provider.setSession, interruptedThreadIds: provider.interruptedThreadIds, @@ -1207,45 +1205,6 @@ describe("ProviderRuntimeIngestion", () => { expect(Option.getOrThrow(side).providerThreadId).toBeNull(); }); - it("records the slash commands a session lists on its thread, once per change", async () => { - const harness = await createHarness(); - const now = "2026-01-01T00:00:00.000Z"; - const threadId = asThreadId("thread-1"); - const listed = (eventId: string, commands: ReadonlyArray<{ name: string }>) => { - harness.emit({ - type: "session.commands.updated", - eventId: asEventId(eventId), - provider: ProviderDriverKind.make("antigravity"), - providerInstanceId: ProviderInstanceId.make("antigravity"), - threadId, - createdAt: now, - payload: { commands }, - }); - }; - listed("evt-commands-1", [{ name: "goal" }, { name: "compact" }]); - // The session lists them again as it reopens: nothing changed. - listed("evt-commands-2", [{ name: "goal" }, { name: "compact" }]); - listed("evt-commands-3", [{ name: "goal" }]); - await harness.drain(); - - const recorded = await Effect.runPromise( - Stream.runCollect(harness.engine.readEvents(0)).pipe( - Effect.map((events) => - Array.from(events).filter((event) => event.type === "thread.agent-commands-set"), - ), - ), - ); - expect(recorded).toHaveLength(2); - const detail = await harness.threadDetail(threadId); - expect(detail?.agentCommands).toEqual({ - primary: { - providerInstanceId: ProviderInstanceId.make("antigravity"), - commands: [{ name: "goal" }], - updatedAt: now, - }, - }); - }); - it("keeps a room agent's check-backs while another agent works, and notes one it had to skip", async () => { const harness = await createHarness(); const now = "2026-01-01T00:00:00.000Z"; diff --git a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts index 5242dee37..dbe3b4490 100644 --- a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts +++ b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts @@ -44,12 +44,10 @@ import * as Stream from "effect/Stream"; import { countUnifiedDiffStats, type DiffLineStats } from "@threadlines/shared/diffStats"; import { makeDrainableWorker } from "@threadlines/shared/DrainableWorker"; import { sameCheckBacks } from "@threadlines/shared/checkBacks"; -import { sameSlashCommands } from "@threadlines/shared/agentCommands"; import { areFilesystemPathsEqual } from "@threadlines/shared/path"; import { ASSISTANT_STREAM_FLUSH_INTERVAL_MS } from "@threadlines/shared/threadLimits"; import { participantSessionKey, - roomAgentKey, sessionSlotParticipantId, } from "@threadlines/shared/threadParticipants"; import { turnAdmission } from "../turnAdmission.ts"; @@ -66,8 +64,6 @@ import { ProviderService } from "../../provider/Services/ProviderService.ts"; import { isCarriedSessionRejection } from "../../provider/nativeSession.ts"; import { ProjectionTurnRepository } from "../../persistence/Services/ProjectionTurns.ts"; import { ProjectionTurnRepositoryLive } from "../../persistence/Layers/ProjectionTurns.ts"; -import { ProjectionThreadRepository } from "../../persistence/Services/ProjectionThreads.ts"; -import { ProjectionThreadRepositoryLive } from "../../persistence/Layers/ProjectionThreads.ts"; import { checkoutEndsTurnsWithCheckpoints, turnEndStateFromRuntime } from "../turnEnd.ts"; import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts"; import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts"; @@ -948,7 +944,6 @@ const make = Effect.gen(function* () { const providerService = yield* ProviderService; const projectionTurnRepository = yield* ProjectionTurnRepository; - const projectionThreadRepository = yield* ProjectionThreadRepository; // Computer links, when this server has them: see RemoteRequestTurnEnds. const remoteRequestTurnEnds = yield* Effect.serviceOption(RemoteRequestTurnEnds); // Scheduled tasks, when this server has them: see ScheduledRunTurnEnds. @@ -2988,42 +2983,6 @@ const make = Effect.gen(function* () { } }); - /** - * The slash commands an agent's session listed, recorded on the thread for - * the composer's `/` list. Like check-backs they belong to the agent, so - * they are recorded whoever holds the session slot. A session lists them - * each time it opens; only a changed list is recorded. - */ - const recordAgentCommands = ( - event: Extract, - thread: NonNullable>>, - ) => - Effect.gen(function* () { - const providerInstanceId = event.providerInstanceId; - if (providerInstanceId === undefined) return; - const participantId = event.participantId ?? null; - const row = yield* projectionThreadRepository.getById({ threadId: thread.id }); - const current = Option.isSome(row) - ? row.value.agentCommands?.[roomAgentKey(participantId)] - : undefined; - if ( - current !== undefined && - current.providerInstanceId === providerInstanceId && - sameSlashCommands(current.commands, event.payload.commands) - ) { - return; - } - yield* orchestrationEngine.dispatch({ - type: "thread.agent-commands.set", - commandId: providerCommandId(event, "agent-commands-set"), - threadId: thread.id, - participantId, - providerInstanceId, - commands: event.payload.commands, - createdAt: event.createdAt, - }); - }); - const processRuntimeEvent = (event: ProviderRuntimeEvent) => Effect.gen(function* () { // Realtime audio/item traffic is intentionally in-memory only. Keep this @@ -3063,10 +3022,6 @@ const make = Effect.gen(function* () { yield* recordCheckBacks(event, thread); return; } - if (event.type === "session.commands.updated") { - yield* recordAgentCommands(event, thread); - return; - } // A thread moving or moved to another computer is frozen here: its // runtime was stopped at the freeze, and a turn one starts by itself // anyway is refused and stopped. @@ -4558,4 +4513,4 @@ const make = Effect.gen(function* () { export const ProviderRuntimeIngestionLive = Layer.effect( ProviderRuntimeIngestionService, make, -).pipe(Layer.provide(Layer.mergeAll(ProjectionTurnRepositoryLive, ProjectionThreadRepositoryLive))); +).pipe(Layer.provide(ProjectionTurnRepositoryLive)); diff --git a/apps/server/src/orchestration/Schemas.ts b/apps/server/src/orchestration/Schemas.ts index 08190829f..ac32fe97b 100644 --- a/apps/server/src/orchestration/Schemas.ts +++ b/apps/server/src/orchestration/Schemas.ts @@ -75,7 +75,6 @@ import { ThreadEffectiveCwdSetPayload as ContractsThreadEffectiveCwdSetPayloadSchema, ThreadGoalStateSetPayload as ContractsThreadGoalStateSetPayloadSchema, ThreadCheckBacksSetPayload as ContractsThreadCheckBacksSetPayloadSchema, - ThreadAgentCommandsSetPayload as ContractsThreadAgentCommandsSetPayloadSchema, ThreadTurnDiffCompletedPayload as ContractsThreadTurnDiffCompletedPayloadSchema, ThreadTurnDiffSummaryUpdatedPayload as ContractsThreadTurnDiffSummaryUpdatedPayloadSchema, ThreadTurnCompletedPayload as ContractsThreadTurnCompletedPayloadSchema, @@ -187,7 +186,6 @@ export const ThreadRealtimeStateSetPayload = ContractsThreadRealtimeStateSetPayl export const ThreadEffectiveCwdSetPayload = ContractsThreadEffectiveCwdSetPayloadSchema; export const ThreadGoalStateSetPayload = ContractsThreadGoalStateSetPayloadSchema; export const ThreadCheckBacksSetPayload = ContractsThreadCheckBacksSetPayloadSchema; -export const ThreadAgentCommandsSetPayload = ContractsThreadAgentCommandsSetPayloadSchema; export const ThreadTurnDiffCompletedPayload = ContractsThreadTurnDiffCompletedPayloadSchema; export const ThreadTurnDiffSummaryUpdatedPayload = ContractsThreadTurnDiffSummaryUpdatedPayloadSchema; diff --git a/apps/server/src/orchestration/decider.ts b/apps/server/src/orchestration/decider.ts index 8a582bc11..d8e5264a9 100644 --- a/apps/server/src/orchestration/decider.ts +++ b/apps/server/src/orchestration/decider.ts @@ -5755,31 +5755,6 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" }; } - case "thread.agent-commands.set": { - yield* requireThread({ - readModel, - command, - threadId: command.threadId, - }); - return { - ...withEventBase({ - aggregateKind: "thread", - aggregateId: command.threadId, - occurredAt: command.createdAt, - commandId: command.commandId, - metadata: {}, - }), - type: "thread.agent-commands-set", - payload: { - threadId: command.threadId, - participantId: command.participantId, - providerInstanceId: command.providerInstanceId, - commands: command.commands, - updatedAt: command.createdAt, - }, - }; - } - case "thread.check-back.cancel": { const thread = yield* requireThread({ readModel, diff --git a/apps/server/src/orchestration/projector.ts b/apps/server/src/orchestration/projector.ts index e75a0a9fa..ec8dc6cb9 100644 --- a/apps/server/src/orchestration/projector.ts +++ b/apps/server/src/orchestration/projector.ts @@ -25,7 +25,6 @@ import { retainThreadActivities } from "@threadlines/shared/threadActivityRetent import { applyRoomAgentUpdate, recordTurnModel } from "@threadlines/shared/threadParticipants"; import { effectiveCwdOf } from "@threadlines/shared/threadCwd"; import { replaceAgentCheckBacks } from "@threadlines/shared/checkBacks"; -import { applyAgentCommands } from "@threadlines/shared/agentCommands"; import { applyPullRequestDismissed } from "@threadlines/shared/pullRequestDismissals"; import { applyLinkedPullRequestSwitches, @@ -142,7 +141,6 @@ import { ThreadEffectiveCwdSetPayload, ThreadGoalStateSetPayload, ThreadCheckBacksSetPayload, - ThreadAgentCommandsSetPayload, ThreadFollowUpSubmittedPayload, ThreadTurnStartRequestedPayload, ThreadFollowUpAcceptedPayload, @@ -1874,26 +1872,6 @@ export function projectEvent( }; }); - case "thread.agent-commands-set": - return Effect.gen(function* () { - const payload = yield* decodeForEvent( - ThreadAgentCommandsSetPayload, - event.payload, - event.type, - "payload", - ); - const thread = nextBase.threads.find((entry) => entry.id === payload.threadId); - if (!thread) { - return nextBase; - } - return { - ...nextBase, - threads: updateThread(nextBase.threads, payload.threadId, { - agentCommands: applyAgentCommands(thread.agentCommands, payload), - }), - }; - }); - case "thread.goal-state-set": return Effect.gen(function* () { const payload = yield* decodeForEvent( diff --git a/apps/server/src/orchestration/threadMoveDecisions.ts b/apps/server/src/orchestration/threadMoveDecisions.ts index b0f683365..670d73050 100644 --- a/apps/server/src/orchestration/threadMoveDecisions.ts +++ b/apps/server/src/orchestration/threadMoveDecisions.ts @@ -705,7 +705,6 @@ const FROZEN_THREAD_COMMANDS: ReadonlySet = new Se "thread.activity.append", "thread.effective-cwd.set", "thread.check-backs.set", - "thread.agent-commands.set", // What the provider reports of its goal as the move's stop pauses it: the // goal bar must say what the provider holds, should the move be dropped. "thread.goal.state.set", diff --git a/apps/server/src/persistence/Layers/ProjectionThreads.ts b/apps/server/src/persistence/Layers/ProjectionThreads.ts index 668be8007..6c56c6a8c 100644 --- a/apps/server/src/persistence/Layers/ProjectionThreads.ts +++ b/apps/server/src/persistence/Layers/ProjectionThreads.ts @@ -20,7 +20,6 @@ import { } from "../Services/ProjectionThreads.ts"; import { ModelSelection, - OrchestrationAgentCommands, OrchestrationCheckBack, OrchestrationThreadGoal, OrchestrationQueuedFollowUp, @@ -83,11 +82,6 @@ const ProjectionThreadDbRow = ProjectionThread.mapFields( Schema.Record(Schema.String, OrchestrationRoomContextCursor), ), sentModels: Schema.fromJsonString(Schema.Record(Schema.String, ModelSelection)), - agentCommands: Schema.optional( - Schema.NullOr( - Schema.fromJsonString(Schema.Record(Schema.String, OrchestrationAgentCommands)), - ), - ), }), ); type ProjectionThreadDbRow = typeof ProjectionThreadDbRow.Type; @@ -128,7 +122,6 @@ const makeProjectionThreadRepository = Effect.gen(function* () { side_turn, room_context, sent_models, - agent_commands, agent_role, agent_requests, parent_thread_id, @@ -198,11 +191,6 @@ const makeProjectionThreadRepository = Effect.gen(function* () { ${sideTurnsColumnValue(row.sideTurns)}, ${JSON.stringify(row.roomContext ?? {})}, ${JSON.stringify(row.sentModels ?? {})}, - ${ - row.agentCommands && Object.keys(row.agentCommands).length > 0 - ? JSON.stringify(row.agentCommands) - : null - }, ${row.agentRole ?? null}, ${row.agentRequests ? JSON.stringify(row.agentRequests) : null}, ${row.parentThreadId ?? null}, @@ -276,7 +264,6 @@ const makeProjectionThreadRepository = Effect.gen(function* () { side_turn = excluded.side_turn, room_context = excluded.room_context, sent_models = excluded.sent_models, - agent_commands = excluded.agent_commands, agent_role = excluded.agent_role, agent_requests = excluded.agent_requests, parent_thread_id = excluded.parent_thread_id, @@ -349,7 +336,6 @@ const makeProjectionThreadRepository = Effect.gen(function* () { side_turn AS "sideTurns", room_context AS "roomContext", sent_models AS "sentModels", - agent_commands AS "agentCommands", agent_role AS "agentRole", agent_requests AS "agentRequests", parent_thread_id AS "parentThreadId", @@ -424,7 +410,6 @@ const makeProjectionThreadRepository = Effect.gen(function* () { side_turn AS "sideTurns", room_context AS "roomContext", sent_models AS "sentModels", - agent_commands AS "agentCommands", agent_role AS "agentRole", agent_requests AS "agentRequests", parent_thread_id AS "parentThreadId", diff --git a/apps/server/src/persistence/Migrations.ts b/apps/server/src/persistence/Migrations.ts index fe60e5b6a..a3a3473a3 100644 --- a/apps/server/src/persistence/Migrations.ts +++ b/apps/server/src/persistence/Migrations.ts @@ -143,7 +143,6 @@ import Migration0120 from "./Migrations/120_ThreadAdoptedFromLink.ts"; import Migration0121 from "./Migrations/121_ProjectionThreadSecretRequests.ts"; import Migration0122 from "./Migrations/122_ProjectBriefs.ts"; import Migration0123 from "./Migrations/123_ProjectNotes.ts"; -import Migration0124 from "./Migrations/124_ProjectionThreadsAgentCommands.ts"; /** * Migration loader with all migrations defined inline. @@ -279,7 +278,6 @@ export const migrationEntries = [ [121, "ProjectionThreadSecretRequests", Migration0121], [122, "ProjectBriefs", Migration0122], [123, "ProjectNotes", Migration0123], - [124, "ProjectionThreadsAgentCommands", Migration0124], ] as const; /** Highest id in the full registry, so the "n of total" count is the real total. */ diff --git a/apps/server/src/persistence/Migrations/124_ProjectionThreadsAgentCommands.ts b/apps/server/src/persistence/Migrations/124_ProjectionThreadsAgentCommands.ts deleted file mode 100644 index bf8427e53..000000000 --- a/apps/server/src/persistence/Migrations/124_ProjectionThreadsAgentCommands.ts +++ /dev/null @@ -1,17 +0,0 @@ -import * as Effect from "effect/Effect"; -import * as SqlClient from "effect/sql/SqlClient"; - -/** Adds `agent_commands`: per agent, the slash commands its session last listed. */ -export default Effect.gen(function* () { - const sql = yield* SqlClient.SqlClient; - - const columns = yield* sql<{ readonly name: string }>` - PRAGMA table_info(projection_threads) - `; - if (!columns.some((column) => column.name === "agent_commands")) { - yield* sql` - ALTER TABLE projection_threads - ADD COLUMN agent_commands TEXT - `; - } -}); diff --git a/apps/server/src/persistence/Services/ProjectionThreads.ts b/apps/server/src/persistence/Services/ProjectionThreads.ts index d89b0dc76..026c1110e 100644 --- a/apps/server/src/persistence/Services/ProjectionThreads.ts +++ b/apps/server/src/persistence/Services/ProjectionThreads.ts @@ -11,7 +11,6 @@ import { MessageId, ModelSelection, NonNegativeInt, - OrchestrationAgentCommands, OrchestrationCheckBack, OrchestrationThreadGoal, OrchestrationQueuedFollowUp, @@ -168,14 +167,6 @@ export const ProjectionThread = Schema.Struct({ * migration 063 decode; absent reads as nothing recorded yet. */ sentModels: Schema.optional(Schema.Record(Schema.String, ModelSelection)), - /** - * Per agent, the slash commands its session last listed; see - * `OrchestrationThread.agentCommands`. Optional so rows written before - * migration 124 decode; absent reads as none reported. - */ - agentCommands: Schema.optional( - Schema.NullOr(Schema.Record(Schema.String, OrchestrationAgentCommands)), - ), /** * The user's name for the thread's own agent; see * `OrchestrationThreadShell.agentRole`. Optional so rows written before diff --git a/apps/server/src/provider/acp/AcpAdapter.ts b/apps/server/src/provider/acp/AcpAdapter.ts index 6c9e8af54..68362b9af 100644 --- a/apps/server/src/provider/acp/AcpAdapter.ts +++ b/apps/server/src/provider/acp/AcpAdapter.ts @@ -25,6 +25,7 @@ import { type ThreadId, TurnId, type UsageTokenTotals, + type ServerProviderSlashCommand, } from "@threadlines/contracts"; import { withFailureCategory } from "../providerFailureCategory.ts"; import { makeAgentProcessLedger } from "../agentProcessLedger.ts"; @@ -40,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"; @@ -134,12 +136,11 @@ import { import { THREADLINES_ACP_CLIENT_INFO } from "./acpClientInfo.ts"; import { type AcpSessionRuntimeShape } from "./AcpSessionRuntime.ts"; -const decodeLostSessions = Schema.decodeUnknownExit( - Schema.fromJsonString(Schema.Array(Schema.String)), -); 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 @@ -172,8 +173,6 @@ const ACP_HELD_REPLY_QUIET_LIMIT = Duration.minutes(2); const ACP_HISTORY_CURSOR_LIMIT = 200; /** How long asking the agent where a prompt landed may take before it goes unanswered. */ const ACP_HISTORY_POSITION_TIMEOUT = Duration.seconds(5); -/** The most lost agent sessions an instance remembers (`markSessionLost`). */ -const ACP_LOST_SESSIONS_LIMIT = 100; const ACP_PLAN_MODE_ALIASES = ["plan", "architect"]; const ACP_IMPLEMENT_MODE_ALIASES = ["code", "agent", "default", "chat", "implement"]; const ACP_APPROVAL_MODE_ALIASES = ["ask"]; @@ -197,6 +196,17 @@ 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>; } interface PendingApproval { @@ -556,16 +566,6 @@ function findModeByAliases( return undefined; } -/** - * Whether a message starts with a slash command, as an agent with - * `agentCommands` reads it: `/` and a name, then whitespace or the end. A - * path (`/tmp/out.log is empty`) has a second `/` in its first word and is - * not one. - */ -export function startsWithAgentCommand(text: string): boolean { - return /^\/[\p{L}\p{N}_][\p{L}\p{N}_.:-]*(?:\s|$)/u.test(text); -} - function isPlanMode(mode: AcpSessionMode): boolean { return findModeByAliases([mode], ACP_PLAN_MODE_ALIASES) !== undefined; } @@ -721,47 +721,6 @@ export function makeAcpAdapter( } >(); const adapterScope = yield* Scope.Scope; - /** - * Agent sessions that can't go on (`AcpPromptFailure.sessionLost`): a - * restart opens a new session instead, seeded with the thread's history. - * Kept on disk per instance, so a server restart before the next message - * doesn't reopen one. - */ - const lostSessionsFile = path.join( - serverConfig.stateDir, - "acp-lost-sessions", - `${encodeURIComponent(boundInstanceId)}.json`, - ); - const lostSessions = new Set( - yield* fileSystem.readFileString(lostSessionsFile).pipe( - Effect.map((raw): ReadonlyArray => { - const parsed = decodeLostSessions(raw); - return Exit.isSuccess(parsed) ? parsed.value : []; - }), - Effect.orElseSucceed((): ReadonlyArray => []), - ), - ); - const saveLostSessions = Effect.gen(function* () { - yield* fileSystem.makeDirectory(path.dirname(lostSessionsFile), { recursive: true }); - yield* fileSystem.writeFileString( - lostSessionsFile, - JSON.stringify([...lostSessions].slice(-ACP_LOST_SESSIONS_LIMIT)), - ); - }).pipe( - Effect.catchCause((cause) => - Effect.logWarning("acp.lost-sessions.save-failed", { - provider: PROVIDER, - cause: Cause.pretty(cause), - }), - ), - ); - const markSessionLost = (sessionId: string) => - Effect.suspend(() => { - lostSessions.add(sessionId); - return saveLostSessions; - }); - const forgetLostSession = (sessionId: string) => - Effect.suspend(() => (lostSessions.delete(sessionId) ? saveLostSessions : Effect.void)); /** * A turn that can outlive its prompt or span several (`heldTurns`, * `steerWithPrompt`) writes each prompt's tokens as it answers. @@ -1400,9 +1359,89 @@ export function makeAcpAdapter( return Effect.succeed(ctx); }; + /** + * 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?: true }, ) => Effect.gen(function* () { if (ctx.stopped) return; @@ -1423,7 +1462,7 @@ export function makeAcpAdapter( ...(yield* makeEventStamp()), provider: PROVIDER, threadId: ctx.threadId, - payload: { exitKind }, + payload: { exitKind, ...exit }, }); }); @@ -1591,13 +1630,7 @@ export function makeAcpAdapter( let ctx!: AcpSessionContext; const resumed = parseAcpResumeCursor(input.resumeCursor); - // 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; + const resumeSessionId = resumed?.sessionId; // 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 @@ -2136,12 +2169,7 @@ export function makeAcpAdapter( modelSelection: boundModelSelection, }); - const resumeFailure = - started.resumeFailure ?? - (lostSession !== undefined - ? `${descriptor.presentation.displayName} can no longer continue its earlier conversation.` - : undefined); - if (lostSession !== undefined) yield* forgetLostSession(lostSession); + const resumeFailure = started.resumeFailure; // A resumed conversation keeps the turn history its cursor carried. const keepsHistory = resumed !== undefined && @@ -2220,9 +2248,7 @@ export function makeAcpAdapter( // A switch from another agent starts without the history: the // thread hands it over. (A failed resume is seeded by the reactor.) pendingContextPreamble: - input.contextSeed !== undefined && - resumeSessionId === undefined && - lostSession === undefined + input.contextSeed !== undefined && resumeSessionId === undefined ? renderThreadContextSeed(input.contextSeed) : undefined, projectBrief, @@ -2306,21 +2332,12 @@ export function makeAcpAdapter( return; } case "AvailableCommandsUpdated": { - // The composer's `/` list for this thread; a side runtime - // answers no messages of its own, so it lists none. - const agentCommands = descriptor.agentCommands; - if (agentCommands === undefined || ctx.lockdown !== undefined) return; - yield* offerRuntimeEvent({ - type: "session.commands.updated", - ...(yield* makeEventStamp()), - provider: PROVIDER, - threadId: ctx.threadId, - payload: { - commands: event.commands.filter( - (command) => !agentCommands.hidden.has(command.name), - ), - }, - }); + // 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": @@ -2637,12 +2654,25 @@ export function makeAcpAdapter( const model = turnModelSelection?.model ?? ctx.session.model; const resolvedModel = resolveModelId(model); - const userText = input.input?.trim() ?? ""; // The agent runs a command (or a skill) only when the message starts - // with it, so one goes as typed: no plan prefix, and the earlier - // context and the project brief wait for the next message. + // with it. A message is one only when the person's own typed text + // (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 && typed.indented !== true + ? slashCommandAtStart(typed.text) + : undefined; const sendsAgentCommand = - descriptor.agentCommands !== undefined && startsWithAgentCommand(userText); + typedCommand !== undefined && (yield* isAgentCommand(ctx, typedCommand)); + const userText = sendsAgentCommand && typed ? typed.text : (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 = @@ -2749,7 +2779,12 @@ export function makeAcpAdapter( yield* sendTurnPrompt(ctx, run, promptParts); - return { threadId: input.threadId, turnId, resumeCursor: ctx.session.resumeCursor }; + return { + threadId: input.threadId, + turnId, + resumeCursor: ctx.session.resumeCursor, + ...(contextDeferred ? { contextDeferred: true as const } : {}), + }; }); /** Starts reading how the turn's prompts end (`promptOutcome`); never fails. */ @@ -2869,14 +2904,16 @@ export function makeAcpAdapter( } if (ctx.openPrompt === prompt) ctx.openPrompt = undefined; yield* Deferred.succeed(prompt.closed, undefined); - // The agent can't go on with this session: it is stopped, and - // the next message opens a new one with the thread's history. + // The agent can't go on with this session: it is stopped, and the + // server forgets it (`conversationLost`), so the next message opens + // a new one with the thread's history. if (lostSession) { - yield* markSessionLost(ctx.acpSessionId); yield* withThreadLock( ctx.threadId, Effect.suspend(() => - sessions.get(ctx.threadId) === ctx ? stopSessionInternal(ctx) : Effect.void, + sessions.get(ctx.threadId) === ctx + ? stopSessionInternal(ctx, "graceful", { conversationLost: true }) + : Effect.void, ), ).pipe(Effect.forkIn(adapterScope)); } @@ -3368,16 +3405,14 @@ export function makeAcpAdapter( /** * For an agent that can't rewind (`rollbackByNewSession`): the session - * ends and is marked lost, so it is never reopened. The next message - * starts a new one, which the thread seeds with the turns it kept - * (`resumeFailed`), and the agent forgets the reverted ones. 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. + * 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* () { - yield* markSessionLost(ctx.acpSessionId); const working = () => ctx.activeTurnId !== undefined || ctx.workAfterPrompt.size > 0 || ctx.subagentsOut > 0; if (working()) { diff --git a/apps/server/src/provider/acp/AcpProviderDescriptor.ts b/apps/server/src/provider/acp/AcpProviderDescriptor.ts index 0055832f3..725c8d139 100644 --- a/apps/server/src/provider/acp/AcpProviderDescriptor.ts +++ b/apps/server/src/provider/acp/AcpProviderDescriptor.ts @@ -506,17 +506,19 @@ export interface AcpProviderDescriptor { */ readonly conversationHistory?: AcpConversationHistory; /** - * For an agent with no `conversationHistory`: a revert stops the session - * (closing it stops what it runs) and the next message opens a new one - * seeded with the turns kept, as after a failed resume, so the agent - * forgets the reverted ones (Antigravity). Without it the agent remembers - * them, and the revert says so. + * 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. Absent: the list is - * ignored, as for agents whose lists were never checked in Threadlines. + * 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; /** diff --git a/apps/server/src/provider/acp/AcpProviderDriver.test.ts b/apps/server/src/provider/acp/AcpProviderDriver.test.ts index 6dda907f6..92e504910 100644 --- a/apps/server/src/provider/acp/AcpProviderDriver.test.ts +++ b/apps/server/src/provider/acp/AcpProviderDriver.test.ts @@ -10,10 +10,32 @@ import { ChildProcessSpawner } from "effect/process"; import { describe, expect, it } from "vite-plus/test"; import { checkAcpProviderStatus, makeAcpCatalogCache } from "./AcpProvider.ts"; -import { makeAcpProviderMaintenanceResolver, resolveAcpBinaryPath } from "./AcpProviderDriver.ts"; +import { + groupSessionCommands, + 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("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 b49c8c293..71ab317b6 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,22 @@ import { makeAcpTextGeneration } from "./AcpTextGeneration.ts"; const SNAPSHOT_REFRESH_INTERVAL = Duration.minutes(5); +/** 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,6 +193,10 @@ export function makeAcpProviderDriver( continuationKey: descriptor.continuationKey(config, processEnv), } : defaultProviderContinuationIdentity({ driverKind: DRIVER_KIND, instanceId }); + // 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 stampIdentity = (snapshot: ServerProviderDraft): ServerProvider => ({ ...snapshot, instanceId, @@ -179,6 +205,9 @@ export function makeAcpProviderDriver( ...(accentColor ? { accentColor } : {}), continuation: { groupKey: continuationIdentity.continuationKey }, ...(descriptor.agentCommands?.slashSkills === true ? { slashSkills: true } : {}), + ...(sessionCommands.size > 0 + ? { sessionCommands: groupSessionCommands(sessionCommands) } + : {}), ...descriptor.snapshotExtras?.(), }); // A bare binary name is resolved once against the server's PATH plus @@ -220,11 +249,47 @@ 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); + return ( + liveSnapshot?.patchSnapshot((current) => { + const { sessionCommands: _previous, ...rest } = current; + return sessionCommands.size > 0 + ? { ...rest, sessionCommands: groupSessionCommands(sessionCommands) } + : rest; + }) ?? 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, @@ -286,6 +351,8 @@ export function makeAcpProviderDriver( ), ); + liveSnapshot = snapshot; + return { instanceId, driverKind: DRIVER_KIND, diff --git a/apps/server/src/provider/acp/AcpRuntimeModel.ts b/apps/server/src/provider/acp/AcpRuntimeModel.ts index c333904b8..49548c148 100644 --- a/apps/server/src/provider/acp/AcpRuntimeModel.ts +++ b/apps/server/src/provider/acp/AcpRuntimeModel.ts @@ -1,4 +1,5 @@ import type * as EffectAcpSchema from "effect-acp/schema"; +import { cleanSlashCommands } from "@threadlines/shared/slashCommands"; import { deriveToolActivityPresentation } from "@threadlines/shared/toolActivity"; import type { ServerProviderSlashCommand, @@ -613,31 +614,6 @@ function sessionInfoStatusMessage(update: { readonly _meta?: unknown }): string return typeof message === "string" && message.trim().length > 0 ? message.trim() : undefined; } -/** - * An agent's command list in the composer's terms: names without a leading - * `/`, each once (the first wins), and none a message could not start with - * (empty, or with whitespace inside). - */ -export function acpSlashCommands( - commands: ReadonlyArray, -): ReadonlyArray { - const seen = new Set(); - return commands.flatMap((command): Array => { - const name = command.name.trim().replace(/^\//u, ""); - if (name.length === 0 || /\s/u.test(name) || seen.has(name)) return []; - seen.add(name); - const description = command.description.trim(); - const hint = command.input?.hint.trim(); - return [ - { - name, - ...(description ? { description } : {}), - ...(hint ? { input: { hint } } : {}), - }, - ]; - }); -} - export function parseSessionUpdateEvent(params: EffectAcpSchema.SessionNotification): { readonly modeId?: string; readonly events: ReadonlyArray; @@ -751,7 +727,7 @@ export function parseSessionUpdateEvent(params: EffectAcpSchema.SessionNotificat case "available_commands_update": { events.push({ _tag: "AvailableCommandsUpdated", - commands: acpSlashCommands(upd.availableCommands), + commands: cleanSlashCommands(upd.availableCommands), }); break; } diff --git a/apps/server/src/provider/antigravity/AntigravityTurns.test.ts b/apps/server/src/provider/antigravity/AntigravityTurns.test.ts index 9de9623d8..556bb280a 100644 --- a/apps/server/src/provider/antigravity/AntigravityTurns.test.ts +++ b/apps/server/src/provider/antigravity/AntigravityTurns.test.ts @@ -90,11 +90,19 @@ const startAgy = ( 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)) }, + { + 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"])), + }, ); yield* made.streamEvents.pipe( Stream.runForEach((event) => Effect.sync(() => void events.push(event))), @@ -125,6 +133,7 @@ const startAgy = ( adapter, events, usage, + commandReports, threadId, session, waitFor, @@ -324,30 +333,19 @@ describe("Antigravity turns", () => { }).pipe(Effect.scoped, Effect.provide(testServices)), ); - it.live( - "starts a new session with the thread's history when Google can't continue the old one", - () => - 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")); - - // A server restart before the next message: a new adapter. - const restartedAdapter = yield* agy.newAdapter; - const restarted = yield* restartedAdapter.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("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({ + payload: { conversationLost: true }, + }); + }).pipe(Effect.scoped, Effect.provide(testServices)), ); }); @@ -531,79 +529,78 @@ const promptTexts = (frames: ReadonlyArray>) => }); describe("Antigravity commands and edits", () => { - it.live("lists the session's own slash commands for its thread, less Threadlines' own", () => - Effect.gen(function* () { - const agy = yield* startAgy("simple"); - yield* agy.waitFor((events) => - events.some((event) => event.type === "session.commands.updated"), - ); - const listed = agy.events.find((event) => event.type === "session.commands.updated"); - expect(listed).toMatchObject({ - threadId: agy.threadId, - payload: { - commands: [ - { name: "goal", description: "Work toward a goal", input: { hint: "objective" } }, - { name: "compact", description: "Summarize the conversation" }, - ], - }, - }); - }).pipe(Effect.scoped, Effect.provide(testServices)), + 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("sends a command as typed in plan mode, and plans the next message", () => + it.live("reports a list that keeps changing at most once per interval, the newest last", () => Effect.gen(function* () { - const agy = yield* startAgy("simple"); - yield* agy.adapter.sendTurn({ - threadId: agy.threadId, - input: "/compact", - interactionMode: "plan", - attachments: [], - }); - yield* agy.waitFor((events) => completedTurns(events).length === 1); - yield* agy.adapter.sendTurn({ - threadId: agy.threadId, - input: "/tmp/out.log is empty", - interactionMode: "plan", - attachments: [], - }); - yield* agy.waitFor((events) => completedTurns(events).length === 2); - expect(promptTexts(yield* agy.frames())).toEqual(["/compact", "/plan /tmp/out.log is empty"]); + 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("forgets reverted turns by ending the session and starting a new one", () => + 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"); - expect(agy.adapter.capabilities.conversationRollback).toBe("new-session"); - yield* agy.adapter.sendTurn({ threadId: agy.threadId, input: "first", attachments: [] }); - yield* agy.waitFor((events) => completedTurns(events).length === 1); - const [beforeRevert] = yield* agy.adapter.listSessions(); - - const rolledBack = yield* agy.adapter.rollbackThread(agy.threadId, 1); - expect(rolledBack.conversationRolledBack).toBe(true); - expect(agy.events.some((event) => event.type === "session.exited")).toBe(true); - expect(yield* agy.adapter.hasSession(agy.threadId)).toBe(false); - - // The next message opens a new conversation the thread seeds, also - // after a server restart (a new adapter). - const restartedAdapter = yield* agy.newAdapter; - const restarted = yield* restartedAdapter.startSession({ - threadId: agy.threadId, - provider: ProviderDriverKind.make("antigravity"), - cwd: process.cwd(), - runtimeMode: "full-access", - resumeCursor: beforeRevert?.resumeCursor, + yield* agy.waitFor(() => agy.commandReports.length > 0); + const send = (input: string, typed?: { text: string; context?: string; indented?: true }) => + 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, plain text and an indented one: 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"); + yield* send("/compact", { text: "/compact", indented: true }); + // 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(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); + 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", + "/plan /compact", + "/compact", + ]); }).pipe(Effect.scoped, Effect.provide(testServices)), ); - it.live("stops the agent's running work, and its turn once, before a revert ends it", () => + 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", @@ -612,7 +609,8 @@ describe("Antigravity commands and edits", () => { yield* agy.waitFor((events) => replyTo(events, turnId).includes("I'll report")); yield* Effect.sleep("300 millis"); - yield* agy.adapter.rollbackThread(agy.threadId, 1); + const rolledBack = yield* agy.adapter.rollbackThread(agy.threadId, 1); + expect(rolledBack.conversationRolledBack).toBe(true); expect(completedTurns(agy.events)).toEqual([ expect.objectContaining({ turnId, @@ -622,6 +620,7 @@ describe("Antigravity commands and edits", () => { 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)), ); }); diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index 60c6e2995..c875b714b 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -296,8 +296,7 @@ export function isThreadDetailEvent(event: OrchestrationEvent): event is Extract | "thread.secret-request-notes-delivered" | "thread.handed-back" | "thread.parent-attachment-set" - | "thread.pull-request-dismissed" - | "thread.agent-commands-set"; + | "thread.pull-request-dismissed"; } > { return ( @@ -339,8 +338,6 @@ export function isThreadDetailEvent(event: OrchestrationEvent): event is Extract // snapshot writes the shell too: one read before a close and delivered // after it would undo the close, so the change follows the snapshot here. event.type === "thread.pull-request-dismissed" || - // The slash commands an agent's session listed: the open chat's `/` list. - event.type === "thread.agent-commands-set" || event.type === "thread.message-sent" || event.type === "thread.follow-up-submitted" || event.type === "thread.follow-up-accepted" || @@ -1149,9 +1146,6 @@ const makeCoreRpcLayer = ( threadId: event.payload.threadId, }), ); - // Detail only: nothing on the thread's shell changed. - case "thread.agent-commands-set": - return Effect.succeed(Option.none()); case "thread.unarchived": return projectionSnapshotQuery.getThreadShellById(event.payload.threadId).pipe( Effect.map((thread) => diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index 8aad0d03f..34257fe02 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -208,7 +208,11 @@ import { useRoomRecipientStore, } from "../../rooms"; import { getPickerModelName } from "./providerIconUtils"; -import { composerProviderSlashList } from "./composerAgentCommands"; +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"; @@ -1329,22 +1333,46 @@ 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: for an agent that lists its own - // commands per session (Antigravity), the list this thread's session sent. - const sessionCommandsKey = roomAgentKey(addressingRoomAgent ? roomRecipientId : null); - const sessionCommands = activeThread?.agentCommands?.[sessionCommandsKey]; + // 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: selectedProviderStatus, - instanceId: selectedInstanceId, + provider: slashProviderStatus, sessionCommands, threadlinesCommands: goalSupported ? THREADLINES_SLASH_COMMANDS_WITH_GOAL : THREADLINES_SLASH_COMMANDS, }), - [goalSupported, selectedInstanceId, selectedProviderStatus, sessionCommands], + [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", @@ -1505,9 +1533,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) // 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", @@ -1521,10 +1549,13 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) // the two kinds score on different scales, so a shared ranker would // interleave them arbitrarily. const skillItems = [ - ...buildComposerSkillItems(searchProviderSkills(composerSkills, query), selectedProvider), ...buildComposerSkillItems( - searchProviderSkills(providerSlashList.slashSkills, query), + searchProviderSkills(slashListCodexSkills, query), selectedProvider, + ), + ...buildComposerSkillItems( + searchProviderSkills(providerSlashList.slashSkills, query), + slashProvider, "slash", ), ]; @@ -1557,6 +1588,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) goalSupported, providerSlashList, selectedProvider, + slashListCodexSkills, + slashProvider, threadGoal, workspaceEntries, ]); @@ -4108,7 +4141,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/composerAgentCommands.test.ts b/apps/web/src/components/chat/composerAgentCommands.test.ts index 48b0da12e..85dd033cc 100644 --- a/apps/web/src/components/chat/composerAgentCommands.test.ts +++ b/apps/web/src/components/chat/composerAgentCommands.test.ts @@ -1,9 +1,21 @@ -import { ProviderInstanceId, type ServerProviderSkill } from "@threadlines/contracts"; +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 { composerProviderSlashList } from "./composerAgentCommands"; +import type { ProviderInstanceEntry } from "../../providerInstances"; +import { + composerProviderSlashList, + composerSlashAgent, + sessionSlashCommands, +} from "./composerAgentCommands"; -const instanceId = ProviderInstanceId.make("antigravity"); const skill = (name: string, enabled = true): ServerProviderSkill => ({ name, path: `/skills/${name}/SKILL.md`, @@ -20,12 +32,7 @@ describe("composerProviderSlashList", () => { expect( composerProviderSlashList({ provider, - instanceId, - sessionCommands: { - providerInstanceId: instanceId, - commands: [{ name: "other" }], - updatedAt: "2026-11-23T00:00:00.000Z", - }, + sessionCommands: [{ name: "other" }], threadlinesCommands: THREADLINES, }), ).toEqual({ commands: provider.slashCommands, slashSkills: [] }); @@ -34,33 +41,32 @@ describe("composerProviderSlashList", () => { 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")], + skills: [ + skill("review"), + skill("compact"), + skill("off", false), + skill("two words"), + skill("a/b"), + ], slashSkills: true, }; - // Before a session has opened: the skills alone. + // Before a session has listed its own: the skills alone, only typeable ones. expect( composerProviderSlashList({ provider, - instanceId, sessionCommands: undefined, threadlinesCommands: THREADLINES, }), ).toEqual({ commands: [], slashSkills: [skill("review"), skill("compact")] }); - const session = { - providerInstanceId: instanceId, - commands: [ - { name: "goal", input: { hint: "objective" } }, - { name: "compact", description: "Summarize the conversation" }, - { name: "model" }, - ], - updatedAt: "2026-11-23T00:00:00.000Z", - }; expect( composerProviderSlashList({ provider, - instanceId, - sessionCommands: session, + sessionCommands: [ + { name: "goal", input: { hint: "objective" } }, + { name: "compact", description: "Summarize the conversation" }, + { name: "model" }, + ], threadlinesCommands: THREADLINES, }), ).toEqual({ @@ -70,15 +76,63 @@ describe("composerProviderSlashList", () => { ], slashSkills: [skill("review")], }); + }); - // A list another account's session sent doesn't describe this one. + 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( - composerProviderSlashList({ - provider, - instanceId: ProviderInstanceId.make("antigravity_work"), - sessionCommands: session, - threadlinesCommands: THREADLINES, - }).commands, - ).toEqual([]); + 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 index 9a0a1cfe6..ce7c1a3b2 100644 --- a/apps/web/src/components/chat/composerAgentCommands.ts +++ b/apps/web/src/components/chat/composerAgentCommands.ts @@ -1,10 +1,15 @@ import type { - OrchestrationAgentCommands, - ProviderInstanceId, + 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. */ @@ -15,31 +20,84 @@ export interface ComposerProviderSlashList { 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. A provider whose agent - * runs skills on `/` (`ServerProvider.slashSkills`, Antigravity) lists - * the commands its session reported for this thread, once there is such a - * list from this provider instance, else the status's; and the status's - * skills, less any the commands already name, so the session's entry wins. + * 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; - readonly instanceId: ProviderInstanceId; - /** The list the agent's session last reported for this thread, if any. */ - readonly sessionCommands: OrchestrationAgentCommands | undefined; + /** 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 sessionCommands = - input.sessionCommands?.providerInstanceId === input.instanceId - ? input.sessionCommands.commands - : undefined; - const commands = (sessionCommands ?? provider.slashCommands).filter( + const commands = (input.sessionCommands ?? provider.slashCommands).filter( (command) => !input.threadlinesCommands.has(command.name), ); const named = new Set(commands.map((command) => command.name)); @@ -48,7 +106,7 @@ export function composerProviderSlashList(input: { skill.enabled && !named.has(skill.name) && !input.threadlinesCommands.has(skill.name) && - !/\s/u.test(skill.name), + isSlashCommandName(skill.name), ); return { commands, slashSkills }; } diff --git a/apps/web/src/store.test.ts b/apps/web/src/store.test.ts index 4bcad493a..fbc1b10cb 100644 --- a/apps/web/src/store.test.ts +++ b/apps/web/src/store.test.ts @@ -1031,33 +1031,6 @@ describe("incremental orchestration updates", () => { expect(threadsOf(reverted)[0]?.workflowRuns?.map((run) => run.taskId)).toEqual(["task-a"]); }); - it("keeps each agent's slash command list from its session's latest report", () => { - const threadId = ThreadId.make("thread-1"); - const instanceId = ProviderInstanceId.make("antigravity"); - const listed = (sequence: number, names: ReadonlyArray) => - makeEvent( - "thread.agent-commands-set", - { - threadId, - participantId: null, - providerInstanceId: instanceId, - commands: names.map((name) => ({ name })), - updatedAt: "2026-02-27T00:00:01.000Z", - }, - { sequence }, - ); - let state = makeState(makeThread()); - state = applyOrchestrationEvent(state, listed(1, ["goal", "compact"]), localEnvironmentId); - state = applyOrchestrationEvent(state, listed(2, ["goal"]), localEnvironmentId); - expect(threadsOf(state)[0]?.agentCommands).toEqual({ - primary: { - providerInstanceId: instanceId, - commands: [{ name: "goal" }], - updatedAt: "2026-02-27T00:00:01.000Z", - }, - }); - }); - it("projects realtime voice state into thread detail and shell state", () => { const state = makeState(makeThread()); diff --git a/apps/web/src/store.ts b/apps/web/src/store.ts index 1807fbb0f..206d0da75 100644 --- a/apps/web/src/store.ts +++ b/apps/web/src/store.ts @@ -1,6 +1,5 @@ import { hasLiveSideTurn, liveSideTurns } from "@threadlines/shared/sideTurns"; import { replaceAgentCheckBacks, sameCheckBacks } from "@threadlines/shared/checkBacks"; -import { applyAgentCommands } from "@threadlines/shared/agentCommands"; import { applyLinkedPullRequestSwitches, applyPullRequestLinked, @@ -20,7 +19,6 @@ import type { OrchestrationAgentPage, OrchestrationCommandRequest, OrchestrationCommandRun, - OrchestrationAgentCommands, OrchestrationReadModel, OrchestrationSecretRequest, OrchestrationSettingsChangeRequest, @@ -215,8 +213,6 @@ export interface EnvironmentState { /** Suggested commands per thread (docs/terminal-command-runs.md); absent until a thread's detail loads. */ commandRequestsByThreadId?: Record>; commandRunsByThreadId?: Record>; - /** The slash commands each thread's agents' sessions listed; absent until a thread's detail loads. */ - agentCommandsByThreadId?: Record>>; /** * Threads whose detail snapshot has landed (syncServerThreadDetail). Events * and optimistic writes fill the detail slices too, so only this says a @@ -281,7 +277,6 @@ const initialEnvironmentState: EnvironmentState = { subagentsByThreadId: {}, commandRequestsByThreadId: {}, commandRunsByThreadId: {}, - agentCommandsByThreadId: {}, threadDetailLoadedById: {}, childRequestsByThreadId: {}, settingsRequestsByThreadId: {}, @@ -297,7 +292,6 @@ const initialState: AppState = { const EMPTY_THREAD_IDS: ThreadId[] = []; const EMPTY_SUBAGENTS: ReadonlyArray = []; -const EMPTY_AGENT_COMMANDS: Readonly> = {}; function arraysEqual(left: readonly T[], right: readonly T[]): boolean { return left.length === right.length && left.every((value, index) => value === right[index]); @@ -881,7 +875,6 @@ function mapThread(thread: OrchestrationThread, environmentId: EnvironmentId): T pages: thread.pages ?? [], commandRequests: thread.commandRequests ?? [], commandRuns: thread.commandRuns ?? [], - agentCommands: thread.agentCommands ?? EMPTY_AGENT_COMMANDS, error: sessionNoticeError(thread.session), createdAt: thread.createdAt, archivedAt: thread.archivedAt, @@ -1872,19 +1865,6 @@ function writeThreadState( }; } - if ( - nextThread.agentCommands !== undefined && - previousThread?.agentCommands !== nextThread.agentCommands - ) { - nextState = { - ...nextState, - agentCommandsByThreadId: { - ...nextState.agentCommandsByThreadId, - [nextThread.id]: nextThread.agentCommands, - }, - }; - } - if ( nextThread.commandRuns !== undefined && previousThread?.commandRuns !== nextThread.commandRuns @@ -2099,8 +2079,6 @@ function removeThreadState(state: EnvironmentState, threadId: ThreadId): Environ state.commandRequestsByThreadId ?? {}; const { [threadId]: _removedCommandRuns, ...commandRunsByThreadId } = state.commandRunsByThreadId ?? {}; - const { [threadId]: _removedAgentCommands, ...agentCommandsByThreadId } = - state.agentCommandsByThreadId ?? {}; const { [threadId]: _removedDetailLoaded, ...threadDetailLoadedById } = state.threadDetailLoadedById ?? {}; const { [threadId]: _removedChildRequests, ...childRequestsByThreadId } = @@ -2131,7 +2109,6 @@ function removeThreadState(state: EnvironmentState, threadId: ThreadId): Environ subagentsByThreadId, commandRequestsByThreadId, commandRunsByThreadId, - agentCommandsByThreadId, threadDetailLoadedById, childRequestsByThreadId, settingsRequestsByThreadId, @@ -2573,10 +2550,6 @@ function syncEnvironmentShellSnapshot( state.commandRunsByThreadId ?? {}, nextThreadIds, ), - agentCommandsByThreadId: retainThreadScopedRecord( - state.agentCommandsByThreadId ?? {}, - nextThreadIds, - ), threadDetailLoadedById: retainThreadScopedRecord( state.threadDetailLoadedById ?? {}, nextThreadIds, @@ -3013,12 +2986,6 @@ function applyEnvironmentOrchestrationEvent( updatedAt: event.payload.updatedAt, })); - case "thread.agent-commands-set": - return updateThreadState(state, event.payload.threadId, (thread) => ({ - ...thread, - agentCommands: applyAgentCommands(thread.agentCommands, event.payload), - })); - case "thread.check-backs-set": return updateThreadState(state, event.payload.threadId, (thread) => ({ ...thread, diff --git a/apps/web/src/threadDerivation.ts b/apps/web/src/threadDerivation.ts index 5791dad3f..04a59f0b1 100644 --- a/apps/web/src/threadDerivation.ts +++ b/apps/web/src/threadDerivation.ts @@ -36,7 +36,6 @@ const threadCache = new WeakMap< subagents: Thread["subagents"]; commandRequests: Thread["commandRequests"]; commandRuns: Thread["commandRuns"]; - agentCommands: Thread["agentCommands"]; thread: Thread; } >(); @@ -125,7 +124,6 @@ export function getThreadFromEnvironmentState( const subagents = state.subagentsByThreadId?.[threadId]; const commandRequests = state.commandRequestsByThreadId?.[threadId]; const commandRuns = state.commandRunsByThreadId?.[threadId]; - const agentCommands = state.agentCommandsByThreadId?.[threadId]; const cached = threadCache.get(shell); if ( @@ -144,8 +142,7 @@ export function getThreadFromEnvironmentState( cached.workflowRuns === workflowRuns && cached.subagents === subagents && cached.commandRequests === commandRequests && - cached.commandRuns === commandRuns && - cached.agentCommands === agentCommands + cached.commandRuns === commandRuns ) { return cached.thread; } @@ -168,7 +165,6 @@ export function getThreadFromEnvironmentState( ...(subagents !== undefined ? { subagents } : {}), ...(commandRequests !== undefined ? { commandRequests } : {}), ...(commandRuns !== undefined ? { commandRuns } : {}), - ...(agentCommands !== undefined ? { agentCommands } : {}), }; threadCache.set(shell, { @@ -187,7 +183,6 @@ export function getThreadFromEnvironmentState( subagents, commandRequests, commandRuns, - agentCommands, thread, }); diff --git a/apps/web/src/types.ts b/apps/web/src/types.ts index c30ef72f5..bc5bbd164 100644 --- a/apps/web/src/types.ts +++ b/apps/web/src/types.ts @@ -8,7 +8,6 @@ import type { OrchestrationCheckBack, OrchestrationCommandRequest, OrchestrationCommandRun, - OrchestrationAgentCommands, OrchestrationSecretRequest, OrchestrationSettingsChangeRequest, PullRequestMergeMethod, @@ -231,11 +230,6 @@ export interface Thread { commandRequests?: ReadonlyArray; /** Runs the user started from a request card or a code block. Absent until the detail loads. */ commandRuns?: ReadonlyArray; - /** - * Per agent (`primary` or a participant id), the slash commands its session - * last listed (OrchestrationThread.agentCommands). Absent until the detail loads. - */ - agentCommands?: Readonly>; error: string | null; createdAt: string; archivedAt: string | null; diff --git a/docs/providers/antigravity.md b/docs/providers/antigravity.md index e6f25ed8f..6ec24f2c5 100644 --- a/docs/providers/antigravity.md +++ b/docs/providers/antigravity.md @@ -110,27 +110,31 @@ Antigravity also picks a skill on its own when the task matches its description. ## 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. - -- Before a chat has started, the list has the skills Threadlines found (above). -- Once Antigravity has started in a thread, 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. Each thread keeps its own list, - saved with the thread, so it is there again after a restart, before Antigravity starts again; a - new list from the agent replaces it. +(`/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. - -A message that starts with `/` and a name goes to Antigravity exactly as typed, since Antigravity -only runs a command at the very start of the message. In plan mode it goes without the `/plan` -prefix, and the project's instructions Threadlines sends with a new chat's first message wait for -the next message. A message that starts with a path (`/tmp/out.log is empty`) is plain text. - -The first message after Threadlines starts Antigravity over with the thread's history (a moved -thread, a conversation Google can't continue, an edited earlier message) carries that history in -front of the words, so a command there arrives as text. Send it again on its own. +- 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 start with `/` and the name +of a command that session offers or a skill Threadlines lists. That message goes to Antigravity +alone, exactly 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, 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 that starts with a space, one sent as plain text, and one an +agent or a scheduled task wrote. ## Turns @@ -167,12 +171,14 @@ history. ### Editing an Earlier Message Antigravity can't rewind its own conversation. When you edit an earlier message (or undo back to -one), Threadlines restores the files, 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. The next message starts a new Antigravity session and sends it the turns that are left, -so Antigravity no longer remembers the removed ones, also when Threadlines restarts before that -message. This also works when no Antigravity was running for the thread: Threadlines opens the -saved session just to end it, since the next message would otherwise continue it as it was. +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. ### Tokens diff --git a/packages/contracts/src/orchestration.ts b/packages/contracts/src/orchestration.ts index f0c083cd8..607cae2bd 100644 --- a/packages/contracts/src/orchestration.ts +++ b/packages/contracts/src/orchestration.ts @@ -42,7 +42,6 @@ import { TurnId, } from "./baseSchemas.ts"; import { ProviderDriverKind, ProviderInstanceId } from "./providerInstance.ts"; -import { ServerProviderSlashCommand } from "./slashCommands.ts"; import { PullRequestMergeMethod } from "./pullRequest.ts"; import { ProjectRevisionFileResult } from "./project.ts"; import { TerminalReuseIds } from "./terminal.ts"; @@ -845,21 +844,6 @@ export type ThreadMoveTarget = typeof ThreadMoveTarget.Type; /** A check-back's prompt is kept up to this many characters (OrchestrationCheckBack.prompt). */ export const CHECK_BACK_PROMPT_MAX_CHARS = 2_000; -/** - * The commands an agent's session last listed for this thread (ACP - * `available_commands_update`): what the composer's `/` list offers while - * that agent and provider instance answer the thread. Kept across restarts, - * so the list is there before the session opens again; a new list from the - * session replaces it. - */ -export const OrchestrationAgentCommands = Schema.Struct({ - /** The provider instance whose session listed them. */ - providerInstanceId: ProviderInstanceId, - commands: Schema.Array(ServerProviderSlashCommand), - updatedAt: IsoDateTime, -}); -export type OrchestrationAgentCommands = typeof OrchestrationAgentCommands.Type; - /** * A time an agent set itself to come back to the thread (Claude's * ScheduleWakeup and CronCreate). It belongs to the agent that set it, not @@ -3245,12 +3229,6 @@ export const OrchestrationThread = Schema.Struct({ * OrchestrationMessage.agentModels). Absent: nothing recorded yet. */ sentModels: Schema.optional(Schema.Record(Schema.String, ModelSelection)), - /** - * Per agent (`primary` or a participant id), the slash commands its - * session last listed; see OrchestrationAgentCommands. Only providers that - * report them fill it. Absent: none reported. - */ - agentCommands: Schema.optional(Schema.Record(Schema.String, OrchestrationAgentCommands)), /** See OrchestrationThreadShell.doneOverride. */ doneOverride: Schema.NullOr(OrchestrationThreadDoneOverride).pipe( Schema.withDecodingDefault(Effect.succeed(null)), @@ -4517,19 +4495,6 @@ const ThreadCheckBacksSetCommand = Schema.Struct({ createdAt: IsoDateTime, }); -/** Provider-internal: the slash commands an agent's session listed; replaces - * that agent's list. Emitted by runtime ingestion off - * `session.commands.updated`, only when the list changed. */ -const ThreadAgentCommandsSetCommand = Schema.Struct({ - type: Schema.Literal("thread.agent-commands.set"), - commandId: CommandId, - threadId: ThreadId, - participantId: Schema.NullOr(ThreadParticipantId), - providerInstanceId: ProviderInstanceId, - commands: Schema.Array(ServerProviderSlashCommand), - createdAt: IsoDateTime, -}); - /** * Server-internal: bring the thread's goal in line with what the thread waits * on (docs/design/goal-wait-pause.md). The decider pauses an active goal while @@ -6113,7 +6078,6 @@ const InternalOrchestrationCommand = Schema.Union([ ThreadRealtimeStateSetCommand, ThreadEffectiveCwdSetCommand, ThreadCheckBacksSetCommand, - ThreadAgentCommandsSetCommand, ThreadGoalSetCommand, ThreadGoalClearCommand, ThreadGoalStateSetCommand, @@ -6245,7 +6209,6 @@ export const OrchestrationEventType = Schema.Literals([ "thread.continue-at-reset-skipped", "thread.effective-cwd-set", "thread.check-backs-set", - "thread.agent-commands-set", "thread.goal-set-requested", "thread.goal-clear-requested", "thread.goal-state-set", @@ -7128,14 +7091,6 @@ export const ThreadCheckBacksSetPayload = Schema.Struct({ updatedAt: IsoDateTime, }); -export const ThreadAgentCommandsSetPayload = Schema.Struct({ - threadId: ThreadId, - participantId: Schema.NullOr(ThreadParticipantId), - providerInstanceId: ProviderInstanceId, - commands: Schema.Array(ServerProviderSlashCommand), - updatedAt: IsoDateTime, -}); - export const ThreadCheckBackCancelRequestedPayload = Schema.Struct({ threadId: ThreadId, participantId: Schema.NullOr(ThreadParticipantId), @@ -7729,11 +7684,6 @@ export const OrchestrationEvent = Schema.Union([ type: Schema.Literal("thread.check-backs-set"), payload: ThreadCheckBacksSetPayload, }), - Schema.Struct({ - ...EventBaseFields, - type: Schema.Literal("thread.agent-commands-set"), - payload: ThreadAgentCommandsSetPayload, - }), Schema.Struct({ ...EventBaseFields, type: Schema.Literal("thread.check-back-cancel-requested"), diff --git a/packages/contracts/src/provider.ts b/packages/contracts/src/provider.ts index 2c9ab5d5c..fe36a1805 100644 --- a/packages/contracts/src/provider.ts +++ b/packages/contracts/src/provider.ts @@ -264,6 +264,11 @@ export const ProviderTypedInput = Schema.Struct({ text: TrimmedNonEmptyString.check(Schema.isMaxLength(PROVIDER_SEND_TURN_MAX_INPUT_CHARS)), /** What the server put in front of `text`. Absent: `input` is `text`. */ context: Schema.optional(Schema.String), + /** + * The person's text began with whitespace, which `text` drops. A driver + * that reads `/name` at the start as a command reads none then. + */ + indented: Schema.optional(Schema.Literal(true)), }); export type ProviderTypedInput = typeof ProviderTypedInput.Type; @@ -411,6 +416,13 @@ 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)), }); export type ProviderTurnStartResult = typeof ProviderTurnStartResult.Type; diff --git a/packages/contracts/src/providerRuntime.ts b/packages/contracts/src/providerRuntime.ts index ce61aa618..3abd7298e 100644 --- a/packages/contracts/src/providerRuntime.ts +++ b/packages/contracts/src/providerRuntime.ts @@ -23,7 +23,6 @@ import { ProviderApprovalDecision, } from "./orchestration.ts"; import { RuntimeMcpAppCall } from "./mcpApps.ts"; -import { ServerProviderSlashCommand } from "./slashCommands.ts"; import { AwaitedWorkflowProgress, WorkflowRunUpdate } from "./workflow.ts"; const TrimmedNonEmptyStringSchema = TrimmedNonEmptyString; @@ -208,7 +207,6 @@ const ProviderRuntimeEventType = Schema.Literals([ "goal.updated", "goal.cleared", "session.check-backs.updated", - "session.commands.updated", "thread.realtime.started", "thread.realtime.item-added", "thread.realtime.audio.delta", @@ -272,7 +270,6 @@ const ThreadTokenUsageUpdatedType = Schema.Literal("thread.token-usage.updated") const GoalUpdatedType = Schema.Literal("goal.updated"); const GoalClearedType = Schema.Literal("goal.cleared"); const SessionCheckBacksUpdatedType = Schema.Literal("session.check-backs.updated"); -const SessionCommandsUpdatedType = Schema.Literal("session.commands.updated"); const ThreadRealtimeStartedType = Schema.Literal("thread.realtime.started"); const ThreadRealtimeItemAddedType = Schema.Literal("thread.realtime.item-added"); const ThreadRealtimeAudioDeltaType = Schema.Literal("thread.realtime.audio.delta"); @@ -420,6 +417,12 @@ 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 (ProviderService.forgetConversation). + */ + conversationLost: Schema.optional(Schema.Literal(true)), }); export type SessionExitedPayload = typeof SessionExitedPayload.Type; @@ -577,17 +580,6 @@ const SessionCheckBacksUpdatedPayload = Schema.Struct({ }); export type SessionCheckBacksUpdatedPayload = typeof SessionCheckBacksUpdatedPayload.Type; -/** - * The commands the session's agent runs when a message starts with - * `/`, as it last listed them (ACP `available_commands_update`). Each - * report replaces the earlier list. Only drivers that let these reach the - * composer send it. - */ -const SessionCommandsUpdatedPayload = Schema.Struct({ - commands: Schema.Array(ServerProviderSlashCommand), -}); -export type SessionCommandsUpdatedPayload = typeof SessionCommandsUpdatedPayload.Type; - const ThreadRealtimeStartedPayload = Schema.Struct({ realtimeSessionId: Schema.optional(TrimmedNonEmptyStringSchema), }); @@ -1202,14 +1194,6 @@ const ProviderRuntimeSessionCheckBacksUpdatedEvent = Schema.Struct({ export type ProviderRuntimeSessionCheckBacksUpdatedEvent = typeof ProviderRuntimeSessionCheckBacksUpdatedEvent.Type; -const ProviderRuntimeSessionCommandsUpdatedEvent = Schema.Struct({ - ...ProviderRuntimeEventBase.fields, - type: SessionCommandsUpdatedType, - payload: SessionCommandsUpdatedPayload, -}); -export type ProviderRuntimeSessionCommandsUpdatedEvent = - typeof ProviderRuntimeSessionCommandsUpdatedEvent.Type; - const ProviderRuntimeGoalClearedEvent = Schema.Struct({ ...ProviderRuntimeEventBase.fields, type: GoalClearedType, @@ -1574,7 +1558,6 @@ export const ProviderRuntimeEventV2 = Schema.Union([ ProviderRuntimeGoalUpdatedEvent, ProviderRuntimeGoalClearedEvent, ProviderRuntimeSessionCheckBacksUpdatedEvent, - ProviderRuntimeSessionCommandsUpdatedEvent, ProviderRuntimeThreadRealtimeStartedEvent, ProviderRuntimeThreadRealtimeItemAddedEvent, ProviderRuntimeThreadRealtimeAudioDeltaEvent, diff --git a/packages/contracts/src/server.ts b/packages/contracts/src/server.ts index 88c783ad6..008d3df5b 100644 --- a/packages/contracts/src/server.ts +++ b/packages/contracts/src/server.ts @@ -26,7 +26,6 @@ import { ModelCapabilities, ModelUpgradeInfo } from "./model.ts"; import { RuntimeMode } from "./orchestration.ts"; import { ProviderDriverKind, ProviderInstanceId } from "./providerInstance.ts"; import { ServerSettings } from "./settings.ts"; -import { ServerProviderSlashCommand, ServerProviderSlashCommandInput } from "./slashCommands.ts"; const KeybindingsMalformedConfigIssue = Schema.Struct({ kind: Schema.Literal("keybindings.malformed-config"), @@ -379,7 +378,24 @@ export const ServerProviderModel = Schema.Struct({ }); export type ServerProviderModel = typeof ServerProviderModel.Type; -export { ServerProviderSlashCommand, ServerProviderSlashCommandInput }; +export const ServerProviderSlashCommandInput = Schema.Struct({ + hint: TrimmedNonEmptyString, +}); +export type ServerProviderSlashCommandInput = typeof ServerProviderSlashCommandInput.Type; + +export const ServerProviderSlashCommand = Schema.Struct({ + name: TrimmedNonEmptyString, + description: Schema.optional(TrimmedNonEmptyString), + input: Schema.optional(ServerProviderSlashCommandInput), +}); +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, @@ -566,6 +582,15 @@ export const ServerProvider = Schema.Struct({ * 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/slashCommands.ts b/packages/contracts/src/slashCommands.ts deleted file mode 100644 index d4b370452..000000000 --- a/packages/contracts/src/slashCommands.ts +++ /dev/null @@ -1,22 +0,0 @@ -import * as Schema from "effect/Schema"; - -import { TrimmedNonEmptyString } from "./baseSchemas.ts"; - -/** - * A command an agent runs when a message starts with `/`: a provider's - * own commands on its status (`ServerProvider.slashCommands`), and the list - * a running session reported for its thread (`OrchestrationThread.agentCommands`). - * Re-exported from `server.ts`; its own module so orchestration contracts can - * use it without importing the server contracts. - */ -export const ServerProviderSlashCommandInput = Schema.Struct({ - hint: TrimmedNonEmptyString, -}); -export type ServerProviderSlashCommandInput = typeof ServerProviderSlashCommandInput.Type; - -export const ServerProviderSlashCommand = Schema.Struct({ - name: TrimmedNonEmptyString, - description: Schema.optional(TrimmedNonEmptyString), - input: Schema.optional(ServerProviderSlashCommandInput), -}); -export type ServerProviderSlashCommand = typeof ServerProviderSlashCommand.Type; diff --git a/packages/shared/package.json b/packages/shared/package.json index d85a0d94b..eb12dbb3a 100644 --- a/packages/shared/package.json +++ b/packages/shared/package.json @@ -239,9 +239,9 @@ "types": "./src/queuedFollowUps.ts", "import": "./src/queuedFollowUps.ts" }, - "./agentCommands": { - "types": "./src/agentCommands.ts", - "import": "./src/agentCommands.ts" + "./slashCommands": { + "types": "./src/slashCommands.ts", + "import": "./src/slashCommands.ts" }, "./checkBacks": { "types": "./src/checkBacks.ts", diff --git a/packages/shared/src/agentCommands.ts b/packages/shared/src/agentCommands.ts deleted file mode 100644 index 7f78a0bc4..000000000 --- a/packages/shared/src/agentCommands.ts +++ /dev/null @@ -1,54 +0,0 @@ -import type { - OrchestrationAgentCommands, - ProviderInstanceId, - ServerProviderSlashCommand, - ThreadParticipantId, -} from "@threadlines/contracts"; - -import { roomAgentKey } from "./threadParticipants.ts"; - -type AgentCommandsByAgent = Readonly>; - -/** - * A thread's agent commands after one agent's session listed its commands: - * that agent's entry is replaced, every other agent's kept. Every reader of - * `thread.agent-commands-set` (server read models, clients) applies it. - */ -export function applyAgentCommands( - current: AgentCommandsByAgent | undefined, - update: { - readonly participantId: ThreadParticipantId | null; - readonly providerInstanceId: ProviderInstanceId; - readonly commands: ReadonlyArray; - readonly updatedAt: string; - }, -): AgentCommandsByAgent { - return { - ...current, - [roomAgentKey(update.participantId)]: { - providerInstanceId: update.providerInstanceId, - commands: update.commands, - updatedAt: update.updatedAt, - }, - }; -} - -/** Whether two command lists say the same thing, in the same order (a - * session lists its commands each time it opens; only a change is recorded). */ -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/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 + ); + }) + ); +} From 1b13d2cf68ab00ce67576d9c950aaac2e54d65e3 Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Mon, 23 Nov 2026 04:16:50 -0500 Subject: [PATCH 36/59] fix(antigravity): forgetting a conversation lives in the saved binding, and happens before files are restored A revert on an agent that can't rewind (conversationRollback "new-session") now stops its running work and ends its session before the checkpoint restores any file, then forgets the conversation in the thread's provider binding: the cursor goes and the binding owes the history (historyOwed). An idle agent is not started to do this. Every later start ignores any cursor, opens a new conversation and reports resumeFailed, so the thread seeds its next message, until a send that carried the history clears it (noteHistoryDelivered). A binding that can't be written makes the revert say the agent still remembers. A conversation the agent reports lost uses the same path. A start handed the thread's history (a switch from another agent) also owes it until a send carries it, and the reactor keeps that debt while a send goes as the agent's own command (contextDeferred), so a restart in between seeds the next start instead of losing the history. --- .../Layers/CheckpointReactor.test.ts | 94 +++++++---- .../orchestration/Layers/CheckpointReactor.ts | 81 +++++---- .../Layers/ProviderCommandReactor.test.ts | 65 +++++++ .../Layers/ProviderCommandReactor.ts | 47 ++++-- .../Layers/ProviderRuntimeIngestion.test.ts | 1 + .../provider/Layers/ProviderService.test.ts | 158 ++++++++++++++++++ .../src/provider/Layers/ProviderService.ts | 129 +++++++++++++- .../Layers/ProviderSessionReaper.test.ts | 1 + .../src/provider/Services/ProviderAdapter.ts | 9 +- .../src/provider/Services/ProviderService.ts | 12 +- 10 files changed, 501 insertions(+), 96 deletions(-) diff --git a/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts b/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts index 8bfb4157c..411706c56 100644 --- a/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts +++ b/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts @@ -162,6 +162,7 @@ function createProviderServiceHarness( adoptNativeSession: () => Effect.void, forgetNativeSession: () => Effect.void, dropResumeCursor: () => Effect.void, + noteHistoryDelivered: () => Effect.void, getCapabilities: () => Effect.succeed({ sessionModelSwitch: "in-session", @@ -3118,48 +3119,73 @@ describe("CheckpointReactor", () => { ); }); - it("still reaches an agent that forgets by starting over when no session runs", async () => { - const harness = await createHarness({ hasSession: false, conversationRollback: "new-session" }); - const threadId = ThreadId.make("thread-1"); - const createdAt = "2026-01-01T00:00:00.000Z"; + 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, + }), + ); + } - 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}`), + type: "thread.checkpoint.revert", + commandId: CommandId.make("cmd-new-session-revert"), 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, + turnCount: 1, 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"); - // The service reopens the saved session to end it, or the next turn would - // pick the conversation up as it was. - expect(harness.provider.rollbackConversation).toHaveBeenCalledTimes(1); - const thread = (await harness.readModel()).threads.find((entry) => entry.id === threadId); - expect( - thread?.activities.some((activity) => activity.kind.startsWith("checkpoint.revert.rollback")), - ).toBe(false); - }); + 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 }); diff --git a/apps/server/src/orchestration/Layers/CheckpointReactor.ts b/apps/server/src/orchestration/Layers/CheckpointReactor.ts index d0ba797b9..b5e403d90 100644 --- a/apps/server/src/orchestration/Layers/CheckpointReactor.ts +++ b/apps/server/src/orchestration/Layers/CheckpointReactor.ts @@ -1222,6 +1222,43 @@ const make = Effect.gen(function* () { } const context = contextResult.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. + const startsOver = + rolledBackTurns > 0 && + (yield* providerService + .getCapabilities( + context.thread.session?.providerInstanceId ?? context.thread.modelSelection.instanceId, + ) + .pipe( + Effect.map((capabilities) => capabilities.conversationRollback === "new-session"), + Effect.orElseSucceed(() => false), + )); + const startedOver = startsOver + ? yield* providerService + .rollbackConversation({ + threadId: event.payload.threadId, + numTurns: rolledBackTurns, + ...(targetUserMessageId !== undefined ? { targetUserMessageId } : {}), + }) + .pipe( + Effect.map((rollback) => rollback.conversationRolledBack), + Effect.catchCause((cause) => + Effect.logWarning("checkpoint revert could not make the agent start over", { + threadId: event.payload.threadId, + cause: Cause.pretty(cause), + }).pipe(Effect.as(false)), + ), + ) + : undefined; + const revertOutcome = yield* checkpointRevert.applyRevert(context); if (revertOutcome === null) { yield* failRevert( @@ -1241,42 +1278,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) { - // An agent that forgets by starting over (Antigravity) is reached with - // no runtime live too: the service reopens its session to end it, or - // the next turn would reopen the conversation as it was. - const startsOver = - !context.hasProviderSession && - (yield* providerService - .getCapabilities( - context.thread.session?.providerInstanceId ?? context.thread.modelSelection.instanceId, - ) - .pipe( - Effect.map((capabilities) => capabilities.conversationRollback === "new-session"), - Effect.orElseSucceed(() => false), - )); - if (context.hasProviderSession || startsOver) { - const targetUserMessageId = targetUserMessageIdForCheckpointRewind({ - thread: context.thread, - targetTurnCount: event.payload.turnCount, - }); - const rollbackRequest = providerService.rollbackConversation({ - threadId: event.payload.threadId, - numTurns: rolledBackTurns, - ...(targetUserMessageId !== undefined ? { targetUserMessageId } : {}), - }); - // A session that can't be reopened to end it is said to remember. - const rollback = yield* startsOver - ? rollbackRequest.pipe( - Effect.catch((cause) => - Effect.logWarning("checkpoint revert could not reopen the session to end it", { - threadId: event.payload.threadId, - cause, - }).pipe(Effect.as({ conversationRolledBack: false })), - ), - ) - : rollbackRequest; + 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/ProviderCommandReactor.test.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts index 768103ca6..3a9673993 100644 --- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts +++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts @@ -454,6 +454,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: @@ -576,6 +579,7 @@ describe("ProviderCommandReactor", () => { adoptNativeSession: () => Effect.void, forgetNativeSession: () => Effect.void, dropResumeCursor, + noteHistoryDelivered, getCapabilities: (_provider) => Effect.succeed({ sessionModelSwitch: input?.sessionModelSwitch ?? "in-session", @@ -829,6 +833,7 @@ describe("ProviderCommandReactor", () => { respondToUserInput, stopSession, dropResumeCursor, + noteHistoryDelivered, renameBranch, refreshStatus, refreshLocalStatus, @@ -1716,6 +1721,66 @@ describe("ProviderCommandReactor", () => { ); }); + 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], diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts index 8ae4c51c1..a917a8a57 100644 --- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts +++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts @@ -1948,23 +1948,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 } + : {}), + carriedBy: handoffSession.createdAt, + }); } // Another agent than the one a move carried a session for. yield* noteCarriedStart("handoff"); @@ -2962,6 +2961,7 @@ const make = Effect.gen(function* () { typed: { text: typedText, ...(providerContext.length > 0 ? { context: providerContext } : {}), + ...(/^\s/u.test(input.messageText) ? { indented: true as const } : {}), }, } : {}), @@ -2987,6 +2987,8 @@ const make = Effect.gen(function* () { if (owedSeed.moved === true) { yield* markHistorySeedDelivered(input.threadId, input.messageId); } + // The binding stops owing it too (ProviderService.noteHistoryDelivered). + yield* providerService.noteHistoryDelivered(sessionKey); }), // A send that failed before the provider took it delivered nothing. historyDebtReturned: @@ -3739,6 +3741,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; + // The send went as the agent's own command, without its context. + let contextDeferred = false; yield* providerService .sendTurn({ ...turnRequest, @@ -3760,7 +3764,14 @@ const make = Effect.gen(function* () { providerTookTurn = true; }), ), - Effect.tap(() => historyDebtPaid), + // A send that went as the agent's own command carried none of the + // context in front of it: every debt it was to pay stays. + Effect.tap((turn) => + Effect.suspend(() => { + contextDeferred = turn.contextDeferred === true; + return contextDeferred ? historyDebtReturned : historyDebtPaid; + }), + ), Effect.onError(() => historyDebtReturned), Effect.tap((turn) => Effect.sync(() => providerTakenTurns.set(event.payload.threadId, turn.turnId)), @@ -3772,11 +3783,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 48de77782..1e1901e21 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/provider/Layers/ProviderService.test.ts b/apps/server/src/provider/Layers/ProviderService.test.ts index e21105bfe..440073c29 100644 --- a/apps/server/src/provider/Layers/ProviderService.test.ts +++ b/apps/server/src/provider/Layers/ProviderService.test.ts @@ -3436,3 +3436,161 @@ 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); + const adapter = { + ...agent.adapter, + capabilities: { ...agent.adapter.capabilities, conversationRollback: "new-session" as const }, + }; + const runtimeRepositoryLayer = ProviderSessionRuntimeRepositoryLive.pipe( + Layer.provide(SqlitePersistenceMemory), + ); + const directoryLayer = 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, 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); + + yield* provider.noteHistoryDelivered(key); + yield* startingOver.agent.stopSession(key); + const whole = yield* start(key); + assert.deepEqual(lastStartCursor(), again.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("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", + payload: { exitKind: "graceful", conversationLost: true }, + }); + 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 f8435d129..df3f7fb59 100644 --- a/apps/server/src/provider/Layers/ProviderService.ts +++ b/apps/server/src/provider/Layers/ProviderService.ts @@ -218,6 +218,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 }; }, @@ -241,9 +243,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 @@ -669,6 +691,7 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( readonly lastRuntimeEvent?: string; readonly lastRuntimeEventAt?: string; readonly earlyUnused?: boolean; + readonly historyOwed?: boolean; readonly startedWith?: { readonly guideTools: boolean }; }, ) => @@ -696,6 +719,13 @@ 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 === true + ? forgetConversation(canonicalEvent.threadId) + : Effect.void, + ), Effect.flatMap((canonicalEvent) => increment(providerRuntimeEventsTotal, { provider: canonicalEvent.provider, @@ -800,10 +830,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(); @@ -1058,8 +1091,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); @@ -1083,9 +1125,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 } : {}), @@ -1129,6 +1174,7 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( session.resumeFailed !== true ? { resumed: true } : {}), + ...(owesHistorySeed ? { resumeFailed: true } : {}), }; yield* stopStaleSessionsForThread({ @@ -1144,6 +1190,9 @@ 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, or the + // seed this start handed over (an adapter may hold it until a send). + ...(historyOwed || input.contextSeed !== undefined ? { historyOwed: true } : {}), startedWith: { guideTools: input.guideTools === true }, }); yield* analytics.record("provider.session.started", { @@ -2826,6 +2875,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", @@ -2875,6 +2926,75 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( ); }); + /** + * Forgets a saved conversation in the thread's binding (see + * readPersistedHistoryOwed): its cursor goes and the history is owed. + * False when the binding couldn't be written; the agent then remembers. + */ + const forgetConversation = (threadId: ThreadId) => + Effect.gen(function* () { + 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 }, + }); + 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* () { + 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)) { + yield* adapter.rollbackThread(threadId, numTurns); + } + const forgotten = yield* forgetConversation(threadId); + yield* analytics.record("provider.conversation.rolled_back", { + provider: adapter.provider, + turns: numTurns, + }); + return forgotten; + }); + + const noteHistoryDelivered: ProviderServiceShape["noteHistoryDelivered"] = (threadId) => + Effect.gen(function* () { + const binding = Option.getOrUndefined(yield* directory.getBinding(threadId)); + if (binding === undefined || !readPersistedHistoryOwed(binding.runtimePayload)) return; + yield* directory.upsert({ + threadId, + provider: binding.provider, + ...(binding.providerInstanceId !== undefined + ? { providerInstanceId: binding.providerInstanceId } + : {}), + runtimePayload: { historyOwed: false }, + }); + }).pipe(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 @@ -3373,6 +3493,7 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( adoptNativeSession, forgetNativeSession, dropResumeCursor, + noteHistoryDelivered, getCapabilities, getInstanceInfo, rollbackConversation, 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 2cb9a5ce1..3ce47ae73 100644 --- a/apps/server/src/provider/Services/ProviderAdapter.ts +++ b/apps/server/src/provider/Services/ProviderAdapter.ts @@ -159,10 +159,11 @@ 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) ends the session instead, and the next turn - * opens a new one seeded with the turns kept; a revert reaches it even - * with no runtime live, since the saved conversation would otherwise be - * reopened as it was. + * `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" | "new-session"; diff --git a/apps/server/src/provider/Services/ProviderService.ts b/apps/server/src/provider/Services/ProviderService.ts index 5f092bbf8..77e2c69cb 100644 --- a/apps/server/src/provider/Services/ProviderService.ts +++ b/apps/server/src/provider/Services/ProviderService.ts @@ -386,6 +386,13 @@ export interface ProviderServiceShape { */ readonly dropResumeCursor: (threadId: ThreadId) => Effect.Effect; + /** + * The thread's history reached the agent of this session key (the send + * that carried it was taken): a conversation forgotten earlier + * (`historyOwed` on its binding) is whole again, so later starts resume it. + */ + readonly noteHistoryDelivered: (threadId: ThreadId) => Effect.Effect; + /** * Read capabilities for the adapter bound to a configured provider instance. */ @@ -400,7 +407,10 @@ 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 and + * its saved conversation forgotten in the thread's binding; nothing is + * started for it, and a binding that couldn't be written answers false. */ readonly rollbackConversation: (input: { readonly threadId: ThreadId; From 5c494db877a421dd110140253516e1e60eff3d7a Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Mon, 23 Nov 2026 04:18:03 -0500 Subject: [PATCH 37/59] refactor(acp): Antigravity turns run on the turn machine The held-turn and steering state that the reader, each prompt fiber, Stop, the hold watcher and the exit watcher all read and wrote is gone. For an agent with descriptor.turnMachine (Antigravity) the adapter steps the pure reducer on the session's event reader, in order with the agent's updates; sends, steers, Stop, prompt answers, outcome reads, timers and the process exit post events there, and the commands it returns run in order. Every other agent runs the plain prompt path it had before the hold work. What the machine settles by construction: Stop always arms its 15-second deadline (also when it lands before the prompt goes out, while its outcome is read, or as it would turn into a hold), and a cancel sent before the prompt went out is sent again once it has; output after a prompt's answer is a reply even while the answer is being read; a batch launch counts each subagent and each finished command owes its own wake; a stopped session ends its held turn (turn.aborted); a cancellation notice is dropped once per cancel whenever it arrives. Also fixed where they live: - Lost sessions are written atomically under one lock per file, merged with what another adapter of the instance wrote, and never removed. - A prompt's tokens and the cost the session reported up to its answer share one ledger line; cost after it gets a line of its own. - An older prompt answering after a steer moves the steer's log reading past it, so a late error stays the older prompt's. - A usage result that only wrote to the cache is kept. The descriptor's heldTurns, steerWithPrompt and promptOutcome become one turnMachine option; the outcome watch gains rebase. --- apps/server/scripts/antigravity-mock-agent.ts | 82 +- apps/server/src/provider/acp/AcpAdapter.ts | 1981 +++++++++-------- .../src/provider/acp/AcpProviderDescriptor.ts | 79 +- .../src/provider/acp/AcpSessionRuntime.ts | 81 +- .../server/src/provider/acp/AcpTurnMachine.ts | 4 +- .../antigravity/AntigravityTurns.test.ts | 211 +- .../provider/antigravity/AntigravityTurns.ts | 165 +- docs/providers/antigravity.md | 22 +- 8 files changed, 1564 insertions(+), 1061 deletions(-) diff --git a/apps/server/scripts/antigravity-mock-agent.ts b/apps/server/scripts/antigravity-mock-agent.ts index 6e4f0ab71..45527d970 100644 --- a/apps/server/scripts/antigravity-mock-agent.ts +++ b/apps/server/scripts/antigravity-mock-agent.ts @@ -17,7 +17,12 @@ * - `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 whose reports come 3 seconds apart. + * - `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 @@ -106,7 +111,8 @@ const program = Effect.gen(function* () { Effect.sync(() => { sessionCount += 1; return { - sessionId: `agy-session-${sessionCount}`, + // Unique per process, as the CLI's are: two threads never share one. + sessionId: `agy-${process.pid}-${sessionCount}`, modes: { currentModeId: "default", availableModes: [ @@ -170,12 +176,20 @@ const program = Effect.gen(function* () { yield* modelCallEnds(sessionId); return { stopReason: "end_turn" as const }; } - if (scenario === "steer" || scenario === "steer-log-error") { + if ( + scenario === "steer" || + scenario === "steer-log-error" || + scenario === "steer-late-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 }, @@ -226,17 +240,23 @@ const program = Effect.gen(function* () { return { stopReason: "end_turn" as const }; } if (scenario === "subagents" || scenario === "subagent-quiet") { - const launch = (toolCallId: string, Role: string) => - update(sessionId, { - sessionUpdate: "tool_call", - toolCallId, - kind: "other", - title: "Running invoke_subagent", - status: "completed", - rawInput: { Role, Prompt: `Work as ${Role}` }, - }); - yield* launch("call_a", "Researcher"); - if (scenario === "subagents") yield* launch("call_b", "Tester"); + // `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* () { @@ -250,6 +270,40 @@ const program = Effect.gen(function* () { }).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."); diff --git a/apps/server/src/provider/acp/AcpAdapter.ts b/apps/server/src/provider/acp/AcpAdapter.ts index bd74267c3..59eaf44bc 100644 --- a/apps/server/src/provider/acp/AcpAdapter.ts +++ b/apps/server/src/provider/acp/AcpAdapter.ts @@ -110,13 +110,12 @@ import { import { makeAcpNativeLoggers } from "./AcpNativeLogging.ts"; import type { AcpExtensionContext, + AcpPromptOutcomeWatch, AcpPromptFailure, - AcpPromptOutcome, AcpPromptPlanMode, AcpProviderDescriptor, AcpProviderSettings, AcpTurnOutcome, - AcpWorkAfterPrompt, } from "./AcpProviderDescriptor.ts"; import { applyAcpModelSelection, @@ -132,6 +131,16 @@ import { 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, +} from "./AcpTurnMachine.ts"; import { type AcpSessionRuntimeShape } from "./AcpSessionRuntime.ts"; const decodeLostSessions = Schema.decodeUnknownExit( @@ -153,8 +162,6 @@ 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); -/** How often a held turn (`heldTurns`) looks whether the agent's work is done. */ -const ACP_HELD_TURN_CHECK = Duration.millis(250); /** * A held turn ends this long after the agent's last word once nothing holds * it: another wake can follow straight after a reply. @@ -162,6 +169,8 @@ const ACP_HELD_TURN_CHECK = Duration.millis(250); 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); /** * The most turns a resume cursor remembers the agent's prompt positions for * (see `conversationHistory`); a revert further back trims Threadlines' turn @@ -172,6 +181,15 @@ const ACP_HISTORY_CURSOR_LIMIT = 200; const ACP_HISTORY_POSITION_TIMEOUT = Duration.seconds(5); /** The most lost agent sessions an instance remembers (`markSessionLost`). */ const ACP_LOST_SESSIONS_LIMIT = 100; +/** One writer at a time per lost-sessions file, whichever adapter writes it. */ +const lostSessionsFileLocks = new Map(); +const lostSessionsFileLock = (file: string): Semaphore.Semaphore => { + const existing = lostSessionsFileLocks.get(file); + if (existing !== undefined) return existing; + const created = Semaphore.makeUnsafe(1); + lostSessionsFileLocks.set(file, created); + return created; +}; const ACP_PLAN_MODE_ALIASES = ["plan", "architect"]; const ACP_IMPLEMENT_MODE_ALIASES = ["code", "agent", "default", "chat", "implement"]; const ACP_APPROVAL_MODE_ALIASES = ["ask"]; @@ -305,49 +323,11 @@ interface AcpSessionContext { | undefined; /** The newest position the agent has listed, so a later prompt is placed after it. */ newestPosition: number | undefined; - /** The turn whose prompts run or last ran (a steered turn has several). */ - turnRun: AcpTurnRun | undefined; - /** The turn kept open while the agent's work goes on (`heldTurns`). */ - held: AcpHeldTurn | undefined; - /** Work the agent goes on with after its prompt answered, by tool call id (`heldTurns`). */ - readonly workAfterPrompt: Map; - /** Subagent launches counted so far, by tool call id, so a repeated update counts once. */ - readonly subagentLaunches: Set; - /** Subagents launched and not heard back from (a reply the agent started by itself ended since). */ - subagentsOut: number; - /** A reply the agent started by itself has output and no closing `usage_update` yet. */ - replyOpen: boolean; - /** A held command or timer ended since the last reply: the next reply is its wake. */ - workEndedSinceReply: boolean; - /** When the agent last sent anything, for a held turn's quiet limits (ms since epoch). */ - lastAgentActivityMs: number; + /** The turn machine and what its commands need (`descriptor.turnMachine`). */ + readonly machine: AcpMachineSession | undefined; stopped: boolean; } -/** - * One turn's prompts: the first, and each one a steer sent after it - * (`steerWithPrompt`). The newest prompt's answer settles the turn; the agent - * answers an older one as the newer takes over. - */ -interface AcpTurnRun { - readonly turnId: TurnId; - readonly planMode: AcpPromptPlanMode | undefined; - readonly resolvedModel: string | undefined; - /** The turn's model as picked (a picker slug where known), for `promptOutcome.watch`. */ - readonly model: string | undefined; - /** The first prompt's text, for placing it in the agent's history. */ - readonly promptText: string; - readonly newestBefore: number | undefined; - /** The open prompt (`openPrompt`) while one runs; undefined between prompts. */ - phase: NonNullable | undefined; - /** How many prompts the turn has sent; the newest is this one. */ - prompts: number; - /** Tokens every answered prompt of the turn reported, added up. */ - usage: UsageTokenTotals | null; -} - -type AcpPromptOutcomeCheck = Effect.Success>; - type AcpTurnCompletedPayload = Extract["payload"]; /** A failed turn's completion, from how the agent's own words say it failed. */ @@ -364,33 +344,78 @@ function failedTurnPayload( }; } -/** Two token counts added up (a steered turn's prompts each report their own). */ -function addUsageTotals(total: UsageTokenTotals | null, next: UsageTokenTotals): UsageTokenTotals { - if (total === null) return next; - return { - uncachedInputTokens: total.uncachedInputTokens + next.uncachedInputTokens, - cachedInputTokens: total.cachedInputTokens + next.cachedInputTokens, - cacheCreationTokens: total.cacheCreationTokens + next.cacheCreationTokens, - outputTokens: total.outputTokens + next.outputTokens, - reasoningTokens: total.reasoningTokens + next.reasoningTokens, - }; +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; +} + +/** 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 turn kept open after its prompt answered: the prompt's own completion, - * sent when the work is done, or none for a turn the agent started itself. + * 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 AcpHeldTurn { - readonly turnId: TurnId; - readonly completion: - | { - readonly payload: AcpTurnCompletedPayload; - readonly model: string | undefined; - readonly usage: UsageTokenTotals | null; - } - | undefined; +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>; + /** Counts what the agent did, so a quiet timer knows the quiet was real. */ + activity: 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; @@ -713,49 +738,50 @@ export function makeAcpAdapter( * Agent sessions that can't go on (`AcpPromptFailure.sessionLost`): a * restart opens a new session instead, seeded with the thread's history. * Kept on disk per instance, so a server restart before the next message - * doesn't reopen one. + * doesn't reopen one. A lost session never comes back, so its mark stays + * (the newest `ACP_LOST_SESSIONS_LIMIT` are kept): nothing has to be + * removed at the moment a replacement takes over. */ const lostSessionsFile = path.join( serverConfig.stateDir, "acp-lost-sessions", `${encodeURIComponent(boundInstanceId)}.json`, ); - const lostSessions = new Set( - yield* fileSystem.readFileString(lostSessionsFile).pipe( - Effect.map((raw): ReadonlyArray => { - const parsed = decodeLostSessions(raw); - return Exit.isSuccess(parsed) ? parsed.value : []; - }), - Effect.orElseSucceed((): ReadonlyArray => []), - ), - ); - const saveLostSessions = Effect.gen(function* () { - yield* fileSystem.makeDirectory(path.dirname(lostSessionsFile), { recursive: true }); - yield* fileSystem.writeFileString( - lostSessionsFile, - JSON.stringify([...lostSessions].slice(-ACP_LOST_SESSIONS_LIMIT)), - ); - }).pipe( - Effect.catchCause((cause) => - Effect.logWarning("acp.lost-sessions.save-failed", { - provider: PROVIDER, - cause: Cause.pretty(cause), - }), - ), + const readLostSessions = fileSystem.readFileString(lostSessionsFile).pipe( + Effect.map((raw): ReadonlyArray => { + const parsed = decodeLostSessions(raw); + return Exit.isSuccess(parsed) ? parsed.value : []; + }), + Effect.orElseSucceed((): ReadonlyArray => []), ); - const markSessionLost = (sessionId: string) => - Effect.suspend(() => { - lostSessions.add(sessionId); - return saveLostSessions; - }); - const forgetLostSession = (sessionId: string) => - Effect.suspend(() => (lostSessions.delete(sessionId) ? saveLostSessions : Effect.void)); + const lostSessions = new Set(yield* readLostSessions); /** - * A turn that can outlive its prompt or span several (`heldTurns`, - * `steerWithPrompt`) writes each prompt's tokens as it answers. + * Adds a mark: one writer at a time per file (adapters of one instance + * share it), the file read again and merged inside the lock, and written + * whole through a temporary file, so a crash never leaves it cut short. */ - const recordsEachPrompt = - descriptor.heldTurns !== undefined || descriptor.steerWithPrompt === true; + const markSessionLost = (sessionId: string) => + lostSessionsFileLock(lostSessionsFile) + .withPermit( + Effect.gen(function* () { + lostSessions.add(sessionId); + const merged = [...new Set([...(yield* readLostSessions), ...lostSessions])].slice( + -ACP_LOST_SESSIONS_LIMIT, + ); + yield* fileSystem.makeDirectory(path.dirname(lostSessionsFile), { recursive: true }); + const temp = `${lostSessionsFile}.${crypto.randomUUID()}.tmp`; + yield* fileSystem.writeFileString(temp, JSON.stringify(merged)); + yield* fileSystem.rename(temp, lostSessionsFile); + }), + ) + .pipe( + Effect.catchCause((cause) => + Effect.logWarning("acp.lost-sessions.save-failed", { + provider: PROVIDER, + cause: Cause.pretty(cause), + }), + ), + ); const threadLocksRef = yield* SynchronizedRef.make(new Map()); const runtimeEventPubSub = yield* PubSub.unbounded(); @@ -1027,27 +1053,6 @@ export function makeAcpAdapter( }); }); - /** Writes down one answered prompt's tokens (`recordsEachPrompt`). */ - const recordPromptUsage = ( - ctx: AcpSessionContext, - run: AcpTurnRun, - promptNumber: number, - totals: UsageTokenTotals, - ) => - Effect.gen(function* () { - const record = options?.recordTurnUsage; - if (!record) return; - yield* record({ - atMs: yield* Clock.currentTimeMillis, - sessionId: ctx.acpSessionId, - // The ledger keeps one line per id: a steer's prompt has its own. - turnId: promptNumber === 1 ? run.turnId : `${run.turnId}:${promptNumber}`, - model: run.resolvedModel ?? ctx.session.model ?? "default", - totals, - costUsd: null, - }); - }); - /** * Opens a turn the agent started itself (`agentTurns`): its wake-up * after background work, opened on the extension's notice (in order with @@ -1064,15 +1069,6 @@ export function makeAcpAdapter( ctx.activeTurnId = turnId; ctx.agentTurn = { turnId, ended: yield* Deferred.make() }; ctx.agentTurnLastActivityMs = Date.now(); - // An agent whose own replies end with a `usage_update` (`heldTurns`) - // keeps the turn open by that, and by the work the reply starts. - const held: AcpHeldTurn | undefined = - descriptor.heldTurns !== undefined ? { turnId, completion: undefined } : undefined; - if (held !== undefined) { - ctx.held = held; - ctx.replyOpen = true; - ctx.lastAgentActivityMs = Date.now(); - } ctx.history.push({ turnId, agentTurn: true }); recordHistory(ctx); resetTurnState(ctx); @@ -1090,9 +1086,7 @@ export function makeAcpAdapter( payload: raw.payload, }, }); - yield* ( - held !== undefined ? watchHeldTurn(ctx, held) : watchAgentTurnQuiet(ctx, turnId) - ).pipe(Effect.forkIn(ctx.scope)); + yield* watchAgentTurnQuiet(ctx, turnId).pipe(Effect.forkIn(ctx.scope)); }); /** @@ -1145,7 +1139,6 @@ export function makeAcpAdapter( } yield* closeReasoning(ctx); ctx.agentTurn = undefined; - if (ctx.held?.turnId === agentTurn.turnId) ctx.held = undefined; if (ctx.agentTurnAhead?.turnId === agentTurn.turnId) ctx.agentTurnAhead = undefined; if (ctx.activeTurnId === agentTurn.turnId) ctx.activeTurnId = undefined; ctx.session = { ...ctx.session, activeTurnId: undefined, updatedAt: yield* nowIso }; @@ -1192,167 +1185,6 @@ export function makeAcpAdapter( } }); - /** - * The agent sent something (`heldTurns`). Outside a prompt that is a - * reply it started by itself, open until its closing `usage_update`. - */ - const noteAgentOutput = (ctx: AcpSessionContext) => { - if (descriptor.heldTurns === undefined) return; - ctx.lastAgentActivityMs = Date.now(); - if (ctx.turnRun?.phase === undefined) ctx.replyOpen = true; - }; - - /** - * The `usage_update` that ends each model call (`heldTurns`): a reply the - * agent started by itself is over. - */ - const noteReplyEnd = (ctx: AcpSessionContext) => { - if (descriptor.heldTurns === undefined) return; - ctx.lastAgentActivityMs = Date.now(); - if (ctx.replyOpen) endReply(ctx); - }; - - /** - * A reply the agent started by itself ended (its `usage_update`, or a - * long quiet). Subagents are known to end only by the report they wake - * the agent to give, so a reply that no finished command or timer woke - * counts as one subagent's report. - */ - const endReply = (ctx: AcpSessionContext) => { - ctx.replyOpen = false; - if (ctx.workEndedSinceReply) ctx.workEndedSinceReply = false; - else if (ctx.subagentsOut > 0) ctx.subagentsOut -= 1; - }; - - /** Keeps count of the work a tool call goes on with after its prompt (`heldTurns`). */ - const trackWorkAfterPrompt = (ctx: AcpSessionContext, toolCall: AcpToolCallState) => { - const kind = descriptor.heldTurns?.workAfterPrompt(toolCall); - const id = toolCall.toolCallId; - if (kind === undefined) { - ctx.workAfterPrompt.delete(id); - return; - } - // A launch returns at once; the subagent works on until it reports. - if (kind === "subagent") { - if (toolCall.status === "completed" && !ctx.subagentLaunches.has(id)) { - ctx.subagentLaunches.add(id); - ctx.subagentsOut += 1; - } - return; - } - if (toolCall.status === "completed" || toolCall.status === "failed") { - // Outside a prompt, its wake (not a subagent's report) is the reply - // that follows. - if (ctx.workAfterPrompt.delete(id) && ctx.turnRun?.phase === undefined) { - ctx.workEndedSinceReply = true; - } - } else { - ctx.workAfterPrompt.set(id, kind); - } - }; - - /** Forgets the agent's outstanding work: it was stopped, or failed with its turn. */ - const clearWorkAfterPrompt = (ctx: AcpSessionContext) => { - ctx.workAfterPrompt.clear(); - ctx.subagentsOut = 0; - ctx.replyOpen = false; - ctx.workEndedSinceReply = false; - }; - - /** - * Ends a held turn, once: the turn the agent started itself as its own - * end would, or a prompt's turn with the completion its prompt answered. - * Run under `turnStartLock`, so a steer or a new message can't race it. - */ - const closeHeldTurn = ( - ctx: AcpSessionContext, - held: AcpHeldTurn, - outcome: "completed" | "cancelled" | { readonly failed: string }, - ) => - Effect.gen(function* () { - if (ctx.held !== held) return; - ctx.held = undefined; - if (outcome !== "completed") clearWorkAfterPrompt(ctx); - const ended: AcpTurnOutcome | undefined = - outcome === "cancelled" - ? { state: "cancelled", stopReason: "cancelled" } - : outcome === "completed" - ? undefined - : { state: "failed", errorMessage: outcome.failed }; - const completion = held.completion; - if (completion === undefined) { - yield* closeAgentTurn(ctx, ended ?? { state: "completed" }); - return; - } - // The reply the agent started by itself ends with the turn. - yield* ctx.acp.closeAssistantSegment; - yield* ctx.acp.flushEvents(); - yield* closeReasoning(ctx); - if (ctx.activeTurnId === held.turnId) { - ctx.activeTurnId = undefined; - ctx.session = { ...ctx.session, activeTurnId: undefined, updatedAt: yield* nowIso }; - } - if (ctx.turnRun?.turnId === held.turnId) ctx.turnRun = undefined; - yield* offerRuntimeEvent({ - type: "turn.completed", - ...(yield* makeEventStamp()), - provider: PROVIDER, - threadId: ctx.threadId, - turnId: held.turnId, - payload: - ended === undefined - ? completion.payload - : { - state: ended.state, - stopReason: ended.stopReason ?? null, - ...(ended.errorMessage !== undefined ? { errorMessage: ended.errorMessage } : {}), - }, - }); - yield* settleTurnUsage(ctx, held.turnId, completion.model, completion.usage); - }); - - /** - * Ends a held turn once the agent's work is done and it has gone quiet, - * or once only commands and subagents hold it and it has said nothing - * for the descriptor's silent limit (a lost wake must not leave the - * thread working forever). A wait on the user's answer is not quiet. - */ - const watchHeldTurn = (ctx: AcpSessionContext, held: AcpHeldTurn) => - Effect.gen(function* () { - const silentLimitMs = Duration.toMillis( - descriptor.heldTurns?.silentLimit ?? ACP_AGENT_TURN_QUIET_LIMIT, - ); - const replyQuietMs = Duration.toMillis( - descriptor.heldTurns?.replyQuietLimit ?? ACP_HELD_REPLY_QUIET_LIMIT, - ); - while (ctx.held === held && !ctx.stopped) { - yield* Effect.sleep(ACP_HELD_TURN_CHECK); - if (ctx.held !== held) return; - const now = Date.now(); - if (ctx.pendingApprovals.size > 0 || ctx.pendingUserInputs.size > 0) { - ctx.lastAgentActivityMs = now; - continue; - } - const quietMs = now - ctx.lastAgentActivityMs; - if (ctx.replyOpen && quietMs >= replyQuietMs) endReply(ctx); - const work = [...ctx.workAfterPrompt.values()]; - const waiting = work.length > 0 || ctx.subagentsOut > 0 || ctx.replyOpen; - const settled = !waiting && quietMs >= Duration.toMillis(ACP_HELD_TURN_SETTLE); - const silent = - waiting && !ctx.replyOpen && !work.includes("wake") && quietMs >= silentLimitMs; - if (!settled && !silent) continue; - const seenAt = ctx.lastAgentActivityMs; - yield* ctx.turnStartLock.withPermit( - Effect.suspend(() => { - // Something arrived while the lock was busy: look again. - if (ctx.held !== held || ctx.lastAgentActivityMs !== seenAt) return Effect.void; - if (silent) clearWorkAfterPrompt(ctx); - return closeHeldTurn(ctx, held, "completed"); - }), - ); - } - }); - /** * 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; @@ -1361,8 +1193,22 @@ export function makeAcpAdapter( const turnForOutput = (ctx: AcpSessionContext, toolCallId?: string) => Effect.gen(function* () { if (ctx.agentTurn !== undefined) ctx.agentTurnLastActivityMs = Date.now(); - noteAgentOutput(ctx); 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 { + machine.activity += 1; + } + return earlier ?? ctx.activeTurnId; + } if (earlier !== undefined) return earlier; if (ctx.activeTurnId !== undefined) return ctx.activeTurnId; if (!descriptor.agentTurns) return undefined; @@ -1403,6 +1249,16 @@ export function makeAcpAdapter( if (ctx.notificationFiber) { yield* Fiber.interrupt(ctx.notificationFiber); } + // The reader is gone, so this is the one place left to step the + // machine: the open turn ends, and every waiting send hears back. + const machine = ctx.machine; + if (machine !== undefined) { + 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" }); + } + } yield* Effect.ignore(Scope.close(ctx.scope, Exit.void)); sessions.delete(ctx.threadId); @@ -1415,32 +1271,6 @@ export function makeAcpAdapter( }); }); - /** - * The agent process ended by itself (`heldTurns`). A prompt in flight - * fails on its own and settles first; a turn held open for the agent's - * work has no request left to fail, so it ends failed here. The session - * stops, and the next message starts the agent again. - */ - const onAgentExited = (ctx: AcpSessionContext) => - Effect.gen(function* () { - yield* awaitPrompt(ctx).pipe(Effect.timeoutOption(ACP_CANCEL_DEADLINE)); - yield* ctx.turnStartLock.withPermit( - Effect.suspend(() => - ctx.held === undefined || ctx.stopped - ? Effect.void - : closeHeldTurn(ctx, ctx.held, { - failed: `${descriptor.presentation.displayName} stopped before its work finished.`, - }), - ), - ); - yield* withThreadLock( - ctx.threadId, - Effect.suspend(() => - sessions.get(ctx.threadId) === ctx ? stopSessionInternal(ctx, "error") : Effect.void, - ), - ); - }); - /** * Tells the descriptor when the agent answered `auth_required`, given the * ACP error or the adapter error that wraps it. Never fails or dies: a @@ -1767,8 +1597,8 @@ export function makeAcpAdapter( clientInfo: THREADLINES_ACP_CLIENT_INFO, mcpServers, runtimeMode: input.runtimeMode, - ...(descriptor.agentTurns ? { liveOutsidePrompt: true } : {}), - ...(descriptor.heldTurns ? { trackSilentToolCalls: true } : {}), + ...(descriptor.agentTurns || descriptor.turnMachine ? { liveOutsidePrompt: true } : {}), + ...(descriptor.turnMachine ? { trackSilentToolCalls: true } : {}), ...acpNativeLoggers, }).pipe( Effect.provideService(Scope.Scope, sessionScope), @@ -1810,15 +1640,16 @@ export function makeAcpAdapter( } else { yield* acp.inOrder( Effect.gen(function* () { - // A request the agent makes while no turn runs (`heldTurns`: - // its wake asks for a permission) opens one of its own. - if (descriptor.heldTurns !== undefined && context.activeTurnId === undefined) { - yield* openAgentTurn(context, { - method: "session/request_permission", - payload: {}, + // 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(), }); } - noteAgentOutput(context); yield* showAs(context.activeTurnId); }), ); @@ -1861,7 +1692,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({ @@ -2084,7 +1920,12 @@ export function makeAcpAdapter( // 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(requestId); + return closeMachineRequest(ctx); + }), + ), ); const turnId = yield* Deferred.await(shown); yield* offerRuntimeEvent( @@ -2129,7 +1970,6 @@ export function makeAcpAdapter( (lostSession !== undefined ? `${descriptor.presentation.displayName} can no longer continue its earlier conversation.` : undefined); - if (lostSession !== undefined) yield* forgetLostSession(lostSession); // A resumed conversation keeps the turn history its cursor carried. const keepsHistory = resumed !== undefined && @@ -2225,14 +2065,17 @@ export function makeAcpAdapter( promptOutcome: undefined, openPrompt: undefined, newestPosition: resumedNewestPosition, - turnRun: undefined, - held: undefined, - workAfterPrompt: new Map(), - subagentLaunches: new Set(), - subagentsOut: 0, - replyOpen: false, - workEndedSinceReply: false, - lastAgentActivityMs: 0, + machine: + descriptor.turnMachine === undefined + ? undefined + : { + state: initialTurnMachineState(), + callers: new Map(), + prompts: new Map(), + turns: new Map(), + timers: new Map(), + activity: 0, + }, stopped: false, }; @@ -2269,7 +2112,9 @@ export function makeAcpAdapter( } return; case "ContextUsage": { - noteReplyEnd(ctx); + // 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. @@ -2302,13 +2147,52 @@ export function makeAcpAdapter( case "ModeChanged": return; case "ToolCallTracked": - // A held turn counts work whose updates show nothing new - // (a timer's "Running schedule" stays as it started). - if (descriptor.heldTurns !== undefined) { - ctx.lastAgentActivityMs = Date.now(); - trackWorkAfterPrompt(ctx, event.toolCall); + // Work whose updates show nothing new still counts (a + // timer's "Running schedule" stays as it started). + if (ctx.machine !== undefined) { + ctx.machine.activity += 1; + yield* trackMachineWork(ctx, event.toolCall); + } + 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); @@ -2360,8 +2244,7 @@ export function makeAcpAdapter( : []; const toolCallId = event.toolCall.toolCallId; const turnId = yield* turnForOutput(ctx, toolCallId); - if (descriptor.heldTurns !== undefined) - trackWorkAfterPrompt(ctx, event.toolCall); + if (ctx.machine !== undefined) yield* trackMachineWork(ctx, event.toolCall); if ( event.toolCall.status === "completed" || event.toolCall.status === "failed" @@ -2414,15 +2297,14 @@ export function makeAcpAdapter( ctx.notificationFiber = notificationFiber; sessions.set(input.threadId, ctx); - // Held turns wait on no request the exit would fail (`onAgentExited`). - if (descriptor.heldTurns !== undefined && acp.process !== undefined) { + // 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 - : onAgentExited(session).pipe(Effect.forkIn(adapterScope), Effect.asVoid), + session.stopped ? Effect.void : postTurnEvent(session, { type: "processExited" }), ), ), Effect.forkIn(sessionScope), @@ -2527,114 +2409,694 @@ 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) => - Effect.gen(function* () { - // ACP serializes prompts per session; a turn sent while one is in - // flight starts after it, never interleaved with it (nor with a - // prompt a steer sent meanwhile). The wait is outside the lock: a - // Stop or a settling prompt that needs the lock must not queue - // behind a send that waits on them. - while (true) { - const awaited = yield* awaitPrompt(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. One that lost the race waits for the winner's. - const started = yield* ctx.turnStartLock.withPermit( - Effect.suspend(() => - ctx.promptFiber === awaited ? startTurn(ctx, input) : Effect.succeed(undefined), - ), - ); - if (started !== undefined) return started; - } - }), - ); + /** + * 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 !== "steer" && + event.type !== "stopRequested" && + event.type !== "timerFired" && + event.type !== "processExited" && + event.type !== "sessionStopping" && + event.type !== "outcomeRead" && + event.type !== "promptDispatched"; + + /** Steps the machine with one event, on the event reader, and runs its commands. */ + const applyTurnEvent = ( + ctx: AcpSessionContext, + event: AcpMachineEvent, + ): Effect.Effect> => + Effect.gen(function* () { + const machine = ctx.machine; + if (machine === undefined) return []; + if (isAgentActivity(event)) machine.activity += 1; + const step = stepTurnMachine(machine.state, event); + machine.state = step.state; + for (const command of step.commands) yield* runTurnCommand(ctx, machine, command); + return step.commands; + }); + + /** 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" }); - /** Waits for the newest prompt (a steer may send another meanwhile); returns its fiber. */ - const awaitPrompt = (ctx: AcpSessionContext) => + /** 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* () { - while (ctx.promptFiber !== undefined) { - const promptFiber = ctx.promptFiber; - yield* Fiber.await(promptFiber); - if (ctx.promptFiber === promptFiber) return promptFiber; + const work = machineOptions?.workAfterPrompt(toolCall); + if (work === undefined) return; + const id = toolCall.toolCallId; + 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; } - return undefined; + yield* applyTurnEvent( + ctx, + ended ? { type: "workEnded", id } : { type: "workStarted", id, kind: work.kind }, + ); }); - /** Waits for the turn's prompts: this one, and any a steer sent after it for the same turn. */ - const awaitTurnPrompts = ( + /** + * Arms one of the machine's timers. A quiet timer fires only after so + * long without the agent doing anything: activity while it waits starts + * it over, so the machine hears it fire only when the quiet was real. + */ + const armTurnTimer = ( ctx: AcpSessionContext, - turnId: TurnId, - first: NonNullable, + machine: AcpMachineSession, + timer: AcpTurnTimer, + generation: number, + ): Effect.Effect => + Effect.gen(function* () { + const seen = machine.activity; + const wait = timer === "cancelDeadline" ? ACP_CANCEL_DEADLINE : quietLimit(timer); + const fiber = yield* Effect.sleep(wait).pipe( + Effect.andThen( + ctx.acp.inOrder( + Effect.suspend(() => { + const armed = machine.state.timers.find(([name]) => name === timer); + if (armed?.[1] !== generation) return Effect.void; + return timer !== "cancelDeadline" && machine.activity !== seen + ? armTurnTimer(ctx, machine, timer, generation) + : applyTurnEvent(ctx, { type: "timerFired", timer, generation }).pipe( + Effect.asVoid, + ); + }), + ), + ), + Effect.forkIn(ctx.scope), + ); + machine.timers.set(timer, fiber); + }); + + /** One prompt of a machine turn: the turn's configuration first, then the prompt. */ + const runMachinePrompt = ( + ctx: AcpSessionContext, + machine: AcpMachineSession, + prompt: number, + sent: AcpMachinePromptSent, ) => Effect.gen(function* () { - let promptFiber = first; - while (true) { - yield* Fiber.await(promptFiber); - const next = ctx.promptFiber; - if (next === undefined || next === promptFiber || ctx.turnRun?.turnId !== turnId) return; - promptFiber = next; - } + const exit = yield* Effect.exit( + Effect.gen(function* () { + if (sent.configure !== undefined) yield* sent.configure; + // Where the agent's records stand as this prompt goes out. + const watch = + machineOptions?.outcome === undefined + ? undefined + : yield* machineOptions.outcome.watch(ctx.acpSessionId, sent.model).pipe( + Effect.catchCause((cause) => + Effect.logWarning("acp.prompt-outcome.watch-failed", { + provider: PROVIDER, + cause: Cause.pretty(cause), + }).pipe(Effect.as(undefined)), + ), + ); + sent.watch = watch; + yield* postTurnEvent(ctx, { type: "promptDispatched", prompt }); + const promptMeta = descriptor.promptMeta?.(sent.turnId); + return yield* ctx.acp.prompt({ + prompt: [...sent.parts], + ...(promptMeta ? { _meta: { ...promptMeta } } : {}), + }); + }), + ); + // A stopping session ends the turn itself. + if (Exit.isFailure(exit) && Cause.hasInterruptsOnly(exit.cause)) return; + sent.exit = exit; + yield* postTurnEvent(ctx, { type: "promptAnswered", prompt }); }); - const startTurn = (ctx: AcpSessionContext, input: Parameters[0]) => + /** + * 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* () { - // 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, or while a - // turn waits on the agent's work, ends that turn here; the agent takes - // the message after it, as Claude does. - if (ctx.held !== undefined) { - yield* closeHeldTurn(ctx, ctx.held, "completed"); - } - if (ctx.agentTurn !== undefined) { - yield* closeAgentTurn(ctx, { state: "completed" }); + 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, + }; } - const turnId = TurnId.make(crypto.randomUUID()); - const turnModelSelection = - input.modelSelection?.instanceId === boundInstanceId ? input.modelSelection : undefined; - const model = turnModelSelection?.model ?? ctx.session.model; - const resolvedModel = resolveModelId(model); - - // 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() ?? ""; - const contextText = - contextPreamble !== undefined - ? withContextSeedPreamble(contextPreamble, userText) - : userText; - // The project's brief leads, as a paragraph of its own. - const seededText = - projectBrief.text !== undefined - ? contextText.length > 0 - ? `${projectBrief.text}\n\n${contextText}` - : projectBrief.text - : contextText; - const promptParts = yield* promptContent( - seededText.length > 0 || planMode - ? planMode - ? `${planMode.promptPrefix}${seededText}` - : seededText - : undefined, - input.attachments, - "session/prompt", - ); + // 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* runMachinePrompt(ctx, machine, command.prompt, sent).pipe( + Effect.forkIn(ctx.scope), + ); + 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* readMachineOutcome(ctx, sent, seen).pipe( + Effect.flatMap((outcome) => + postTurnEvent(ctx, { type: "outcomeRead", prompt: command.prompt, outcome }), + ), + Effect.forkIn(ctx.scope), + ); + return; + } + case "rebaseOutcome": { + const watch = machine.prompts.get(command.prompt)?.watch; + if (watch !== undefined) yield* watch.rebase.pipe(Effect.ignore); + 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": + yield* stopFromMachine(ctx, command.reason === "exited" ? "error" : "graceful"); + return; + case "markSessionLost": + yield* markSessionLost(ctx.acpSessionId).pipe(Effect.forkIn(adapterScope)); + return; + case "dropNotice": + return; + } + }); + + /** Stops the session from a machine command, off the reader (stopping interrupts it). */ + const stopFromMachine = (ctx: AcpSessionContext, exitKind: "graceful" | "error") => + withThreadLock( + ctx.threadId, + Effect.suspend(() => + sessions.get(ctx.threadId) === ctx ? stopSessionInternal(ctx, exitKind) : 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 sendId = `send:${turnId}`; + machine.callers.set(sendId, { + prompt: { + parts: prepared.promptParts, + configure: prepared.configure, + model: prepared.model, + resolvedModel: prepared.resolvedModel, + }, + ...(input.messageId !== undefined ? { messageId: input.messageId } : {}), + planMode: prepared.planMode, + reply, + }); + if (ctx.stopped) { + machine.callers.delete(sendId); + return yield* new ProviderAdapterSessionNotFoundError({ + provider: PROVIDER, + threadId: input.threadId, + }); + } + yield* postTurnEvent(ctx, { type: "send", sendId, turnId }); + const answer = yield* Deferred.await(reply); + if ("rejected" in answer) { + if (ctx.projectBriefCarrier?.turnId === turnId) requeueProjectBrief(ctx); + return yield* new ProviderAdapterSessionNotFoundError({ + provider: PROVIDER, + threadId: input.threadId, + }); + } + return { threadId: input.threadId, turnId, resumeCursor: ctx.session.resumeCursor }; + }); + + /** 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( + 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 }, + 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); + // 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() ?? ""; + const contextText = + contextPreamble !== undefined + ? withContextSeedPreamble(contextPreamble, userText) + : userText; + // The project's brief leads, as a paragraph of its own. + const seededText = + projectBrief.text !== undefined + ? contextText.length > 0 + ? `${projectBrief.text}\n\n${contextText}` + : projectBrief.text + : contextText; + const promptParts = yield* promptContent( + seededText.length > 0 || planMode + ? planMode + ? `${planMode.promptPrefix}${seededText}` + : seededText + : undefined, + input.attachments, + "session/prompt", + ); if (promptParts.length === 0) { return yield* new ProviderAdapterValidationError({ provider: PROVIDER, @@ -2642,62 +3104,118 @@ 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, + }; + }); + + /** 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 run: AcpTurnRun = { + const prompt = { turnId, - planMode, - resolvedModel, - model, - promptText: promptParts - .flatMap((part) => (part.type === "text" ? [part.text] : [])) - .join("\n"), - newestBefore: ctx.newestPosition, - phase: undefined, - prompts: 0, - usage: null, + drained: yield* Deferred.make(), + closed: yield* Deferred.make(), }; - ctx.turnRun = run; - yield* openPromptPhase(ctx, run); + 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, ...(input.messageId !== undefined ? { messageId: input.messageId } : {}), }); recordHistory(ctx); + const promptText = promptParts + .flatMap((part) => (part.type === "text" ? [part.text] : [])) + .join("\n"); + const newestBefore = ctx.newestPosition; yield* offerRuntimeEvent({ type: "turn.started", @@ -2708,142 +3226,22 @@ export function makeAcpAdapter( payload: { model: resolvedModel }, }); - yield* sendTurnPrompt(ctx, run, promptParts); - - return { threadId: input.threadId, turnId, resumeCursor: ctx.session.resumeCursor }; - }); - - /** Starts reading how the turn's prompts end (`promptOutcome`); never fails. */ - const watchPromptOutcome = (ctx: AcpSessionContext, model: string | undefined) => - descriptor.promptOutcome === undefined - ? Effect.succeed(undefined) - : descriptor.promptOutcome.watch(ctx.acpSessionId, model).pipe( - Effect.catchCause((cause) => - Effect.logWarning("acp.prompt-outcome.watch-failed", { - provider: PROVIDER, - cause: Cause.pretty(cause), - }).pipe(Effect.as(undefined)), - ), + const runPrompt = Effect.gen(function* () { + const promptMeta = descriptor.promptMeta?.(turnId); + const exit = yield* Effect.exit( + ctx.acp.prompt({ + prompt: promptParts, + ...(promptMeta ? { _meta: { ...promptMeta } } : {}), + }), ); - - /** The turn's prompts' answer as the agent's own words tell it (`promptOutcome`). */ - const checkPromptOutcome = ( - checkOutcome: AcpPromptOutcomeCheck | undefined, - answer: Parameters[0], - ): Effect.Effect => - checkOutcome === undefined - ? Effect.succeed(undefined) - : checkOutcome(answer).pipe( - Effect.catchCause((cause) => - Effect.logWarning("acp.prompt-outcome.check-failed", { - provider: PROVIDER, - cause: Cause.pretty(cause), - }).pipe(Effect.as(undefined)), - ), + // Deltas travel through the notification fiber; make sure every one + // queued before the prompt returned is out before the turn closes. + // The reader may be past them already, held at a turn the agent + // began after them (`beginAgentTurnInOrder`). + yield* Effect.raceFirst( + ctx.acp.flushEvents(prompt.closed), + Deferred.await(prompt.drained), ); - - /** The turn's open prompt (`openPrompt`), opened now unless a prompt is already open. */ - const openPromptPhase = (ctx: AcpSessionContext, run: AcpTurnRun) => - Effect.gen(function* () { - if (run.phase !== undefined) return run.phase; - const phase = { - turnId: run.turnId, - drained: yield* Deferred.make(), - closed: yield* Deferred.make(), - }; - run.phase = phase; - ctx.openPrompt = phase; - // What the agent did by itself is over: this prompt carries the turn on. - ctx.replyOpen = false; - ctx.workEndedSinceReply = false; - return phase; - }); - - /** - * Sends one of a turn's prompts: its first, or a steer - * (`steerWithPrompt`). It runs in the session scope; the newest prompt's - * answer settles the turn. - */ - const sendTurnPrompt = ( - ctx: AcpSessionContext, - run: AcpTurnRun, - promptParts: ReadonlyArray, - ) => - Effect.gen(function* () { - // Each prompt reads its own outcome from where the agent's records - // stand as it goes out, not where the turn's first prompt found them. - const checkOutcome = yield* watchPromptOutcome(ctx, run.model); - run.prompts += 1; - const promptNumber = run.prompts; - const phase = yield* openPromptPhase(ctx, run); - const answered = yield* Deferred.make(); - ctx.promptFiber = yield* Effect.forkIn( - runTurnPrompt(ctx, run, { phase, answered, promptNumber, promptParts, checkOutcome }), - ctx.scope, - ); - }); - - /** - * One prompt of a turn, from its answer to the turn's end. `phase` is the - * turn's open prompt, shared with a steer's; `answered` is this prompt's - * own: the reader holds what follows its answer until it is settled, and - * a superseded prompt releases it at once, so its successor's output (a - * permission request included) is never stuck behind it. - */ - const runTurnPrompt = ( - ctx: AcpSessionContext, - run: AcpTurnRun, - input: { - readonly phase: NonNullable; - readonly answered: Deferred.Deferred; - readonly promptNumber: number; - readonly promptParts: ReadonlyArray; - readonly checkOutcome: AcpPromptOutcomeCheck | undefined; - }, - ) => { - const { phase: prompt, answered, promptNumber, promptParts, checkOutcome } = input; - const turnId = run.turnId; - const threadId = ctx.threadId; - const { planMode, resolvedModel, promptText, newestBefore } = run; - const usageTotals = descriptor.turnUsageTotals ?? acpTurnUsageTotals; - /** A newer prompt took the turn over (a steer): this one's answer settles nothing. */ - const superseded = () => promptNumber !== run.prompts; - /** - * Settling runs under the turn lock when a steer sends a prompt, so a - * steer lands before the settle starts (and supersedes it) or after - * it ended (and finds the turn over, or held). - */ - const settleLocked = (settle: Effect.Effect) => - descriptor.steerWithPrompt === true ? ctx.turnStartLock.withPermit(settle) : settle; - let lostSession = false; - let finalized = false; - const finalize = Effect.gen(function* () { - if (finalized || superseded()) return; - finalized = true; - if (run.phase === prompt) run.phase = undefined; - if (ctx.held?.turnId !== turnId) { - if (ctx.activeTurnId === turnId) { - ctx.activeTurnId = undefined; - ctx.session = { ...ctx.session, activeTurnId: undefined, updatedAt: yield* nowIso }; - } - if (ctx.turnRun === run) ctx.turnRun = undefined; - } - if (ctx.openPrompt === prompt) ctx.openPrompt = undefined; - yield* Deferred.succeed(prompt.closed, undefined); - // The agent can't go on with this session: it is stopped, and - // the next message opens a new one with the thread's history. - if (lostSession) { - yield* markSessionLost(ctx.acpSessionId); - yield* withThreadLock( - ctx.threadId, - Effect.suspend(() => - sessions.get(ctx.threadId) === ctx ? stopSessionInternal(ctx) : Effect.void, - ), - ).pipe(Effect.forkIn(adapterScope)); - } - }); - const settle = (exit: Exit.Exit) => - Effect.gen(function* () { // A turn that ends mid-thought (or on one) still settles its row. yield* closeReasoning(ctx); // Where the prompt landed, known before the turn reads as ended, @@ -2860,7 +3258,7 @@ export function makeAcpAdapter( type: "turn.proposed.completed", ...(yield* makeEventStamp()), provider: PROVIDER, - threadId, + threadId: input.threadId, turnId, payload: { planMarkdown }, }); @@ -2870,163 +3268,54 @@ export function makeAcpAdapter( updatedAt: yield* nowIso, ...(resolvedModel !== undefined ? { model: resolvedModel } : {}), }; - // An agent that ends a turn normally on an upstream error says so - // in its own records (`promptOutcome`). - const hidden = - result.stopReason === "cancelled" - ? undefined - : yield* checkPromptOutcome(checkOutcome, { response: result }); - // 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; - const payload: AcpTurnCompletedPayload = hidden - ? failedTurnPayload(hidden, result.stopReason ?? null) - : 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, - }; - lostSession = hidden?.sessionLost === true; - // The agent goes on with work it started (`heldTurns`): the turn - // stays open, working and stoppable, until that work is done. - if ( - payload.state === "completed" && - descriptor.heldTurns !== undefined && - (ctx.workAfterPrompt.size > 0 || ctx.subagentsOut > 0) - ) { - const held: AcpHeldTurn = { - turnId, - completion: { payload, model: resolvedModel, usage: run.usage }, - }; - ctx.held = held; - ctx.replyOpen = false; - ctx.lastAgentActivityMs = Date.now(); - yield* watchHeldTurn(ctx, held).pipe(Effect.forkIn(ctx.scope)); - return; - } - if (payload.state !== "completed") clearWorkAfterPrompt(ctx); yield* offerRuntimeEvent({ type: "turn.completed", ...(yield* makeEventStamp()), provider: PROVIDER, - threadId, + threadId: input.threadId, turnId, - payload, + payload: answeredTurnPayload( + result.stopReason, + ctx.activeTurnText, + ctx.lastProviderStatus, + ), }); - yield* settleTurnUsage(ctx, turnId, resolvedModel, run.usage); + yield* settleTurnUsage(ctx, turnId, resolvedModel, usageTotalsOf(result.usage)); return; } if (Cause.hasInterruptsOnly(exit.cause)) { return; } - clearWorkAfterPrompt(ctx); // The agent may never have taken the prompt: the brief goes again. if (ctx.projectBriefCarrier?.turnId === turnId) requeueProjectBrief(ctx); const failure = Cause.squash(exit.cause); yield* notifyAuthRequired(failure); - const reported = yield* checkPromptOutcome(checkOutcome, { error: failure }); - if (reported !== undefined) { - lostSession = reported.sessionLost === true; - yield* offerRuntimeEvent({ - type: "turn.completed", - ...(yield* makeEventStamp()), - provider: PROVIDER, - threadId, - turnId, - payload: failedTurnPayload(reported, null), - }); - yield* settleTurnUsage(ctx, turnId, resolvedModel, run.usage); - return; - } - 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, - threadId, - "session/prompt", - failure as EffectAcpErrors.AcpError, - ).message - : String(failure); yield* offerRuntimeEvent({ type: "turn.completed", ...(yield* makeEventStamp()), provider: PROVIDER, - threadId, + 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 (but what a steered prompt before it - // reported); a running cost the agent reported still counts. - yield* settleTurnUsage(ctx, turnId, resolvedModel, run.usage); - }).pipe(Effect.ensuring(finalize)); - return Effect.gen(function* () { - const promptMeta = descriptor.promptMeta?.(turnId); - const exit = yield* Effect.exit( - ctx.acp.prompt({ - prompt: [...promptParts], - ...(promptMeta ? { _meta: { ...promptMeta } } : {}), - }), + // No result, so no tokens; a running cost the agent reported still counts. + yield* settleTurnUsage(ctx, turnId, resolvedModel, null); + }).pipe( + Effect.ensuring( + Effect.gen(function* () { + if (ctx.activeTurnId === turnId) { + ctx.activeTurnId = undefined; + ctx.session = { ...ctx.session, activeTurnId: undefined, updatedAt: yield* nowIso }; + } + if (ctx.openPrompt === prompt) ctx.openPrompt = undefined; + yield* Deferred.succeed(prompt.closed, undefined); + }), + ), ); - if (Exit.isSuccess(exit)) { - const totals = usageTotals(exit.value.usage); - if (totals !== null) { - // Written as the prompt answers, so a turn held open (or - // stopped, or outlived by a restart) never loses it, and it is - // dated when it was spent. - if (recordsEachPrompt) yield* recordPromptUsage(ctx, run, promptNumber, totals); - else run.usage = addUsageTotals(run.usage, totals); - } - } - if (superseded()) return; - // Deltas travel through the notification fiber; make sure every one - // queued before the prompt returned is out before the turn closes. - // The reader may be past them already, held at a turn the agent - // began after them (`beginAgentTurnInOrder`). - yield* Effect.raceFirst(ctx.acp.flushEvents(answered), Deferred.await(prompt.drained)); - // A steer sent while the reader caught up carries the turn on. - yield* settleLocked(Effect.suspend(() => (superseded() ? Effect.void : settle(exit)))); - }).pipe( - Effect.ensuring(finalize.pipe(Effect.andThen(Deferred.succeed(answered, undefined)))), - ); - }; + ctx.promptFiber = yield* Effect.forkIn(runPrompt, ctx.scope); + + return { threadId: input.threadId, turnId, resumeCursor: ctx.session.resumeCursor }; + }); /** * A prompt that outlived `ACP_CANCEL_DEADLINE` after `session/cancel`: @@ -3068,6 +3357,11 @@ export function makeAcpAdapter( const promptFiber = ctx.promptFiber; 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) => @@ -3075,38 +3369,16 @@ export function makeAcpAdapter( ), ), ); - if (turnId === undefined) return; - // A turn waiting on the agent's work (`heldTurns`) has no prompt to - // wait on: the cancel stopped that work, and the turn ends here. Taken - // under the turn lock, inside the deadline: a stuck holder of the lock - // must not keep Stop from recycling the agent. - const closeHeld = - descriptor.heldTurns === undefined - ? Effect.succeed(false) - : ctx.turnStartLock.withPermit( - Effect.suspend(() => { - const held = ctx.held; - return held?.turnId === turnId - ? closeHeldTurn(ctx, held, "cancelled").pipe(Effect.as(true)) - : Effect.succeed(false); - }), - ); // The agent's own turn has no prompt to wait on; its end notice // settles it, and the same deadline applies. const agentTurn = ctx.agentTurn?.turnId === turnId ? ctx.agentTurn : undefined; - const awaitTurn = + const settled = agentTurn !== undefined ? Deferred.await(agentTurn.ended) : promptFiber !== undefined - ? awaitTurnPrompts(ctx, turnId, promptFiber) + ? Fiber.await(promptFiber).pipe(Effect.asVoid) : undefined; - const settled = - descriptor.heldTurns === undefined - ? awaitTurn - : closeHeld.pipe( - Effect.flatMap((closed) => (closed ? Effect.void : (awaitTurn ?? Effect.void))), - ); - if (settled !== undefined) { + if (turnId !== undefined && settled !== undefined) { yield* settled.pipe( Effect.timeoutOption(ACP_CANCEL_DEADLINE), Effect.flatMap((outcome) => @@ -3119,102 +3391,49 @@ export function makeAcpAdapter( /** * A message sent mid-turn, added to the running turn: by the agent's own - * steer (`descriptor.steer`), or as another prompt (`steerWithPrompt`). + * steer (`descriptor.steer`), or as another prompt (`turnMachine`). */ - const steerTurn: AcpAdapterShape["steerTurn"] = - descriptor.steer || descriptor.steerWithPrompt - ? (input) => - Effect.gen(function* () { - const ctx = yield* requireSession(input.threadId); - const turnId = ctx.activeTurnId; - const sessionId = parseAcpResumeCursor(ctx.session.resumeCursor)?.sessionId; - if (turnId === undefined) { - return yield* steerRejectedError( - PROVIDER, - descriptor.presentation.displayName, - "no-active-turn", - ); - } - if (turnId !== input.expectedTurnId || !sessionId) { - return yield* new ProviderAdapterRequestError({ - provider: PROVIDER, - method: "turn/steer", - detail: `Expected active turn '${input.expectedTurnId}' but ${descriptor.presentation.displayName} is running '${turnId}'.`, - }); - } - const text = input.input?.trim() ?? ""; - const content = yield* promptContent( - text.length > 0 ? text : undefined, - input.attachments, - "turn/steer", + const steerTurn: AcpAdapterShape["steerTurn"] = descriptor.steer + ? (input) => + Effect.gen(function* () { + const ctx = yield* requireSession(input.threadId); + const turnId = ctx.activeTurnId; + const sessionId = parseAcpResumeCursor(ctx.session.resumeCursor)?.sessionId; + if (turnId === undefined) { + return yield* steerRejectedError( + PROVIDER, + descriptor.presentation.displayName, + "no-active-turn", ); - if (descriptor.steer === undefined) { - yield* ctx.turnStartLock.withPermit(steerWithPrompt(ctx, turnId, content)); - return { threadId: input.threadId, turnId, resumeCursor: ctx.session.resumeCursor }; - } - // The text of every block: a file travels as a note naming its path. - const steerText = content - .flatMap((block) => (block.type === "text" ? [block.text] : [])) - .join("\n\n"); - yield* descriptor - .steer({ acp: ctx.acp, sessionId, text: steerText, content }) - .pipe( - Effect.mapError((cause) => - mapAcpToAdapterError(PROVIDER, input.threadId, "turn/steer", cause), - ), - ); - return { threadId: input.threadId, turnId, resumeCursor: ctx.session.resumeCursor }; - }) + } + if (turnId !== input.expectedTurnId || !sessionId) { + return yield* new ProviderAdapterRequestError({ + provider: PROVIDER, + method: "turn/steer", + detail: `Expected active turn '${input.expectedTurnId}' but ${descriptor.presentation.displayName} is running '${turnId}'.`, + }); + } + const text = input.input?.trim() ?? ""; + const content = yield* promptContent( + text.length > 0 ? text : undefined, + input.attachments, + "turn/steer", + ); + // The text of every block: a file travels as a note naming its path. + const steerText = content + .flatMap((block) => (block.type === "text" ? [block.text] : [])) + .join("\n\n"); + yield* descriptor.steer!({ acp: ctx.acp, sessionId, text: steerText, content }).pipe( + Effect.mapError((cause) => + mapAcpToAdapterError(PROVIDER, input.threadId, "turn/steer", cause), + ), + ); + return { threadId: input.threadId, turnId, resumeCursor: ctx.session.resumeCursor }; + }) + : descriptor.turnMachine !== undefined + ? steerTurnByMachine : undefined; - /** - * Steers the running turn with another prompt (`steerWithPrompt`): the - * agent answers the prompt it was on and carries the turn on under this - * one. A turn waiting on the agent's work, or one the agent started by - * itself, takes it the same way: the prompt's answer settles it. - */ - const steerWithPrompt = ( - ctx: AcpSessionContext, - turnId: TurnId, - content: ReadonlyArray, - ) => - Effect.gen(function* () { - // The turn ended while the lock was busy: the message starts its own. - if (ctx.stopped || ctx.activeTurnId !== turnId) { - return yield* steerRejectedError( - PROVIDER, - descriptor.presentation.displayName, - "no-active-turn", - ); - } - if (ctx.held?.turnId === turnId) ctx.held = undefined; - let run = ctx.turnRun; - if (run?.turnId !== turnId) { - // The agent's own turn: the prompt makes it an ordinary one. - const agentTurn = ctx.agentTurn; - if (agentTurn?.turnId === turnId) { - ctx.agentTurn = undefined; - if (ctx.agentTurnAhead?.turnId === turnId) ctx.agentTurnAhead = undefined; - yield* Deferred.succeed(agentTurn.ended, undefined); - } - run = { - turnId, - planMode: undefined, - resolvedModel: resolveModelId(ctx.session.model), - promptText: content - .flatMap((part) => (part.type === "text" ? [part.text] : [])) - .join("\n"), - newestBefore: ctx.newestPosition, - phase: undefined, - prompts: 0, - usage: null, - model: ctx.session.model, - }; - ctx.turnRun = run; - } - yield* sendTurnPrompt(ctx, run, content); - }); - const respondToRequest: AcpAdapterShape["respondToRequest"] = (threadId, requestId, decision) => Effect.gen(function* () { const ctx = yield* requireSession(threadId); @@ -3363,7 +3582,7 @@ export function makeAcpAdapter( capabilities: { sessionModelSwitch: "in-session", conversationRollback: "none", - ...(descriptor.steer || descriptor.steerWithPrompt + ...(descriptor.steer || descriptor.turnMachine ? { activeTurnSteering: "supported" as const } : {}), ...(descriptor.conversationHistory ? { nativeThreadFork: "supported" as const } : {}), diff --git a/apps/server/src/provider/acp/AcpProviderDescriptor.ts b/apps/server/src/provider/acp/AcpProviderDescriptor.ts index 368459fa9..f58cf537a 100644 --- a/apps/server/src/provider/acp/AcpProviderDescriptor.ts +++ b/apps/server/src/provider/acp/AcpProviderDescriptor.ts @@ -164,53 +164,67 @@ export interface AcpPromptFailure { } /** - * Reads how a prompt really ended. `watch` runs as a turn's first prompt goes - * out (it may note where the agent's own records stand) and returns the check - * run when the turn's last prompt answers or fails. + * 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< - ( - answer: - | { readonly response: EffectAcpSchema.PromptResponse } - /** What `session/prompt` failed with, usually an `AcpRequestError`. */ - | { readonly error: unknown }, - ) => Effect.Effect - >; + ) => 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; + /** + * An older prompt of the turn answered after this one went out: what the + * agent recorded until now was the older prompt's, so the check reads + * only what comes after. + */ + readonly rebase: Effect.Effect; } /** - * What a tool call the agent goes on with after its prompt answers is - * (`AcpHeldTurns`): a command it awaits, a scheduled wake-up, or a subagent - * it launched. `undefined` for one that ends with the prompt. + * 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 = "command" | "wake" | "subagent"; +export type AcpWorkAfterPrompt = + | { readonly kind: "command" | "timer" } + | { readonly kind: "subagents"; readonly count: number }; /** - * An agent that answers its prompt while work it started goes on, and - * replies by itself when that work ends (Antigravity 1.5.10+). 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. + * 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; a message + * sent mid-turn goes as another `session/prompt`, which steers the turn. + * 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. */ -export interface AcpHeldTurns { +export interface AcpTurnMachineOptions { readonly workAfterPrompt: (toolCall: AcpToolCallState) => AcpWorkAfterPrompt | undefined; /** * How long the turn waits without a word from the agent while only - * commands and subagents hold it; past it, the turn ends. A scheduled - * wake-up holds it with no limit (a timer is silent until it fires). + * 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 may go without output - * before it counts as ended when its closing `usage_update` never comes - * (default 2 minutes). + * 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; } /** Runtime hooks handed to a vendor's extension registration. */ @@ -442,17 +456,8 @@ export interface AcpProviderDescriptor { readonly text: string; readonly content: ReadonlyArray; }) => Effect.Effect; - /** - * A message sent mid-turn goes as another `session/prompt` (Antigravity - * 1.5): the agent answers the running prompt and carries the turn on under - * the new one, its commands and subagents left running. The turn ends with - * the last prompt's answer. Ignored when `steer` is set. - */ - readonly steerWithPrompt?: boolean; - /** Keeps a turn open while work the agent goes on with after its prompt runs. */ - readonly heldTurns?: AcpHeldTurns; - /** How a prompt really ended, where the agent's answer can hide a failure. */ - readonly promptOutcome?: AcpPromptOutcome; + /** Turns run on the turn machine (`AcpTurnMachineOptions`); `steer` and `agentTurns` don't apply. */ + readonly turnMachine?: AcpTurnMachineOptions; /** * 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: diff --git a/apps/server/src/provider/acp/AcpSessionRuntime.ts b/apps/server/src/provider/acp/AcpSessionRuntime.ts index 59eba6c91..261c81544 100644 --- a/apps/server/src/provider/acp/AcpSessionRuntime.ts +++ b/apps/server/src/provider/acp/AcpSessionRuntime.ts @@ -153,13 +153,13 @@ export interface AcpSessionRuntimeOptions { /** * 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.heldTurns`). + * count of running work (`AcpProviderDescriptor.turnMachine`). */ readonly trackSilentToolCalls?: boolean; /** - * Text the agent appends when a prompt is cancelled. After a cancel and - * until the next prompt, a reply chunk that is just this text is dropped - * before it starts a message. + * 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`). */ @@ -253,6 +253,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 @@ -297,6 +310,13 @@ export interface AcpSessionToolCallTracked { 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; +} + /** Work for the reader to run where it was queued (see `inOrder`). */ export interface AcpSessionInOrderWork { readonly _tag: "InOrder"; @@ -307,7 +327,8 @@ export type AcpSessionRuntimeEvent = | AcpParsedSessionEvent | AcpSessionEventStreamBarrier | AcpSessionInOrderWork - | AcpSessionToolCallTracked; + | AcpSessionToolCallTracked + | AcpSessionCancellationNotice; /** Upper bound on waiting for the reader; a dead consumer must not wedge a turn. */ const EVENT_FLUSH_TIMEOUT = "5 seconds"; @@ -517,8 +538,6 @@ const makeAcpSessionRuntime = ( // 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); - /** A cancel was sent and no prompt since: the agent's cancellation notice is dropped. */ - const cancelledRef = yield* Ref.make(false); /** Turns the agent started or ended itself so far (`markAgentTurnBoundary`). */ const agentTurnBoundariesRef = yield* Ref.make(0); const liveOutsidePromptRef = yield* Ref.make(false); @@ -561,7 +580,7 @@ const makeAcpSessionRuntime = ( ...(nativeControls ? { configOptionsRef } : {}), ...(options.trackSilentToolCalls ? { trackSilentToolCalls: true } : {}), ...(options.cancellationNotice !== undefined - ? { cancellationNotice: { text: options.cancellationNotice, cancelledRef } } + ? { cancellationNotice: options.cancellationNotice } : {}), }); }), @@ -988,6 +1007,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, @@ -1001,7 +1051,6 @@ const makeAcpSessionRuntime = ( return Effect.gen(function* () { yield* closeActiveAssistantSegment({ queue: eventQueue, assistantSegmentRef }); const boundariesBefore = yield* Ref.get(agentTurnBoundariesRef); - yield* Ref.set(cancelledRef, false); yield* Ref.update(promptsInFlightRef, (count) => count + 1); const response = yield* runLoggedRequest( "session/prompt", @@ -1023,7 +1072,6 @@ const makeAcpSessionRuntime = ( }), ), cancel: getStartedState.pipe( - Effect.tap(() => Ref.set(cancelledRef, true)), Effect.flatMap((started) => acp.agent.cancel({ sessionId: started.sessionId, @@ -1134,7 +1182,7 @@ const handleSessionUpdate = ({ /** Given for native controls only: the agent's own option updates land here. */ readonly configOptionsRef?: Ref.Ref>; readonly trackSilentToolCalls?: boolean; - readonly cancellationNotice?: { readonly text: string; readonly cancelledRef: Ref.Ref }; + readonly cancellationNotice?: string; }): Effect.Effect => Effect.gen(function* () { if (configOptionsRef && params.update.sessionUpdate === "config_option_update") { @@ -1193,11 +1241,12 @@ const handleSessionUpdate = ({ continue; } if (event._tag === "ContentDelta") { - if ( - cancellationNotice !== undefined && - event.text.trim() === cancellationNotice.text && - (yield* Ref.get(cancellationNotice.cancelledRef)) - ) { + 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) { diff --git a/apps/server/src/provider/acp/AcpTurnMachine.ts b/apps/server/src/provider/acp/AcpTurnMachine.ts index 63035dae0..c0d0f9c8a 100644 --- a/apps/server/src/provider/acp/AcpTurnMachine.ts +++ b/apps/server/src/provider/acp/AcpTurnMachine.ts @@ -503,6 +503,8 @@ export function stepTurnMachine( const turn = state.turn; 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 cancel stops the agent's work, and the turn ends now. clearWork(); @@ -510,8 +512,6 @@ export function stepTurnMachine( break; } state.turn = { ...turn, stopRequested: true }; - // A cancelled prompt is followed by the agent's notice. - if (turn.phase.tag === "prompting") state.noticesExpected += 1; break; } case "timerFired": { diff --git a/apps/server/src/provider/antigravity/AntigravityTurns.test.ts b/apps/server/src/provider/antigravity/AntigravityTurns.test.ts index 582e460fb..848f61713 100644 --- a/apps/server/src/provider/antigravity/AntigravityTurns.test.ts +++ b/apps/server/src/provider/antigravity/AntigravityTurns.test.ts @@ -390,6 +390,24 @@ describe("Antigravity turns, the hard cases", () => { }).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"); @@ -414,7 +432,7 @@ describe("Antigravity turns, the hard cases", () => { }).pipe(Effect.scoped, Effect.provide(testServices)), ); - it.live("settles a turn once when a steer comes while its answer is read", () => + 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(); @@ -422,22 +440,32 @@ describe("Antigravity turns, the hard cases", () => { // The first prompt's outcome check waits for the test. const agy = yield* startAgy( "permission-second", - (descriptor) => ({ - ...descriptor, - promptOutcome: { - watch: (sessionId, model) => - descriptor.promptOutcome!.watch(sessionId, model).pipe( - Effect.map((check) => (answer: Parameters[0]) => { - if (!first) return check(answer); - first = false; - return Deferred.succeed(reading, undefined).pipe( - Effect.andThen(Deferred.await(release)), - Effect.andThen(check(answer)), - ); - }), - ), - }, - }), + (descriptor) => { + const machine = descriptor.turnMachine!; + const outcome = machine.outcome!; + return { + ...descriptor, + turnMachine: { + ...machine, + 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({ @@ -446,34 +474,53 @@ describe("Antigravity turns, the hard cases", () => { attachments: [], }); yield* Deferred.await(reading); - const steer = yield* agy.adapter.steerTurn!({ + // 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", - }).pipe(Effect.exit, Effect.forkScoped); - yield* Effect.sleep("200 millis"); + }); + 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); - // The turn had ended: the steer is turned down, to be sent as a turn of its own. - expect(Exit.isFailure(yield* Fiber.join(steer))).toBe(true); + 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" }), }), ]); - const next = yield* agy.adapter.sendTurn({ + 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"); + const { turnId } = yield* agy.adapter.sendTurn({ threadId: agy.threadId, - input: "second", + input: "go", attachments: [], }); - yield* agy.waitFor((events) => events.some((event) => event.type === "request.opened")); - expect(agy.events.find((event) => event.type === "request.opened")?.turnId).toBe(next.turnId); + 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 the error the earlier prompt left in the log", () => + it.live("steers without inheriting an error the earlier prompt writes late", () => Effect.gen(function* () { - const agy = yield* startAgy("steer-log-error"); + const agy = yield* startAgy("steer-late-log-error"); const { turnId } = yield* agy.adapter.sendTurn({ threadId: agy.threadId, input: "go", @@ -490,6 +537,69 @@ describe("Antigravity turns, the hard cases", () => { }).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("keeps every lost session another adapter of the instance marked, across a restart", () => + Effect.gen(function* () { + const agy = yield* startAgy("lost-signature"); + // The instance's adapter rebuilt while the first still runs a thread + // (a settings change): both write the same instance's marks. + const rebuilt = yield* agy.newAdapter; + const otherThread = ThreadId.make("agy-lost-signature-2"); + const other = yield* rebuilt.startSession({ + threadId: otherThread, + provider: ProviderDriverKind.make("antigravity"), + cwd: process.cwd(), + runtimeMode: "full-access", + }); + yield* agy.adapter.sendTurn({ threadId: agy.threadId, input: "hi", attachments: [] }); + yield* agy.waitFor( + (events) => events.filter((event) => event.type === "session.exited").length === 1, + ); + yield* rebuilt.sendTurn({ threadId: otherThread, input: "hi", attachments: [] }); + yield* agy.waitFor( + (events) => events.filter((event) => event.type === "session.exited").length === 2, + ); + // A server restart: neither lost session is reopened. + const restartedAdapter = yield* agy.newAdapter; + for (const [threadId, session] of [ + [agy.threadId, agy.session], + [otherThread, other], + ] as const) { + const restarted = yield* restartedAdapter.startSession({ + threadId, + provider: ProviderDriverKind.make("antigravity"), + cwd: process.cwd(), + runtimeMode: "full-access", + resumeCursor: session.resumeCursor, + }); + expect(restarted.resumeFailed).toBe(true); + } + }).pipe(Effect.scoped, Effect.provide(testServices)), + ); + it.live("holds a turn until each subagent has reported", () => Effect.gen(function* () { const agy = yield* startAgy("subagents"); @@ -508,7 +618,7 @@ describe("Antigravity turns, the hard cases", () => { Effect.gen(function* () { const agy = yield* startAgy("subagent-quiet", (descriptor) => ({ ...descriptor, - heldTurns: { ...descriptor.heldTurns!, replyQuietLimit: Duration.seconds(1) }, + turnMachine: { ...descriptor.turnMachine!, replyQuietLimit: Duration.seconds(1) }, })); const { turnId } = yield* agy.adapter.sendTurn({ threadId: agy.threadId, @@ -534,7 +644,7 @@ describe("Antigravity turn reading", () => { antigravityWorkAfterPrompt( tool({ kind: "execute", data: { rawInput: { CommandLine: "npm test" } } }), ), - ).toBe("command"); + ).toEqual({ kind: "command" }); // A daemon (a dev server) may never end. expect( antigravityWorkAfterPrompt( @@ -544,9 +654,9 @@ describe("Antigravity turn reading", () => { }), ), ).toBeUndefined(); - expect(antigravityWorkAfterPrompt(tool({ kind: "other", title: "Running schedule" }))).toBe( - "wake", - ); + expect(antigravityWorkAfterPrompt(tool({ kind: "other", title: "Running schedule" }))).toEqual({ + kind: "timer", + }); expect( antigravityWorkAfterPrompt( tool({ @@ -555,7 +665,24 @@ describe("Antigravity turn reading", () => { data: { rawInput: { Role: "Artist", Prompt: "Paint" } }, }), ), - ).toBe("subagent"); + ).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(); }); @@ -617,7 +744,10 @@ describe("Antigravity turn reading", () => { return { window: "weekly" as const, resetsAt: "2026-11-24T00:00:00.000Z" }; }), ); - const check = yield* behavior.promptOutcome!.watch("session-1", "claude-sonnet-agent"); + const { check } = yield* behavior.turnMachine!.outcome!.watch( + "session-1", + "claude-sonnet-agent", + ); const quota = { _tag: "AcpRequestError", errorMessage: "Details: [map[reason:QUOTA_EXHAUSTED]]", @@ -639,6 +769,17 @@ describe("Antigravity turn reading", () => { }), ); + 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({ diff --git a/apps/server/src/provider/antigravity/AntigravityTurns.ts b/apps/server/src/provider/antigravity/AntigravityTurns.ts index 5066ce3b8..fe20b619a 100644 --- a/apps/server/src/provider/antigravity/AntigravityTurns.ts +++ b/apps/server/src/provider/antigravity/AntigravityTurns.ts @@ -26,6 +26,8 @@ import type * as EffectAcpSchema from "effect-acp/schema"; import { httpStatusFailureCategory } from "../providerFailureCategory.ts"; import type { AcpPromptFailure, + AcpPromptOutcome, + AcpPromptOutcomeWatch, AcpProviderDescriptor, AcpProviderSettings, AcpWorkAfterPrompt, @@ -52,11 +54,11 @@ export const ANTIGRAVITY_SILENT_WORK_LIMIT = Duration.minutes(30); const isRecord = (value: unknown): value is Record => typeof value === "object" && value !== null && !Array.isArray(value); -/** A launch's input: one subagent (`Role`, `Prompt`), or a batch (`Subagents`). */ -function isSubagentLaunch(input: unknown): boolean { - if (!isRecord(input)) return false; - if (typeof input.Role === "string" && typeof input.Prompt === "string") return true; - return Array.isArray(input.Subagents) && input.Subagents.length > 0; +/** How many subagents a launch starts: one (`Role`, `Prompt`), or a batch (`Subagents`). */ +function subagentLaunchCount(input: unknown): number { + if (!isRecord(input)) return 0; + if (typeof input.Role === "string" && typeof input.Prompt === "string") return 1; + return Array.isArray(input.Subagents) ? input.Subagents.length : 0; } /** @@ -67,18 +69,21 @@ function isSubagentLaunch(input: unknown): boolean { export function antigravityWorkAfterPrompt( toolCall: AcpToolCallState, ): AcpWorkAfterPrompt | undefined { - if (toolCall.title !== undefined && SCHEDULE_TITLES.has(toolCall.title)) return "wake"; + 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 : "command"; + return isRecord(input) && input.IsDaemon === true ? undefined : { kind: "command" }; } + const count = subagentLaunchCount(input); if ( (toolCall.kind === undefined || toolCall.kind === "other") && toolCall.title !== undefined && SUBAGENT_TITLES.has(toolCall.title) && - isSubagentLaunch(input) + count > 0 ) { - return "subagent"; + return { kind: "subagents", count }; } return undefined; } @@ -103,7 +108,11 @@ export function antigravityTurnUsageTotals( outputTokens, reasoningTokens: Math.min(outputTokens, count(usage.thoughtTokens)), }; - return totals.uncachedInputTokens + totals.cachedInputTokens + totals.outputTokens > 0 + return totals.uncachedInputTokens + + totals.cachedInputTokens + + totals.cacheCreationTokens + + totals.outputTokens > + 0 ? totals : null; } @@ -239,72 +248,86 @@ function acpErrorText(error: unknown): string | undefined { export function antigravityTurnBehavior( profileDir: string, readUsageLimit?: (model: string) => Effect.Effect, -): Pick< - AcpProviderDescriptor, - | "agentTurns" - | "heldTurns" - | "steerWithPrompt" - | "promptOutcome" - | "usageLedger" - | "turnUsageTotals" -> { +): Pick, "turnMachine" | "usageLedger" | "turnUsageTotals"> { return { - // What the agent does after a prompt ended is live (1.5.10), and opens a - // turn of its own when no turn is held open for it. - agentTurns: true, - heldTurns: { + // 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). + turnMachine: { workAfterPrompt: antigravityWorkAfterPrompt, silentLimit: ANTIGRAVITY_SILENT_WORK_LIMIT, - }, - steerWithPrompt: true, - promptOutcome: { - 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); - return (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, - }), - ); - }); - }), + 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. + * + * A log step is the prompt's only if it is written after the prompt went + * out and after every older prompt of its turn answered: the CLI writes a + * prompt's steps before it answers it, and answers a steered prompt only + * once the steer arrives, so an older prompt's late error lands before its + * own answer and `rebase` moves past it. When the log can't say (it can't be + * read, or a step's prompt is in doubt), 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* () { + let 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 rebase = Effect.gen(function* () { + const now = yield* antigravityLogPosition(profileDir, sessionId); + if (now !== undefined) before = before === undefined ? now : Math.max(before, now); + }); + 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, rebase }; + }), + }; +} diff --git a/docs/providers/antigravity.md b/docs/providers/antigravity.md index ab7014369..a9006f0cc 100644 --- a/docs/providers/antigravity.md +++ b/docs/providers/antigravity.md @@ -112,26 +112,38 @@ set (`schedule`), or a subagent it launched. When that work ends, the agent wake 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 reply the agent starts after the turn ended opens a turn of its own. +a cancel). If the agent hasn't answered 15 seconds after Stop, Threadlines restarts it and the turn +ends cancelled; the next message picks the conversation up again. 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. 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. A timer holds the turn until it fires. Subagents are only known to finish by the report the agent gives when -one ends, so each report (a reply no finished command or timer woke) frees one subagent. If the CLI -sends several reports in one reply, the turn holds until the 30-minute limit or Stop. If the agent +one ends, so each report (a reply no finished command or timer woke) frees one subagent; a batch +launch counts each subagent in it. If the CLI sends several reports in one reply, the turn holds +until the 30-minute limit or Stop. 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 works steers the turn instead of waiting: Threadlines sends it as another prompt, which the CLI takes into the running turn (1.5.0+), leaving its commands and -subagents running. +subagents running. The turn ends with the newest prompt's answer. + +All of this is one state machine (`apps/server/src/provider/acp/AcpTurnMachine.ts`), stepped in +order with the agent's updates; its test walks every sequence of up to ten events and checks that +each turn ends exactly once, Stop always has a deadline, and a hold with nothing left ends. ### 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 turn then fails with Google's words and a Retry. An +private format read only for this). A log step counts for a prompt only if it was written after that prompt went out and after every +older prompt of the turn answered; when the log can't say, 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 From 793e2cab2ad8fc1115637a6fb24aa749c33f6cff Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Mon, 23 Nov 2026 04:21:52 -0500 Subject: [PATCH 38/59] fix(antigravity): subagent records are read through a verified open, and couldn't-read never means finished The record readers checked a path step by step and then opened it afresh, so a folder on the way swapped for a link between the two could hand over a file from outside the profile. openAntigravityProfileFile now opens without following or blocking and then checks the open file: the path must still resolve to itself inside the profile, and the file held must be the one at that path now. The session-log reader holds the file open while SQLite reads it and checks it again afterwards. Folders are read one entry at a time and every entry counts toward the limit, so a huge folder costs no more than the limit. A message that doesn't read (one the CLI is still writing) is skipped and counted instead of making the whole reading unavailable; a child whose entry doesn't read counts as running. The subagent view never settles a child from a reading it couldn't take. A subagent shown done because its turn ended is a guess a later reading can correct, and only running and guessed subagents are kept (guesses capped at 32, launch ids remembered up to 512), so the roster stays small for a long session. --- .../src/provider/acp/AcpProviderDescriptor.ts | 12 +- .../provider/acp/AcpSubagentRoster.test.ts | 154 ++++++++++++++++++ .../src/provider/acp/AcpSubagentRoster.ts | 96 ++++++++--- .../AntigravityChildRecords.test.ts | 98 ++++++++++- .../antigravity/AntigravityChildRecords.ts | 135 +++++++++++---- .../antigravity/AntigravitySessionLog.ts | 109 ++++++++++--- .../antigravity/AntigravitySubagents.ts | 2 +- 7 files changed, 515 insertions(+), 91 deletions(-) create mode 100644 apps/server/src/provider/acp/AcpSubagentRoster.test.ts diff --git a/apps/server/src/provider/acp/AcpProviderDescriptor.ts b/apps/server/src/provider/acp/AcpProviderDescriptor.ts index dcc177e7b..263e05c7b 100644 --- a/apps/server/src/provider/acp/AcpProviderDescriptor.ts +++ b/apps/server/src/provider/acp/AcpProviderDescriptor.ts @@ -257,12 +257,20 @@ export interface AcpSubagents { 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; `undefined` when they can't be read. + * 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 | undefined>; + }) => 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. 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..6fd724f4b --- /dev/null +++ b/apps/server/src/provider/acp/AcpSubagentRoster.test.ts @@ -0,0 +1,154 @@ +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); + }), + ); +}); diff --git a/apps/server/src/provider/acp/AcpSubagentRoster.ts b/apps/server/src/provider/acp/AcpSubagentRoster.ts index ee0189039..60ed86f30 100644 --- a/apps/server/src/provider/acp/AcpSubagentRoster.ts +++ b/apps/server/src/provider/acp/AcpSubagentRoster.ts @@ -9,11 +9,15 @@ * 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 the records don't name - * show as done; + * until its subagents reported, so its launches a complete reading doesn't + * name show as done, 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"; @@ -26,13 +30,17 @@ import type { } from "./AcpProviderDescriptor.ts"; import type { AcpToolCallState } from "./AcpRuntimeModel.ts"; import { - type AcpSubagentStatus, 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; + export interface AcpSubagentRoster { /** A tool call update: a launch that went through shows as a running subagent, once. */ readonly noteToolCall: ( @@ -43,12 +51,15 @@ export interface AcpSubagentRoster { 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; - status: AcpSubagentStatus; + /** `guessed`: shown done because its turn ended; no record said so yet. */ + status: "running" | "guessed"; } export function makeAcpSubagentRoster(input: { @@ -63,9 +74,13 @@ export function makeAcpSubagentRoster(input: { readonly fork: (effect: Effect.Effect) => Effect.Effect; }): AcpSubagentRoster { const entries = new Map(); + const seen = 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( @@ -77,38 +92,66 @@ export function makeAcpSubagentRoster(input: { ), ); - const settle = (id: string, status: Exclude, report?: string) => + /** 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 = status; - for (const event of acpSubagentSettledEvents(id, status, report)) { - yield* input.emit(event, entry.turnId); + 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; }); /** - * Settles the running subagents the records say are done. With `ended`, - * the launches of that turn the records don't name show as done too. + * Brings the kept subagents in line with the records. With `ended`, the + * launches of that turn a complete reading doesn't name are guessed done. */ const read = (ended: TurnId | undefined) => Effect.gen(function* () { - const ids = running(); + const ids = [...entries.keys()]; if (ids.length === 0) return; - const states = yield* input.subagents.states({ + const reading = yield* input.subagents.states({ sessionId: input.sessionId, launchCallIds: ids, }); + if (reading === undefined) return; for (const id of ids) { - const state = states?.get(id); + const state = reading.byLaunch.get(id); if (state === undefined) { - if (ended !== undefined && entries.get(id)?.turnId === ended) - yield* settle(id, "completed"); + if (reading.complete && ended !== undefined && entries.get(id)?.turnId === ended) { + yield* guessDone(id); + } continue; } - if (state.state === "working") continue; - yield* settle(id, state.state === "killed" ? "interrupted" : "completed", state.report); + if (state.state === "working") yield* reopen(id); + else + yield* settle(id, state.state === "killed" ? "interrupted" : "completed", state.report); } }); @@ -117,7 +160,7 @@ export function makeAcpSubagentRoster(input: { let again: { ended: TurnId | undefined } | undefined; const requestRead = (ended: TurnId | undefined): Effect.Effect => Effect.suspend(() => { - if (running().length === 0) return Effect.void; + if (entries.size === 0) return Effect.void; if (reading) { again = { ended: ended ?? again?.ended }; return Effect.void; @@ -143,14 +186,18 @@ export function makeAcpSubagentRoster(input: { return { noteToolCall: (toolCall, turnId) => Effect.gen(function* () { - if (toolCall.status !== "completed" || entries.has(toolCall.toolCallId)) return; + const id = toolCall.toolCallId; + if (toolCall.status !== "completed" || seen.has(id)) return; const launches = input.subagents.launches(toolCall); if (launches === undefined) return; - const launch = describeAcpSubagentLaunches(launches); - entries.set(toolCall.toolCallId, { turnId, launch, status: "running" }); - for (const event of acpSubagentStartedEvents(toolCall.toolCallId, launch)) { - yield* input.emit(event, turnId); + 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) => { @@ -164,6 +211,7 @@ export function makeAcpSubagentRoster(input: { if (event.payload.state === "cancelled") return stopAll; return requestRead(event.payload.state === "completed" ? event.turnId : undefined); }, - end: stopAll, + end: Effect.suspend(() => stopAll.pipe(Effect.andThen(Effect.sync(() => entries.clear())))), + size: () => entries.size, }; } diff --git a/apps/server/src/provider/antigravity/AntigravityChildRecords.test.ts b/apps/server/src/provider/antigravity/AntigravityChildRecords.test.ts index 4eb445393..e3fc37c37 100644 --- a/apps/server/src/provider/antigravity/AntigravityChildRecords.test.ts +++ b/apps/server/src/provider/antigravity/AntigravityChildRecords.test.ts @@ -1,7 +1,7 @@ // @effect-diagnostics nodeBuiltinImport:off import * as os from "node:os"; import * as path from "node:path"; -import { mkdir, mkdtemp, rm, symlink, writeFile } from "node:fs/promises"; +import { mkdir, mkdtemp, rename, rm, symlink, writeFile } from "node:fs/promises"; import { it } from "@effect/vitest"; import * as Effect from "effect/Effect"; @@ -13,6 +13,7 @@ import { antigravityChildTranscript, readAntigravityChildren, } from "./AntigravityChildRecords.ts"; +import { openAntigravityProfileFile } from "./AntigravitySessionLog.ts"; const PARENT = "7d40e54d-5977-4239-940b-246cdd81a12b"; @@ -133,14 +134,6 @@ describe("readAntigravityChildren", () => { }); yield* Effect.promise(() => records.child("child-a", "call_a")); expect((yield* readAntigravityChildren(records.profile, PARENT)).available).toBe(true); - // A message that isn't JSON could be the report that matters. - yield* Effect.promise(() => - records.write([PARENT, ".system_generated", "messages", "broken.json"], "{not json"), - ); - expect(yield* readAntigravityChildren(records.profile, PARENT)).toEqual({ - available: false, - reason: "unreadable", - }); }), ), ); @@ -180,4 +173,91 @@ describe("readAntigravityChildren", () => { }), ), ); + + 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("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 index c2b30b91c..41e27098d 100644 --- a/apps/server/src/provider/antigravity/AntigravityChildRecords.ts +++ b/apps/server/src/provider/antigravity/AntigravityChildRecords.ts @@ -35,8 +35,7 @@ import * as NodeFSP from "node:fs/promises"; import type { ProviderSubagentTranscriptEntry } from "@threadlines/contracts"; import * as Effect from "effect/Effect"; -import { openRegularFile, readRegularFile } from "./AntigravityFileReads.ts"; -import { antigravityProfileEntry } from "./AntigravitySessionLog.ts"; +import { antigravityProfileEntry, openAntigravityProfileFile } from "./AntigravitySessionLog.ts"; import { boundAntigravityText } from "./AntigravityToolCalls.ts"; /** Ids as the CLI names conversations: nothing that walks a path. */ @@ -109,20 +108,60 @@ 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, - * linked, too big, past the read's budget, or unreadable. + * 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 entry = await antigravityProfileEntry(profileDir, segments, "file"); - if (entry === undefined || entry.size > MAX_RECORD_BYTES || entry.size > budget.bytes) + 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; - budget.bytes -= entry.size; - const bytes = await readRegularFile(entry.path, { - maxBytes: Math.min(MAX_RECORD_BYTES, entry.size + budget.bytes), - followLink: false, - }).catch(() => undefined); - return bytes === undefined ? undefined : parseJson(bytes.toString("utf8")); + } + return names; } const generated = (conversationId: string, ...rest: ReadonlyArray) => [ @@ -133,24 +172,30 @@ const generated = (conversationId: string, ...rest: ReadonlyArray) => [ ]; /** - * A conversation's inbox: every message, or `undefined` when it can't all be - * read (one unread message could be the one that matters). No inbox is empty. + * 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, or holds more than the limit. No inbox is empty. */ async function readInbox( profileDir: string, conversationId: string, budget: ReadBudget, -): Promise | undefined> { +): Promise<{ readonly messages: ReadonlyArray; readonly unreadable: number } | undefined> { const segments = generated(conversationId, "messages"); const inbox = await antigravityProfileEntry(profileDir, segments, "directory"); - if (inbox === undefined) return []; - const names = await NodeFSP.readdir(inbox.path).catch(() => undefined); + if (inbox === undefined) return { messages: [], unreadable: 0 }; + // `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 = names.filter((name) => name.endsWith(".json") && name !== "read.json"); - if (messages.length > MAX_INBOX_MESSAGES) return undefined; - const read: Array = []; - for (const name of messages) read.push(await readRecord(profileDir, [...segments, name], budget)); - return read.every(isRecord) ? read : 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. */ @@ -179,6 +224,7 @@ function launchCall(message: unknown, parentId: string) { * - `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" } @@ -187,6 +233,12 @@ export type AntigravityChildrenReading = 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; @@ -196,7 +248,7 @@ async function readChildren( profileDir: string, parentId: string, ): Promise< - | { readonly children: ReadonlyArray } + | { readonly children: ReadonlyArray; readonly unreadable: number } | { readonly reason: "no-records" | "unreadable" } > { if (!NATIVE_ID.test(parentId)) return { reason: "unreadable" }; @@ -206,15 +258,15 @@ async function readChildren( "directory", ); if (folder === undefined) return { reason: "no-records" }; - const names = await NodeFSP.readdir(folder.path).catch(() => undefined); + 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)] : [], ); - if (childIds.length > MAX_CHILDREN) return { reason: "unreadable" }; 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( @@ -222,12 +274,23 @@ async function readChildren( generated(parentId, "subagents", `${childId}.json`), budget, ); - if (!isRecord(record)) return { reason: "unreadable" }; const recordedId = stringField(record, "conversationId"); - if (recordedId !== undefined && recordedId !== childId) return { reason: "unreadable" }; const inbox = await readInbox(profileDir, childId, budget); - if (inbox === undefined) return { reason: "unreadable" }; - const launches = inbox.flatMap((message) => { + // 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") }]; }); @@ -235,7 +298,7 @@ async function readChildren( const launch = launches.length === 1 ? launches[0] : undefined; const [fromArgs] = antigravityChildLaunches(launch?.call.args) ?? []; const descriptor = record.subagentDescriptor; - const reports = parentInbox.flatMap((message) => + const reports = parentInbox.messages.flatMap((message) => stringField(message, "sender") === childId ? [stringField(message, "content") ?? ""] : [], ); children.push({ @@ -262,6 +325,7 @@ async function readChildren( } } return { + unreadable, children: children.map((child) => child.launchCallId !== undefined && claims.get(child.launchCallId) !== 1 ? { ...child, launchCallId: undefined } @@ -286,6 +350,7 @@ export const readAntigravityChildren = (profileDir: string, sessionId: string) = running: inState("working"), reported: inState("reported"), killed: inState("killed"), + unreadable: read.unreadable, }; }).pipe(Effect.orElseSucceed((): AntigravityChildrenReading => UNREADABLE)); @@ -407,19 +472,17 @@ export function antigravityTranscriptEntries( /** The end of a child's transcript, parsed; `undefined` when it has none. */ async function readTranscriptTail(profileDir: string, childId: string) { - const entry = await antigravityProfileEntry( + const file = await openAntigravityProfileFile( profileDir, generated(childId, "logs", "transcript.jsonl"), - "file", ); - if (entry === undefined) return undefined; - const opened = await openRegularFile(entry.path, { followLink: false }); - if (opened === undefined) return undefined; - const { handle, size } = opened; + 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); diff --git a/apps/server/src/provider/antigravity/AntigravitySessionLog.ts b/apps/server/src/provider/antigravity/AntigravitySessionLog.ts index 677a1cb89..c762a16c1 100644 --- a/apps/server/src/provider/antigravity/AntigravitySessionLog.ts +++ b/apps/server/src/provider/antigravity/AntigravitySessionLog.ts @@ -26,6 +26,7 @@ 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. */ @@ -57,8 +58,18 @@ export async function antigravityProfileEntry( segments: ReadonlyArray, kind: "file" | "directory", ): Promise<{ readonly path: string; readonly size: number } | undefined> { + const found = await profileEntry(profileDir, segments, kind); + return typeof found === "string" ? undefined : found; +} + +/** 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 undefined; + if (root === undefined) return "missing"; let current = root; let size = 0; const path = [ANTIGRAVITY_APP_DATA_DIR, ...segments]; @@ -66,24 +77,86 @@ export async function antigravityProfileEntry( current = NodePath.join(current, segment); const info = await NodeFSP.lstat(current).catch(() => undefined); const last = index === path.length - 1; - if (info === undefined || info.isSymbolicLink()) return undefined; - if (last && kind === "file" ? !info.isFile() : !info.isDirectory()) return undefined; + 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 }; +} + /** - * The session's log file when it is a plain file in the profile (no link at - * any step of the path), or `undefined` when there is none yet. + * 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 sessionLogFile(profileDir: string, sessionId: string): Promise { - const entry = await antigravityProfileEntry( - profileDir, - ["conversations", `${sessionId}.db`], - "file", - ); - return entry?.path; +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 { @@ -108,22 +181,19 @@ function readLog(file: string, read: (database: DatabaseSync) => A): A | unde export const antigravityLogPosition = (profileDir: string, sessionId: string) => Effect.tryPromise(async () => { if (!SESSION_ID.test(sessionId)) return undefined; - const file = await sessionLogFile(profileDir, sessionId); - if (file === undefined) return -1; - const index = readLog(file, (database) => { + 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; }); - return index ?? -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 file = await sessionLogFile(profileDir, sessionId); - if (file === undefined) return undefined; - return readLog(file, (database) => { + const steps = await withSessionLog(profileDir, sessionId, (database) => { const last = database .prepare( `SELECT step_type AS type, substr(step_payload, 1, ?) AS payload @@ -146,4 +216,5 @@ export const antigravityTurnSteps = (profileDir: string, sessionId: string, afte : undefined; return { errorText, reachedModel }; }); + return typeof steps === "string" ? undefined : steps.value; }).pipe(Effect.orElseSucceed(() => undefined)); diff --git a/apps/server/src/provider/antigravity/AntigravitySubagents.ts b/apps/server/src/provider/antigravity/AntigravitySubagents.ts index bd8525bb3..f44f1f968 100644 --- a/apps/server/src/provider/antigravity/AntigravitySubagents.ts +++ b/apps/server/src/provider/antigravity/AntigravitySubagents.ts @@ -61,7 +61,7 @@ export function antigravitySubagents(profileDir: string): AcpSubagents { ...(child.report !== undefined ? { report: child.report } : {}), }); } - return states; + return { byLaunch: states, complete: reading.unreadable === 0 }; }), ), transcript: ({ sessionId, launchCallId }) => From 24463602da825213ec09f3c563e8d4131294ef9e Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Mon, 23 Nov 2026 04:27:43 -0500 Subject: [PATCH 39/59] fix(antigravity): attachments are read through a handle within their real size, and PDFs are linked without embedded-text support A staged attachment was size-checked from its record and then read whole by path: a file replaced by a link was followed, a file that grew was read in full, images had no limit of their own, and the 50 MB message allowance was charged with the recorded size. Now each file is opened without following a link, must be a regular file, and is read only up to its kind's limit (images 10 MB, audio 20 MB, text 100 KB) and what is left of the message's allowance, one byte past the cap telling a file that grew. The allowance is charged with the bytes read. A link to a PDF is refused the same way. PDFs go as a resource_link whatever embeddedContext says: every ACP agent must read links, and that capability is only for embedded resources. --- apps/server/src/provider/acp/AcpAdapter.ts | 1 - .../provider/acp/AcpPromptAttachments.test.ts | 116 ++++++++++++++++++ .../src/provider/acp/AcpPromptAttachments.ts | 111 +++++++++++++---- .../antigravity/AntigravityAttachments.ts | 3 +- docs/providers/antigravity.md | 15 ++- 5 files changed, 216 insertions(+), 30 deletions(-) create mode 100644 apps/server/src/provider/acp/AcpPromptAttachments.test.ts diff --git a/apps/server/src/provider/acp/AcpAdapter.ts b/apps/server/src/provider/acp/AcpAdapter.ts index 1a38358c7..0b087e04f 100644 --- a/apps/server/src/provider/acp/AcpAdapter.ts +++ b/apps/server/src/provider/acp/AcpAdapter.ts @@ -2615,7 +2615,6 @@ export function makeAcpAdapter( path: attachmentPath, delivery, budget, - fileSystem, }).pipe( Effect.mapError( (cause) => 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..430d7a5c0 --- /dev/null +++ b/apps/server/src/provider/acp/AcpPromptAttachments.test.ts @@ -0,0 +1,116 @@ +// @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); + }), + ), + ); +}); + +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 index 14b0b5228..49e3941cc 100644 --- a/apps/server/src/provider/acp/AcpPromptAttachments.ts +++ b/apps/server/src/provider/acp/AcpPromptAttachments.ts @@ -1,4 +1,4 @@ -// @effect-diagnostics nodeBuiltinImport:off -- node:url makes a staged file's file:// link. +// @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 @@ -16,10 +16,12 @@ * * @module provider/acp/AcpPromptAttachments */ -import type { ChatAttachment } from "@threadlines/contracts"; +import { type ChatAttachment, PROVIDER_SEND_TURN_MAX_IMAGE_BYTES } from "@threadlines/contracts"; import * as Effect from "effect/Effect"; -import type * as FileSystem from "effect/FileSystem"; +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 { @@ -69,23 +71,92 @@ const note = (attachment: ChatAttachment, path: string): EffectAcpSchema.Content 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. Fails only when the staged file - * can't be read. + * 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; - readonly fileSystem: FileSystem.FileSystem; }) => Effect.gen(function* () { - const { attachment, path, delivery, budget, fileSystem } = input; + 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", @@ -96,22 +167,14 @@ export const acpAttachmentContent = (input: { }, ] satisfies ReadonlyArray; } - const audio = mimeType.startsWith("audio/"); - const limit = - delivery === "text" - ? INLINE_TEXT_ATTACHMENT_MAX_BYTES - : audio - ? INLINE_AUDIO_MAX_BYTES - : Number.POSITIVE_INFINITY; - // Sizes are checked before reading, so a large file is never read whole. - if (attachment.sizeBytes > limit) return [note(attachment, path)]; - if ( - delivery === "inline" && - budget.inlineBytes + attachment.sizeBytes > INLINE_MESSAGE_MAX_BYTES - ) - return [note(attachment, path)]; - const bytes = yield* fileSystem.readFile(path); - if (bytes.byteLength > limit) return [note(attachment, path)]; + const cap = + delivery === "inline" + ? Math.min(deliveryLimit(delivery, mimeType), INLINE_MESSAGE_MAX_BYTES - budget.inlineBytes) + : deliveryLimit(delivery, mimeType); + // 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)]; @@ -125,7 +188,7 @@ export const acpAttachmentContent = (input: { budget.inlineBytes += bytes.byteLength; const data = Buffer.from(bytes).toString("base64"); return [ - audio + mimeType.startsWith("audio/") ? { type: "audio", data, mimeType } : { type: "image", data, mimeType: mimeType || attachment.mimeType }, ] satisfies ReadonlyArray; diff --git a/apps/server/src/provider/antigravity/AntigravityAttachments.ts b/apps/server/src/provider/antigravity/AntigravityAttachments.ts index 9b7e1673d..05871a5f8 100644 --- a/apps/server/src/provider/antigravity/AntigravityAttachments.ts +++ b/apps/server/src/provider/antigravity/AntigravityAttachments.ts @@ -59,8 +59,9 @@ export function antigravityAttachmentDelivery( return IMAGE_MIME_TYPES.has(mimeType) && capabilities?.image === true ? "inline" : "note"; } if (AUDIO_MIME_TYPES.has(mimeType)) return capabilities?.audio === true ? "inline" : "note"; - if (capabilities?.embeddedContext !== true) return "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/docs/providers/antigravity.md b/docs/providers/antigravity.md index 4f45cdef5..d7ca91242 100644 --- a/docs/providers/antigravity.md +++ b/docs/providers/antigravity.md @@ -166,7 +166,10 @@ each reply ends and when the turn ends: - 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". + "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. How long the turn stays open is the rule above; the records don't change it. @@ -174,7 +177,9 @@ rule above; the records don't change it. ### 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. + 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. - 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. @@ -187,8 +192,10 @@ Images (PNG, JPEG, WebP, BMP) and audio go to Antigravity inline. PDFs go as a l 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. Each of these needs Antigravity to say it reads that kind; otherwise the file -goes as a path. A MIME type's parameters (`; charset=utf-8`) don't change the choice. +open with its tools. Images, audio and text each need Antigravity to say it reads that kind; +otherwise the file goes as a path. 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 From 2fdea0ad104d49df37076594f9916e512c7116be Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Mon, 23 Nov 2026 10:41:21 -0500 Subject: [PATCH 40/59] fix(antigravity): call_mcp_tool is judged from the update as sent, and a call that stops being one loses its MCP look The wrapper check read the update after bounding, so a large Arguments object could use up the payload allowance and drop a later field (a command, a working folder) before the check saw it. The session runtime now hands normalizeToolCall the update as the agent sent it. The rule is now exactly the stated one: object Arguments required, the title compared as sent, non-empty names. A later update that turns a call back from MCP (a location, a terminal, a diff) now rebuilds the row from its merged data the way the core shows any call (makeToolCallState, now exported), so no MCP title or label stays; a diff with no kind makes it the edit it is, so it still counts as file-change evidence. A restatement with new arguments shows the new ones. The runtime emits a mid-flight update whose row type changed even when its words and detail did not. Storage: an inline data: link or resource is left out, a long link and a terminal id are bounded, and the input is budgeted before output, content and metadata, with command-line fields first, so a stored command is never just the cut marker. The session runtime also exposes getToolCall for the approval fix that follows. --- apps/server/scripts/antigravity-mock-agent.ts | 51 +++++- .../src/provider/acp/AcpRuntimeModel.ts | 7 +- .../src/provider/acp/AcpSessionRuntime.ts | 21 ++- .../antigravity/AntigravityToolCalls.test.ts | 87 +++++++++- .../antigravity/AntigravityToolCalls.ts | 164 +++++++++++++----- .../antigravity/AntigravityTurns.test.ts | 32 ++++ 6 files changed, 311 insertions(+), 51 deletions(-) diff --git a/apps/server/scripts/antigravity-mock-agent.ts b/apps/server/scripts/antigravity-mock-agent.ts index f0bccc60a..a556899ca 100644 --- a/apps/server/scripts/antigravity-mock-agent.ts +++ b/apps/server/scripts/antigravity-mock-agent.ts @@ -36,7 +36,10 @@ * - `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. It writes no subagent records. + * 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. 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 @@ -276,6 +279,52 @@ const program = Effect.gen(function* () { yield* say(sessionId, "Thinking hard."); return yield* Effect.never; } + 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({ diff --git a/apps/server/src/provider/acp/AcpRuntimeModel.ts b/apps/server/src/provider/acp/AcpRuntimeModel.ts index 33f0ee68e..8f01f9030 100644 --- a/apps/server/src/provider/acp/AcpRuntimeModel.ts +++ b/apps/server/src/provider/acp/AcpRuntimeModel.ts @@ -432,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; diff --git a/apps/server/src/provider/acp/AcpSessionRuntime.ts b/apps/server/src/provider/acp/AcpSessionRuntime.ts index 0e44e3e23..0ffefca8f 100644 --- a/apps/server/src/provider/acp/AcpSessionRuntime.ts +++ b/apps/server/src/provider/acp/AcpSessionRuntime.ts @@ -235,6 +235,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; /** @@ -588,6 +594,9 @@ const makeAcpSessionRuntime = ( 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 } : {}), @@ -995,6 +1004,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) => @@ -1178,6 +1189,7 @@ const handleSessionUpdate = ({ liveOutsidePromptRef, itemIdScope, params, + receivedUpdate, configOptionsRef, normalizeToolCall, trackSilentToolCalls, @@ -1192,6 +1204,8 @@ const handleSessionUpdate = ({ /** 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?: ( @@ -1236,7 +1250,7 @@ const handleSessionUpdate = ({ const { previous, merged } = yield* Ref.modify(toolCallsRef, (current) => { const previous = current.get(event.toolCall.toolCallId); const mergedToolCall = mergeToolCallState(previous, event.toolCall); - const report = params.update as AcpToolCallReport; + 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") { @@ -1309,6 +1323,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; } diff --git a/apps/server/src/provider/antigravity/AntigravityToolCalls.test.ts b/apps/server/src/provider/antigravity/AntigravityToolCalls.test.ts index b39d59acc..d151066c3 100644 --- a/apps/server/src/provider/antigravity/AntigravityToolCalls.test.ts +++ b/apps/server/src/provider/antigravity/AntigravityToolCalls.test.ts @@ -2,7 +2,11 @@ import * as Schema from "effect/Schema"; import * as EffectAcpSchema from "effect-acp/schema"; import { describe, expect, it } from "vite-plus/test"; -import type { AcpToolCallState } from "../acp/AcpRuntimeModel.ts"; +import { + type AcpToolCallState, + makeToolCallState, + mergeToolCallState, +} from "../acp/AcpRuntimeModel.ts"; import { ANTIGRAVITY_TOOL_TEXT_LIMIT, antigravityProxiedMcpTool, @@ -164,3 +168,84 @@ describe("Antigravity call_mcp_tool", () => { 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 index a4f08a88c..3b46f8032 100644 --- a/apps/server/src/provider/antigravity/AntigravityToolCalls.ts +++ b/apps/server/src/provider/antigravity/AntigravityToolCalls.ts @@ -20,7 +20,7 @@ import * as Schema from "effect/Schema"; import * as EffectAcpSchema from "effect-acp/schema"; -import type { AcpToolCallState } from "../acp/AcpRuntimeModel.ts"; +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; @@ -109,12 +109,22 @@ function boundValue(value: unknown, budget: Budget, depth: number, field?: strin } if (!isRecord(value)) return value; const image = isInlineImage(value); - const kept: Record = {}; - for (const [key, entry] of Object.entries(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; - const bounded = boundValue(entry, budget, depth + 1, key); - if (bounded !== undefined) kept[key] = bounded; + 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; } @@ -142,6 +152,11 @@ 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; @@ -156,11 +171,13 @@ function boundContentEntry( }; 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: block.uri, + 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) } : {}), @@ -170,13 +187,13 @@ function boundContentEntry( break; case "resource": { const resource = block.resource; - if (!("text" in resource)) return undefined; + if (!("text" in resource) || /^data:/iu.test(resource.uri)) return undefined; bounded = { type: "content", content: { type: "resource", resource: { - uri: resource.uri, + uri: boundField(resource.uri, budget, "command"), text: boundField(resource.text, budget), ...(typeof resource.mimeType === "string" ? { mimeType: resource.mimeType } : {}), }, @@ -201,7 +218,16 @@ export function normalizeAntigravitySessionUpdate( 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]; @@ -215,12 +241,8 @@ export function normalizeAntigravitySessionUpdate( update: { ...update, ...(typeof update.title === "string" ? { title: boundAntigravityText(update.title) } : {}), - ...(update.rawInput !== undefined - ? { rawInput: boundAntigravityToolPayload(update.rawInput, budget) } - : {}), - ...(update.rawOutput !== undefined - ? { rawOutput: boundAntigravityToolPayload(update.rawOutput, budget) } - : {}), + ...(update.rawInput !== undefined ? { rawInput } : {}), + ...(update.rawOutput !== undefined ? { rawOutput } : {}), ...(update.content !== undefined && update.content !== null ? { content: content ?? [] } : {}), @@ -264,12 +286,17 @@ function commandOrEditEvidence(update: AntigravityToolCallUpdate): boolean { ); } +/** 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`: - * an `execute` call titled "MCP Tool " whose input is exactly - * `ServerName`, `ToolName` and optional object `Arguments` (agy 1.5.12, T3 - * Code 7f928416b2), with no command or edit about it. Anything else is - * `undefined` and stays what the agent called it. + * 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, @@ -277,31 +304,48 @@ export function antigravityProxiedMcpTool( const input = update.rawInput; if (!isRecord(input) || commandOrEditEvidence(update)) return undefined; if (update.kind !== "execute") return undefined; - if (!Object.keys(input).every((key) => WRAPPER_INPUT_KEYS.has(key))) return undefined; - const server = typeof input.ServerName === "string" ? input.ServerName.trim() : ""; - const tool = typeof input.ToolName === "string" ? input.ToolName.trim() : ""; - if (!server || !tool) return undefined; - if (input.Arguments !== undefined && !isRecord(input.Arguments)) return undefined; - if (update.title?.trim() !== `MCP Tool ${tool}`) return undefined; - return { server, tool, ...(isRecord(input.Arguments) ? { arguments: input.Arguments } : {}) }; + 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, the tool and its arguments. */ +/** + * 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): AntigravityProxiedMcpTool | undefined { - const { server, tool, arguments: args } = toolCall.data; - if (typeof server !== "string" || typeof tool !== "string") return undefined; - return { server, tool, ...(isRecord(args) ? { arguments: args } : {}) }; +function shownMcpTool(toolCall: AcpToolCallState): { server: string; tool: string } | undefined { + const { server, tool } = toolCall.data; + return typeof server === "string" && typeof tool === "string" ? { server, tool } : undefined; } -function asMcpToolCall(toolCall: AcpToolCallState, mcp: AntigravityProxiedMcpTool) { +/** + * 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", @@ -310,31 +354,55 @@ function asMcpToolCall(toolCall: AcpToolCallState, mcp: AntigravityProxiedMcpToo title: mcp.tool, detail: antigravityMcpToolLabel(mcp), data: { - ...data, + ...withoutArguments, kind: "other", server: mcp.server, tool: mcp.tool, ...(mcp.arguments !== undefined ? { arguments: mcp.arguments } : {}), }, - } satisfies AcpToolCallState; + }; } /** - * The merged call without the MCP fields an earlier update gave it, back to - * the kind the agent gives it (a wrapper was an `execute` call). + * 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, kind: string): AcpToolCallState { - const { server: _server, tool: _tool, arguments: _args, ...data } = toolCall.data; +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 { ...rest, kind, data: { ...data, kind } }; + return rebuilt ?? { ...rest, kind, data: { ...data, kind } }; } /** * A tool call as the timeline should show it, given the update that just - * arrived. 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. Anything else stays as the agent - * described it. + * 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, @@ -348,11 +416,13 @@ export function normalizeAntigravityToolCall( 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)); - return conflicting - ? withoutMcpTool(toolCall, update.kind ?? "execute") - : asMcpToolCall(toolCall, shown); + 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 index a14b36846..bb5a76eee 100644 --- a/apps/server/src/provider/antigravity/AntigravityTurns.test.ts +++ b/apps/server/src/provider/antigravity/AntigravityTurns.test.ts @@ -1084,6 +1084,38 @@ describe("Antigravity tool rows and attachments", () => { }).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"); From a8e3749d046e5d34f8390f320217b5b310bc8710 Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Mon, 23 Nov 2026 10:50:59 -0500 Subject: [PATCH 41/59] fix(acp): an approval shows everything known about its call, and is asked again when that changes A permission request may carry only part of its call (its id, say). The handler parsed the request alone, so a command an earlier update named could be missing: the kind fell to unknown and the words to "Session ". The request is now read on top of what the session already knows of the call (getToolCall, its updates merged). This applies to every ACP agent, and only changes what a partial request shows. An approval still waiting when a later update changes what it is for (an MCP call shown to run a command) is withdrawn and asked again in the new words under a new id, against the same answer the agent waits on; the old card closes unanswered and can no longer be answered. Its kind stays as on first asking, so every access mode asks and answers as before. Antigravity's plan-file exemption, which approves without asking and hides the row, now applies only to an edit whose every change is a diff of brain//plan.md and that names no other path and no command. Before, any call whose paths sat anywhere under brain qualified, a shell command included, and was answered allow_once in Supervised mode. --- apps/server/scripts/antigravity-mock-agent.ts | 95 ++++++++++++++- apps/server/src/provider/acp/AcpAdapter.ts | 108 +++++++++++++++--- .../src/provider/acp/AcpCoreRuntimeEvents.ts | 5 +- .../src/provider/acp/AcpRuntimeModel.ts | 28 ++++- .../src/provider/acp/AntigravityAcpSupport.ts | 59 +++++++--- .../antigravity/AntigravityTurns.test.ts | 88 ++++++++++++++ 6 files changed, 349 insertions(+), 34 deletions(-) diff --git a/apps/server/scripts/antigravity-mock-agent.ts b/apps/server/scripts/antigravity-mock-agent.ts index a556899ca..0a0c9f298 100644 --- a/apps/server/scripts/antigravity-mock-agent.ts +++ b/apps/server/scripts/antigravity-mock-agent.ts @@ -39,7 +39,13 @@ * 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. It writes no subagent records. + * - `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. + * - `plan-file-permission`: asks for a command naming the plan file, then + * for an edit of the plan file. 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 @@ -279,6 +285,93 @@ const program = Effect.gen(function* () { 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 === "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, { diff --git a/apps/server/src/provider/acp/AcpAdapter.ts b/apps/server/src/provider/acp/AcpAdapter.ts index bae2cdeec..9f56bbe2d 100644 --- a/apps/server/src/provider/acp/AcpAdapter.ts +++ b/apps/server/src/provider/acp/AcpAdapter.ts @@ -135,6 +135,8 @@ import { type AcpSessionModeState, type AcpToolCallState, acpTurnUsageTotals, + describePermissionRequest, + mergeToolCallState, parsePermissionRequest, } from "./AcpRuntimeModel.ts"; import { THREADLINES_ACP_CLIENT_INFO } from "./acpClientInfo.ts"; @@ -1175,6 +1177,33 @@ export function makeAcpAdapter( * (`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, + }; + const same = + next.detail === current.detail && next.toolCall?.title === current.toolCall?.title; + return same ? undefined : next; + }; + const normalizedPermissionRequest = ( request: AcpPermissionRequest, report: EffectAcpSchema.RequestPermissionRequest["toolCall"], @@ -1489,6 +1518,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; @@ -1939,8 +1976,11 @@ export function makeAcpAdapter( }); return selected(question.optionIdForAnswers(answers)); } + // 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), + parsePermissionRequest(params, known), params.toolCall, ); const planFileWrite = @@ -1965,10 +2005,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; @@ -1985,7 +2029,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({ @@ -1993,10 +2037,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, @@ -2007,14 +2051,48 @@ 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.suspend(() => { - pendingApprovals.delete(requestId); + pendingApprovals.delete(card.requestId); + if (openApprovals.get(toolCallId) === openApproval) { + openApprovals.delete(toolCallId); + } return closeMachineRequest(ctx); }), ), @@ -2026,8 +2104,8 @@ export function makeAcpAdapter( provider: PROVIDER, threadId: input.threadId, turnId, - requestId: runtimeRequestId, - permissionRequest, + requestId: RuntimeRequestId.make(card.requestId), + permissionRequest: card.permissionRequest, decision: resolved, }), ); @@ -2373,6 +2451,10 @@ export function makeAcpAdapter( 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" diff --git a/apps/server/src/provider/acp/AcpCoreRuntimeEvents.ts b/apps/server/src/provider/acp/AcpCoreRuntimeEvents.ts index a7f8da337..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 } : {}), }, }; } diff --git a/apps/server/src/provider/acp/AcpRuntimeModel.ts b/apps/server/src/provider/acp/AcpRuntimeModel.ts index 8f01f9030..579b261c4 100644 --- a/apps/server/src/provider/acp/AcpRuntimeModel.ts +++ b/apps/server/src/provider/acp/AcpRuntimeModel.ts @@ -596,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, @@ -612,9 +619,24 @@ 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); +} + +/** 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) ?? diff --git a/apps/server/src/provider/acp/AntigravityAcpSupport.ts b/apps/server/src/provider/acp/AntigravityAcpSupport.ts index c858fc988..7ba8163d3 100644 --- a/apps/server/src/provider/acp/AntigravityAcpSupport.ts +++ b/apps/server/src/provider/acp/AntigravityAcpSupport.ts @@ -34,7 +34,7 @@ import { spawn as spawnChild } from "node:child_process"; import { existsSync } from "node:fs"; import * as fs from "node:fs/promises"; import { homedir, tmpdir } from "node:os"; -import { join, resolve as resolvePath, sep } from "node:path"; +import { isAbsolute, join, normalize, relative, resolve as resolvePath, sep } from "node:path"; import { createInterface } from "node:readline"; import { @@ -115,7 +115,7 @@ 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); @@ -516,15 +516,50 @@ 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"]; + +/** + * Whether a tool call is the agent writing its own plan, and nothing else: + * an edit whose every change is a diff of a `plan.md` directly in one of the + * session folders under the profile's `brain` (`/plan` writes + * `brain//plan.md`), with no command about it. Such a write is + * approved without asking and shows as the plan card, so a call that runs + * anything, or touches any other file, never passes. + */ +export function isAntigravityPlanFileEdit(toolCall: AcpToolCallState, brain: string): boolean { + 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 isPlanPath = (path: string) => { + if (!isAbsolute(path)) return false; + const parts = relative(brain, normalize(path)).split(sep); + return parts.length === 2 && parts[0] !== ".." && parts[0] !== "" && parts[1] === "plan.md"; + }; + // 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 ──────────────────────────────────────────────────── /** @@ -837,13 +872,7 @@ export function makeAntigravityDescriptor( ...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) => isAntigravityPlanFileEdit(toolCall, brainDir(paths.profileDir)), planMarkdown: (toolCall) => { const content = toolCall.data.content; if (!Array.isArray(content)) return undefined; diff --git a/apps/server/src/provider/antigravity/AntigravityTurns.test.ts b/apps/server/src/provider/antigravity/AntigravityTurns.test.ts index bb5a76eee..72c3b129d 100644 --- a/apps/server/src/provider/antigravity/AntigravityTurns.test.ts +++ b/apps/server/src/provider/antigravity/AntigravityTurns.test.ts @@ -1084,6 +1084,94 @@ describe("Antigravity tool rows and attachments", () => { }).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("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"); From 5578f1369e1e6dc8d406cb528d70b14421bcc766 Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Mon, 23 Nov 2026 10:53:30 -0500 Subject: [PATCH 42/59] fix(antigravity): a refused subagent folder reads as unread, and a failed read at a turn's end no longer strands a launch A child's inbox, the parent's inbox or the subagents folder that is a link or not a folder read as an empty one, so a child could lose its launch, the reading counted as complete, and the turn's end could show the row done. antigravityProfileEntry now says "missing" or "refused" apart: a refused child inbox makes that child unknown and the reading incomplete, a refused parent inbox or subagents folder makes the reading unavailable. The subagent view remembers which turns completed (the last 64), so a launch of one that no complete reading names is guessed done on the first complete reading after a failed one, not only on the reading at the turn's end. A launch it still keeps is never shown again, even after 512 newer launches pushed it out of the seen list. Also: embedded text counts toward the 50 MB per-message allowance like inline bytes, and the session-log module says what it accepts about SQLite opening the database by path. --- .../provider/acp/AcpPromptAttachments.test.ts | 27 +++++++++++ .../src/provider/acp/AcpPromptAttachments.ts | 10 ++-- .../provider/acp/AcpSubagentRoster.test.ts | 34 +++++++++++++ .../src/provider/acp/AcpSubagentRoster.ts | 48 +++++++++++++------ .../AntigravityChildRecords.test.ts | 31 ++++++++++++ .../antigravity/AntigravityChildRecords.ts | 10 ++-- .../antigravity/AntigravitySessionLog.ts | 23 ++++++--- 7 files changed, 155 insertions(+), 28 deletions(-) diff --git a/apps/server/src/provider/acp/AcpPromptAttachments.test.ts b/apps/server/src/provider/acp/AcpPromptAttachments.test.ts index 430d7a5c0..0d0423974 100644 --- a/apps/server/src/provider/acp/AcpPromptAttachments.test.ts +++ b/apps/server/src/provider/acp/AcpPromptAttachments.test.ts @@ -92,6 +92,33 @@ describe("acpAttachmentContent", () => { }); 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); }), ), ); diff --git a/apps/server/src/provider/acp/AcpPromptAttachments.ts b/apps/server/src/provider/acp/AcpPromptAttachments.ts index 49e3941cc..dc339ae2a 100644 --- a/apps/server/src/provider/acp/AcpPromptAttachments.ts +++ b/apps/server/src/provider/acp/AcpPromptAttachments.ts @@ -167,10 +167,11 @@ export const acpAttachmentContent = (input: { }, ] satisfies ReadonlyArray; } - const cap = - delivery === "inline" - ? Math.min(deliveryLimit(delivery, mimeType), INLINE_MESSAGE_MAX_BYTES - budget.inlineBytes) - : deliveryLimit(delivery, mimeType); + // 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); @@ -178,6 +179,7 @@ export const acpAttachmentContent = (input: { if (delivery === "text") { const text = decodeAttachmentText(bytes); if (text === undefined) return [note(attachment, path)]; + budget.inlineBytes += bytes.byteLength; return [ { type: "resource", diff --git a/apps/server/src/provider/acp/AcpSubagentRoster.test.ts b/apps/server/src/provider/acp/AcpSubagentRoster.test.ts index 6fd724f4b..2d7cae392 100644 --- a/apps/server/src/provider/acp/AcpSubagentRoster.test.ts +++ b/apps/server/src/provider/acp/AcpSubagentRoster.test.ts @@ -151,4 +151,38 @@ describe("AcpSubagentRoster", () => { 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 index 60ed86f30..c1e39a372 100644 --- a/apps/server/src/provider/acp/AcpSubagentRoster.ts +++ b/apps/server/src/provider/acp/AcpSubagentRoster.ts @@ -10,7 +10,8 @@ * 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, as a guess a later reading can still correct; + * 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. * @@ -40,6 +41,8 @@ import { 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. */ @@ -75,6 +78,12 @@ export function makeAcpSubagentRoster(input: { }): 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] : [])); @@ -129,10 +138,10 @@ export function makeAcpSubagentRoster(input: { }); /** - * Brings the kept subagents in line with the records. With `ended`, the - * launches of that turn a complete reading doesn't name are guessed done. + * 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 = (ended: TurnId | undefined) => + const read = () => Effect.gen(function* () { const ids = [...entries.keys()]; if (ids.length === 0) return; @@ -144,7 +153,8 @@ export function makeAcpSubagentRoster(input: { for (const id of ids) { const state = reading.byLaunch.get(id); if (state === undefined) { - if (reading.complete && ended !== undefined && entries.get(id)?.turnId === ended) { + const turnId = entries.get(id)?.turnId; + if (reading.complete && turnId !== undefined && endedTurns.has(turnId)) { yield* guessDone(id); } continue; @@ -157,22 +167,22 @@ export function makeAcpSubagentRoster(input: { // One read at a time; a request while one runs reads once more after it. let reading = false; - let again: { ended: TurnId | undefined } | undefined; - const requestRead = (ended: TurnId | undefined): Effect.Effect => + let again = false; + const requestRead = (): Effect.Effect => Effect.suspend(() => { if (entries.size === 0) return Effect.void; if (reading) { - again = { ended: ended ?? again?.ended }; + again = true; return Effect.void; } reading = true; - const loop: Effect.Effect = read(ended).pipe( + const loop: Effect.Effect = read().pipe( Effect.ensuring(Effect.sync(() => (reading = false))), Effect.andThen( Effect.suspend(() => { - const next = again; - again = undefined; - return next === undefined ? Effect.void : requestRead(next.ended); + if (!again) return Effect.void; + again = false; + return requestRead(); }), ), ); @@ -187,7 +197,8 @@ export function makeAcpSubagentRoster(input: { noteToolCall: (toolCall, turnId) => Effect.gen(function* () { const id = toolCall.toolCallId; - if (toolCall.status !== "completed" || seen.has(id)) return; + // 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); @@ -205,11 +216,18 @@ export function makeAcpSubagentRoster(input: { event.type === "thread.token-usage.updated" || (event.type === "item.completed" && event.payload.itemType === "assistant_message") ) { - return requestRead(undefined); + return requestRead(); } if (event.type !== "turn.completed") return Effect.void; if (event.payload.state === "cancelled") return stopAll; - return requestRead(event.payload.state === "completed" ? event.turnId : undefined); + 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/antigravity/AntigravityChildRecords.test.ts b/apps/server/src/provider/antigravity/AntigravityChildRecords.test.ts index e3fc37c37..9bc511e5b 100644 --- a/apps/server/src/provider/antigravity/AntigravityChildRecords.test.ts +++ b/apps/server/src/provider/antigravity/AntigravityChildRecords.test.ts @@ -215,6 +215,37 @@ describe("readAntigravityChildren", () => { ); }); +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) => diff --git a/apps/server/src/provider/antigravity/AntigravityChildRecords.ts b/apps/server/src/provider/antigravity/AntigravityChildRecords.ts index 41e27098d..831109c6d 100644 --- a/apps/server/src/provider/antigravity/AntigravityChildRecords.ts +++ b/apps/server/src/provider/antigravity/AntigravityChildRecords.ts @@ -174,7 +174,8 @@ const generated = (conversationId: string, ...rest: ReadonlyArray) => [ /** * 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, or holds more than the limit. No inbox is empty. + * 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, @@ -183,7 +184,9 @@ async function readInbox( ): Promise<{ readonly messages: ReadonlyArray; readonly unreadable: number } | undefined> { const segments = generated(conversationId, "messages"); const inbox = await antigravityProfileEntry(profileDir, segments, "directory"); - if (inbox === undefined) return { messages: [], unreadable: 0 }; + // 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; @@ -257,7 +260,8 @@ async function readChildren( generated(parentId, "subagents"), "directory", ); - if (folder === undefined) return { reason: "no-records" }; + 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) => diff --git a/apps/server/src/provider/antigravity/AntigravitySessionLog.ts b/apps/server/src/provider/antigravity/AntigravitySessionLog.ts index c762a16c1..d85f7b950 100644 --- a/apps/server/src/provider/antigravity/AntigravitySessionLog.ts +++ b/apps/server/src/provider/antigravity/AntigravitySessionLog.ts @@ -15,6 +15,16 @@ * 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). * @@ -49,17 +59,18 @@ export interface AntigravityTurnSteps { /** * 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; `undefined` otherwise. 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`). + * 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 } | undefined> { - const found = await profileEntry(profileDir, segments, kind); - return typeof found === "string" ? undefined : found; +): 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). */ From 99861dcf1df27216e106d80a794fb1dba64ea5ee Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Mon, 23 Nov 2026 10:53:46 -0500 Subject: [PATCH 43/59] docs(antigravity): what plan mode approves without asking, and approvals that are asked again --- docs/providers/antigravity.md | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/docs/providers/antigravity.md b/docs/providers/antigravity.md index ef2864966..629030a7a 100644 --- a/docs/providers/antigravity.md +++ b/docs/providers/antigravity.md @@ -55,7 +55,10 @@ has them. The reasoning level is its own choice next to the model. | 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. A message +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). @@ -195,6 +198,10 @@ turn stays open (see Turns above). 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. From 69af46f3b2fbba7654268996b0d031a7c4ed23d1 Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Mon, 23 Nov 2026 11:02:24 -0500 Subject: [PATCH 44/59] fix(antigravity): a session's command list never lingers on the status or reaches the disk cache The provider status cache wrote the live lists to disk, and a status enrichment that read a snapshot while a session ran could republish its list after the session ended, because the driver only replaced the field when some list was live. Every snapshot now goes through withSessionCommands, which sets the lists as they are (dropping a stale one) and returns the same snapshot when nothing changed, so an unchanged list publishes nothing. The status cache drops sessionCommands before writing. --- .../provider/acp/AcpProviderDriver.test.ts | 22 +++++++++ .../src/provider/acp/AcpProviderDriver.ts | 46 +++++++++++++++---- .../src/provider/providerStatusCache.test.ts | 18 ++++++++ .../src/provider/providerStatusCache.ts | 7 ++- 4 files changed, 82 insertions(+), 11 deletions(-) diff --git a/apps/server/src/provider/acp/AcpProviderDriver.test.ts b/apps/server/src/provider/acp/AcpProviderDriver.test.ts index 92e504910..67523f74d 100644 --- a/apps/server/src/provider/acp/AcpProviderDriver.test.ts +++ b/apps/server/src/provider/acp/AcpProviderDriver.test.ts @@ -7,11 +7,13 @@ 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 { groupSessionCommands, + withSessionCommands, makeAcpProviderMaintenanceResolver, resolveAcpBinaryPath, } from "./AcpProviderDriver.ts"; @@ -36,6 +38,26 @@ describe("groupSessionCommands", () => { }); }); +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 71ab317b6..09954c2f3 100644 --- a/apps/server/src/provider/acp/AcpProviderDriver.ts +++ b/apps/server/src/provider/acp/AcpProviderDriver.ts @@ -57,6 +57,33 @@ 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>, @@ -197,7 +224,7 @@ export function makeAcpProviderDriver( // 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 stampIdentity = (snapshot: ServerProviderDraft): ServerProvider => ({ + const stampInstance = (snapshot: ServerProviderDraft): ServerProvider => ({ ...snapshot, instanceId, driver: DRIVER_KIND, @@ -205,11 +232,12 @@ export function makeAcpProviderDriver( ...(accentColor ? { accentColor } : {}), continuation: { groupKey: continuationIdentity.continuationKey }, ...(descriptor.agentCommands?.slashSkills === true ? { slashSkills: true } : {}), - ...(sessionCommands.size > 0 - ? { sessionCommands: groupSessionCommands(sessionCommands) } - : {}), ...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. @@ -262,13 +290,11 @@ export function makeAcpProviderDriver( Effect.suspend(() => { if (commands === undefined) sessionCommands.delete(sessionKey); else sessionCommands.set(sessionKey, commands); + // An unchanged status is not published again. return ( - liveSnapshot?.patchSnapshot((current) => { - const { sessionCommands: _previous, ...rest } = current; - return sessionCommands.size > 0 - ? { ...rest, sessionCommands: groupSessionCommands(sessionCommands) } - : rest; - }) ?? Effect.void + liveSnapshot?.patchSnapshot((current) => + withSessionCommands(current, sessionCommands), + ) ?? Effect.void ); }).pipe(Effect.ignoreCause({ log: true })), skillNames: Effect.suspend( diff --git a/apps/server/src/provider/providerStatusCache.test.ts b/apps/server/src/provider/providerStatusCache.test.ts index 79da99414..2e3fecab9 100644 --- a/apps/server/src/provider/providerStatusCache.test.ts +++ b/apps/server/src/provider/providerStatusCache.test.ts @@ -45,6 +45,24 @@ const makeProvider = ( }); it.layer(NodeServices.layer)("providerStatusCache", (it) => { + 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`, From f114223612e181499570b2bd745ee68823f28c3c Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Mon, 23 Nov 2026 11:02:24 -0500 Subject: [PATCH 45/59] fix(antigravity): history counts as given only once it went out, and a revert never restores under a running agent - The adapter contract gains turnDispatched: whether a turn's first prompt went out to the agent. The reactor pays a history debt (and the binding's historyOwed mark) only on true; a send accepted and then failed while the agent was being configured keeps the debt. Adapters without the signal behave as before. - historyOwed acknowledgements and lost-session forgets name the runtime (its start time, kept in the binding): a late word from an older session neither clears a newer debt nor forgets a replacement conversation. session.exited's conversationLost now carries that session. - A failed resume (Codex's fallback, and every other adapter's resumeFailed) marks the binding too, so a restart before a history-bearing send seeds the next start instead of resuming the replacement conversation. - A fork's summarized source is owed until a prompt carrying it went out: a first message that went as the agent's own command no longer loses it. - A handoff's debt no longer makes a room's catch-up note repeat the agent's own turns. - A revert stops a new-session agent before restoring files and restores nothing if it can't be stopped (a rollback that can't stop the work ends the runtime); if files can't be restored after the agent forgot, the failure says both. - An agent command is read from the trimmed typed text; the indented mark is gone. --- .../Layers/CheckpointReactor.test.ts | 74 +++++- .../orchestration/Layers/CheckpointReactor.ts | 44 ++-- .../Layers/ProviderCommandReactor.test.ts | 222 ++++++++++++++++++ .../Layers/ProviderCommandReactor.ts | 77 +++++- .../Layers/ProviderRuntimeIngestion.test.ts | 1 + .../provider/Layers/ProviderService.test.ts | 106 ++++++++- .../src/provider/Layers/ProviderService.ts | 88 ++++++- .../Layers/ProviderSessionReaper.test.ts | 1 + .../src/provider/Services/ProviderAdapter.ts | 13 + .../src/provider/Services/ProviderService.ts | 35 ++- apps/server/src/provider/acp/AcpAdapter.ts | 23 +- .../antigravity/AntigravityTurns.test.ts | 12 +- docs/providers/antigravity.md | 27 ++- packages/contracts/src/provider.ts | 5 - packages/contracts/src/providerRuntime.ts | 6 +- 15 files changed, 652 insertions(+), 82 deletions(-) diff --git a/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts b/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts index 411706c56..fb7ba37c9 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"; @@ -103,7 +104,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 = () => @@ -163,6 +165,7 @@ function createProviderServiceHarness( forgetNativeSession: () => Effect.void, dropResumeCursor: () => Effect.void, noteHistoryDelivered: () => Effect.void, + turnDispatched: () => Effect.succeed(true), getCapabilities: () => Effect.succeed({ sessionModelSwitch: "in-session", @@ -3119,6 +3122,75 @@ describe("CheckpointReactor", () => { ); }); + 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 }, diff --git a/apps/server/src/orchestration/Layers/CheckpointReactor.ts b/apps/server/src/orchestration/Layers/CheckpointReactor.ts index b5e403d90..7353cef5a 100644 --- a/apps/server/src/orchestration/Layers/CheckpointReactor.ts +++ b/apps/server/src/orchestration/Layers/CheckpointReactor.ts @@ -1241,28 +1241,42 @@ const make = Effect.gen(function* () { Effect.map((capabilities) => capabilities.conversationRollback === "new-session"), Effect.orElseSucceed(() => false), )); - const startedOver = startsOver - ? yield* providerService - .rollbackConversation({ + // 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 } : {}), - }) - .pipe( - Effect.map((rollback) => rollback.conversationRolledBack), - Effect.catchCause((cause) => - Effect.logWarning("checkpoint revert could not make the agent start over", { - threadId: event.payload.threadId, - cause: Cause.pretty(cause), - }).pipe(Effect.as(false)), - ), - ) + }), + ) : 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 revertOutcome = yield* checkpointRevert.applyRevert(context); + 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; } diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts index 13faa5dab..54b5dbf2e 100644 --- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts +++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts @@ -457,6 +457,10 @@ describe("ProviderCommandReactor", () => { const noteHistoryDelivered = vi.fn( () => Effect.void, ); + // Every accepted turn has gone out to the agent unless a test says otherwise. + const turnDispatched = vi.fn(() => + Effect.succeed(true), + ); const renameBranch = vi.fn((input: unknown) => Effect.succeed({ branch: @@ -580,6 +584,7 @@ describe("ProviderCommandReactor", () => { forgetNativeSession: () => Effect.void, dropResumeCursor, noteHistoryDelivered, + turnDispatched, getCapabilities: (_provider) => Effect.succeed({ sessionModelSwitch: input?.sessionModelSwitch ?? "in-session", @@ -834,6 +839,7 @@ describe("ProviderCommandReactor", () => { stopSession, dropResumeCursor, noteHistoryDelivered, + turnDispatched, renameBranch, refreshStatus, refreshLocalStatus, @@ -1721,6 +1727,65 @@ 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.turnDispatched.mockImplementationOnce(() => Effect.succeed(false)); + await turnStart("2", "second question"); + await waitFor(() => harness.sendTurn.mock.calls.length === 2); + await waitFor(() => harness.turnDispatched.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("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"; @@ -2736,6 +2801,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"; @@ -7430,6 +7590,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"; @@ -7559,6 +7721,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) @@ -7655,6 +7826,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 a917a8a57..3af21afc6 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 @@ -1961,7 +1967,7 @@ const make = Effect.gen(function* () { thread.historySeedOwed === true && contextSeed.entries.length > 0 ? { moved: true as const } - : {}), + : { handoff: true as const }), carriedBy: handoffSession.createdAt, }); } @@ -2546,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 @@ -2729,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 @@ -2772,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 @@ -2903,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 @@ -2916,7 +2943,7 @@ const make = Effect.gen(function* () { } : {}), }; - yield* orchestrationEngine + forkSeedOutcome = orchestrationEngine .dispatch({ type: "thread.activity.append", commandId: serverCommandId("thread-fork-seed-outcome"), @@ -2934,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 ?? @@ -2961,7 +2995,6 @@ const make = Effect.gen(function* () { typed: { text: typedText, ...(providerContext.length > 0 ? { context: providerContext } : {}), - ...(/^\s/u.test(input.messageText) ? { indented: true as const } : {}), }, } : {}), @@ -2987,9 +3020,17 @@ const make = Effect.gen(function* () { if (owedSeed.moved === true) { yield* markHistorySeedDelivered(input.threadId, input.messageId); } - // The binding stops owing it too (ProviderService.noteHistoryDelivered). - yield* providerService.noteHistoryDelivered(sessionKey); + // 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, // A send that failed before the provider took it delivered nothing. historyDebtReturned: owedSeed === undefined @@ -3703,6 +3744,7 @@ const make = Effect.gen(function* () { historyDebtClaimed, historyDebtPaid, historyDebtReturned, + contextDelivered, notesDelivered, } = sendTurnRequest.value; @@ -3766,10 +3808,25 @@ const make = Effect.gen(function* () { ), // A send that went as the agent's own command carried none of the // context in front of it: every debt it was to pay stays. + // The history and a fork's summary count as delivered only once + // the prompt carrying them went out to the agent, not when the send + // was accepted (an agent configures its session first, and that can + // fail). Settled on its own, so the turn's bookkeeping doesn't wait. Effect.tap((turn) => Effect.suspend(() => { contextDeferred = turn.contextDeferred === true; - return contextDeferred ? historyDebtReturned : historyDebtPaid; + if (contextDeferred) return historyDebtReturned; + return providerService + .turnDispatched({ threadId: turnRequest.threadId, turnId: turn.turnId }) + .pipe( + Effect.flatMap((wentOut) => + wentOut + ? Effect.andThen(historyDebtPaid, contextDelivered) + : historyDebtReturned, + ), + Effect.forkScoped, + Effect.asVoid, + ); }), ), Effect.onError(() => historyDebtReturned), diff --git a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts index 1e1901e21..a4b6c0b3f 100644 --- a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts +++ b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts @@ -166,6 +166,7 @@ function createProviderServiceHarness() { ? Effect.die(new Error("the session would not stop")) : Effect.sync(() => void droppedCursors.push(threadId)), noteHistoryDelivered: () => Effect.void, + turnDispatched: () => Effect.succeed(true), getCapabilities: () => Effect.succeed({ sessionModelSwitch: "in-session" }), getInstanceInfo: (instanceId) => { const driverKind = ProviderDriverKind.make(String(instanceId)); diff --git a/apps/server/src/provider/Layers/ProviderService.test.ts b/apps/server/src/provider/Layers/ProviderService.test.ts index 440073c29..226185f77 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 @@ -3440,7 +3451,7 @@ 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); + const agent = makeFakeCodexAdapter(ANTIGRAVITY, { distinctStarts: true }); const adapter = { ...agent.adapter, capabilities: { ...agent.adapter.capabilities, conversationRollback: "new-session" as const }, @@ -3524,10 +3535,22 @@ startingOver.layer("ProviderServiceLive forgetting a conversation", (it) => { assert.isUndefined(lastStartCursor()); assert.isTrue(again.resumeFailed); - yield* provider.noteHistoryDelivered(key); + // 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(), again.resumeCursor); + assert.deepEqual(lastStartCursor(), stillOwed.resumeCursor); assert.isUndefined(whole.resumeFailed); }), ); @@ -3554,6 +3577,61 @@ startingOver.layer("ProviderServiceLive forgetting a conversation", (it) => { }), ); + 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("stops a running agent's work through its rollback before forgetting", () => Effect.gen(function* () { const provider = yield* ProviderService; @@ -3580,7 +3658,23 @@ startingOver.layer("ProviderServiceLive forgetting a conversation", (it) => { providerInstanceId: instanceId, threadId: key, createdAt: "2026-01-01T00:00:00.000Z", - payload: { exitKind: "graceful", conversationLost: true }, + // 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); + 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)); diff --git a/apps/server/src/provider/Layers/ProviderService.ts b/apps/server/src/provider/Layers/ProviderService.ts index df3f7fb59..78ea9ecd5 100644 --- a/apps/server/src/provider/Layers/ProviderService.ts +++ b/apps/server/src/provider/Layers/ProviderService.ts @@ -229,6 +229,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 @@ -256,6 +259,19 @@ function toRuntimePayloadFromSession( * clears it (`noteHistoryDelivered`). Kept in the binding, so a restart in * between can't reopen the conversation as it was. */ +/** The start time of the runtime the binding last described (ProviderSession.createdAt). */ +function readPersistedSessionCreatedAt( + runtimePayload: ProviderRuntimeBinding["runtimePayload"], +): string | undefined { + return runtimePayload !== null && + typeof runtimePayload === "object" && + !Array.isArray(runtimePayload) && + "sessionCreatedAt" in runtimePayload && + typeof runtimePayload.sessionCreatedAt === "string" + ? runtimePayload.sessionCreatedAt + : undefined; +} + function readPersistedHistoryOwed(runtimePayload: ProviderRuntimeBinding["runtimePayload"]) { return ( runtimePayload !== null && @@ -722,8 +738,11 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( // 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 === true - ? forgetConversation(canonicalEvent.threadId) + canonicalEvent.type === "session.exited" && + canonicalEvent.payload.conversationLost !== undefined + ? forgetConversation(canonicalEvent.threadId, { + onlySession: canonicalEvent.payload.conversationLost.sessionCreatedAt, + }) : Effect.void, ), Effect.flatMap((canonicalEvent) => @@ -1190,9 +1209,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, or the - // seed this start handed over (an adapter may hold it until a send). - ...(historyOwed || input.contextSeed !== undefined ? { historyOwed: true } : {}), + // 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", { @@ -2928,13 +2950,23 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( /** * Forgets a saved conversation in the thread's binding (see - * readPersistedHistoryOwed): its cursor goes and the history is owed. - * False when the binding couldn't be written; the agent then remembers. + * 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) => + const forgetConversation = (threadId: ThreadId, options?: { readonly onlySession?: string }) => Effect.gen(function* () { const binding = Option.getOrUndefined(yield* directory.getBinding(threadId)); if (binding === undefined) return true; + if ( + options?.onlySession !== undefined && + readPersistedSessionCreatedAt(binding.runtimePayload) !== options.onlySession + ) { + return true; + } yield* directory.upsert({ threadId, provider: binding.provider, @@ -2942,7 +2974,7 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( ? { providerInstanceId: binding.providerInstanceId } : {}), resumeCursor: null, - runtimePayload: { historyOwed: true }, + runtimePayload: { historyOwed: true, sessionCreatedAt: null }, }); return true; }).pipe( @@ -2962,6 +2994,8 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( */ 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; @@ -2971,7 +3005,16 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( .pipe(Effect.orElseSucceed(() => undefined)); if (adapter?.capabilities.conversationRollback !== "new-session") return undefined; if (yield* adapter.hasSession(threadId)) { - yield* adapter.rollbackThread(threadId, numTurns); + // 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))), + ), + ); } const forgotten = yield* forgetConversation(threadId); yield* analytics.record("provider.conversation.rolled_back", { @@ -2981,10 +3024,15 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( return forgotten; }); - const noteHistoryDelivered: ProviderServiceShape["noteHistoryDelivered"] = (threadId) => + const noteHistoryDelivered: ProviderServiceShape["noteHistoryDelivered"] = ({ + threadId, + sessionCreatedAt, + }) => Effect.gen(function* () { const binding = Option.getOrUndefined(yield* directory.getBinding(threadId)); if (binding === undefined || !readPersistedHistoryOwed(binding.runtimePayload)) return; + // Another runtime than the one that sent it: that one still owes it. + if (readPersistedSessionCreatedAt(binding.runtimePayload) !== sessionCreatedAt) return; yield* directory.upsert({ threadId, provider: binding.provider, @@ -2995,6 +3043,23 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( }); }).pipe(Effect.ignoreCause({ log: true })); + const turnDispatched: ProviderServiceShape["turnDispatched"] = ({ threadId, turnId }) => + Effect.gen(function* () { + const binding = Option.getOrUndefined(yield* directory.getBinding(threadId)); + if (binding?.providerInstanceId === undefined) return false; + const adapter = yield* registry.getByInstance(binding.providerInstanceId); + const dispatched = adapter.turnDispatched; + // Without the signal, an accepted send has already gone out. + return dispatched === undefined ? true : yield* dispatched(threadId, turnId); + }).pipe( + Effect.catchCause((cause) => + Effect.logWarning("provider service could not tell whether a turn went out", { + threadId, + cause: Cause.pretty(cause), + }).pipe(Effect.as(false)), + ), + ); + /** * 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 @@ -3494,6 +3559,7 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( forgetNativeSession, dropResumeCursor, noteHistoryDelivered, + turnDispatched, getCapabilities, getInstanceInfo, rollbackConversation, diff --git a/apps/server/src/provider/Layers/ProviderSessionReaper.test.ts b/apps/server/src/provider/Layers/ProviderSessionReaper.test.ts index 321ed5672..863d8707c 100644 --- a/apps/server/src/provider/Layers/ProviderSessionReaper.test.ts +++ b/apps/server/src/provider/Layers/ProviderSessionReaper.test.ts @@ -255,6 +255,7 @@ describe("ProviderSessionReaper", () => { forgetNativeSession: () => Effect.void, dropResumeCursor: () => Effect.void, noteHistoryDelivered: () => Effect.void, + turnDispatched: () => Effect.succeed(true), 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 3ce47ae73..4ef9a2dd4 100644 --- a/apps/server/src/provider/Services/ProviderAdapter.ts +++ b/apps/server/src/provider/Services/ProviderAdapter.ts @@ -231,6 +231,19 @@ export interface ProviderAdapterShape { readonly expectedCwd: string; }) => Effect.Effect; + /** + * Whether the first prompt of a turn `sendTurn` accepted went out to the + * agent: true once it was written to the agent (after the session was + * configured for it), false once it is known it never will be (the + * configuration failed, the session stopped, the turn was stopped first) + * or the adapter knows no such turn. Context that prompt carried (the + * thread's history, a handoff preamble) counts as delivered only on true; + * an adapter that holds such context itself keeps it for the next prompt + * on false. Absent: `sendTurn` returns only after the prompt was written, + * so an accepted turn has gone out. + */ + readonly turnDispatched?: (threadId: ThreadId, turnId: TurnId) => Effect.Effect; + /** * Send a turn to an active provider session. */ diff --git a/apps/server/src/provider/Services/ProviderService.ts b/apps/server/src/provider/Services/ProviderService.ts index 77e2c69cb..53adead1d 100644 --- a/apps/server/src/provider/Services/ProviderService.ts +++ b/apps/server/src/provider/Services/ProviderService.ts @@ -37,6 +37,7 @@ import type { RuntimeThreadGoalSnapshot, ThreadGoalStatus, ThreadId, + TurnId, ProviderSubagentInputRequest, ProviderSubagentInputResult, ProviderCommandOutputInput, @@ -387,11 +388,28 @@ export interface ProviderServiceShape { readonly dropResumeCursor: (threadId: ThreadId) => Effect.Effect; /** - * The thread's history reached the agent of this session key (the send - * that carried it was taken): a conversation forgotten earlier - * (`historyOwed` on its binding) is whole again, so later starts resume it. + * 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 (`turnDispatched`). 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: (threadId: ThreadId) => Effect.Effect; + readonly noteHistoryDelivered: (input: { + readonly threadId: ThreadId; + readonly sessionCreatedAt: string; + }) => Effect.Effect; + + /** + * Whether the first prompt of a turn `sendTurn` accepted went out to the + * agent (see ProviderAdapterShape.turnDispatched): what context that + * prompt carried is delivered only on true. Never fails; false when the + * turn's agent can't be found. + */ + readonly turnDispatched: (input: { + readonly threadId: ThreadId; + readonly turnId: TurnId; + }) => Effect.Effect; /** * Read capabilities for the adapter bound to a configured provider instance. @@ -408,9 +426,12 @@ 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`). An agent that - * forgets by starting over (`new-session`) has its running work stopped and - * its saved conversation forgotten in the thread's binding; nothing is - * started for it, and a binding that couldn't be written answers false. + * 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/acp/AcpAdapter.ts b/apps/server/src/provider/acp/AcpAdapter.ts index bae2cdeec..7b8088ed8 100644 --- a/apps/server/src/provider/acp/AcpAdapter.ts +++ b/apps/server/src/provider/acp/AcpAdapter.ts @@ -1323,7 +1323,7 @@ export function makeAcpAdapter( const stopSessionInternal = ( ctx: AcpSessionContext, exitKind: "graceful" | "error" = "graceful", - exit?: { readonly conversationLost?: true }, + exit?: { readonly conversationLost?: { readonly sessionCreatedAt: string } }, ) => Effect.gen(function* () { if (ctx.stopped) return; @@ -3010,7 +3010,9 @@ export function makeAcpAdapter( yield* stopFromMachine( ctx, command.reason === "exited" ? "error" : "graceful", - command.reason === "sessionLost" ? { conversationLost: true } : undefined, + command.reason === "sessionLost" + ? { conversationLost: { sessionCreatedAt: ctx.session.createdAt } } + : undefined, ); return; case "markSessionLost": @@ -3026,7 +3028,7 @@ export function makeAcpAdapter( const stopFromMachine = ( ctx: AcpSessionContext, exitKind: "graceful" | "error", - exit?: { readonly conversationLost?: true }, + exit?: { readonly conversationLost?: { readonly sessionCreatedAt: string } }, ) => withThreadLock( ctx.threadId, @@ -3280,21 +3282,22 @@ export function makeAcpAdapter( 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 - // (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 + // 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 && typed.indented !== true - ? slashCommandAtStart(typed.text) + descriptor.agentCommands !== undefined && typed !== undefined + ? slashCommandAtStart(typed.text.trim()) : undefined; const sendsAgentCommand = typedCommand !== undefined && (yield* isAgentCommand(ctx, typedCommand)); - const userText = sendsAgentCommand && typed ? typed.text : (input.input?.trim() ?? ""); + const userText = + sendsAgentCommand && typed ? typed.text.trim() : (input.input?.trim() ?? ""); const contextDeferred = sendsAgentCommand && (typed?.context !== undefined || ctx.pendingContextPreamble !== undefined); diff --git a/apps/server/src/provider/antigravity/AntigravityTurns.test.ts b/apps/server/src/provider/antigravity/AntigravityTurns.test.ts index a14b36846..c2eadaed4 100644 --- a/apps/server/src/provider/antigravity/AntigravityTurns.test.ts +++ b/apps/server/src/provider/antigravity/AntigravityTurns.test.ts @@ -448,7 +448,8 @@ describe("Antigravity turns", () => { // 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({ - payload: { conversationLost: true }, + // Named, so only a binding still on this session forgets it. + payload: { conversationLost: { sessionCreatedAt: agy.session.createdAt } }, }); }).pipe(Effect.scoped, Effect.provide(testServices)), ); @@ -784,7 +785,7 @@ describe("Antigravity commands and edits", () => { Effect.gen(function* () { const agy = yield* startAgy("simple"); yield* agy.waitFor(() => agy.commandReports.length > 0); - const send = (input: string, typed?: { text: string; context?: string; indented?: true }) => + const send = (input: string, typed?: { text: string; context?: string }) => Effect.gen(function* () { const before = completedTurns(agy.events).length; const turn = yield* agy.adapter.sendTurn({ @@ -800,11 +801,12 @@ describe("Antigravity commands and edits", () => { // 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, plain text and an indented one: ordinary text. + // 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"); - yield* send("/compact", { text: "/compact", indented: true }); + // 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", @@ -817,7 +819,7 @@ describe("Antigravity commands and edits", () => { "/plan /etc is missing", "/plan /tmp/out.log is empty", "/plan /compact", - "/plan /compact", + "/compact", "/compact", ]); }).pipe(Effect.scoped, Effect.provide(testServices)), diff --git a/docs/providers/antigravity.md b/docs/providers/antigravity.md index ef2864966..00baf580d 100644 --- a/docs/providers/antigravity.md +++ b/docs/providers/antigravity.md @@ -126,15 +126,19 @@ list is the one of the agent the message goes to. `.`, `:` 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 start with `/` and the name -of a command that session offers or a skill Threadlines lists. That message goes to Antigravity -alone, exactly 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, 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 that starts with a space, one sent as plain text, and one an -agent or a scheduled task wrote. +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 @@ -236,7 +240,10 @@ saved conversation from its own record of the thread, so the next message starts 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. +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 diff --git a/packages/contracts/src/provider.ts b/packages/contracts/src/provider.ts index fe36a1805..59976d29b 100644 --- a/packages/contracts/src/provider.ts +++ b/packages/contracts/src/provider.ts @@ -264,11 +264,6 @@ export const ProviderTypedInput = Schema.Struct({ text: TrimmedNonEmptyString.check(Schema.isMaxLength(PROVIDER_SEND_TURN_MAX_INPUT_CHARS)), /** What the server put in front of `text`. Absent: `input` is `text`. */ context: Schema.optional(Schema.String), - /** - * The person's text began with whitespace, which `text` drops. A driver - * that reads `/name` at the start as a command reads none then. - */ - indented: Schema.optional(Schema.Literal(true)), }); export type ProviderTypedInput = typeof ProviderTypedInput.Type; diff --git a/packages/contracts/src/providerRuntime.ts b/packages/contracts/src/providerRuntime.ts index 3abd7298e..de67c8668 100644 --- a/packages/contracts/src/providerRuntime.ts +++ b/packages/contracts/src/providerRuntime.ts @@ -420,9 +420,11 @@ const SessionExitedPayload = Schema.Struct({ /** * 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 (ProviderService.forgetConversation). + * 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.Literal(true)), + conversationLost: Schema.optional(Schema.Struct({ sessionCreatedAt: IsoDateTime })), }); export type SessionExitedPayload = typeof SessionExitedPayload.Type; From 88d2b4c1cb9a5c1b139fe6d16e545661f259e902 Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Mon, 23 Nov 2026 11:20:46 -0500 Subject: [PATCH 46/59] feat(effect-acp): a request whose answer keeps its place among the notifications requestInOrder returns once the request is queued for the wire and hands its answer to a callback on the reader, before any message read after it. A connection that ends first gives the callback that failure. --- packages/effect-acp/src/client.ts | 3 + packages/effect-acp/src/protocol.test.ts | 36 ++++++++++ packages/effect-acp/src/protocol.ts | 92 +++++++++++++++++++++--- 3 files changed, 120 insertions(+), 11 deletions(-) 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..6231d8727 100644 --- a/packages/effect-acp/src/protocol.test.ts +++ b/packages/effect-acp/src/protocol.test.ts @@ -228,6 +228,42 @@ 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("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..165fc5483 100644 --- a/packages/effect-acp/src/protocol.ts +++ b/packages/effect-acp/src/protocol.ts @@ -65,6 +65,18 @@ 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 it is queued for the wire, ahead of + * anything sent after. 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; } @@ -99,6 +111,21 @@ export const makeAcpPatchedProtocol = Effect.fn("makeAcpPatchedProtocol")(functi 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; + }); const logProtocol = (event: AcpProtocolLogEvent) => { if (event.direction === "incoming" && !options.logIncoming) { @@ -175,14 +202,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( @@ -327,9 +353,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 +384,6 @@ export const makeAcpPatchedProtocol = Effect.fn("makeAcpPatchedProtocol")(functi ); }), ); - }; const routeDecodedMessage = ( message: RpcMessage.FromClientEncoded | RpcMessage.FromServerEncoded, @@ -531,6 +564,29 @@ 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)); + yield* offerOutgoing({ + _tag: "Request", + id: requestId, + tag: method, + payload, + headers: [], + }).pipe( + Effect.catch((error) => + takeOrderedPending(requestId).pipe(Effect.andThen(Effect.fail(error))), + ), + ); + }); + return { clientProtocol, serverProtocol, @@ -538,6 +594,7 @@ export const makeAcpPatchedProtocol = Effect.fn("makeAcpPatchedProtocol")(functi return Stream.fromQueue(notificationQueue); }, request: sendRequest, + requestInOrder: sendRequestInOrder, notify: sendNotification, } satisfies AcpPatchedProtocol; }); @@ -571,6 +628,19 @@ function asRequestFailure(message: RpcMessage.ResponseExitEncoded): RpcMessage.R }; } +/** 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 } { From 3e4a1de336c0a30e195a304dbe822fd434dac77f Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Mon, 23 Nov 2026 11:20:46 -0500 Subject: [PATCH 47/59] fix(acp): the turn machine's driver keeps the reducer's order - One ordered path in: a prompt's answer is queued where the wire reader read it (promptInOrder), and a written prompt is marked there too. Child-record readings carry the generation that asked; older ones drop. - One ordered path out: a single sender writes the machine's prompts in order, each turn's mode and model setup first. - A step and its commands run as one unit. Stopping a session is an event the reader takes after what is queued, so a turn's end and an answered prompt's usage are never lost; the turn's end precedes the recycle. - Stop on held work ends the turn at once but keeps the commands and subagents (stopping) under the cancel deadline until the agent shows they ended; a send waits for it. - Launches match child records by call id, not by count. - No outcome rebase: an error step counts for the newest prompt when it is the log's last, which never hides that prompt's failure. - Quiet timers count from the agent's last activity. - A lost session's exit names the session; the binding forgets it only while it still points there. - A send whose setup fails reports undelivered and leaves its context pending; the reactor keeps the history owed. - turnMachine.steer switches steering; off, a mid-turn message queues. - Explorer widened (restarted work, readings out of order, stacked requests, stale timers, delivery, liveness) and run with steering on and off; a seam harness forces each driver ordering against the stand-in. --- apps/server/scripts/antigravity-mock-agent.ts | 79 ++- .../Layers/ProviderCommandReactor.test.ts | 10 +- .../Layers/ProviderCommandReactor.ts | 3 +- .../provider/Layers/ProviderService.test.ts | 47 +- .../src/provider/Layers/ProviderService.ts | 53 +- apps/server/src/provider/acp/AcpAdapter.ts | 359 +++++++++--- .../src/provider/acp/AcpProviderDescriptor.ts | 33 +- .../src/provider/acp/AcpSessionRuntime.ts | 123 +++- .../src/provider/acp/AcpTurnMachine.test.ts | 545 ++++++++++++++---- .../server/src/provider/acp/AcpTurnMachine.ts | 236 ++++++-- .../antigravity/AntigravityTurns.test.ts | 329 ++++++++++- .../provider/antigravity/AntigravityTurns.ts | 46 +- docs/providers/antigravity.md | 46 +- packages/contracts/src/provider.ts | 8 + packages/contracts/src/providerRuntime.ts | 11 +- 15 files changed, 1610 insertions(+), 318 deletions(-) diff --git a/apps/server/scripts/antigravity-mock-agent.ts b/apps/server/scripts/antigravity-mock-agent.ts index f0bccc60a..2ec72d669 100644 --- a/apps/server/scripts/antigravity-mock-agent.ts +++ b/apps/server/scripts/antigravity-mock-agent.ts @@ -29,6 +29,8 @@ * 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 @@ -42,6 +44,13 @@ * - `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. + * - `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. @@ -248,6 +257,24 @@ const program = Effect.gen(function* () { }; }), ); + // 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 }) => @@ -333,7 +360,8 @@ const program = Effect.gen(function* () { if ( scenario === "steer" || scenario === "steer-log-error" || - scenario === "steer-late-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]]); @@ -349,8 +377,16 @@ const program = Effect.gen(function* () { 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 { @@ -643,9 +679,48 @@ const program = Effect.gen(function* () { }).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 }; + return { + stopReason: "end_turn" as const, + usage: { inputTokens: 10, outputTokens: 3, totalTokens: 13 }, + }; }), ); diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts index 13faa5dab..1d582c46a 100644 --- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts +++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts @@ -1721,7 +1721,10 @@ describe("ProviderCommandReactor", () => { ); }); - it("keeps the history owed while a send goes as the agent's own command, without it", async () => { + it.each([ + ["goes as the agent's own command, without it", { contextDeferred: true as const }], + ["never reaches the agent (its setup failed)", { undelivered: true as const }], + ])("keeps the history owed while a send %s", async (_, outcome) => { const harness = await createHarness(); const now = "2026-01-01T00:00:00.000Z"; const turnStart = (id: string, text: string) => @@ -1760,12 +1763,13 @@ describe("ProviderCommandReactor", () => { ); await waitFor(() => harness.startSession.mock.calls.length === 2); - // The agent ran it as its own command and sent none of the context. + // None of the context went: the agent ran it as its own command, or + // the prompt was never written. harness.sendTurn.mockImplementationOnce(() => Effect.succeed({ threadId: ThreadId.make("thread-1"), turnId: asTurnId("turn-2"), - contextDeferred: true as const, + ...outcome, }), ); await turnStart("2", "/compact"); diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts index a917a8a57..67cf3a600 100644 --- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts +++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts @@ -3768,7 +3768,8 @@ const make = Effect.gen(function* () { // context in front of it: every debt it was to pay stays. Effect.tap((turn) => Effect.suspend(() => { - contextDeferred = turn.contextDeferred === true; + // Or its prompt never went out (`undelivered`): nothing was paid. + contextDeferred = turn.contextDeferred === true || turn.undelivered === true; return contextDeferred ? historyDebtReturned : historyDebtPaid; }), ), diff --git a/apps/server/src/provider/Layers/ProviderService.test.ts b/apps/server/src/provider/Layers/ProviderService.test.ts index 440073c29..6549dbfff 100644 --- a/apps/server/src/provider/Layers/ProviderService.test.ts +++ b/apps/server/src/provider/Layers/ProviderService.test.ts @@ -3580,7 +3580,10 @@ startingOver.layer("ProviderServiceLive forgetting a conversation", (it) => { providerInstanceId: instanceId, threadId: key, createdAt: "2026-01-01T00:00:00.000Z", - payload: { exitKind: "graceful", conversationLost: true }, + payload: { + exitKind: "graceful", + conversationLost: { sessionId: "session-lost", resumeCursor: first.resumeCursor }, + }, }); for (let attempt = 0; attempt < 100; attempt += 1) { const binding = Option.getOrUndefined(yield* directory.getBinding(key)); @@ -3593,4 +3596,46 @@ startingOver.layer("ProviderServiceLive forgetting a conversation", (it) => { assert.isTrue(reopened.resumeFailed); }), ); + + it.effect("keeps a conversation started since when a lost one's exit comes late", () => + Effect.gen(function* () { + const directory = yield* ProviderSessionDirectory; + const key = asThreadId("thread-conversation-lost-late"); + const first = yield* start(key); + yield* advanceTestClock(10); + // A new conversation took the binding before the old one's exit was heard. + const replacement = { schemaVersion: 1, sessionId: "replacement", history: [] }; + yield* directory.upsert({ + threadId: key, + provider: startingOver.ANTIGRAVITY, + providerInstanceId: instanceId, + resumeCursor: replacement, + }); + const lostExit = (eventId: string, sessionId: string) => + startingOver.agent.emit({ + type: "session.exited", + eventId: asEventId(eventId), + provider: startingOver.ANTIGRAVITY, + providerInstanceId: instanceId, + threadId: key, + createdAt: "2026-01-01T00:00:00.000Z", + payload: { exitKind: "graceful", conversationLost: { sessionId } }, + }); + const cursorNow = Effect.map( + directory.getBinding(key), + (binding) => Option.getOrUndefined(binding)?.resumeCursor ?? null, + ); + lostExit("evt-lost-late", "lost"); + for (let attempt = 0; attempt < 20; attempt += 1) yield* advanceTestClock(5); + assert.deepEqual(yield* cursorNow, replacement); + // The exit of the conversation the binding holds does forget it, though + // its cursor moved on since (a later turn's history). + lostExit("evt-lost-current", "replacement"); + for (let attempt = 0; attempt < 100; attempt += 1) { + if ((yield* cursorNow) === null) break; + yield* advanceTestClock(5); + } + assert.equal(yield* cursorNow, null); + }), + ); }); diff --git a/apps/server/src/provider/Layers/ProviderService.ts b/apps/server/src/provider/Layers/ProviderService.ts index df3f7fb59..d0e57ddc4 100644 --- a/apps/server/src/provider/Layers/ProviderService.ts +++ b/apps/server/src/provider/Layers/ProviderService.ts @@ -142,6 +142,43 @@ const ProviderClearThreadGoalServiceInput = Schema.Struct({ * canonical copy is left out. Reply text and tool output pieces are kept: a * reply cut off mid-stream may have no whole copy anywhere. */ +/** + * Whether a saved resume cursor is the lost session's: by the session id in + * it when the cursor carries one (`sessionId`, as ACP's do; the rest of the + * cursor moves on with every turn), else the whole cursor. + */ +function cursorPointsAt( + cursor: unknown, + lost: { readonly sessionId: string; readonly resumeCursor?: unknown }, +): boolean { + if (typeof cursor === "object" && cursor !== null && "sessionId" in cursor) { + return cursor.sessionId === lost.sessionId; + } + return "resumeCursor" in lost && sameJsonValue(cursor, lost.resumeCursor ?? null); +} + +/** Two JSON values (resume cursors) are the same, whatever their keys' order. */ +function sameJsonValue(left: unknown, right: unknown): boolean { + if (left === right) return true; + if (typeof left !== "object" || typeof right !== "object" || left === null || right === null) { + return false; + } + if (Array.isArray(left) !== Array.isArray(right)) return false; + const leftKeys = Object.keys(left); + const rightKeys = Object.keys(right); + return ( + leftKeys.length === rightKeys.length && + leftKeys.every( + (key) => + Object.hasOwn(right, key) && + sameJsonValue( + (left as Record)[key], + (right as Record)[key], + ), + ) + ); +} + function isCanonicalStreamFragment(event: ProviderRuntimeEvent): boolean { return ( event.type === "content.delta" && @@ -722,8 +759,9 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( // 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 === true - ? forgetConversation(canonicalEvent.threadId) + canonicalEvent.type === "session.exited" && + canonicalEvent.payload.conversationLost !== undefined + ? forgetConversation(canonicalEvent.threadId, canonicalEvent.payload.conversationLost) : Effect.void, ), Effect.flatMap((canonicalEvent) => @@ -2931,10 +2969,19 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( * readPersistedHistoryOwed): its cursor goes and the history is owed. * False when the binding couldn't be written; the agent then remembers. */ - const forgetConversation = (threadId: ThreadId) => + /** + * Drops the thread's saved conversation, so the next start opens a new + * one seeded with its history. With `lost`, only while the binding still + * points at that session: a conversation started since is not the lost one. + */ + const forgetConversation = ( + threadId: ThreadId, + lost?: { readonly sessionId: string; readonly resumeCursor?: unknown }, + ) => Effect.gen(function* () { const binding = Option.getOrUndefined(yield* directory.getBinding(threadId)); if (binding === undefined) return true; + if (lost !== undefined && !cursorPointsAt(binding.resumeCursor ?? null, lost)) return true; yield* directory.upsert({ threadId, provider: binding.provider, diff --git a/apps/server/src/provider/acp/AcpAdapter.ts b/apps/server/src/provider/acp/AcpAdapter.ts index bae2cdeec..ffa91300a 100644 --- a/apps/server/src/provider/acp/AcpAdapter.ts +++ b/apps/server/src/provider/acp/AcpAdapter.ts @@ -54,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"; @@ -185,6 +186,14 @@ const ACP_OUTCOME_CHECK_TIMEOUT = Duration.seconds(10); * 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 @@ -227,6 +236,8 @@ export interface AcpAdapterOptions { ) => 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 { @@ -377,6 +388,10 @@ interface AcpMachinePrompt { 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. */ @@ -416,10 +431,37 @@ interface AcpMachineSession { } >; readonly timers: Map>; - /** Counts what the agent did, so a quiet timer knows the quiet was real. */ - activity: number; + /** 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"]>; + } + /** 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 } + /** 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"; @@ -1212,7 +1254,7 @@ export function makeAcpAdapter( newTurnId: crypto.randomUUID(), }); } else { - machine.activity += 1; + yield* noteActivity(machine); } return earlier ?? ctx.activeTurnId; } @@ -1323,7 +1365,9 @@ export function makeAcpAdapter( const stopSessionInternal = ( ctx: AcpSessionContext, exitKind: "graceful" | "error" = "graceful", - exit?: { readonly conversationLost?: true }, + exit?: { + readonly conversationLost?: { readonly sessionId: string; readonly resumeCursor?: unknown }; + }, ) => Effect.gen(function* () { if (ctx.stopped) return; @@ -1335,14 +1379,31 @@ export function makeAcpAdapter( 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); } - // The reader is gone, so this is the one place left to step the - // machine: the open turn ends, and every waiting send hears back. - const machine = ctx.machine; if (machine !== undefined) { - yield* applyTurnEvent(ctx, { type: "sessionStopping" }); + // 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" }); @@ -2183,7 +2244,8 @@ export function makeAcpAdapter( prompts: new Map(), turns: new Map(), timers: new Map(), - activity: 0, + lastActivityMs: yield* Clock.currentTimeMillis, + outbox: yield* Queue.unbounded(), }, stopped: false, }; @@ -2202,6 +2264,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* applyTurnEvent(ctx, { type: "promptAnswered", prompt: event.key }); + return; + } case "SessionStatus": if (event.message === ctx.lastProviderStatus) { return; @@ -2268,7 +2341,7 @@ export function makeAcpAdapter( // Work whose updates show nothing new still counts (a // timer's "Running schedule" stays as it started). if (ctx.machine !== undefined) { - ctx.machine.activity += 1; + yield* noteActivity(ctx.machine); yield* trackMachineWork(ctx, event.toolCall); } // A launch approved earlier completes with nothing new to show. @@ -2424,6 +2497,9 @@ 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. @@ -2658,20 +2734,42 @@ export function makeAcpAdapter( event.type !== "outcomeRead" && event.type !== "promptDispatched"; - /** Steps the machine with one event, on the event reader, and runs its commands. */ + /** 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.gen(function* () { - const machine = ctx.machine; - if (machine === undefined) return []; - if (isAgentActivity(event)) machine.activity += 1; - const step = stepTurnMachine(machine.state, event); - machine.state = step.state; - for (const command of step.commands) yield* runTurnCommand(ctx, machine, command); - return step.commands; - }); + 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), + }); + for (const command of step.commands) yield* runTurnCommand(ctx, machine, command); + return step.commands; + }), + ); /** A request the agent made was answered (or given up on): quiet limits may run again. */ const closeMachineRequest = (ctx: AcpSessionContext | undefined) => @@ -2709,9 +2807,9 @@ export function makeAcpAdapter( }); /** - * Arms one of the machine's timers. A quiet timer fires only after so - * long without the agent doing anything: activity while it waits starts - * it over, so the machine hears it fire only when the quiet was real. + * 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, @@ -2720,47 +2818,70 @@ export function makeAcpAdapter( generation: number, ): Effect.Effect => Effect.gen(function* () { - const seen = machine.activity; - const wait = + 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 - : quietLimit(timer); - const fiber = yield* Effect.sleep(wait).pipe( - Effect.andThen( - ctx.acp.inOrder( - Effect.suspend(() => { - const armed = machine.state.timers.find(([name]) => name === timer); - if (armed?.[1] !== generation) return Effect.void; - return timer !== "cancelDeadline" && - timer !== "noticeExpiry" && - machine.activity !== seen - ? armTurnTimer(ctx, machine, timer, generation) - : applyTurnEvent(ctx, { type: "timerFired", timer, generation }).pipe( - Effect.asVoid, - ); - }), + : 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 }); + }), + ), ), - ), - Effect.forkIn(ctx.scope), - ); - machine.timers.set(timer, fiber); + ); + machine.timers.set(timer, yield* wait(limitMs).pipe(Effect.forkIn(ctx.scope))); }); - /** One prompt of a machine turn: the turn's configuration first, then the prompt. */ - const runMachinePrompt = ( + /** + * 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, - sent: AcpMachinePromptSent, ) => 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. - const watch = + sent.watch = machineOptions?.outcome === undefined ? undefined : yield* machineOptions.outcome.watch(ctx.acpSessionId, sent.model).pipe( @@ -2771,19 +2892,25 @@ export function makeAcpAdapter( }).pipe(Effect.as(undefined)), ), ); - sent.watch = watch; - yield* postTurnEvent(ctx, { type: "promptDispatched", prompt }); const promptMeta = descriptor.promptMeta?.(sent.turnId); - return yield* ctx.acp.prompt({ - prompt: [...sent.parts], - ...(promptMeta ? { _meta: { ...promptMeta } } : {}), - }); + yield* ctx.acp.promptInOrder( + prompt, + { + prompt: [...sent.parts], + ...(promptMeta ? { _meta: { ...promptMeta } } : {}), + }, + seam({ point: "answerRead", prompt }), + ); }), ); // A stopping session ends the turn itself. - if (Exit.isFailure(exit) && Cause.hasInterruptsOnly(exit.cause)) return; - sent.exit = exit; - yield* postTurnEvent(ctx, { type: "promptAnswered", prompt }); + if (Exit.isSuccess(exit) || Cause.hasInterruptsOnly(exit.cause)) return; + yield* ctx.acp.inOrder( + Effect.suspend(() => { + sent.exit = Exit.failCause(exit.cause); + return applyTurnEvent(ctx, { type: "promptAnswered", prompt }); + }).pipe(Effect.asVoid), + ); }); /** @@ -2904,9 +3031,22 @@ export function makeAcpAdapter( exit: undefined, }; machine.prompts.set(command.prompt, sent); - yield* runMachinePrompt(ctx, machine, command.prompt, sent).pipe( - Effect.forkIn(ctx.scope), - ); + 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": @@ -2929,7 +3069,8 @@ export function makeAcpAdapter( const sent = machine.prompts.get(command.prompt); if (sent === undefined) return; const seen = { turnText: ctx.activeTurnText, providerStatus: ctx.lastProviderStatus }; - yield* readMachineOutcome(ctx, sent, seen).pipe( + 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 }), ), @@ -2938,31 +3079,39 @@ export function makeAcpAdapter( return; } case "readChildren": { - // The agent's own records, off the reader and bounded; a reading - // that can't say leaves the protocol count standing. - const read = machineOptions?.childrenAtWork; - if (read === undefined) return; - yield* read(ctx.acpSessionId).pipe( + // 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.flatMap((children) => - children === undefined - ? Effect.void - : postTurnEvent(ctx, { - type: "childrenAtWork", - running: children.running, - known: children.known, - }), - ), + 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 "rebaseOutcome": { - const watch = machine.prompts.get(command.prompt)?.watch; - if (watch !== undefined) yield* watch.rebase.pipe(Effect.ignore); - return; - } case "recordUsage": { const sent = machine.prompts.get(command.prompt); if (sent === undefined) return; @@ -3006,11 +3155,19 @@ export function makeAcpAdapter( yield* stopFromMachine(ctx, "graceful"); return; case "stopSession": - // A lost conversation: ProviderService forgets it in the thread's binding. + // 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: true } : undefined, + command.reason === "sessionLost" + ? { + conversationLost: { + sessionId: ctx.acpSessionId, + resumeCursor: ctx.session.resumeCursor, + }, + } + : undefined, ); return; case "markSessionLost": @@ -3026,7 +3183,9 @@ export function makeAcpAdapter( const stopFromMachine = ( ctx: AcpSessionContext, exitKind: "graceful" | "error", - exit?: { readonly conversationLost?: true }, + exit?: { + readonly conversationLost?: { readonly sessionId: string; readonly resumeCursor?: unknown }; + }, ) => withThreadLock( ctx.threadId, @@ -3174,13 +3333,23 @@ export function makeAcpAdapter( 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, @@ -3188,6 +3357,7 @@ export function makeAcpAdapter( }); if (ctx.stopped) { machine.callers.delete(sendId); + keepContext(); return yield* new ProviderAdapterSessionNotFoundError({ provider: PROVIDER, threadId: input.threadId, @@ -3196,18 +3366,22 @@ export function makeAcpAdapter( yield* postTurnEvent(ctx, { type: "send", sendId, turnId }); const answer = yield* Deferred.await(reply); if ("rejected" in answer) { - if (ctx.projectBriefCarrier?.turnId === turnId) requeueProjectBrief(ctx); + keepContext(); return yield* new ProviderAdapterSessionNotFoundError({ provider: PROVIDER, threadId: input.threadId, }); } + // The result says whether the prompt was written: only then did the + // agent get the message and the context in front of it. + 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 }), }; }); @@ -3233,7 +3407,14 @@ export function makeAcpAdapter( const reply = yield* Deferred.make(); const steerId = `steer:${crypto.randomUUID()}`; machine.callers.set(steerId, { - prompt: { parts, configure: undefined, model: undefined, resolvedModel: undefined }, + prompt: { + parts, + configure: undefined, + model: undefined, + resolvedModel: undefined, + preamble: undefined, + delivered: undefined, + }, planMode: undefined, reply, }); @@ -3670,7 +3851,7 @@ export function makeAcpAdapter( ); return { threadId: input.threadId, turnId, resumeCursor: ctx.session.resumeCursor }; }) - : descriptor.turnMachine !== undefined + : descriptor.turnMachine?.steer === true ? steerTurnByMachine : undefined; @@ -3800,7 +3981,9 @@ export function makeAcpAdapter( // 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)); + 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* () { @@ -3896,7 +4079,7 @@ export function makeAcpAdapter( capabilities: { sessionModelSwitch: "in-session", conversationRollback: descriptor.rollbackByNewSession ? "new-session" : "none", - ...(descriptor.steer || descriptor.turnMachine + ...(descriptor.steer || descriptor.turnMachine?.steer === true ? { activeTurnSteering: "supported" as const } : {}), ...(descriptor.conversationHistory ? { nativeThreadFork: "supported" as const } : {}), diff --git a/apps/server/src/provider/acp/AcpProviderDescriptor.ts b/apps/server/src/provider/acp/AcpProviderDescriptor.ts index 3cf6a250d..aa0bfbf57 100644 --- a/apps/server/src/provider/acp/AcpProviderDescriptor.ts +++ b/apps/server/src/provider/acp/AcpProviderDescriptor.ts @@ -201,12 +201,6 @@ export interface AcpPromptOutcomeWatch { /** What `session/prompt` failed with, usually an `AcpRequestError`. */ | { readonly error: unknown }, ) => Effect.Effect; - /** - * An older prompt of the turn answered after this one went out: what the - * agent recorded until now was the older prompt's, so the check reads - * only what comes after. - */ - readonly rebase: Effect.Effect; } /** @@ -222,13 +216,18 @@ export type AcpWorkAfterPrompt = * 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; a message - * sent mid-turn goes as another `session/prompt`, which steers the turn. - * 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. + * 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 @@ -243,16 +242,6 @@ export interface AcpTurnMachineOptions { readonly replyQuietLimit?: Duration.Duration; /** How a prompt really ended, where the agent's answer can hide a failure. */ readonly outcome?: AcpPromptOutcome; - /** - * How many of the session's subagents are still at work, by the agent's - * own records, and how many children the records know of at all; - * `undefined` when they can't say. The hold then covers exactly the - * children still running; without it, each report the agent wakes to give - * frees one launched subagent. Never fails. - */ - readonly childrenAtWork?: ( - sessionId: string, - ) => Effect.Effect<{ readonly running: number; readonly known: number } | undefined>; } /** A subagent a tool call launched, as the launch named it. */ @@ -273,8 +262,8 @@ export interface AcpSubagentState { * 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`). It - * plays no part in how long a turn is held (`turnMachine.childrenAtWork` does). + * 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. */ diff --git a/apps/server/src/provider/acp/AcpSessionRuntime.ts b/apps/server/src/provider/acp/AcpSessionRuntime.ts index 0e44e3e23..7989eeff8 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"; @@ -287,6 +288,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, @@ -327,6 +345,19 @@ export interface AcpSessionCancellationNotice { 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"; @@ -338,7 +369,9 @@ export type AcpSessionRuntimeEvent = | AcpSessionEventStreamBarrier | AcpSessionInOrderWork | AcpSessionToolCallTracked - | AcpSessionCancellationNotice; + | AcpSessionCancellationNotice + | AcpSessionPromptSent + | AcpSessionPromptAnswered; /** Upper bound on waiting for the reader; a dead consumer must not wedge a turn. */ const EVENT_FLUSH_TIMEOUT = "5 seconds"; @@ -1083,6 +1116,90 @@ const makeAcpSessionRuntime = ( }); }), ), + 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({ @@ -1356,6 +1473,8 @@ const ensureActiveAssistantSegment = ({ ), ); +const decodePromptResponse = Schema.decodeUnknownExit(EffectAcpSchema.PromptResponse); + const closeActiveAssistantSegment = ({ queue, assistantSegmentRef, diff --git a/apps/server/src/provider/acp/AcpTurnMachine.test.ts b/apps/server/src/provider/acp/AcpTurnMachine.test.ts index c14d4b978..116ce03be 100644 --- a/apps/server/src/provider/acp/AcpTurnMachine.test.ts +++ b/apps/server/src/provider/acp/AcpTurnMachine.test.ts @@ -1,3 +1,6 @@ +// @effect-diagnostics nodeBuiltinImport:off -- the explorer hashes its seen states. +import { createHash } from "node:crypto"; + import { describe, expect, it } from "vite-plus/test"; import { @@ -34,9 +37,20 @@ interface Monitor { readonly unansweredCallers: ReadonlyArray; /** `readOutcome` commands whose `outcomeRead` hasn't come back. */ readonly reads: ReadonlyArray; - readonly workUsed: ReadonlyArray; - readonly launched: boolean; - readonly childrenReported: boolean; + /** 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 { @@ -54,20 +68,33 @@ const initialWorld: World = { closed: [], unansweredCallers: [], reads: [], - workUsed: [], - launched: false, - childrenReported: false, + workStarts: 0, + launches: 0, + childReads: [], + stopAsked: false, + prompts: [], + written: [], + reported: [], }, }; -/** Every event the adapter could produce next, with small bounded domains. */ -function possibleEvents(world: World): ReadonlyArray { +/** 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 (monitor.steers < 2) { + if (steer && monitor.steers < 2) { const steerId = `t${monitor.steers + 1}`; if (state.turn !== undefined) { events.push({ type: "steer", steerId, expectedTurnId: state.turn.id }); @@ -84,28 +111,53 @@ function possibleEvents(world: World): ReadonlyArray { { type: "outcomeRead", prompt, outcome: outcome("failed", true) }, ); } - if (!monitor.workUsed.includes("c1")) - events.push({ type: "workStarted", id: "c1", kind: "command" }); - if (!monitor.workUsed.includes("w1")) - events.push({ type: "workStarted", id: "w1", kind: "timer" }); - for (const [id] of state.running) { - events.push({ type: "workEnded", id }, { type: "workDropped", id }); + // 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] }); } - if (!monitor.launched) events.push({ type: "subagentsLaunched", id: "l1", count: 2 }); - // The records: none running, one running, or a reading that missed a launch. - if (monitor.launched && !monitor.childrenReported) { + // 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", running: 0, known: state.launchedTotal }, - { type: "childrenAtWork", running: 1, known: state.launchedTotal }, - { type: "childrenAtWork", running: 0, known: 0 }, + { + 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 === 0 ? [{ type: "requestOpened" as const, newTurnId }] : []), + ...(state.requestsOpen < 2 ? [{ type: "requestOpened" as const, newTurnId }] : []), ); } else if (state.turn !== undefined) { events.push({ type: "agentOutput", newTurnId }, { type: "cancellationNotice", newTurnId }); @@ -113,8 +165,10 @@ function possibleEvents(world: World): ReadonlyArray { 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; @@ -128,6 +182,8 @@ function check(condition: boolean, message: string, trail: ReadonlyArray) } } +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; @@ -142,13 +198,51 @@ function advance(world: World, event: Event, trail: ReadonlyArray): World const caller = event.type === "send" ? event.sendId : event.steerId; monitor = { ...monitor, unansweredCallers: [...monitor.unansweredCallers, caller] }; } - if (event.type === "workStarted") - monitor = { ...monitor, workUsed: [...monitor.workUsed, event.id] }; - if (event.type === "subagentsLaunched") monitor = { ...monitor, launched: true }; - if (event.type === "childrenAtWork") monitor = { ...monitor, childrenReported: true }; + 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 prompt whose setup failed was not reported undelivered", + 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) { @@ -156,6 +250,11 @@ function advance(world: World, event: Event, trail: ReadonlyArray): World 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 }; @@ -198,7 +297,33 @@ function advance(world: World, event: Event, trail: ReadonlyArray): World 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 counted as delivered" + : "a written prompt counted as undelivered", + 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; @@ -239,14 +364,27 @@ function advance(world: World, event: Event, trail: ReadonlyArray): World "the armed timers are not the ones the state needs", trail, ); - // Stop always has a deadline armed until the turn ends. - if (state.turn?.stopRequested === true) { + // 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( @@ -262,7 +400,13 @@ function advance(world: World, event: Event, trail: ReadonlyArray): World } } // A notice owed by a cancel is expected only until its expiry fires. - if (event.type === "timerFired" && event.timer === "noticeExpiry") { + 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) { @@ -280,6 +424,7 @@ function advance(world: World, event: Event, trail: ReadonlyArray): World 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); @@ -293,33 +438,87 @@ function callersSettled(world: World): boolean { return world.monitor.unansweredCallers.every((caller) => waiting.has(caller)); } -/** Breadth-first over every event sequence up to `depth`, skipping states already seen. */ -function explore(depth: number): { - readonly states: number; - readonly worlds: ReadonlyArray; -} { +/** + * 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: [] }, ]; - const all: Array = [initialWorld]; + 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)) { + 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); - const key = JSON.stringify(advanced); + // 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); - all.push(advanced); - next.push({ world: advanced, trail: nextTrail }); + visit(advanced); + if (level < depth - 1) next.push({ world: advanced, trail: nextTrail }); } } frontier = next; } - return { states: seen.size, worlds: all }; + return seen.size; } /** Runs events from a fresh machine, returning every command in order and the last state. */ @@ -343,57 +542,91 @@ const fire = (state: State, timer: AcpTurnTimer): Event => { const ends = (commands: ReadonlyArray) => commands.flatMap((command) => (command.type === "endTurn" ? [command] : [])); -describe("AcpTurnMachine, every reachable state", () => { - // Depth 10 reaches every race below (the longest takes 10 events): about - // 2.3 million distinct states, under a minute. The alphabet is bounded to - // two sends, two steers, one command, one timer, one batch of two - // subagents, one reading of the child records (none running, one running, - // or one that missed a launch) and two turns of the agent's own. - const { states, worlds } = explore(10); - - it("explores a state space large enough to mean something", () => { - expect(states).toBeGreaterThan(1_000_000); - }); - - it("reaches a terminal event from every Stop through the deadline alone", () => { - for (const world of worlds) { - const turn = world.state.turn; - if (turn?.stopRequested !== true) continue; - const step = stepTurnMachine(world.state, fire(world.state, "cancelDeadline")); - expect(ends(step.commands).map((end) => end.turnId)).toEqual([turn.id]); - expect(step.commands.some((command) => command.type === "recycleAgent")).toBe(true); - } - }); - - it("ends every open turn exactly once when the session stops or the agent exits", () => { - for (const world of worlds) { - for (const type of ["sessionStopping", "processExited"] as const) { - if (type === "processExited" && world.state.ended) continue; - const step = stepTurnMachine(world.state, { type }); - const ended = ends(step.commands).map((end) => end.turnId); - expect(ended).toEqual(world.state.turn === undefined ? [] : [world.state.turn.id]); - expect(step.state.turn).toBeUndefined(); - expect(step.commands.some((command) => command.type === "startTurn")).toBe(false); +/** 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); +} + +describe.each([ + { steer: true, depth: 9 }, + { steer: false, depth: 10 }, +])("AcpTurnMachine, every reachable state (steering $steer)", ({ steer, depth }) => { + // 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. Depth 9 with steering (about 2.1 million + // states) and 10 without (about 2.6 million) take about three minutes; + // every named race below is shorter. + let checked = 0; + const states = explore(depth, steer, (world) => { + checkWorld(world, steer); + checked += 1; }); - it("ends a hold through timers alone once the agent's work is done", () => { - for (const world of worlds) { - const state = world.state; - if (state.turn?.phase.tag !== "waiting" || state.requestsOpen > 0) continue; - // Each quiet limit that can run, run in turn, ends the hold unless a timer the agent set still runs. - const heldId = state.turn.id; - let current = state; - for (let round = 0; round < 6 && current.turn?.id === heldId; round += 1) { - const armed = current.timers.find(([timer]) => timer !== "cancelDeadline"); - 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); - } + it("explores a state space large enough to mean something", () => { + expect(states).toBeGreaterThan(1_000_000); + expect(checked).toBe(states + 1); }); }); @@ -481,6 +714,13 @@ describe("AcpTurnMachine, the reviewed races", () => { { 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, @@ -489,19 +729,25 @@ describe("AcpTurnMachine, the reviewed races", () => { ]); // One reply: the protocol count alone would still hold one subagent. expect(state.subagents).toBe(1); - expect(commands).toContainEqual({ type: "readChildren" }); - const read = stepTurnMachine(state, { type: "childrenAtWork", running: 0, known: 2 }); + 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 { state } = run([...holdingTwo, { type: "childrenAtWork", running: 0, known: 2 }]); + 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 missed = run([...holdingTwo, { type: "childrenAtWork", running: 0, known: 1 }]); + 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. @@ -513,6 +759,113 @@ describe("AcpTurnMachine, the reviewed races", () => { 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" }, @@ -546,6 +899,7 @@ describe("AcpTurnMachine, the reviewed races", () => { 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)", () => { @@ -591,13 +945,4 @@ describe("AcpTurnMachine, the reviewed races", () => { expect(state.turn?.newest).toBe(2); expect(state.turn?.phase.tag).toBe("prompting"); }); - - it("an older prompt answering after a steer moves the newer one's outcome reading on", () => { - const { commands } = run([ - { type: "send", sendId: "s1", turnId: "u1" }, - { type: "steer", steerId: "t1", expectedTurnId: "u1" }, - { type: "promptAnswered", prompt: 1 }, - ]); - expect(commands).toContainEqual({ type: "rebaseOutcome", prompt: 2 }); - }); }); diff --git a/apps/server/src/provider/acp/AcpTurnMachine.ts b/apps/server/src/provider/acp/AcpTurnMachine.ts index 0819a4f00..ea145bf98 100644 --- a/apps/server/src/provider/acp/AcpTurnMachine.ts +++ b/apps/server/src/provider/acp/AcpTurnMachine.ts @@ -15,9 +15,14 @@ * * 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") restart on the - * agent's activity in the adapter; the machine only arms, disarms and hears - * them fire. + * 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 */ @@ -38,7 +43,9 @@ export type AcpTurnTimer = /** 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"; + | "noticeExpiry" + /** A stop waits on subagents: their records are read again. */ + | "stopCheck"; export const ACP_TURN_TIMERS: ReadonlyArray = [ "cancelDeadline", @@ -46,6 +53,7 @@ export const ACP_TURN_TIMERS: ReadonlyArray = [ "replyQuiet", "silent", "noticeExpiry", + "stopCheck", ]; /** How a prompt's answer reads, once the adapter has checked it. `answer` is the adapter's own. */ @@ -89,24 +97,38 @@ export interface AcpTurnMachineState { readonly nextPrompt: number; /** Prompts sent and not answered yet, of any turn. */ readonly unanswered: ReadonlyArray; - /** Prompts whose fiber hasn't reported sending them yet. */ + /** 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. */ + /** 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; - /** Every subagent the session's launches started. */ - readonly launchedTotal: number; /** - * The children still at work by the agent's own records, and how many - * children those records knew of, once a reading covered every launch: - * then the hold follows the records, not the protocol count. + * 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 children: { readonly running: number; readonly known: number } | undefined; + 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. */ @@ -124,9 +146,12 @@ export type AcpTurnEvent = | { 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's fiber is sending it now. */ + /** A prompt was written to the agent. */ | { readonly type: "promptDispatched"; readonly prompt: number } - /** A prompt answered or failed. Placed after every update it produced. */ + /** + * 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`). */ | { @@ -140,10 +165,15 @@ export type AcpTurnEvent = | { readonly type: "workDropped"; readonly id: string } | { readonly type: "subagentsLaunched"; readonly id: string; readonly count: number } /** - * The agent's own records say `running` children are still at work, of - * `known` children they know of (`readChildren`). + * 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 running: number; readonly known: number } + | { + 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. */ @@ -168,6 +198,12 @@ export type AcpTurnCommand = 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 } | { @@ -177,17 +213,19 @@ export type AcpTurnCommand = } /** Read how the prompt really ended, then report `outcomeRead`. */ | { readonly type: "readOutcome"; readonly prompt: number } - /** An older prompt answered after this one went out: its outcome reads only from here on. */ - | { readonly type: "rebaseOutcome"; readonly prompt: number } - /** Read which children are still at work, then report `childrenAtWork` (if the records say). */ - | { readonly type: "readChildren" } + /** 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. */ + /** 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" } @@ -209,9 +247,11 @@ export function initialTurnMachineState(): AcpTurnMachineState { queue: [], running: [], launches: [], + held: [], subagents: 0, - launchedTotal: 0, children: undefined, + childRead: { generation: 0, launches: [] }, + stopping: undefined, replyOpen: false, wakesOwed: 0, requestsOpen: 0, @@ -221,14 +261,19 @@ export function initialTurnMachineState(): AcpTurnMachineState { }; } +/** 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 launch (plus any launched since), else the protocol count. + * every held launch (any launched since counting in full), else the + * protocol count. */ export function subagentsOut(state: AcpTurnMachineState): number { - const children = state.children; - if (children === undefined) return state.subagents; - return children.running + Math.max(0, state.launchedTotal - children.known); + 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. */ @@ -244,8 +289,9 @@ export function desiredTimers(state: AcpTurnMachineState): ReadonlyArra 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; - if (turn.stopRequested) timers.push("cancelDeadline"); 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)) { @@ -276,6 +322,7 @@ export function stepTurnMachine( const clearWork = () => { state.running = []; + state.held = []; state.subagents = 0; // Back to counting by protocol until the records are read again. state.children = undefined; @@ -283,6 +330,42 @@ export function stepTurnMachine( 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; @@ -311,7 +394,7 @@ export function stepTurnMachine( * the agent's to answer and holds nothing up. */ const startQueued = () => { - if (state.ended || state.turn !== undefined) return; + if (state.ended || state.turn !== undefined || state.stopping !== undefined) return; const [next, ...rest] = state.queue; if (next === undefined) return; state.queue = rest; @@ -337,7 +420,13 @@ export function stepTurnMachine( 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. */ @@ -371,11 +460,19 @@ export function stepTurnMachine( readChildren(); }; - /** Asks for the records' count of children at work, when any were launched. */ + /** + * 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 && state.launchedTotal > 0 && subagentsOut(state) > 0) { - commands.push({ type: "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. */ @@ -429,6 +526,7 @@ export function stepTurnMachine( 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)) { @@ -439,7 +537,11 @@ export function stepTurnMachine( case "promptAnswered": { if (!state.unanswered.includes(event.prompt)) break; state.unanswered = state.unanswered.filter((prompt) => prompt !== event.prompt); - state.undispatched = state.undispatched.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) { @@ -447,13 +549,6 @@ export function stepTurnMachine( state.turn = { ...turn, phase: { tag: "settling" } }; commands.push({ type: "readOutcome", prompt: event.prompt }); readChildren(); - } else if ( - turn.prompts.includes(event.prompt) && - turn.newest !== undefined && - state.unanswered.includes(turn.newest) - ) { - // What the older prompt left in the agent's records is its own. - commands.push({ type: "rebaseOutcome", prompt: turn.newest }); } } break; @@ -476,7 +571,7 @@ export function stepTurnMachine( break; } if (turn.stopRequested) { - clearWork(); + stopWork(); endTurn(end); break; } @@ -496,6 +591,16 @@ export function stepTurnMachine( 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. @@ -504,20 +609,42 @@ export function stepTurnMachine( } 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; - state.launchedTotal += event.count; break; } case "childrenAtWork": { - // A reading that misses a launch (its record not written yet) proves - // nothing about it: the count stands as it was. - if (event.known >= state.launchedTotal) { - state.children = { running: Math.max(0, event.running), known: event.known }; + // 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; } @@ -553,7 +680,7 @@ export function stepTurnMachine( if (!state.ended && turn === undefined && workPending(state)) { commands.push({ type: "sendCancel" }); state.noticesExpected += 1; - clearWork(); + stopWork(); break; } if (state.ended || turn === undefined || turn.stopRequested) break; @@ -561,8 +688,9 @@ export function stepTurnMachine( // 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 cancel stops the agent's work, and the turn ends now. - clearWork(); + // 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; } @@ -575,12 +703,16 @@ export function stepTurnMachine( state.timers = state.timers.filter(([timer]) => timer !== event.timer); switch (event.timer) { case "cancelDeadline": - if (state.turn?.stopRequested === true) { - commands.push({ type: "recycleAgent" }); + 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. diff --git a/apps/server/src/provider/antigravity/AntigravityTurns.test.ts b/apps/server/src/provider/antigravity/AntigravityTurns.test.ts index a14b36846..758a9ec4d 100644 --- a/apps/server/src/provider/antigravity/AntigravityTurns.test.ts +++ b/apps/server/src/provider/antigravity/AntigravityTurns.test.ts @@ -12,6 +12,7 @@ import { type ChatAttachment, ProviderDriverKind, type ProviderRuntimeEvent, + type ThreadContextSeed, ThreadId, type TurnId, } from "@threadlines/contracts"; @@ -28,7 +29,7 @@ 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 { makeAcpAdapter } from "../acp/AcpAdapter.ts"; +import { type AcpTurnMachineSeam, makeAcpAdapter } from "../acp/AcpAdapter.ts"; import type { AcpToolCallState } from "../acp/AcpRuntimeModel.ts"; import { makeAntigravityDescriptor } from "../acp/AntigravityAcpSupport.ts"; import { @@ -80,7 +81,9 @@ type AgyDescriptor = ReturnType; const startAgy = ( scenario: string, adjust?: (descriptor: AgyDescriptor) => AgyDescriptor, - runtimeMode: "full-access" | "approval-required" = "full-access", + 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)); @@ -105,6 +108,7 @@ const startAgy = ( 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( @@ -120,6 +124,7 @@ const startAgy = ( provider: ProviderDriverKind.make("antigravity"), cwd: process.cwd(), runtimeMode, + ...(contextSeed !== undefined ? { contextSeed } : {}), }); const waitFor = ( predicate: (events: ReadonlyArray) => boolean, @@ -447,8 +452,10 @@ describe("Antigravity turns", () => { 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. + // It names the lost conversation: the agent's session id, as in its cursor. + const sessionId = (agy.session.resumeCursor as { readonly sessionId: string }).sessionId; expect(agy.events.find((event) => event.type === "session.exited")).toMatchObject({ - payload: { conversationLost: true }, + payload: { conversationLost: { sessionId } }, }); }).pipe(Effect.scoped, Effect.provide(testServices)), ); @@ -640,6 +647,31 @@ describe("Antigravity turns, the hard cases", () => { }).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"); + 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"); @@ -851,6 +883,297 @@ describe("Antigravity commands and edits", () => { ); }); +/** + * 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", undefined, "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("keeps the history for the next message when a send's mode setup fails", () => + 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" }], + }); + // Plan mode asks for the `default` mode: 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("queues a message sent mid-turn when steering is off", () => + Effect.gen(function* () { + const agy = yield* startAgy("background", (descriptor) => ({ + ...descriptor, + turnMachine: { ...descriptor.turnMachine!, steer: false }, + })); + 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", diff --git a/apps/server/src/provider/antigravity/AntigravityTurns.ts b/apps/server/src/provider/antigravity/AntigravityTurns.ts index 2fdaaecd0..956f54afb 100644 --- a/apps/server/src/provider/antigravity/AntigravityTurns.ts +++ b/apps/server/src/provider/antigravity/AntigravityTurns.ts @@ -34,7 +34,7 @@ import type { } from "../acp/AcpProviderDescriptor.ts"; import type { AcpToolCallState } from "../acp/AcpRuntimeModel.ts"; import { antigravityLogPosition, antigravityTurnSteps } from "./AntigravitySessionLog.ts"; -import { antigravityChildLaunches, readAntigravityChildren } from "./AntigravityChildRecords.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. */ @@ -45,6 +45,11 @@ const SCHEDULE_TITLES = new Set(["Run schedule", "Running schedule"]); * 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. + */ +export const ANTIGRAVITY_STEERS = true; const isRecord = (value: unknown): value is Record => typeof value === "object" && value !== null && !Array.isArray(value); @@ -236,23 +241,13 @@ export function antigravityTurnBehavior( ): 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). + // 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), - // Which children are still at work, by the CLI's own records. - childrenAtWork: (sessionId) => - readAntigravityChildren(profileDir, sessionId).pipe( - Effect.map((reading) => - reading.available - ? { - running: reading.running.length, - known: reading.running.length + reading.reported.length + reading.killed.length, - } - : undefined, - ), - ), }, usageLedger: { provider: "antigravity" }, turnUsageTotals: antigravityTurnUsageTotals, @@ -263,13 +258,14 @@ export function antigravityTurnBehavior( * 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. * - * A log step is the prompt's only if it is written after the prompt went - * out and after every older prompt of its turn answered: the CLI writes a - * prompt's steps before it answers it, and answers a steered prompt only - * once the steer arrives, so an older prompt's late error lands before its - * own answer and `rebase` moves past it. When the log can't say (it can't be - * read, or a step's prompt is in doubt), the prompt's own answer stands: the - * turn completes and the agent's own words about the error stay in its reply. + * 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, @@ -278,7 +274,7 @@ function antigravityPromptOutcome( return { watch: (sessionId, model) => Effect.gen(function* () { - let before = yield* antigravityLogPosition(profileDir, sessionId); + const before = yield* antigravityLogPosition(profileDir, sessionId); const withMeterReset = (failure: AcpPromptFailure | undefined) => failure?.usageLimit !== undefined && failure.usageLimit.resetsAt === undefined && @@ -288,10 +284,6 @@ function antigravityPromptOutcome( Effect.map((limit) => (limit ? { ...failure, usageLimit: limit } : failure)), ) : Effect.succeed(failure); - const rebase = Effect.gen(function* () { - const now = yield* antigravityLogPosition(profileDir, sessionId); - if (now !== undefined) before = before === undefined ? now : Math.max(before, now); - }); const check: AcpPromptOutcomeWatch["check"] = (answer) => Effect.gen(function* () { const nowMs = yield* Clock.currentTimeMillis; @@ -324,7 +316,7 @@ function antigravityPromptOutcome( }), ); }); - return { check, rebase }; + return { check }; }), }; } diff --git a/docs/providers/antigravity.md b/docs/providers/antigravity.md index ef2864966..e001db41d 100644 --- a/docs/providers/antigravity.md +++ b/docs/providers/antigravity.md @@ -143,30 +143,46 @@ set (`schedule`), or a subagent it launched. When that work ends, the agent wake 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). If the agent hasn't answered 15 seconds after Stop, Threadlines restarts it and the turn -ends cancelled; the next message picks the conversation up again. Stopping the session (or +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. A timer +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. When the -records can't be read, or name fewer subagents than were launched, each report (a reply no finished -command or timer woke) frees one subagent, and a batch launch counts each subagent in it. If the +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 works steers the turn instead of waiting: Threadlines sends it as another prompt, which the CLI takes into the running turn (1.5.0+), leaving its commands and -subagents running. The turn ends with the newest prompt's answer. +subagents running. The turn ends with the newest prompt's answer. Prompts reach the agent in the +order they were sent, the first one's mode and model setup included, so a steer never arrives ahead +of the message it steers. Steering is one switch (`ANTIGRAVITY_STEERS` in +`apps/server/src/provider/antigravity/AntigravityTurns.ts`); off, a message sent mid-turn waits for +the turn to end. All of this is one state machine (`apps/server/src/provider/acp/AcpTurnMachine.ts`), stepped in -order with the agent's updates; its test walks every sequence of up to ten events and checks that -each turn ends exactly once, Stop always has a deadline, and a hold with nothing left ends. +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 @@ -217,14 +233,18 @@ never through a link, up to each kind's limit and 50 MB inline per message. 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). A log step counts for a prompt only if it was written after that prompt went out and after every -older prompt of the turn answered; when the log can't say, 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 +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. +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 diff --git a/packages/contracts/src/provider.ts b/packages/contracts/src/provider.ts index fe36a1805..3ceff3c9a 100644 --- a/packages/contracts/src/provider.ts +++ b/packages/contracts/src/provider.ts @@ -423,6 +423,14 @@ export const ProviderTurnStartResult = Schema.Struct({ * 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. 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. + */ + undelivered: 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 3abd7298e..c5d527487 100644 --- a/packages/contracts/src/providerRuntime.ts +++ b/packages/contracts/src/providerRuntime.ts @@ -421,8 +421,17 @@ const SessionExitedPayload = Schema.Struct({ * 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 (ProviderService.forgetConversation). + * It names the conversation lost: the agent's own session id, and the + * resume cursor the session last had. The binding forgets only while it + * still points at that session, so a late exit never clears a + * conversation started since. */ - conversationLost: Schema.optional(Schema.Literal(true)), + conversationLost: Schema.optional( + Schema.Struct({ + sessionId: TrimmedNonEmptyStringSchema, + resumeCursor: Schema.optional(Schema.Unknown), + }), + ), }); export type SessionExitedPayload = typeof SessionExitedPayload.Type; From 4e95b2a91d5f24ca7c8111a50a8128393c9b1d67 Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Mon, 23 Nov 2026 11:23:16 -0500 Subject: [PATCH 48/59] test(acp): the explorer's state counts as measured --- apps/server/src/provider/acp/AcpTurnMachine.test.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/apps/server/src/provider/acp/AcpTurnMachine.test.ts b/apps/server/src/provider/acp/AcpTurnMachine.test.ts index 116ce03be..ce9932985 100644 --- a/apps/server/src/provider/acp/AcpTurnMachine.test.ts +++ b/apps/server/src/provider/acp/AcpTurnMachine.test.ts @@ -615,8 +615,8 @@ describe.each([ // 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. Depth 9 with steering (about 2.1 million - // states) and 10 without (about 2.6 million) take about three minutes; + // turns of the agent's own. Depth 9 with steering (about 2.6 million + // states) and 10 without (about 2.8 million) take under three minutes; // every named race below is shorter. let checked = 0; const states = explore(depth, steer, (world) => { From 19c911c26837703b7311da2eb5ac809e5b05ef42 Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Mon, 23 Nov 2026 12:05:04 -0500 Subject: [PATCH 49/59] test(acp): the turn machine explorer runs at depth 8 by default, full depths on request ACP_EXPLORER_FULL=1 runs depth 9 with steering and 10 without (about 2.6 and 2.8 million states, two and a half minutes, 2.5 GB). The default, 8 and 8, covers about 720,000 and 290,000 states in 22 seconds and 0.55 GB. --- .../src/provider/acp/AcpTurnMachine.test.ts | 43 +++++++++++++++---- 1 file changed, 35 insertions(+), 8 deletions(-) diff --git a/apps/server/src/provider/acp/AcpTurnMachine.test.ts b/apps/server/src/provider/acp/AcpTurnMachine.test.ts index 822fada51..afd06b4fa 100644 --- a/apps/server/src/provider/acp/AcpTurnMachine.test.ts +++ b/apps/server/src/provider/acp/AcpTurnMachine.test.ts @@ -1,4 +1,13 @@ // @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"; @@ -605,19 +614,37 @@ function checkWorld(world: World, steer: boolean): void { if (world.monitor.unansweredCallers.length > 0) drain(world, steer); } -describe.each([ - { steer: true, depth: 9 }, - { steer: false, depth: 10 }, -])("AcpTurnMachine, every reachable state (steering $steer)", ({ steer, depth }) => { +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. Depth 9 with steering (about 2.6 million - // states) and 10 without (about 2.8 million) take under three minutes; - // every named race below is shorter. + // 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); @@ -625,7 +652,7 @@ describe.each([ }); it("explores a state space large enough to mean something", () => { - expect(states).toBeGreaterThan(1_000_000); + expect(states).toBeGreaterThan(atLeast); expect(checked).toBe(states + 1); }); }); From 0a411b8c5e56314986259f35a8be8366b00a3269 Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Mon, 23 Nov 2026 12:05:04 -0500 Subject: [PATCH 50/59] fix(antigravity): history counts as delivered only by the send's own result A machine agent's send returns once its prompt is written, or its setup failed or the session stopped first; the result then says undelivered. The reactor keeps every debt (the history, a fork's summarized source, the binding's historyOwed mark) when a send is undelivered or went as the agent's own command. turnDispatched is gone from the adapter and service contracts; other agents' sends already return after the write. Also tested: an approval asked again during a held turn keeps it open until answered, a real call_mcp_tool call holds nothing once normalized, and a lost-session exit still forgets after the runtime's cursor moved on. --- apps/server/scripts/antigravity-mock-agent.ts | 44 ++++++++++ .../Layers/CheckpointReactor.test.ts | 1 - .../Layers/ProviderCommandReactor.test.ts | 15 ++-- .../Layers/ProviderCommandReactor.ts | 29 +++---- .../Layers/ProviderRuntimeIngestion.test.ts | 1 - .../provider/Layers/ProviderService.test.ts | 7 ++ .../src/provider/Layers/ProviderService.ts | 18 ---- .../Layers/ProviderSessionReaper.test.ts | 1 - .../src/provider/Services/ProviderAdapter.ts | 13 --- .../src/provider/Services/ProviderService.ts | 15 +--- apps/server/src/provider/acp/AcpAdapter.ts | 47 ++-------- .../antigravity/AntigravityTurns.test.ts | 86 +++++++++++++++---- packages/contracts/src/provider.ts | 10 +++ 13 files changed, 156 insertions(+), 131 deletions(-) diff --git a/apps/server/scripts/antigravity-mock-agent.ts b/apps/server/scripts/antigravity-mock-agent.ts index 6201f00e7..2d65d8fb2 100644 --- a/apps/server/scripts/antigravity-mock-agent.ts +++ b/apps/server/scripts/antigravity-mock-agent.ts @@ -58,6 +58,8 @@ * - `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. * - `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 @@ -821,6 +823,48 @@ const program = Effect.gen(function* () { }).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" || diff --git a/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts b/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts index fb7ba37c9..9b0d2126b 100644 --- a/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts +++ b/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts @@ -165,7 +165,6 @@ function createProviderServiceHarness( forgetNativeSession: () => Effect.void, dropResumeCursor: () => Effect.void, noteHistoryDelivered: () => Effect.void, - turnDispatched: () => Effect.succeed(true), getCapabilities: () => Effect.succeed({ sessionModelSwitch: "in-session", diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts index 54b5dbf2e..e2498733b 100644 --- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts +++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts @@ -457,10 +457,6 @@ describe("ProviderCommandReactor", () => { const noteHistoryDelivered = vi.fn( () => Effect.void, ); - // Every accepted turn has gone out to the agent unless a test says otherwise. - const turnDispatched = vi.fn(() => - Effect.succeed(true), - ); const renameBranch = vi.fn((input: unknown) => Effect.succeed({ branch: @@ -584,7 +580,6 @@ describe("ProviderCommandReactor", () => { forgetNativeSession: () => Effect.void, dropResumeCursor, noteHistoryDelivered, - turnDispatched, getCapabilities: (_provider) => Effect.succeed({ sessionModelSwitch: input?.sessionModelSwitch ?? "in-session", @@ -839,7 +834,6 @@ describe("ProviderCommandReactor", () => { stopSession, dropResumeCursor, noteHistoryDelivered, - turnDispatched, renameBranch, refreshStatus, refreshLocalStatus, @@ -1766,10 +1760,15 @@ describe("ProviderCommandReactor", () => { await waitFor(() => harness.startSession.mock.calls.length === 2); // Accepted, but the agent never got the prompt (its configuration failed). - harness.turnDispatched.mockImplementationOnce(() => Effect.succeed(false)); + 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 waitFor(() => harness.turnDispatched.mock.calls.length === 2); await Effect.runPromise(Effect.sleep("50 millis")); expect(harness.noteHistoryDelivered).not.toHaveBeenCalled(); diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts index 3af21afc6..9936b542d 100644 --- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts +++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts @@ -3783,7 +3783,7 @@ 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; - // The send went as the agent's own command, without its context. + // None of the context in front of the message went (see below). let contextDeferred = false; yield* providerService .sendTurn({ @@ -3806,27 +3806,18 @@ const make = Effect.gen(function* () { providerTookTurn = true; }), ), - // A send that went as the agent's own command carried none of the - // context in front of it: every debt it was to pay stays. // The history and a fork's summary count as delivered only once - // the prompt carrying them went out to the agent, not when the send - // was accepted (an agent configures its session first, and that can - // fail). Settled on its own, so the turn's bookkeeping doesn't wait. + // 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; - if (contextDeferred) return historyDebtReturned; - return providerService - .turnDispatched({ threadId: turnRequest.threadId, turnId: turn.turnId }) - .pipe( - Effect.flatMap((wentOut) => - wentOut - ? Effect.andThen(historyDebtPaid, contextDelivered) - : historyDebtReturned, - ), - Effect.forkScoped, - Effect.asVoid, - ); + contextDeferred = turn.contextDeferred === true || turn.undelivered === true; + return contextDeferred + ? historyDebtReturned + : Effect.andThen(historyDebtPaid, contextDelivered); }), ), Effect.onError(() => historyDebtReturned), diff --git a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts index a4b6c0b3f..1e1901e21 100644 --- a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts +++ b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts @@ -166,7 +166,6 @@ function createProviderServiceHarness() { ? Effect.die(new Error("the session would not stop")) : Effect.sync(() => void droppedCursors.push(threadId)), noteHistoryDelivered: () => Effect.void, - turnDispatched: () => Effect.succeed(true), getCapabilities: () => Effect.succeed({ sessionModelSwitch: "in-session" }), getInstanceInfo: (instanceId) => { const driverKind = ProviderDriverKind.make(String(instanceId)); diff --git a/apps/server/src/provider/Layers/ProviderService.test.ts b/apps/server/src/provider/Layers/ProviderService.test.ts index 226185f77..6cea20177 100644 --- a/apps/server/src/provider/Layers/ProviderService.test.ts +++ b/apps/server/src/provider/Layers/ProviderService.test.ts @@ -3667,6 +3667,13 @@ startingOver.layer("ProviderServiceLive forgetting a conversation", (it) => { 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"), diff --git a/apps/server/src/provider/Layers/ProviderService.ts b/apps/server/src/provider/Layers/ProviderService.ts index 78ea9ecd5..f7658efda 100644 --- a/apps/server/src/provider/Layers/ProviderService.ts +++ b/apps/server/src/provider/Layers/ProviderService.ts @@ -3043,23 +3043,6 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( }); }).pipe(Effect.ignoreCause({ log: true })); - const turnDispatched: ProviderServiceShape["turnDispatched"] = ({ threadId, turnId }) => - Effect.gen(function* () { - const binding = Option.getOrUndefined(yield* directory.getBinding(threadId)); - if (binding?.providerInstanceId === undefined) return false; - const adapter = yield* registry.getByInstance(binding.providerInstanceId); - const dispatched = adapter.turnDispatched; - // Without the signal, an accepted send has already gone out. - return dispatched === undefined ? true : yield* dispatched(threadId, turnId); - }).pipe( - Effect.catchCause((cause) => - Effect.logWarning("provider service could not tell whether a turn went out", { - threadId, - cause: Cause.pretty(cause), - }).pipe(Effect.as(false)), - ), - ); - /** * 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 @@ -3559,7 +3542,6 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( forgetNativeSession, dropResumeCursor, noteHistoryDelivered, - turnDispatched, getCapabilities, getInstanceInfo, rollbackConversation, diff --git a/apps/server/src/provider/Layers/ProviderSessionReaper.test.ts b/apps/server/src/provider/Layers/ProviderSessionReaper.test.ts index 863d8707c..321ed5672 100644 --- a/apps/server/src/provider/Layers/ProviderSessionReaper.test.ts +++ b/apps/server/src/provider/Layers/ProviderSessionReaper.test.ts @@ -255,7 +255,6 @@ describe("ProviderSessionReaper", () => { forgetNativeSession: () => Effect.void, dropResumeCursor: () => Effect.void, noteHistoryDelivered: () => Effect.void, - turnDispatched: () => Effect.succeed(true), 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 4ef9a2dd4..3ce47ae73 100644 --- a/apps/server/src/provider/Services/ProviderAdapter.ts +++ b/apps/server/src/provider/Services/ProviderAdapter.ts @@ -231,19 +231,6 @@ export interface ProviderAdapterShape { readonly expectedCwd: string; }) => Effect.Effect; - /** - * Whether the first prompt of a turn `sendTurn` accepted went out to the - * agent: true once it was written to the agent (after the session was - * configured for it), false once it is known it never will be (the - * configuration failed, the session stopped, the turn was stopped first) - * or the adapter knows no such turn. Context that prompt carried (the - * thread's history, a handoff preamble) counts as delivered only on true; - * an adapter that holds such context itself keeps it for the next prompt - * on false. Absent: `sendTurn` returns only after the prompt was written, - * so an accepted turn has gone out. - */ - readonly turnDispatched?: (threadId: ThreadId, turnId: TurnId) => Effect.Effect; - /** * Send a turn to an active provider session. */ diff --git a/apps/server/src/provider/Services/ProviderService.ts b/apps/server/src/provider/Services/ProviderService.ts index 53adead1d..7338fb346 100644 --- a/apps/server/src/provider/Services/ProviderService.ts +++ b/apps/server/src/provider/Services/ProviderService.ts @@ -37,7 +37,6 @@ import type { RuntimeThreadGoalSnapshot, ThreadGoalStatus, ThreadId, - TurnId, ProviderSubagentInputRequest, ProviderSubagentInputResult, ProviderCommandOutputInput, @@ -390,7 +389,8 @@ export interface ProviderServiceShape { /** * 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 (`turnDispatched`). Its + * (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. @@ -400,17 +400,6 @@ export interface ProviderServiceShape { readonly sessionCreatedAt: string; }) => Effect.Effect; - /** - * Whether the first prompt of a turn `sendTurn` accepted went out to the - * agent (see ProviderAdapterShape.turnDispatched): what context that - * prompt carried is delivered only on true. Never fails; false when the - * turn's agent can't be found. - */ - readonly turnDispatched: (input: { - readonly threadId: ThreadId; - readonly turnId: TurnId; - }) => Effect.Effect; - /** * Read capabilities for the adapter bound to a configured provider instance. */ diff --git a/apps/server/src/provider/acp/AcpAdapter.ts b/apps/server/src/provider/acp/AcpAdapter.ts index c9674185c..ff62f1c43 100644 --- a/apps/server/src/provider/acp/AcpAdapter.ts +++ b/apps/server/src/provider/acp/AcpAdapter.ts @@ -196,8 +196,6 @@ const ACP_STOP_CHECK_INTERVAL = Duration.seconds(1); * The reader never waits on I/O, so this is only a guard against a bug. */ const ACP_STOP_DRAIN_LIMIT = Duration.seconds(5); -/** How many machine sends' dispatch answers an adapter keeps (`turnDispatched`). */ -const ACP_DISPATCH_MEMORY = 256; /** * The most turns a resume cursor remembers the agent's prompt positions for * (see `conversationHistory`); a revert further back trims Threadlines' turn @@ -3424,8 +3422,6 @@ export function makeAcpAdapter( } if (ctx.projectBriefCarrier?.turnId === turnId) requeueProjectBrief(ctx); }; - // Whether its prompt goes out is asked later (`turnDispatched`). - noteDispatch(ctx.threadId, turnId, delivered); machine.callers.set(sendId, { prompt: { parts: prepared.promptParts, @@ -3442,7 +3438,6 @@ export function makeAcpAdapter( if (ctx.stopped) { machine.callers.delete(sendId); keepContext(); - yield* Deferred.succeed(delivered, false); return yield* new ProviderAdapterSessionNotFoundError({ provider: PROVIDER, threadId: input.threadId, @@ -3452,55 +3447,25 @@ export function makeAcpAdapter( const answer = yield* Deferred.await(reply); if ("rejected" in answer) { keepContext(); - yield* Deferred.succeed(delivered, false); return yield* new ProviderAdapterSessionNotFoundError({ provider: PROVIDER, threadId: input.threadId, }); } + // 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 }), }; }); - /** - * Whether each machine send's prompt was written to the agent, by thread - * and turn, kept past the session's end for a caller that asks late. The - * oldest go once there are more than `ACP_DISPATCH_MEMORY`. - */ - const dispatches = new Map>(); - const dispatchKey = (threadId: ThreadId, turnId: TurnId) => `${threadId}\u0000${turnId}`; - const noteDispatch = ( - threadId: ThreadId, - turnId: TurnId, - written: Deferred.Deferred, - ) => { - dispatches.set(dispatchKey(threadId, turnId), written); - while (dispatches.size > ACP_DISPATCH_MEMORY) { - const oldest = dispatches.keys().next().value; - if (oldest === undefined) break; - dispatches.delete(oldest); - } - }; - - /** - * `ProviderAdapterShape.turnDispatched` for machine agents: true once the - * turn's first prompt was written (after its mode and model setup), false - * once it never will be (the setup failed, the session or the turn - * stopped first) or for a turn this adapter doesn't know. A session's - * stop settles every one still open, so it never hangs. On false, the - * context preamble the send took is pending again (`reportDelivery`). - */ - const turnDispatched = (threadId: ThreadId, turnId: TurnId): Effect.Effect => - Effect.suspend(() => { - const written = dispatches.get(dispatchKey(threadId, turnId)); - return written === undefined ? Effect.succeed(false) : Deferred.await(written); - }); - /** A message sent mid-turn to a machine agent: another prompt of the running turn. */ const steerTurnByMachine: NonNullable = (input) => Effect.gen(function* () { @@ -4203,8 +4168,6 @@ export function makeAcpAdapter( }, startSession, sendTurn, - // Machine sends return once taken: whether the prompt went out comes later. - ...(descriptor.turnMachine !== undefined ? { turnDispatched } : {}), ...(steerTurn ? { steerTurn } : {}), interruptTurn, readThread, diff --git a/apps/server/src/provider/antigravity/AntigravityTurns.test.ts b/apps/server/src/provider/antigravity/AntigravityTurns.test.ts index cc0d1f55b..bf1db2655 100644 --- a/apps/server/src/provider/antigravity/AntigravityTurns.test.ts +++ b/apps/server/src/provider/antigravity/AntigravityTurns.test.ts @@ -38,6 +38,7 @@ import { antigravityTurnUsageTotals, antigravityWorkAfterPrompt, } from "./AntigravityTurns.ts"; +import { normalizeAntigravityToolCall } from "./AntigravityToolCalls.ts"; const decodeSettings = Schema.decodeSync(AntigravitySettings); const mockAgentPath = path.join( @@ -1105,7 +1106,7 @@ describe("Antigravity turn driver, the orderings", () => { ); it.live( - "reports a send whose mode setup failed undispatched, keeping its history for the next", + "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, { @@ -1121,7 +1122,7 @@ describe("Antigravity turn driver, the orderings", () => { interactionMode: "plan", attachments: [], }); - expect(yield* agy.adapter.turnDispatched!(agy.threadId, first.turnId)).toBe(false); + expect(first.undelivered).toBe(true); yield* agy.waitFor((events) => completedTurns(events).length === 1); expect(completedTurns(agy.events)[0]?.payload.state).toBe("failed"); const prompts = () => @@ -1138,7 +1139,7 @@ describe("Antigravity turn driver, the orderings", () => { interactionMode: "plan", attachments: [], }); - expect(yield* agy.adapter.turnDispatched!(agy.threadId, second.turnId)).toBe(true); + expect(second.undelivered).toBeUndefined(); yield* agy.waitFor((events) => completedTurns(events).length === 2); const sent = yield* prompts(); expect(sent).toHaveLength(1); @@ -1148,29 +1149,63 @@ describe("Antigravity turn driver, the orderings", () => { ); it.live( - "answers undispatched, never hanging, when the session stops before the prompt goes out", + "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); - const { turnId } = yield* agy.adapter.sendTurn({ - threadId: agy.threadId, - input: "hi", - attachments: [], - }); + // 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; - const asked = yield* agy.adapter.turnDispatched!(agy.threadId, turnId).pipe( - Effect.forkScoped, - ); yield* agy.adapter.stopSession(agy.threadId); - expect(yield* Fiber.join(asked)).toBe(false); - // A turn this adapter never took is not dispatched either. - expect(yield* agy.adapter.turnDispatched!(agy.threadId, "unknown" as TurnId)).toBe(false); + 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("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 when steering is off", () => Effect.gen(function* () { const agy = yield* startAgy("background", (descriptor) => ({ @@ -1208,6 +1243,27 @@ describe("Antigravity turn reading", () => { ...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( diff --git a/packages/contracts/src/provider.ts b/packages/contracts/src/provider.ts index 59976d29b..1e401de59 100644 --- a/packages/contracts/src/provider.ts +++ b/packages/contracts/src/provider.ts @@ -418,6 +418,16 @@ export const ProviderTurnStartResult = Schema.Struct({ * 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)), }); export type ProviderTurnStartResult = typeof ProviderTurnStartResult.Type; From 1ad06d36ef6923d2e25c4cadd7a3091e375630a4 Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Mon, 23 Nov 2026 12:33:03 -0500 Subject: [PATCH 51/59] fix(acp): an open approval is asked again when what it would authorize changes An approval was re-asked only when its words or title changed. An edit whose replacement text changed under the same title and path read the same, so the original request id stayed answerable for the changed edit. The session runtime could also drop such an update before the approval saw it, since it showed nothing new on the row. An approval is now tied to the call's substance (toolCallSubstance: kind, row type, command, the paths it names, its input, and each diff's old and new text). The adapter asks the runtime for ToolCallRevised, an unseen event for an update that changes only that substance, and an open approval whose substance changed is withdrawn and asked again as before. This is the shared ACP path and reaches every ACP agent; the runtime emits the event only when asked, so its own event stream is unchanged. --- apps/server/scripts/antigravity-mock-agent.ts | 34 +++++++++++++++++++ apps/server/src/provider/acp/AcpAdapter.ts | 14 +++++++- .../src/provider/acp/AcpRuntimeModel.ts | 30 ++++++++++++++++ .../src/provider/acp/AcpSessionRuntime.ts | 29 ++++++++++++++++ .../antigravity/AntigravityTurns.test.ts | 33 ++++++++++++++++++ 5 files changed, 139 insertions(+), 1 deletion(-) diff --git a/apps/server/scripts/antigravity-mock-agent.ts b/apps/server/scripts/antigravity-mock-agent.ts index 2d65d8fb2..e5ad2cf93 100644 --- a/apps/server/scripts/antigravity-mock-agent.ts +++ b/apps/server/scripts/antigravity-mock-agent.ts @@ -46,6 +46,8 @@ * 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. It writes no subagent records. * - `records-one-reply`: as `subagent-records`, but both children report @@ -366,6 +368,38 @@ const program = Effect.gen(function* () { 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-permission") { const plan = join(profileDir ?? "", "antigravity-acp", "brain", sessionId, "plan.md"); const options = [ diff --git a/apps/server/src/provider/acp/AcpAdapter.ts b/apps/server/src/provider/acp/AcpAdapter.ts index ff62f1c43..7dcde170b 100644 --- a/apps/server/src/provider/acp/AcpAdapter.ts +++ b/apps/server/src/provider/acp/AcpAdapter.ts @@ -138,6 +138,7 @@ import { acpTurnUsageTotals, describePermissionRequest, mergeToolCallState, + toolCallSubstance, parsePermissionRequest, } from "./AcpRuntimeModel.ts"; import { THREADLINES_ACP_CLIENT_INFO } from "./acpClientInfo.ts"; @@ -1241,8 +1242,11 @@ export function makeAcpAdapter( ...(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; + next.detail === current.detail && + next.toolCall?.title === current.toolCall?.title && + toolCallSubstance(next.toolCall) === toolCallSubstance(current.toolCall); return same ? undefined : next; }; @@ -1791,6 +1795,8 @@ export function makeAcpAdapter( runtimeMode: input.runtimeMode, ...(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), @@ -2420,6 +2426,12 @@ 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). diff --git a/apps/server/src/provider/acp/AcpRuntimeModel.ts b/apps/server/src/provider/acp/AcpRuntimeModel.ts index 579b261c4..f491b3b2b 100644 --- a/apps/server/src/provider/acp/AcpRuntimeModel.ts +++ b/apps/server/src/provider/acp/AcpRuntimeModel.ts @@ -626,6 +626,36 @@ export function parsePermissionRequest( 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, diff --git a/apps/server/src/provider/acp/AcpSessionRuntime.ts b/apps/server/src/provider/acp/AcpSessionRuntime.ts index e5d51e637..08d5b44e3 100644 --- a/apps/server/src/provider/acp/AcpSessionRuntime.ts +++ b/apps/server/src/provider/acp/AcpSessionRuntime.ts @@ -28,6 +28,7 @@ import { LEGACY_MODE_OPTION_ID, legacyControlConfigOptions, mergeToolCallState, + toolCallSubstance, parseSessionModeState, parseSessionUpdateEvent, type AcpParsedSessionEvent, @@ -167,6 +168,12 @@ export interface AcpSessionRuntimeOptions { * 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 @@ -344,6 +351,16 @@ export interface AcpSessionToolCallTracked { 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"; @@ -375,6 +392,7 @@ export type AcpSessionRuntimeEvent = | AcpSessionEventStreamBarrier | AcpSessionInOrderWork | AcpSessionToolCallTracked + | AcpSessionToolCallRevised | AcpSessionCancellationNotice | AcpSessionPromptSent | AcpSessionPromptAnswered; @@ -633,6 +651,7 @@ const makeAcpSessionRuntime = ( ...(nativeControls ? { configOptionsRef } : {}), ...(options.normalizeToolCall ? { normalizeToolCall: options.normalizeToolCall } : {}), ...(options.trackSilentToolCalls ? { trackSilentToolCalls: true } : {}), + ...(options.reportRevisedToolCalls ? { reportRevisedToolCalls: true } : {}), ...(options.cancellationNotice !== undefined ? { cancellationNotice: options.cancellationNotice } : {}), @@ -1310,6 +1329,7 @@ const handleSessionUpdate = ({ configOptionsRef, normalizeToolCall, trackSilentToolCalls, + reportRevisedToolCalls, cancellationNotice, }: { readonly queue: Queue.Queue; @@ -1330,6 +1350,12 @@ const handleSessionUpdate = ({ 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* () { @@ -1381,6 +1407,9 @@ const handleSessionUpdate = ({ 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, { diff --git a/apps/server/src/provider/antigravity/AntigravityTurns.test.ts b/apps/server/src/provider/antigravity/AntigravityTurns.test.ts index bf1db2655..3b329d215 100644 --- a/apps/server/src/provider/antigravity/AntigravityTurns.test.ts +++ b/apps/server/src/provider/antigravity/AntigravityTurns.test.ts @@ -1556,6 +1556,39 @@ describe("Antigravity tool rows and attachments", () => { }).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("approves only an edit of the plan file itself without asking", () => Effect.gen(function* () { const agy = yield* startAgy("plan-file-permission", undefined, "approval-required"); From c0bb127eca62873be69c763489127e44233d8ea6 Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Mon, 23 Nov 2026 12:34:47 -0500 Subject: [PATCH 52/59] fix(antigravity): the plan exemption covers only the asking session's own plan.md The exemption accepted a plan.md in any session folder under the profile's brain, so one session could write another's plan without asking, and it trimmed paths before comparing, so "plan.md " passed on POSIX. isPlanFile now gets the asking session (the adapter passes its own session id only when the request comes from that session) and compares every path the call names, as given, with exactly brain//plan.md. --- apps/server/scripts/antigravity-mock-agent.ts | 31 ++++++++++++++- apps/server/src/provider/acp/AcpAdapter.ts | 11 +++++- .../src/provider/acp/AcpProviderDescriptor.ts | 10 +++-- .../src/provider/acp/AntigravityAcpSupport.ts | 38 +++++++++++-------- .../antigravity/AntigravityTurns.test.ts | 23 +++++++++++ 5 files changed, 91 insertions(+), 22 deletions(-) diff --git a/apps/server/scripts/antigravity-mock-agent.ts b/apps/server/scripts/antigravity-mock-agent.ts index e5ad2cf93..73245a56c 100644 --- a/apps/server/scripts/antigravity-mock-agent.ts +++ b/apps/server/scripts/antigravity-mock-agent.ts @@ -49,7 +49,9 @@ * - `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. It writes no subagent records. + * 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 @@ -400,6 +402,33 @@ const program = Effect.gen(function* () { 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 = [ diff --git a/apps/server/src/provider/acp/AcpAdapter.ts b/apps/server/src/provider/acp/AcpAdapter.ts index 7dcde170b..e795f786e 100644 --- a/apps/server/src/provider/acp/AcpAdapter.ts +++ b/apps/server/src/provider/acp/AcpAdapter.ts @@ -2057,7 +2057,14 @@ export function makeAcpAdapter( ); 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, @@ -2527,7 +2534,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; diff --git a/apps/server/src/provider/acp/AcpProviderDescriptor.ts b/apps/server/src/provider/acp/AcpProviderDescriptor.ts index aa0bfbf57..c12546f27 100644 --- a/apps/server/src/provider/acp/AcpProviderDescriptor.ts +++ b/apps/server/src/provider/acp/AcpProviderDescriptor.ts @@ -92,11 +92,13 @@ 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; } diff --git a/apps/server/src/provider/acp/AntigravityAcpSupport.ts b/apps/server/src/provider/acp/AntigravityAcpSupport.ts index 7ba8163d3..842a88b35 100644 --- a/apps/server/src/provider/acp/AntigravityAcpSupport.ts +++ b/apps/server/src/provider/acp/AntigravityAcpSupport.ts @@ -34,7 +34,7 @@ import { spawn as spawnChild } from "node:child_process"; import { existsSync } from "node:fs"; import * as fs from "node:fs/promises"; import { homedir, tmpdir } from "node:os"; -import { isAbsolute, join, normalize, relative, resolve as resolvePath, sep } from "node:path"; +import { isAbsolute, join, normalize, resolve as resolvePath } from "node:path"; import { createInterface } from "node:readline"; import { @@ -495,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) { @@ -522,15 +523,24 @@ const brainDir = (profileDir: string) => join(profileDir, "antigravity-acp", "br /** 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 the agent writing its own plan, and nothing else: - * an edit whose every change is a diff of a `plan.md` directly in one of the - * session folders under the profile's `brain` (`/plan` writes - * `brain//plan.md`), with no command about it. Such a write is - * approved without asking and shows as the plan card, so a call that runs - * anything, or touches any other file, never passes. + * 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): boolean { +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 ( @@ -540,11 +550,8 @@ export function isAntigravityPlanFileEdit(toolCall: AcpToolCallState, brain: str ) { return false; } - const isPlanPath = (path: string) => { - if (!isAbsolute(path)) return false; - const parts = relative(brain, normalize(path)).split(sep); - return parts.length === 2 && parts[0] !== ".." && parts[0] !== "" && parts[1] === "plan.md"; - }; + const planPath = join(brain, sessionId, "plan.md"); + const isPlanPath = (path: string) => isAbsolute(path) && normalize(path) === planPath; // Every change is a diff, and every path the call names (diffs, // locations, its target) is the plan file. const diffsOnly = @@ -872,7 +879,8 @@ export function makeAntigravityDescriptor( ...antigravityTurnBehavior(paths.profileDir, usage?.usageLimitFor), planMode: { promptPrefix: "/plan ", - isPlanFile: (toolCall) => isAntigravityPlanFileEdit(toolCall, 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; diff --git a/apps/server/src/provider/antigravity/AntigravityTurns.test.ts b/apps/server/src/provider/antigravity/AntigravityTurns.test.ts index 3b329d215..26864b354 100644 --- a/apps/server/src/provider/antigravity/AntigravityTurns.test.ts +++ b/apps/server/src/provider/antigravity/AntigravityTurns.test.ts @@ -1589,6 +1589,29 @@ describe("Antigravity tool rows and attachments", () => { }).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"); From 9a80412b2bebd0c959334a7fee605c6a927bd252 Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Mon, 23 Nov 2026 12:46:07 -0500 Subject: [PATCH 53/59] fix(antigravity): a revert waits for the agent's process, and late runtime writes can't touch a replacement - A revert on an agent that starts over now waits until the agent's process is gone (new adapter hook whenStopped), not just until hasSession stops reporting it. A wait past 20 seconds ends the runtime and waits once more; if it still won't go, the revert fails without restoring files. A capability lookup that fails also fails the revert without restoring. - History acknowledgements and lost-session forgets check the runtime and write in one statement (ProviderSessionDirectory.patchIfSession), so a replacement persisted between the check and the write keeps its debt and its resume cursor. - A send that had to reopen its runtime, where the conversation couldn't be resumed, marks the binding historyOwed and returns historyOwed on its result; the reactor records the debt, so the next message carries the history. The message already prepared still goes out. --- .../Layers/CheckpointReactor.test.ts | 63 ++++++- .../orchestration/Layers/CheckpointReactor.ts | 32 +++- .../Layers/ProviderCommandReactor.test.ts | 37 +++++ .../Layers/ProviderCommandReactor.ts | 16 ++ .../Layers/ProviderSessionRuntime.ts | 24 +++ .../Services/ProviderSessionRuntime.ts | 21 +++ .../src/provider/Layers/CodexAdapter.test.ts | 1 + .../provider/Layers/ProviderService.test.ts | 155 +++++++++++++++++- .../src/provider/Layers/ProviderService.ts | 96 ++++++----- .../Layers/ProviderSessionDirectory.test.ts | 50 +++++- .../Layers/ProviderSessionDirectory.ts | 9 + .../src/provider/Services/ProviderAdapter.ts | 9 + .../Services/ProviderSessionDirectory.ts | 13 ++ packages/contracts/src/provider.ts | 7 + 14 files changed, 480 insertions(+), 53 deletions(-) diff --git a/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts b/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts index 9b0d2126b..8ab4183ff 100644 --- a/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts +++ b/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts @@ -96,6 +96,7 @@ function createProviderServiceHarness( 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()); @@ -166,10 +167,18 @@ function createProviderServiceHarness( dropResumeCursor: () => Effect.void, noteHistoryDelivered: () => Effect.void, getCapabilities: () => - Effect.succeed({ - sessionModelSwitch: "in-session", - ...(conversationRollback !== undefined ? { conversationRollback } : {}), - }), + 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, @@ -375,6 +384,7 @@ describe("CheckpointReactor", () => { readonly extraProviderSessions?: ReadonlyArray; readonly gitStatusRefreshCalls?: Array; readonly conversationRollback?: "native" | "none" | "new-session"; + readonly capabilitiesFail?: boolean; }) { const cwd = createGitRepository(); tempDirs.push(cwd); @@ -403,6 +413,7 @@ describe("CheckpointReactor", () => { options?.providerName ?? ProviderDriverKind.make("codex"), extraProviderSessions, options?.conversationRollback, + options?.capabilitiesFail === true, ); const orchestrationLayer = OrchestrationEngineLive.pipe( Layer.provide(OrchestrationProjectionSnapshotQueryLive), @@ -3121,6 +3132,50 @@ describe("CheckpointReactor", () => { ); }); + it("restores nothing when it can't tell whether the agent still runs", 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, + }), + ); + const thread = await waitForThread(harness.readModel, (entry) => + entry.activities.some((activity) => activity.kind === "checkpoint.revert.failed"), + ); + const detail = ( + thread.activities.find((activity) => activity.kind === "checkpoint.revert.failed") + ?.payload as { readonly detail?: string } | undefined + )?.detail; + expect(detail).toContain("no file was restored"); + expect(harness.provider.rollbackConversation).not.toHaveBeenCalled(); + expect( + fs.readFileSync(path.join(harness.cwd, "README.md"), "utf8").replaceAll("\r\n", "\n"), + ).toBe("v3\n"); + }); + it.each([ { case: "the agent can't be stopped", stopFails: true }, { case: "the files can't be restored after it forgot", stopFails: false }, diff --git a/apps/server/src/orchestration/Layers/CheckpointReactor.ts b/apps/server/src/orchestration/Layers/CheckpointReactor.ts index 7353cef5a..b395952a8 100644 --- a/apps/server/src/orchestration/Layers/CheckpointReactor.ts +++ b/apps/server/src/orchestration/Layers/CheckpointReactor.ts @@ -1231,16 +1231,30 @@ const make = Effect.gen(function* () { // 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. + // An agent whose capabilities can't be read may be one of those, and + // may still be running: the revert fails and restores nothing. + const capabilities = + rolledBackTurns > 0 + ? yield* Effect.result( + providerService.getCapabilities( + context.thread.session?.providerInstanceId ?? + context.thread.modelSelection.instanceId, + ), + ) + : undefined; + if (capabilities?._tag === "Failure") { + yield* Effect.logWarning("checkpoint revert could not read the agent's capabilities", { + threadId: event.payload.threadId, + cause: String(capabilities.failure), + }); + yield* failRevert( + "Threadlines couldn't check whether the agent still runs, so no file was restored. Try again.", + ); + return; + } const startsOver = - rolledBackTurns > 0 && - (yield* providerService - .getCapabilities( - context.thread.session?.providerInstanceId ?? context.thread.modelSelection.instanceId, - ) - .pipe( - Effect.map((capabilities) => capabilities.conversationRollback === "new-session"), - Effect.orElseSucceed(() => false), - )); + 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 diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts index d8ac96706..656f0aea3 100644 --- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts +++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts @@ -1788,6 +1788,43 @@ describe("ProviderCommandReactor", () => { }); }); + 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"; diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts index 33e4529bb..4ae3b1b16 100644 --- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts +++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts @@ -3031,6 +3031,18 @@ const make = Effect.gen(function* () { }), // 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: owedSeed === undefined @@ -3748,6 +3760,7 @@ const make = Effect.gen(function* () { historyDebtPaid, historyDebtReturned, contextDelivered, + historyOwedAfterSend, notesDelivered, } = sendTurnRequest.value; @@ -3825,6 +3838,9 @@ const make = Effect.gen(function* () { }), ), 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)), ), 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/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/ProviderService.test.ts b/apps/server/src/provider/Layers/ProviderService.test.ts index 6cea20177..fe90828ed 100644 --- a/apps/server/src/provider/Layers/ProviderService.test.ts +++ b/apps/server/src/provider/Layers/ProviderService.test.ts @@ -3452,14 +3452,39 @@ fence.layer("ProviderServiceLive moving threads", (it) => { 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 = ProviderSessionDirectoryLive.pipe(Layer.provide(runtimeRepositoryLayer)); + 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( @@ -3480,7 +3505,7 @@ function makeStartingOverLayer() { NodeServices.layer, ), ); - return { agent, ANTIGRAVITY, layer }; + return { agent, ANTIGRAVITY, hooks, layer }; } const startingOver = makeStartingOverLayer(); @@ -3632,6 +3657,132 @@ startingOver.layer("ProviderServiceLive forgetting a conversation", (it) => { }), ); + 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("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; diff --git a/apps/server/src/provider/Layers/ProviderService.ts b/apps/server/src/provider/Layers/ProviderService.ts index b259faadf..9f4c66087 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, @@ -259,19 +265,6 @@ function toRuntimePayloadFromSession( * clears it (`noteHistoryDelivered`). Kept in the binding, so a restart in * between can't reopen the conversation as it was. */ -/** The start time of the runtime the binding last described (ProviderSession.createdAt). */ -function readPersistedSessionCreatedAt( - runtimePayload: ProviderRuntimeBinding["runtimePayload"], -): string | undefined { - return runtimePayload !== null && - typeof runtimePayload === "object" && - !Array.isArray(runtimePayload) && - "sessionCreatedAt" in runtimePayload && - typeof runtimePayload.sessionCreatedAt === "string" - ? runtimePayload.sessionCreatedAt - : undefined; -} - function readPersistedHistoryOwed(runtimePayload: ProviderRuntimeBinding["runtimePayload"]) { return ( runtimePayload !== null && @@ -875,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; } } @@ -926,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, @@ -936,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({ @@ -995,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; }); @@ -1824,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, @@ -2964,14 +2968,19 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( */ const forgetConversation = (threadId: ThreadId, options?: { readonly onlySession?: string }) => Effect.gen(function* () { - const binding = Option.getOrUndefined(yield* directory.getBinding(threadId)); - if (binding === undefined) return true; - if ( - options?.onlySession !== undefined && - readPersistedSessionCreatedAt(binding.runtimePayload) !== options.onlySession - ) { + // 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, @@ -3021,6 +3030,28 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( ), ); } + // 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, + }); + yield* adapter.stopSession(threadId).pipe(Effect.ignore); + 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, @@ -3033,20 +3064,11 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( threadId, sessionCreatedAt, }) => - Effect.gen(function* () { - const binding = Option.getOrUndefined(yield* directory.getBinding(threadId)); - if (binding === undefined || !readPersistedHistoryOwed(binding.runtimePayload)) return; - // Another runtime than the one that sent it: that one still owes it. - if (readPersistedSessionCreatedAt(binding.runtimePayload) !== sessionCreatedAt) return; - yield* directory.upsert({ - threadId, - provider: binding.provider, - ...(binding.providerInstanceId !== undefined - ? { providerInstanceId: binding.providerInstanceId } - : {}), - runtimePayload: { historyOwed: false }, - }); - }).pipe(Effect.ignoreCause({ log: true })); + // 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 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/Services/ProviderAdapter.ts b/apps/server/src/provider/Services/ProviderAdapter.ts index 3ce47ae73..27722e544 100644 --- a/apps/server/src/provider/Services/ProviderAdapter.ts +++ b/apps/server/src/provider/Services/ProviderAdapter.ts @@ -371,6 +371,15 @@ export interface ProviderAdapterShape { */ readonly hasSession: (threadId: ThreadId) => Effect.Effect; + /** + * Resolves once no runtime of this session key can still act: at once when + * none runs or is stopping, otherwise once a stopping runtime's process + * (with every child process it started) is gone. A runtime `hasSession` + * stopped reporting may still be stopping. A revert waits on it before it + * restores files. Absent: a runtime `hasSession` no longer reports is gone. + */ + readonly whenStopped?: (threadId: ThreadId) => Effect.Effect; + /** * Read a provider thread snapshot. */ 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/packages/contracts/src/provider.ts b/packages/contracts/src/provider.ts index 8870b1337..81c821c4f 100644 --- a/packages/contracts/src/provider.ts +++ b/packages/contracts/src/provider.ts @@ -430,6 +430,13 @@ export const ProviderTurnStartResult = Schema.Struct({ * 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; From c6455c621fc554936c4a8b4e0bafee144405d603 Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Mon, 23 Nov 2026 12:48:36 -0500 Subject: [PATCH 54/59] fix(server): a revert still restores files when the thread's provider is no longer registered A provider instance that was removed or turned off has no runtime left, so nothing of it can write over a restored file. Refusing the revert there would have blocked file restores on every thread of a removed account. --- .../Layers/CheckpointReactor.test.ts | 15 ++++++--------- .../orchestration/Layers/CheckpointReactor.ts | 16 ++++------------ 2 files changed, 10 insertions(+), 21 deletions(-) diff --git a/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts b/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts index 8ab4183ff..cc4141983 100644 --- a/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts +++ b/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts @@ -3132,7 +3132,7 @@ describe("CheckpointReactor", () => { ); }); - it("restores nothing when it can't tell whether the agent still runs", async () => { + 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"; @@ -3162,18 +3162,15 @@ describe("CheckpointReactor", () => { createdAt, }), ); - const thread = await waitForThread(harness.readModel, (entry) => - entry.activities.some((activity) => activity.kind === "checkpoint.revert.failed"), + // 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"), ); - const detail = ( - thread.activities.find((activity) => activity.kind === "checkpoint.revert.failed") - ?.payload as { readonly detail?: string } | undefined - )?.detail; - expect(detail).toContain("no file was restored"); expect(harness.provider.rollbackConversation).not.toHaveBeenCalled(); expect( fs.readFileSync(path.join(harness.cwd, "README.md"), "utf8").replaceAll("\r\n", "\n"), - ).toBe("v3\n"); + ).toBe("v2\n"); }); it.each([ diff --git a/apps/server/src/orchestration/Layers/CheckpointReactor.ts b/apps/server/src/orchestration/Layers/CheckpointReactor.ts index b395952a8..75a36a1b7 100644 --- a/apps/server/src/orchestration/Layers/CheckpointReactor.ts +++ b/apps/server/src/orchestration/Layers/CheckpointReactor.ts @@ -1231,8 +1231,10 @@ const make = Effect.gen(function* () { // 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. - // An agent whose capabilities can't be read may be one of those, and - // may still be running: the revert fails and restores nothing. + // 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( @@ -1242,16 +1244,6 @@ const make = Effect.gen(function* () { ), ) : undefined; - if (capabilities?._tag === "Failure") { - yield* Effect.logWarning("checkpoint revert could not read the agent's capabilities", { - threadId: event.payload.threadId, - cause: String(capabilities.failure), - }); - yield* failRevert( - "Threadlines couldn't check whether the agent still runs, so no file was restored. Try again.", - ); - return; - } const startsOver = capabilities?._tag === "Success" && capabilities.success.conversationRollback === "new-session"; From 6bb3ce30c58f4dc74033a932277a03f6d9b61939 Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Mon, 23 Nov 2026 13:02:43 -0500 Subject: [PATCH 55/59] fix(effect-acp): an in-order request counts as sent only once the agent's stdin took it requestInOrder used to return once the frame entered the writer's queue. It now returns when the sink asks for the next frame, after write() took this one with no error it reports at once. When the writer stops, every frame not handed over fails, along with the requests it carried (never answered) and those written but unanswered, so none is stranded. --- packages/effect-acp/src/protocol.test.ts | 44 ++++++++++++ packages/effect-acp/src/protocol.ts | 85 +++++++++++++++++++----- 2 files changed, 113 insertions(+), 16 deletions(-) diff --git a/packages/effect-acp/src/protocol.test.ts b/packages/effect-acp/src/protocol.test.ts index 6231d8727..87541c033 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"; @@ -264,6 +267,47 @@ it.layer(NodeServices.layer)("effect-acp protocol", (it) => { }), ); + 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("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 165fc5483..e2271bffd 100644 --- a/packages/effect-acp/src/protocol.ts +++ b/packages/effect-acp/src/protocol.ts @@ -66,11 +66,13 @@ export interface AcpPatchedProtocol { readonly incoming: Stream.Stream; readonly request: (method: string, payload: unknown) => Effect.Effect; /** - * Sends a request and returns once it is queued for the wire, ahead of - * anything sent after. 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. + * 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, @@ -105,7 +107,7 @@ 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( @@ -142,6 +144,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. @@ -168,7 +172,9 @@ export const makeAcpPatchedProtocol = Effect.fn("makeAcpPatchedProtocol")(functi payload: typeof encoded === "string" ? encoded : new TextDecoder().decode(encoded), }); - yield* Queue.offer(outgoing, encoded).pipe(Effect.asVoid); + yield* Queue.offer(outgoing, { data: encoded, written, requestId }).pipe(Effect.asVoid); + } else if (written !== undefined) { + yield* Deferred.succeed(written, undefined); } }); @@ -487,7 +493,44 @@ 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. + let handedOver: OutgoingFrame | undefined; + 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), + }); + 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); + } + // 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) => @@ -540,7 +583,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) { @@ -574,13 +617,15 @@ export const makeAcpPatchedProtocol = Effect.fn("makeAcpPatchedProtocol")(functi (current) => [current, current + 1] as const, ); yield* Ref.update(orderedPending, (pending) => new Map(pending).set(requestId, onAnswer)); - yield* offerOutgoing({ - _tag: "Request", - id: requestId, - tag: method, - payload, - headers: [], - }).pipe( + 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))), ), @@ -628,6 +673,14 @@ 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, From 52373f452d3c896330de9a958ee8cb77bfd4d951 Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Mon, 23 Nov 2026 13:02:43 -0500 Subject: [PATCH 56/59] fix(antigravity): release fixes for the turn machine's driver - A send whose prompt the agent's stdin never took (it closed its end) returns undelivered, with its history pending again. - Steering ships off (ANTIGRAVITY_STEERS): a mid-turn message waits for the turn, as for other agents; the docs and the app guide say so. - A prompt's record (parts, setup, outcome watch, answer) is dropped once its answer is stepped, a late answer to a steered prompt included. - Noting the log's position before a prompt waits at most 2 seconds; past it the prompt goes with no baseline and its own answer stands. - sessionStopped(threadId) on the adapter contract resolves once a stop under way has closed the session's process scope, for a revert to wait on. --- apps/server/scripts/antigravity-mock-agent.ts | 16 ++- apps/server/src/guide/topics.ts | 2 +- .../src/provider/Services/ProviderAdapter.ts | 11 ++ apps/server/src/provider/acp/AcpAdapter.ts | 43 +++++- .../antigravity/AntigravityTurns.test.ts | 129 ++++++++++++++++-- .../provider/antigravity/AntigravityTurns.ts | 3 +- docs/providers/antigravity.md | 14 +- 7 files changed, 196 insertions(+), 22 deletions(-) diff --git a/apps/server/scripts/antigravity-mock-agent.ts b/apps/server/scripts/antigravity-mock-agent.ts index 2d65d8fb2..b4af7a244 100644 --- a/apps/server/scripts/antigravity-mock-agent.ts +++ b/apps/server/scripts/antigravity-mock-agent.ts @@ -60,6 +60,7 @@ * - `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 @@ -72,7 +73,7 @@ * (`available_commands_update`), as the 1.5 CLI does. Under `flapping` it * then changes the list ten times in a row. */ -import { appendFileSync, mkdirSync, writeFileSync } from "node:fs"; +import { appendFileSync, closeSync, mkdirSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { DatabaseSync } from "node:sqlite"; @@ -227,6 +228,19 @@ const program = 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( diff --git a/apps/server/src/guide/topics.ts b/apps/server/src/guide/topics.ts index 16fb15413..4c079c3c5 100644 --- a/apps/server/src/guide/topics.ts +++ b/apps/server/src/guide/topics.ts @@ -313,7 +313,7 @@ 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. -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 meanwhile steers the turn. 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}. +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. diff --git a/apps/server/src/provider/Services/ProviderAdapter.ts b/apps/server/src/provider/Services/ProviderAdapter.ts index 3ce47ae73..fb2142192 100644 --- a/apps/server/src/provider/Services/ProviderAdapter.ts +++ b/apps/server/src/provider/Services/ProviderAdapter.ts @@ -371,6 +371,17 @@ export interface ProviderAdapterShape { */ readonly hasSession: (threadId: ThreadId) => Effect.Effect; + /** + * Resolves once no runtime of this thread runs: at once when there is + * none, or once a stop already under way has closed the runtime's process + * scope (its child processes are 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 sessionStopped?: (threadId: ThreadId) => Effect.Effect; + /** * Read a provider thread snapshot. */ diff --git a/apps/server/src/provider/acp/AcpAdapter.ts b/apps/server/src/provider/acp/AcpAdapter.ts index ff62f1c43..c81aa3b97 100644 --- a/apps/server/src/provider/acp/AcpAdapter.ts +++ b/apps/server/src/provider/acp/AcpAdapter.ts @@ -183,6 +183,12 @@ const ACP_HELD_TURN_SETTLE = Duration.seconds(2); 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. @@ -253,6 +259,8 @@ interface PendingUserInput { interface AcpSessionContext { readonly threadId: ThreadId; + /** Done once a stop has closed the session's process scope (`sessionStopped`). */ + 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; @@ -454,6 +462,8 @@ export type AcpTurnMachineSeam = 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 } @@ -461,6 +471,8 @@ export type AcpTurnMachineSeam = | { 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 }; @@ -1444,8 +1456,10 @@ export function makeAcpAdapter( } } + 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()), @@ -2331,6 +2345,7 @@ export function makeAcpAdapter( outbox: yield* Queue.unbounded(), }, stopped: false, + closed: yield* Deferred.make(), }; const notificationFiber = yield* Stream.runDrain( @@ -2355,7 +2370,7 @@ export function makeAcpAdapter( // In its place among the updates (`promptInOrder`). const sent = ctx.machine?.prompts.get(event.key); if (sent !== undefined) sent.exit = event.answer; - yield* applyTurnEvent(ctx, { type: "promptAnswered", prompt: event.key }); + yield* answerMachinePrompt(ctx, event.key); return; } case "SessionStatus": @@ -2852,12 +2867,25 @@ export function makeAcpAdapter( 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; }), ); + /** + * 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" }); @@ -2972,6 +3000,9 @@ export function makeAcpAdapter( 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, @@ -2995,7 +3026,7 @@ export function makeAcpAdapter( yield* ctx.acp.inOrder( Effect.suspend(() => { sent.exit = Exit.failCause(exit.cause); - return applyTurnEvent(ctx, { type: "promptAnswered", prompt }); + return answerMachinePrompt(ctx, prompt); }).pipe(Effect.asVoid), ); }); @@ -4095,6 +4126,13 @@ export function makeAcpAdapter( ), ); + /** `ProviderAdapterShape.sessionStopped`: the stopping session stays in `sessions` until its scope closed. */ + const sessionStopped = (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); @@ -4177,6 +4215,7 @@ export function makeAcpAdapter( stopSession, listSessions, hasSession, + sessionStopped, stopAll, noteBeforeStop: processes.beforeStop, confirmThreadStopped: processes.confirm, diff --git a/apps/server/src/provider/antigravity/AntigravityTurns.test.ts b/apps/server/src/provider/antigravity/AntigravityTurns.test.ts index bf1db2655..17c66ac5d 100644 --- a/apps/server/src/provider/antigravity/AntigravityTurns.test.ts +++ b/apps/server/src/provider/antigravity/AntigravityTurns.test.ts @@ -151,6 +151,12 @@ const startAgy = ( }; }); +/** 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] : [])); @@ -382,7 +388,7 @@ describe("Antigravity turns", () => { it.live("steers a running turn with a second prompt, never cancelling it", () => Effect.gen(function* () { - const agy = yield* startAgy("steer"); + const agy = yield* startAgy("steer", withSteering); expect(agy.adapter.capabilities.activeTurnSteering).toBe("supported"); const { turnId } = yield* agy.adapter.sendTurn({ threadId: agy.threadId, @@ -557,6 +563,7 @@ describe("Antigravity turns, the hard cases", () => { ...descriptor, turnMachine: { ...machine, + steer: true, outcome: { watch: (sessionId, model) => outcome.watch(sessionId, model).pipe( @@ -611,7 +618,7 @@ describe("Antigravity turns, the hard cases", () => { it.live("steers without inheriting the error the earlier prompt left in the log", () => Effect.gen(function* () { - const agy = yield* startAgy("steer-log-error"); + const agy = yield* startAgy("steer-log-error", withSteering); const { turnId } = yield* agy.adapter.sendTurn({ threadId: agy.threadId, input: "go", @@ -630,7 +637,7 @@ describe("Antigravity turns, the hard cases", () => { it.live("steers without inheriting an error the earlier prompt writes late", () => Effect.gen(function* () { - const agy = yield* startAgy("steer-late-log-error"); + const agy = yield* startAgy("steer-late-log-error", withSteering); const { turnId } = yield* agy.adapter.sendTurn({ threadId: agy.threadId, input: "go", @@ -651,7 +658,7 @@ describe("Antigravity turns, the hard cases", () => { "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"); + const agy = yield* startAgy("steer-own-log-error", withSteering); const { turnId } = yield* agy.adapter.sendTurn({ threadId: agy.threadId, input: "go", @@ -942,7 +949,7 @@ describe("Antigravity turn driver, the orderings", () => { 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", undefined, "full-access", gate.seams); + 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: [] }) @@ -1166,6 +1173,111 @@ describe("Antigravity turn driver, the orderings", () => { }).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.sessionStopped!(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.sessionStopped!(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) => @@ -1206,12 +1318,9 @@ describe("Antigravity turn driver, the orderings", () => { }).pipe(Effect.scoped, Effect.provide(testServices)), ); - it.live("queues a message sent mid-turn when steering is off", () => + it.live("queues a message sent mid-turn, steering being off for Antigravity", () => Effect.gen(function* () { - const agy = yield* startAgy("background", (descriptor) => ({ - ...descriptor, - turnMachine: { ...descriptor.turnMachine!, steer: false }, - })); + const agy = yield* startAgy("background"); expect(agy.adapter.steerTurn).toBeUndefined(); expect(agy.adapter.capabilities.activeTurnSteering).toBeUndefined(); const first = yield* agy.adapter.sendTurn({ diff --git a/apps/server/src/provider/antigravity/AntigravityTurns.ts b/apps/server/src/provider/antigravity/AntigravityTurns.ts index 956f54afb..95aa30092 100644 --- a/apps/server/src/provider/antigravity/AntigravityTurns.ts +++ b/apps/server/src/provider/antigravity/AntigravityTurns.ts @@ -49,7 +49,8 @@ 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. */ -export const ANTIGRAVITY_STEERS = true; +// 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); diff --git a/docs/providers/antigravity.md b/docs/providers/antigravity.md index dd91740c6..59ca9006e 100644 --- a/docs/providers/antigravity.md +++ b/docs/providers/antigravity.md @@ -175,13 +175,13 @@ 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 works steers the turn instead of waiting: Threadlines sends it as -another prompt, which the CLI takes into the running turn (1.5.0+), leaving its commands and -subagents running. The turn ends with the newest prompt's answer. Prompts reach the agent in the -order they were sent, the first one's mode and model setup included, so a steer never arrives ahead -of the message it steers. Steering is one switch (`ANTIGRAVITY_STEERS` in -`apps/server/src/provider/antigravity/AntigravityTurns.ts`); off, a message sent mid-turn waits for -the turn to end. +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 From d2eb1cd1de8d588f44c6ce99a7a579760b51c8a9 Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Mon, 23 Nov 2026 13:38:32 -0500 Subject: [PATCH 57/59] fix(acp): a broken pipe to the agent fails what was never written, and a stalled stop can't hang a revert - effect-acp: when the agent's output ends or the writer fails, every frame its stdin has not taken fails, the in-order requests they carried are not reported as answered, and a request made afterwards fails at once instead of queueing behind a pipe that is gone. - Antigravity's plan-file exemption never takes a path with `.` or `..` steps: through a link in the session's folder such a path reads as the session's plan and opens another file. - A revert's fallback stop is bounded, so a stop that already stalled can't keep the revert waiting on its lock. --- .../provider/Layers/ProviderService.test.ts | 19 ++++++++ .../src/provider/Layers/ProviderService.ts | 5 ++- .../acp/AntigravityAcpSupport.test.ts | 21 +++++++++ .../src/provider/acp/AntigravityAcpSupport.ts | 8 +++- packages/effect-acp/src/protocol.test.ts | 43 +++++++++++++++++++ packages/effect-acp/src/protocol.ts | 40 ++++++++++++----- 6 files changed, 124 insertions(+), 12 deletions(-) diff --git a/apps/server/src/provider/Layers/ProviderService.test.ts b/apps/server/src/provider/Layers/ProviderService.test.ts index fe90828ed..2547dc10a 100644 --- a/apps/server/src/provider/Layers/ProviderService.test.ts +++ b/apps/server/src/provider/Layers/ProviderService.test.ts @@ -3703,6 +3703,25 @@ startingOver.layer("ProviderServiceLive forgetting a conversation", (it) => { }), ); + 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; diff --git a/apps/server/src/provider/Layers/ProviderService.ts b/apps/server/src/provider/Layers/ProviderService.ts index 9f4c66087..e5d48c980 100644 --- a/apps/server/src/provider/Layers/ProviderService.ts +++ b/apps/server/src/provider/Layers/ProviderService.ts @@ -3041,7 +3041,10 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( yield* Effect.logWarning("provider service ends a runtime still stopping at a revert", { threadId, }); - yield* adapter.stopSession(threadId).pipe(Effect.ignore); + // 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({ diff --git a/apps/server/src/provider/acp/AntigravityAcpSupport.test.ts b/apps/server/src/provider/acp/AntigravityAcpSupport.test.ts index 629840856..81e979654 100644 --- a/apps/server/src/provider/acp/AntigravityAcpSupport.test.ts +++ b/apps/server/src/provider/acp/AntigravityAcpSupport.test.ts @@ -7,6 +7,7 @@ import { antigravityAgentProblem, antigravityModelsFromCatalog, antigravityModelsFromChoices, + isAntigravityPlanFileEdit, isLegacyAntigravityServerPath, nextAntigravityCatalog, parseAntigravitySignInUrl, @@ -204,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 842a88b35..7b3e319fd 100644 --- a/apps/server/src/provider/acp/AntigravityAcpSupport.ts +++ b/apps/server/src/provider/acp/AntigravityAcpSupport.ts @@ -551,7 +551,13 @@ export function isAntigravityPlanFileEdit( return false; } const planPath = join(brain, sessionId, "plan.md"); - const isPlanPath = (path: string) => isAbsolute(path) && normalize(path) === planPath; + // 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 = diff --git a/packages/effect-acp/src/protocol.test.ts b/packages/effect-acp/src/protocol.test.ts index 87541c033..b3de75f18 100644 --- a/packages/effect-acp/src/protocol.test.ts +++ b/packages/effect-acp/src/protocol.test.ts @@ -308,6 +308,49 @@ it.layer(NodeServices.layer)("effect-acp protocol", (it) => { }), ); + 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 e2271bffd..3a1ae1fd2 100644 --- a/packages/effect-acp/src/protocol.ts +++ b/packages/effect-acp/src/protocol.ts @@ -129,6 +129,30 @@ export const makeAcpPatchedProtocol = Effect.fn("makeAcpPatchedProtocol")(functi 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) { return Effect.void; @@ -172,6 +196,8 @@ export const makeAcpPatchedProtocol = Effect.fn("makeAcpPatchedProtocol")(functi payload: typeof encoded === "string" ? encoded : new TextDecoder().decode(encoded), }); + // 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); @@ -249,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) { @@ -499,7 +528,6 @@ export const makeAcpPatchedProtocol = Effect.fn("makeAcpPatchedProtocol")(functi // 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. - let handedOver: OutgoingFrame | undefined; const nextFrame = Effect.gen(function* () { const last = handedOver; handedOver = undefined; @@ -514,15 +542,7 @@ export const makeAcpPatchedProtocol = Effect.fn("makeAcpPatchedProtocol")(functi detail: "Failed to write to the ACP agent", cause: Cause.squash(cause), }); - 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); - } + yield* failUnwrittenFrames(error); // Requests written earlier can no longer be answered over this pipe. yield* failAllExtPending(error); }); From 53ffceae105f66de8264d001d56af17dbed9b1c1 Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Mon, 23 Nov 2026 13:43:02 -0500 Subject: [PATCH 58/59] docs(antigravity): audio goes as a path until the CLI says it reads audio --- docs/providers/antigravity.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/providers/antigravity.md b/docs/providers/antigravity.md index 59ca9006e..e3f299b89 100644 --- a/docs/providers/antigravity.md +++ b/docs/providers/antigravity.md @@ -235,7 +235,8 @@ which Antigravity reads as a document. Text files go as text, in UTF-8, or UTF-1 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. A PDF link needs nothing: every ACP agent reads links. A MIME +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. From 7b9d59583957a8f33a0d0026ad439feacbbf8ae6 Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Mon, 23 Nov 2026 14:03:18 -0500 Subject: [PATCH 59/59] test(antigravity): the redirect test names Google's two hosts exactly --- apps/server/src/provider/antigravity/AntigravityUsage.test.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/apps/server/src/provider/antigravity/AntigravityUsage.test.ts b/apps/server/src/provider/antigravity/AntigravityUsage.test.ts index 8fc500db1..00830a784 100644 --- a/apps/server/src/provider/antigravity/AntigravityUsage.test.ts +++ b/apps/server/src/provider/antigravity/AntigravityUsage.test.ts @@ -521,7 +521,8 @@ describe("Antigravity plan limits", () => { Effect.gen(function* () { const { readOnce, google } = yield* setup({ route: (url) => - url.host.endsWith("cloudcode-pa.googleapis.com") + url.host === "cloudcode-pa.googleapis.com" || + url.host === "daily-cloudcode-pa.googleapis.com" ? { status: 302, headers: { location: "https://collector.example/steal" } } : { status: 404 }, });