From e1dbabae1f6b247c4672d02283e803d3b99ed295 Mon Sep 17 00:00:00 2001 From: "Patrick C. Toulme" <135739773+patrick-toulme@users.noreply.github.com> Date: Sat, 21 Nov 2026 14:39:13 +0000 Subject: [PATCH 01/11] fix(antigravity): keep native ACP swarm runs active and stream worker subagents Opt into Antigravity ACP swarm streaming (`_antigravity/swarm`), project each swarm worker as a native subagent with live child tool, reasoning, and message updates, hold turn settlement and session idle eviction while swarm workers or queued coordinator wakes remain active, and format swarm board tools cleanly. Keep disk-backed worker transcript and roster tracking for released agy 1.5 servers that do not yet advertise native swarm notifications. --- .../Adapters/AntigravityAdapterV2.test.ts | 433 ++++++++++++++++++ .../Adapters/AntigravityAdapterV2.ts | 114 ++++- .../provider/acp/AntigravityChildWork.test.ts | 107 +++++ .../src/provider/acp/AntigravityChildWork.ts | 190 +++++++- .../provider/acp/AntigravityProtocol.test.ts | 62 +++ .../src/provider/acp/AntigravityProtocol.ts | 271 ++++++++++- .../src/provider/acp/AntigravitySwarm.test.ts | 204 +++++++++ .../src/provider/acp/AntigravitySwarm.ts | 331 +++++++++++++ packages/provider-acp/src/server/adapter.ts | 391 ++++++++++++++-- 9 files changed, 2013 insertions(+), 90 deletions(-) create mode 100644 apps/server/src/provider/acp/AntigravitySwarm.test.ts create mode 100644 apps/server/src/provider/acp/AntigravitySwarm.ts diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts index fca472c6c433e..34fcdd427ffc7 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts @@ -2505,3 +2505,436 @@ describe("AntigravityAdapterV2 session system prompt", () => { }).pipe(Effect.provide(layerSession)), ); }); + +describe("AntigravityAdapterV2 native swarm protocol", () => { + it("projects legacy swarm add calls as native subagents and delegates native-protocol swarm cards to _antigravity/swarm", () => { + const legacySingle = flavor.extractSubagentUpdate?.({ + toolCallId: "swarm-call-1", + title: "Add swarm worker @alpha", + kind: "other", + status: "completed", + data: { + meta: { antigravity: { swarm: { tool: "swarm", action: "add" } } }, + rawInput: { action: "add", name: "alpha", brief: "Check config", model: "fast-model" }, + rawOutput: { status: "added", name: "alpha", conversation_id: "child-alpha" }, + }, + }); + assert.equal(legacySingle?.title, "@alpha"); + assert.equal(legacySingle?.prompt, "Check config"); + assert.equal(legacySingle?.model, "fast-model"); + assert.equal(legacySingle?.childSessionId, "child-alpha"); + assert.equal(legacySingle?.status, "running"); + }); + + it.effect( + "keeps turns open across background swarm workers, streams worker child activity, blocks idle eviction, and reopens woken workers", + () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const workspace = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-ag-swarm-" }); + + type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"]; + let onSessionUpdate: Parameters[0] | undefined; + let onSwarmNotification: + | ((payload: unknown) => Effect.Effect) + | undefined; + let seenClientCapsMeta: unknown; + let promptCalls = 0; + + const rootSessionId = "11111111-1111-4000-8000-000000000001"; + const alphaSessionId = "11111111-1111-4000-8000-00000000000a"; + const betaSessionId = "11111111-1111-4000-8000-00000000000b"; + + const continuationRequests = { + offer: () => Effect.succeed(true), + } as unknown as NonNullable< + Parameters[0]["continuationRequests"] + >; + + const instanceId = ProviderInstanceId.make("antigravity-swarm-e2e"); + const adapter = yield* makeAntigravityAdapterV2({ + instanceId, + continuationRequests, + selfInvocation: yield* resolveSelfInvocation(), + withProcess: (_stop, task) => task, + defaultModel: Effect.undefined, + makeRuntime: (runtimeInput) => + Effect.sync((): RuntimeService => { + seenClientCapsMeta = runtimeInput.clientCapabilities?._meta; + return { + start: () => + Effect.succeed({ + initializeResult: { + protocolVersion: 1, + agentInfo: { name: "Antigravity ACP Server", version: "1.5.14" }, + agentCapabilities: { + loadSession: true, + _meta: { + antigravity: { tier: true, systemPrompt: { append: true }, swarm: true }, + }, + }, + }, + sessionId: rootSessionId, + resumed: false, + sessionSetupResult: { + sessionId: rootSessionId, + modes: { + currentModeId: "default", + availableModes: [{ id: "default", name: "Default" }], + }, + models: { + currentModelId: "test-model", + availableModels: [{ modelId: "test-model", name: "Test Model" }], + }, + configOptions: [], + }, + } as unknown as AcpSessionRuntime.AcpSessionRuntimeStartResult), + getEvents: () => Stream.empty, + drainEvents: Effect.void, + getSessionId: Effect.succeed(rootSessionId), + getConfigOptions: Effect.succeed([]), + getModeState: Effect.succeed({ + currentModeId: "default", + availableModes: [{ id: "default", name: "Default" }], + }), + getModelState: Effect.succeed({ + currentModelId: "test-model", + availableModels: [{ modelId: "test-model", name: "Test Model" }], + }), + setConfigOption: () => Effect.succeed({ configOptions: [] }), + setMode: () => Effect.void, + setModel: () => Effect.void, + prompt: ( + _payload: Parameters[0], + promptOptions: Parameters[1], + ) => + Effect.gen(function* () { + promptCalls += 1; + if (promptOptions?.dispatched !== undefined) { + yield* Deferred.succeed(promptOptions.dispatched, undefined); + } + if (promptCalls === 1) { + yield* onSessionUpdate!({ + sessionId: rootSessionId, + update: { + sessionUpdate: "tool_call", + toolCallId: "coord-add-1", + kind: "other", + title: "Add 2 swarm workers (@worker-1..2)", + status: "completed", + rawInput: { action: "add", name: "worker", n: 2, brief: "Inspect repo" }, + _meta: { antigravity: { swarm: { tool: "swarm", action: "add" } } }, + }, + }); + yield* onSwarmNotification!({ + sessionId: rootSessionId, + title: "Repo Audit", + head: 1, + activeWorkers: 2, + workingWorkers: 2, + waitingWorkers: 0, + members: [ + { + name: "alpha", + role: "worker", + conversationId: alphaSessionId, + brief: "Inspect frontend", + modelLabel: "Test Model", + state: "working", + }, + { + name: "beta", + role: "worker", + conversationId: betaSessionId, + brief: "Inspect backend", + modelLabel: "Test Model", + state: "working", + }, + ], + }); + yield* onSessionUpdate!({ + sessionId: rootSessionId, + update: { + sessionUpdate: "agent_message_chunk", + content: { type: "text", text: "Spawned @alpha and @beta." }, + }, + }); + } else { + yield* onSwarmNotification!({ + sessionId: rootSessionId, + head: 4, + activeWorkers: 1, + workingWorkers: 1, + waitingWorkers: 1, + members: [ + { + name: "alpha", + role: "worker", + conversationId: alphaSessionId, + brief: "Inspect frontend", + state: "working", + }, + { + name: "beta", + role: "worker", + conversationId: betaSessionId, + brief: "Inspect backend", + state: "waiting", + }, + ], + }); + yield* onSessionUpdate!({ + sessionId: rootSessionId, + update: { + sessionUpdate: "agent_message_chunk", + content: { type: "text", text: "Sent follow-up to @alpha." }, + }, + }); + } + return { stopReason: "end_turn" as const }; + }), + cancel: () => Effect.void, + closeSession: () => Effect.void, + extRequest: () => Effect.die("unused"), + extNotification: () => Effect.void, + handleSessionUpdate: ( + handler: Parameters[0], + ) => + Effect.sync(() => { + onSessionUpdate = handler; + }), + handleRequestPermission: () => Effect.void, + handleReadTextFile: () => Effect.void, + handleWriteTextFile: () => Effect.void, + handleCreateTerminal: () => Effect.void, + handleTerminalOutput: () => Effect.void, + handleWaitForTerminalExit: () => Effect.void, + handleKillTerminalCommand: () => Effect.void, + handleReleaseTerminal: () => Effect.void, + handleElicitation: () => Effect.void, + handleElicitationComplete: () => Effect.void, + handleExtRequest: () => Effect.void, + handleExtNotification: ( + method: string, + _schema: unknown, + handler: (payload: unknown) => Effect.Effect, + ) => + Effect.sync(() => { + if (method === "_antigravity/swarm") { + onSwarmNotification = handler; + } + }), + } as unknown as RuntimeService; + }), + }); + + const threadId = ThreadId.make("thread-ag-swarm"); + const modelSelection = { instanceId, model: "antigravity-default" } as const; + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: workspace, + }); + const session = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make("ps-ag-swarm"), + modelSelection, + runtimePolicy, + }); + assert.deepEqual(seenClientCapsMeta, { antigravity: { swarm: true } }); + + const collected: Array = []; + const reader = yield* session.events.pipe( + Stream.runForEach((event) => + Effect.sync(() => { + collected.push(event); + }), + ), + Effect.forkScoped, + ); + + const providerThread = yield* session.ensureThread({ + threadId, + modelSelection, + runtimePolicy, + }); + const turn1Input = makeTurnInput({ + instanceId, + threadId, + providerThread, + modelSelection, + runtimePolicy, + now: yield* DateTime.now, + }); + yield* session.startTurn(turn1Input); + + // Stream live worker reasoning, tool call, and reply on @alpha while prompt has already returned. + yield* onSessionUpdate!({ + sessionId: alphaSessionId, + update: { + sessionUpdate: "agent_thought_chunk", + content: { type: "text", text: "Reviewing UI routes." }, + }, + }); + yield* onSessionUpdate!({ + sessionId: alphaSessionId, + update: { + sessionUpdate: "tool_call", + toolCallId: "alpha-tool-1", + kind: "execute", + title: "pnpm test", + status: "completed", + rawInput: { CommandLine: "pnpm test" }, + rawOutput: { combinedOutput: "ok" }, + }, + }); + + // Turn stays open past deferred-finalize debounce and protects the session from idle eviction. + yield* TestClock.adjust("5 seconds"); + yield* Effect.yieldNow; + assert.equal( + collected.filter((event) => event.type === "turn.terminal").length, + 0, + "turn must remain active while swarm workers are running", + ); + assert.isTrue(yield* session.hasPendingBackgroundWork ?? Effect.succeed(false)); + + // Workers finish and hold coordinatorPendingWake through the coordinator's out-of-turn synthesis. + yield* onSwarmNotification!({ + sessionId: rootSessionId, + head: 3, + activeWorkers: 0, + workingWorkers: 0, + waitingWorkers: 2, + coordinatorPendingWake: true, + members: [ + { name: "alpha", role: "worker", conversationId: alphaSessionId, state: "waiting" }, + { name: "beta", role: "worker", conversationId: betaSessionId, state: "waiting" }, + ], + posts: [ + { seq: 2, agent: "alpha", text: "@coordinator Frontend passed." }, + { seq: 3, agent: "beta", text: "@coordinator Backend passed." }, + ], + }); + yield* TestClock.adjust("5 seconds"); + yield* Effect.yieldNow; + assert.equal( + collected.filter((event) => event.type === "turn.terminal").length, + 0, + "turn must stay open while coordinatorPendingWake is true", + ); + + yield* onSessionUpdate!({ + sessionId: rootSessionId, + update: { + sessionUpdate: "agent_message_chunk", + content: { type: "text", text: "Combined summary ready." }, + }, + }); + yield* onSessionUpdate!({ + sessionId: rootSessionId, + update: { sessionUpdate: "usage_update", used: 420, size: 100_000 }, + }); + yield* onSwarmNotification!({ + sessionId: rootSessionId, + head: 3, + activeWorkers: 0, + workingWorkers: 0, + waitingWorkers: 2, + coordinatorPendingWake: false, + members: [ + { name: "alpha", role: "worker", conversationId: alphaSessionId, state: "waiting" }, + { name: "beta", role: "worker", conversationId: betaSessionId, state: "waiting" }, + ], + }); + + yield* TestClock.adjust("4 seconds"); + yield* Effect.yieldNow; + assert.equal(collected.filter((event) => event.type === "turn.terminal").length, 1); + assert.isFalse(yield* session.hasPendingBackgroundWork ?? Effect.succeed(true)); + + const subagentsByTitle = () => { + const map = new Map< + string, + Extract< + ProviderAdapter.ProviderAdapterV2Event, + { type: "subagent.updated" } + >["subagent"] + >(); + for (const event of collected) { + if (event.type === "subagent.updated") { + map.set(event.subagent.title ?? event.subagent.id, event.subagent); + } + } + return map; + }; + const alphaAfterTurn1 = subagentsByTitle().get("@alpha"); + const betaAfterTurn1 = subagentsByTitle().get("@beta"); + assert.equal(alphaAfterTurn1?.status, "idle"); + assert.equal(alphaAfterTurn1?.result, "Frontend passed."); + assert.equal(betaAfterTurn1?.status, "idle"); + assert.equal(betaAfterTurn1?.result, "Backend passed."); + assert.isTrue( + collected.some( + (event) => + event.type === "turn_item.updated" && + event.turnItem.threadId === alphaAfterTurn1?.childThreadId && + event.turnItem.type === "reasoning" && + event.turnItem.text === "Reviewing UI routes.", + ), + ); + + // Turn 2 wakes @alpha again on the exact same child thread, then kills @alpha after reporting. + const turn2Input = makeTurnInput({ + instanceId, + threadId, + providerThread, + modelSelection, + runtimePolicy, + now: yield* DateTime.now, + }); + yield* session.startTurn({ + ...turn2Input, + runId: RunId.make("run-2"), + runOrdinal: 2, + providerTurnOrdinal: 2, + attemptId: RunAttemptId.make("attempt-2"), + rootNodeId: NodeId.make("root-2"), + runtimePolicy, + }); + yield* TestClock.adjust("5 seconds"); + yield* Effect.yieldNow; + assert.equal(subagentsByTitle().get("@alpha")?.status, "running"); + assert.equal( + subagentsByTitle().get("@alpha")?.childThreadId, + alphaAfterTurn1?.childThreadId, + ); + assert.equal(collected.filter((event) => event.type === "turn.terminal").length, 1); + + yield* onSwarmNotification!({ + sessionId: rootSessionId, + head: 5, + activeWorkers: 0, + workingWorkers: 0, + waitingWorkers: 1, + coordinatorPendingWake: false, + members: [ + { name: "alpha", role: "worker", conversationId: alphaSessionId, state: "killed" }, + { name: "beta", role: "worker", conversationId: betaSessionId, state: "waiting" }, + ], + posts: [{ seq: 5, agent: "alpha", text: "@coordinator Follow-up complete." }], + }); + yield* onSessionUpdate!({ + sessionId: rootSessionId, + update: { sessionUpdate: "usage_update", used: 620, size: 100_000 }, + }); + yield* TestClock.adjust("4 seconds"); + yield* Effect.yieldNow; + assert.equal(collected.filter((event) => event.type === "turn.terminal").length, 2); + assert.equal(subagentsByTitle().get("@alpha")?.status, "completed"); + assert.equal(subagentsByTitle().get("@alpha")?.result, "Follow-up complete."); + + yield* Fiber.interrupt(reader); + }).pipe(Effect.provide(layerSession), Effect.scoped), + ); +}); diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts index 3f629c813b615..414d412535d4b 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts @@ -40,14 +40,24 @@ import { readAntigravityClientTextFile } from "../../provider/acp/AntigravityCli import { watchAntigravityPromptOutcome } from "../../provider/acp/AntigravityTurnOutcome.ts"; import { antigravityApprovalOptions, + antigravitySwarmAddChildSessionId, + antigravitySwarmAddModel, antigravityToolOutlivesPrompt, antigravitySubagentOutput, classifyAntigravitySubagentToolCall, extractAntigravityUserInputQuestion, + identifyAntigravitySwarmToolCall, makeAntigravityReadRepair, makeAntigravityUserInputResponse, normalizeAntigravityToolCall, } from "../../provider/acp/AntigravityProtocol.ts"; +import { + ANTIGRAVITY_SWARM_CAPABILITIES_META, + ANTIGRAVITY_SWARM_NOTIFICATION_METHOD, + AntigravitySwarmNotification, + agentAdvertisesAntigravitySwarm, + makeAntigravitySwarmTracker, +} from "../../provider/acp/AntigravitySwarm.ts"; import { isAntigravitySignInRequiredError } from "../../provider/antigravityAuthSupport.ts"; import { AcpProviderCapabilitiesV2, @@ -106,15 +116,23 @@ export interface AntigravityAdapterV2Options { } /** - * Native subagent tools report no child session ids, so children stay read-only. - * Only permission prompts carry the launch; NativeChildWorkQuery matches their ids by this text. + * Projects `invoke_subagent`, `start_subagent`, and legacy `swarm` (`action: "add"`) tool calls as + * native subagents. When the connected `agy acp` server streams `_antigravity/swarm` notifications, + * worker subagents are projected directly from the swarm roster with their live child session ids. */ -const extractAntigravitySubagentUpdate: NonNullable = ( - toolCall, -) => { +function extractAntigravitySubagentUpdate( + toolCall: Parameters>[0], + options?: { readonly nativeSwarmProtocol?: boolean | undefined }, +): ReturnType> { if (classifyAntigravitySubagentToolCall(toolCall) !== "subagent") { return undefined; } + if ( + options?.nativeSwarmProtocol === true && + identifyAntigravitySwarmToolCall(toolCall)?.tool === "swarm" + ) { + return undefined; + } const status = toolCall.status === "failed" ? "failed" : toolCall.status === "pending" ? "pending" : "running"; const launches = antigravitySubagentLaunches(toolCall.data.rawInput); @@ -122,18 +140,18 @@ const extractAntigravitySubagentUpdate: NonNullable cwd === null ? [options.host.paths.attachmentsDir] : [cwd, options.host.paths.attachmentsDir]; const makeRuntime = Effect.fn("AntigravityAdapterV2.makeRuntime")( @@ -198,13 +218,17 @@ export function makeAntigravityAcpAdapterFlavor( ); }, start: () => - runtime - .start() - .pipe( - Effect.tap( - (started) => options.onSessionStarted?.(started, input.cwd) ?? Effect.void, + runtime.start().pipe( + Effect.tap((started) => + Effect.sync(() => { + nativeSwarmProtocol = agentAdvertisesAntigravitySwarm( + started.initializeResult.agentCapabilities, + ); + }).pipe( + Effect.andThen(options.onSessionStarted?.(started, input.cwd) ?? Effect.void), ), ), + ), } satisfies typeof runtime; }, Effect.provideService(SecureRandom.SecureRandom, options.random), @@ -285,7 +309,38 @@ export function makeAntigravityAcpAdapterFlavor( }; }, normalizeToolCall: normalizeAntigravityToolCall, - extractSubagentUpdate: extractAntigravitySubagentUpdate, + clientCapabilitiesMeta: ANTIGRAVITY_SWARM_CAPABILITIES_META, + registerExtensions: (context) => + context.runtime.handleExtNotification( + ANTIGRAVITY_SWARM_NOTIFICATION_METHOD, + AntigravitySwarmNotification, + (notification) => + Effect.gen(function* () { + nativeSwarmProtocol = true; + const mutation = swarmTracker.applyNotification(notification); + if (mutation.activeBackgroundWork) { + yield* context.setExternalBackgroundWork({ + sessionId: mutation.sessionId, + active: true, + }); + } + for (const subagent of mutation.subagents) { + yield* context.upsertSubagent({ + sessionId: mutation.sessionId, + subagent, + allowReopenFromIdle: true, + }); + } + if (!mutation.activeBackgroundWork) { + yield* context.setExternalBackgroundWork({ + sessionId: mutation.sessionId, + active: false, + }); + } + }), + ), + extractSubagentUpdate: (toolCall) => + extractAntigravitySubagentUpdate(toolCall, { nativeSwarmProtocol }), supportsImagePrompts: true, compactViaAdvertisedCommand: true, requiresSignIn: isAntigravitySignInRequiredError, @@ -294,17 +349,28 @@ export function makeAntigravityAcpAdapterFlavor( promptInactivityTimeout: "15 minutes", reportsPerTurnPromptUsage: true, geminiPromptUsage: true, + subagentsOutlivingPrompt: Effect.fn("AntigravityAdapterV2.subagentsOutlivingPrompt")( + function* ({ sessionId, nativeTaskIds }) { + const { runningSwarmTaskIds, unmanagedTaskIds } = swarmTracker.partitionTaskIds( + sessionId, + nativeTaskIds, + ); + if (profileDirectory === undefined || unmanagedTaskIds.length === 0) { + return runningSwarmTaskIds; + } + const diskAtWork = yield* readAntigravityChildrenAtWork({ + profileDirectory, + rootSessionId: sessionId, + toolCallIds: unmanagedTaskIds, + }); + return [...new Set([...runningSwarmTaskIds, ...diskAtWork])]; + }, + ), ...(profileDirectory === undefined ? {} : { watchPromptOutcome: (sessionId: string) => watchAntigravityPromptOutcome(profileDirectory, sessionId), - subagentsOutlivingPrompt: ({ sessionId, nativeTaskIds }) => - readAntigravityChildrenAtWork({ - profileDirectory, - rootSessionId: sessionId, - toolCallIds: nativeTaskIds, - }), hasPendingReply: (sessionId: string) => readAntigravityPendingReply({ profileDirectory, diff --git a/apps/server/src/provider/acp/AntigravityChildWork.test.ts b/apps/server/src/provider/acp/AntigravityChildWork.test.ts index e0336da84ac64..35e9e2dabd4f2 100644 --- a/apps/server/src/provider/acp/AntigravityChildWork.test.ts +++ b/apps/server/src/provider/acp/AntigravityChildWork.test.ts @@ -541,6 +541,113 @@ it.layer(NodeServices.layer)("readAntigravityChildWork", (it) => { }), ); + it.effect( + "reads legacy disk-backed swarm worker transcripts and tracks working vs parked or killed members", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const profile = yield* fs.makeTempDirectoryScoped({ prefix: "t3-agy-swarm-disk-" }); + const workerOne = "11111111-1111-4000-8000-111111111111"; + const workerTwo = "22222222-2222-4000-8000-222222222222"; + const workerKilled = "33333333-3333-4000-8000-333333333333"; + const writeFile = (segments: ReadonlyArray, body: string) => { + const file = path.join(profile, "antigravity-acp", "brain", ...segments); + return fs + .makeDirectory(path.dirname(file), { recursive: true }) + .pipe(Effect.andThen(fs.writeFileString(file, body))); + }; + const writeWorker = ( + convId: string, + name: string, + callId: string, + args: Record, + reply: string, + ) => + Effect.all([ + writeFile( + [ROOT, ".system_generated", "subagents", `${convId}.json`], + JSON.stringify({ + conversationId: convId, + subagentDescriptor: { typeName: "self", role: `Swarm Worker (${name})` }, + state: "SUBAGENT_STATE_ALIVE", + }), + ), + writeFile( + [convId, ".system_generated", "messages", "launch.json"], + JSON.stringify({ + sender: ROOT, + content: `Task for ${name}`, + sourceMetadata: { + tool: { + conversationId: ROOT, + toolCall: { id: callId, name: "swarm", argumentsJson: JSON.stringify(args) }, + }, + }, + }), + ), + writeFile( + [convId, ".system_generated", "logs", "transcript.jsonl"], + `${JSON.stringify({ step_index: 0, type: "PLANNER_RESPONSE", status: "DONE", content: reply })}\n`, + ), + ]); + + const batchArgs = { + action: "add", + name: "shard", + brief: "Inspect shard", + tasks: ["First shard", "Second shard"], + }; + yield* writeWorker(workerOne, "shard-1", "call_batch", batchArgs, "shard-1 finished"); + yield* writeWorker(workerTwo, "shard-2", "call_batch", batchArgs, "shard-2 working"); + yield* writeWorker( + workerKilled, + "retired", + "call_retired", + { action: "add", name: "retired", brief: "Old task" }, + "stopped", + ); + yield* writeFile( + [ROOT, ".system_generated", "swarm", "members.json"], + JSON.stringify({ + title: "Shard audit", + members: { + coordinator: { conversation_id: ROOT, role: "coordinator", wake_mode: "mentions" }, + "shard-1": { conversation_id: workerOne, role: "worker", wake_mode: "mentions" }, + "shard-2": { conversation_id: workerTwo, role: "worker", wake_mode: "working" }, + retired: { + conversation_id: workerKilled, + role: "worker", + desired_state: "KILLED", + phase: "KILLED", + wake_mode: "working", + }, + }, + }), + ); + + // shard-1 is parked on mentions and retired is killed; only shard-2 keeps call_batch active. + expect( + yield* readAntigravityChildrenAtWork({ + profileDirectory: profile, + rootSessionId: ROOT, + toolCallIds: ["call_batch", "call_retired"], + }), + ).toEqual(["call_batch"]); + + const batchChildren = yield* read(profile, "call_batch"); + expect(batchChildren.map((child) => [child.role, child.prompt])).toEqual([ + ["@shard-1", "Inspect shard\n\nFirst shard"], + ["@shard-2", "Inspect shard\n\nSecond shard"], + ]); + expect(batchChildren[0]?.steps?.[0]?.text).toBe("shard-1 finished"); + + const direct = yield* read(profile, `swarm:${workerOne}`); + expect(direct).toHaveLength(1); + expect(direct[0]?.role).toBe("@shard-1"); + }), + ); + it.effect("shares one transcript budget across the batch", () => Effect.gen(function* () { const filler = JSON.stringify({ diff --git a/apps/server/src/provider/acp/AntigravityChildWork.ts b/apps/server/src/provider/acp/AntigravityChildWork.ts index aa0932cf0f41a..d23dd67ed58ef 100644 --- a/apps/server/src/provider/acp/AntigravityChildWork.ts +++ b/apps/server/src/provider/acp/AntigravityChildWork.ts @@ -46,17 +46,64 @@ interface AntigravityChildLaunch { readonly prompt: string; } +import { swarmWorkerConversationIdFromTaskId } from "./AntigravitySwarm.ts"; + const LaunchInput = Schema.Struct({ Role: Schema.String, Prompt: Schema.String }); +const SwarmAddInput = Schema.Struct({ + action: Schema.String, + name: Schema.optional(Schema.String), + role: Schema.optional(Schema.String), + brief: Schema.optional(Schema.String), + n: Schema.optional(Schema.Number), + tasks: Schema.optional(Schema.Array(Schema.String)), +}); // agy 1.5 launches one child per call with a flat input; earlier releases send a batch. const decodeLaunchInput = Schema.decodeUnknownOption( Schema.Union([Schema.Struct({ Subagents: Schema.NonEmptyArray(LaunchInput) }), LaunchInput]), ); +const decodeSwarmAddInput = Schema.decodeUnknownOption(SwarmAddInput); + +function swarmAddLaunches(input: unknown): ReadonlyArray | undefined { + const decoded = Option.getOrUndefined(decodeSwarmAddInput(input)); + if (decoded === undefined || decoded.action.trim().toLowerCase() !== "add") return undefined; + const baseName = decoded.name?.trim().replace(/^@/, "") ?? ""; + const brief = decoded.brief?.trim() ?? ""; + const tasks = decoded.tasks ?? []; + const requestedCount = + decoded.n !== undefined && Number.isFinite(decoded.n) ? Math.trunc(decoded.n) : 0; + const count = Math.max(tasks.length, requestedCount, 1); + const roleSuffix = + decoded.role !== undefined && decoded.role.trim().length > 0 && decoded.role !== "worker" + ? ` (${decoded.role.trim()})` + : ""; + + if (count === 1) { + const task = tasks[0]?.trim() ?? ""; + const prompt = brief.length > 0 && task.length > 0 ? `${brief}\n\n${task}` : brief || task; + return [ + { + role: baseName.length > 0 ? `@${baseName}${roleSuffix}` : `Swarm worker${roleSuffix}`, + prompt, + }, + ]; + } + + return Array.from({ length: count }, (_, index) => { + const task = tasks[index]?.trim() ?? ""; + const prompt = brief.length > 0 && task.length > 0 ? `${brief}\n\n${task}` : task || brief; + const role = + baseName.length > 0 + ? `@${baseName}-${index + 1}${roleSuffix}` + : `Swarm worker ${index + 1}${roleSuffix}`; + return { role, prompt }; + }); +} -/** `invoke_subagent` arguments, from the permission prompt or the persisted record. */ +/** `invoke_subagent` or native `swarm` (`action: "add"`) arguments. */ export function antigravitySubagentLaunches( input: unknown, ): ReadonlyArray | undefined { - return Option.getOrUndefined( + const classic = Option.getOrUndefined( Option.map(decodeLaunchInput(input), (decoded) => ("Subagents" in decoded ? decoded.Subagents : [decoded]).map((entry) => ({ role: entry.Role, @@ -64,6 +111,7 @@ export function antigravitySubagentLaunches( })), ), ); + return classic ?? swarmAddLaunches(input); } /** Batch title and prompt; reads match permission-prompt tool call ids against this exact text. */ @@ -580,11 +628,71 @@ function detachedLaunchCall(message: ChildMessage, rootSessionId: string) { const call = tool?.toolCall; return message.sender === rootSessionId && (tool?.conversationId === undefined || tool.conversationId === rootSessionId) && - call?.name === "invoke_subagent" + (call?.name === "invoke_subagent" || call?.name === "swarm") ? call : undefined; } +function swarmRoleLabel(descriptorRole: string | undefined): string | undefined { + const trimmed = descriptorRole?.trim() ?? ""; + const match = /^Swarm Worker \((.+)\)$/.exec(trimmed); + return match?.[1] !== undefined ? `@${match[1].trim()}` : undefined; +} + +const decodeSwarmRoster = Schema.decodeUnknownOption( + Schema.fromJsonString( + Schema.Struct({ + members: Schema.optional( + Schema.Record( + Schema.String, + Schema.Struct({ + conversation_id: Schema.optional(Schema.String), + role: Schema.optional(Schema.String), + desired_state: Schema.optional(Schema.String), + phase: Schema.optional(Schema.String), + wake_mode: Schema.optional(Schema.String), + }), + ), + ), + }), + ), +); + +interface DiskSwarmMember { + readonly name: string; + readonly role: string; + readonly killed: boolean; + readonly parked: boolean; +} + +async function readDiskSwarmMembersByConversationId( + profileRoot: string, + rootSessionId: string, +): Promise> { + const file = await antigravityManagedPath( + profileRoot, + ["antigravity-acp", "brain", rootSessionId, ".system_generated", "swarm", "members.json"], + "file", + ); + if (file === undefined || file.info.size > MAX_STEP_BYTES) return new Map(); + const raw = await NodeFSP.readFile(file.path, "utf8").catch(() => undefined); + if (raw === undefined) return new Map(); + const decoded = Option.getOrUndefined(decodeSwarmRoster(raw)); + const members = decoded?.members; + if (members === undefined) return new Map(); + const byConversation = new Map(); + for (const [name, member] of Object.entries(members)) { + const convId = member.conversation_id; + if (convId === undefined || !NATIVE_ID.test(convId)) continue; + const role = member.role ?? "worker"; + if (role === "coordinator") continue; + const killed = member.desired_state === "KILLED" || member.phase === "KILLED"; + const parked = member.wake_mode === "mentions" || member.wake_mode === "anything"; + byConversation.set(convId, { name, role, killed, parked }); + } + return byConversation; +} + async function readDetachedSubagent(profileRoot: string, rootSessionId: string, childId: string) { const file = await antigravityManagedPath( profileRoot, @@ -617,9 +725,30 @@ async function findDetachedInvokeRecord( rootSessionId: string, nativeTaskId: string, ): Promise { + const directSwarmChildId = swarmWorkerConversationIdFromTaskId(nativeTaskId); + if (directSwarmChildId !== undefined) { + if (!NATIVE_ID.test(directSwarmChildId)) return undefined; + const subagent = await readDetachedSubagent(profileRoot, rootSessionId, directSwarmChildId); + if (subagent === undefined) return undefined; + const messages = await readInbox(profileRoot, directSwarmChildId).catch(() => undefined); + const firstPrompt = messages?.find((message) => typeof message.content === "string")?.content; + return { + toolCallId: nativeTaskId, + launches: [ + { + role: + swarmRoleLabel(subagent.subagentDescriptor?.role) ?? + subagent.subagentDescriptor?.role ?? + "", + prompt: firstPrompt ?? "", + }, + ], + children: [{ conversationId: directSwarmChildId }], + }; + } const childIds = await listDetachedChildIds(profileRoot, rootSessionId); if (childIds === undefined || childIds.length === 0) return undefined; - const matches: Array = []; + const matches: Array = []; for (const childId of childIds) { const messages = await readInbox(profileRoot, childId).catch(() => undefined); // An unreadable or oversized sibling inbox could also claim this id, so uniqueness is unproven. @@ -630,25 +759,50 @@ async function findDetachedInvokeRecord( if (launchMessage === undefined) continue; const subagent = await readDetachedSubagent(profileRoot, rootSessionId, childId); if (subagent === undefined) return undefined; - const argumentsJson = launchMessage.sourceMetadata?.tool?.toolCall?.argumentsJson; + const call = launchMessage.sourceMetadata?.tool?.toolCall; + const isSwarm = call?.name === "swarm"; + const argumentsJson = call?.argumentsJson; const parsedArgs = argumentsJson === undefined ? undefined : Option.getOrUndefined(decodeArgument(argumentsJson)); - const [fromArgs] = antigravitySubagentLaunches(parsedArgs) ?? []; + const argLaunches = antigravitySubagentLaunches(parsedArgs); + const descriptorLabel = swarmRoleLabel(subagent.subagentDescriptor?.role); + const matchedLaunch = + isSwarm && descriptorLabel !== undefined + ? (argLaunches?.find((entry) => entry.role.startsWith(descriptorLabel)) ?? { + role: descriptorLabel, + prompt: launchMessage.content ?? argLaunches?.[0]?.prompt ?? "", + }) + : argLaunches?.[0]; matches.push({ + isSwarm, toolCallId: nativeTaskId, launches: [ - fromArgs ?? { - role: subagent.subagentDescriptor?.role ?? "", + matchedLaunch ?? { + role: descriptorLabel ?? subagent.subagentDescriptor?.role ?? "", prompt: launchMessage.content ?? "", }, ], children: [{ conversationId: childId }], }); } - const [match] = matches; - return matches.length === 1 ? match : undefined; + if (matches.length === 1) { + return matches[0]; + } + if (matches.length > 1 && matches.every((entry) => entry.isSwarm)) { + const ordered = [...matches].sort((left, right) => + (left.launches[0]?.role ?? "").localeCompare(right.launches[0]?.role ?? "", undefined, { + numeric: true, + }), + ); + return { + toolCallId: nativeTaskId, + launches: ordered.flatMap((entry) => entry.launches), + children: ordered.flatMap((entry) => entry.children), + }; + } + return undefined; } const PENDING_REPLY_TAIL_BYTES = 64 * 1024; @@ -799,20 +953,30 @@ export const readAntigravityChildrenAtWork = Effect.fn("readAntigravityChildrenA const reported = new Set( (await readInbox(profileRoot, input.rootSessionId)).map((message) => message.sender), ); - const atWork: Array = []; + const swarmMembers = await readDiskSwarmMembersByConversationId( + profileRoot, + input.rootSessionId, + ); + const atWork = new Set(); for (const childId of childIds) { if (reported.has(childId)) continue; + const swarmMember = swarmMembers.get(childId); + if (swarmMember?.killed === true || swarmMember?.parked === true) continue; // `manage_subagents` kill only marks the record; a killed child never reports. const subagent = await readDetachedSubagent(profileRoot, input.rootSessionId, childId); if (subagent?.state === "SUBAGENT_STATE_KILLED") continue; + const directTaskId = `swarm:${childId}`; + if (input.toolCallIds.includes(directTaskId)) { + atWork.add(directTaskId); + } for (const message of await readInbox(profileRoot, childId)) { const launch = detachedLaunchCall(message, input.rootSessionId); if (launch !== undefined && input.toolCallIds.includes(launch.id)) { - atWork.push(launch.id); + atWork.add(launch.id); } } } - return atWork; + return [...atWork]; }; return yield* Effect.tryPromise({ try: read, diff --git a/apps/server/src/provider/acp/AntigravityProtocol.test.ts b/apps/server/src/provider/acp/AntigravityProtocol.test.ts index cfe47280fc4f1..dd15b886d4bcc 100644 --- a/apps/server/src/provider/acp/AntigravityProtocol.test.ts +++ b/apps/server/src/provider/acp/AntigravityProtocol.test.ts @@ -74,6 +74,68 @@ describe("native Antigravity subagent tools", () => { antigravitySubagentOutput({ toolCallId: "trajectory:4", data: { rawOutput: {} } }), ).toBeUndefined(); }); + + it("classifies swarm worker launches and formats legacy swarm board tools cleanly", () => { + const addCall = normalizeAntigravityToolCall({ + toolCallId: "swarm-add-1", + title: "Run swarm", + kind: "other", + status: "completed", + data: { + rawInput: { action: "add", name: "parser", brief: "Audit parser module" }, + rawOutput: { status: "added", name: "parser", conversation_id: "child-1" }, + }, + }); + expect(addCall.title).toBe("Add swarm worker @parser"); + expect(classifyAntigravitySubagentToolCall(addCall, {})).toBe("subagent"); + expect( + classifyAntigravitySubagentToolCall( + { + toolCallId: "swarm-mcp", + title: "Run swarm", + kind: "other", + data: { rawInput: { action: "add", name: "parser" } }, + }, + { update: { _meta: { is_mcp_tool_call: true } } }, + ), + ).toBe("mcp"); + + const killCall = normalizeAntigravityToolCall({ + toolCallId: "swarm-kill-1", + title: "Run swarm", + kind: "other", + data: { rawInput: { action: "kill", name: "parser" } }, + }); + expect(killCall.title).toBe("Stop swarm worker @parser"); + expect(classifyAntigravitySubagentToolCall(killCall, {})).toBeUndefined(); + + const postCall = normalizeAntigravityToolCall({ + toolCallId: "swarm-post-1", + title: "Run post_message", + kind: "other", + data: { rawInput: { channel: "backend", text: "@coordinator done" } }, + }); + expect(postCall.title).toBe("Post to #backend"); + expect(classifyAntigravitySubagentToolCall(postCall, {})).toBeUndefined(); + + const readCall = normalizeAntigravityToolCall({ + toolCallId: "swarm-read-1", + title: "Run read_board", + kind: "other", + data: { rawInput: { since: 1 } }, + }); + expect(readCall.title).toBe("Read swarm board"); + expect(readCall.kind).toBe("other"); + + const waitCall = normalizeAntigravityToolCall({ + toolCallId: "swarm-wait-1", + title: "Run swarm_wait", + kind: "other", + data: { rawInput: { since: 2, wake_on: "mentions" } }, + }); + expect(waitCall.title).toBe("Wait for swarm board"); + expect(waitCall.kind).toBe("think"); + }); }); const questionRequest = { diff --git a/apps/server/src/provider/acp/AntigravityProtocol.ts b/apps/server/src/provider/acp/AntigravityProtocol.ts index 2ba17c8a86db5..f8f16c4635879 100644 --- a/apps/server/src/provider/acp/AntigravityProtocol.ts +++ b/apps/server/src/provider/acp/AntigravityProtocol.ts @@ -509,7 +509,7 @@ export function normalizeAntigravityToolCall( ...(exitCode !== undefined ? { exitCode } : {}), }; } - return { + const normalized: AcpToolCallState = { ...toolCall, ...(kind !== undefined ? { kind } : {}), ...(command !== undefined ? { command } : {}), @@ -521,6 +521,7 @@ export function normalizeAntigravityToolCall( : {}), data, }; + return normalizeAntigravitySwarmToolPresentation(normalized); } const ANTIGRAVITY_SUBAGENT_TITLES = new Set([ @@ -532,19 +533,271 @@ const ANTIGRAVITY_SUBAGENT_TITLES = new Set([ "Run invoke_subagent", ]); -/** The ACP agent reports subagent calls as ordinary tools without child IDs or models. */ +const ANTIGRAVITY_SWARM_TOOLS = new Set([ + "swarm", + "post_message", + "read_board", + "swarm_wait", +] as const); + +export type AntigravitySwarmToolName = "swarm" | "post_message" | "read_board" | "swarm_wait"; + +const LEGACY_SWARM_TITLE_TO_TOOL = new Map([ + ["Running swarm", "swarm"], + ["Run swarm?", "swarm"], + ["Run swarm", "swarm"], + ["Running post_message", "post_message"], + ["Run post_message?", "post_message"], + ["Run post_message", "post_message"], + ["Running read_board", "read_board"], + ["Run read_board?", "read_board"], + ["Run read_board", "read_board"], + ["Running swarm_wait", "swarm_wait"], + ["Run swarm_wait?", "swarm_wait"], + ["Run swarm_wait", "swarm_wait"], +]); + +function readToolMeta(toolCall: AcpToolCallState, rawPayload?: unknown): unknown { + const update = Predicate.isObject(rawPayload) ? rawPayload.update : undefined; + if (Predicate.isObject(update) && update._meta !== undefined) return update._meta; + return toolCall.data.meta ?? toolCall.data._meta; +} + +function isSwarmToolName(value: unknown): value is AntigravitySwarmToolName { + return ( + typeof value === "string" && ANTIGRAVITY_SWARM_TOOLS.has(value as AntigravitySwarmToolName) + ); +} + +export function identifyAntigravitySwarmToolCall( + toolCall: AcpToolCallState, + rawPayload?: unknown, +): + | { + readonly tool: AntigravitySwarmToolName; + readonly action?: string | undefined; + readonly mcp: boolean; + } + | undefined { + const meta = readToolMeta(toolCall, rawPayload); + const mcp = Predicate.isObject(meta) && meta.is_mcp_tool_call === true; + const antigravity = Predicate.isObject(meta) ? meta.antigravity : undefined; + const swarmMeta = Predicate.isObject(antigravity) ? antigravity.swarm : undefined; + const metaTool = Predicate.isObject(swarmMeta) ? swarmMeta.tool : undefined; + const tool = isSwarmToolName(metaTool) + ? metaTool + : toolCall.title === undefined + ? undefined + : LEGACY_SWARM_TITLE_TO_TOOL.get(toolCall.title.trim()); + if (tool === undefined) return undefined; + if ( + (tool === "swarm" || tool === "post_message") && + toolCall.kind !== undefined && + toolCall.kind !== "other" + ) { + return undefined; + } + if ( + tool === "read_board" && + toolCall.kind !== undefined && + toolCall.kind !== "other" && + toolCall.kind !== "read" + ) { + return undefined; + } + if ( + tool === "swarm_wait" && + toolCall.kind !== undefined && + toolCall.kind !== "other" && + toolCall.kind !== "think" + ) { + return undefined; + } + const metaAction = + Predicate.isObject(swarmMeta) && typeof swarmMeta.action === "string" + ? swarmMeta.action.trim() + : undefined; + const rawInput = toolCall.data.rawInput; + const inputAction = + Predicate.isObject(rawInput) && typeof rawInput.action === "string" + ? rawInput.action.trim() + : undefined; + const action = metaAction || inputAction; + return { tool, ...(action === undefined ? {} : { action }), mcp }; +} + +function formatSwarmToolPresentation( + tool: AntigravitySwarmToolName, + action: string | undefined, + rawInput: unknown, +): { readonly kind: NonNullable; readonly title: string } { + const input = Predicate.isObject(rawInput) ? rawInput : undefined; + const cleanHandle = (value: unknown) => + typeof value === "string" ? value.trim().replace(/^@/, "") : ""; + const cleanChannel = (value: unknown) => + typeof value === "string" ? value.trim().replace(/^#/, "") : ""; + + switch (tool) { + case "swarm": { + const name = cleanHandle(input?.name); + switch (action?.toLowerCase()) { + case "add": { + const tasks = Array.isArray(input?.tasks) ? input.tasks.length : 0; + const n = + typeof input?.n === "number" && Number.isFinite(input.n) ? Math.trunc(input.n) : 0; + const count = Math.max(tasks, n); + if (count > 1 && name.length > 0) { + return { kind: "other", title: `Add ${count} swarm workers (@${name}-1..${count})` }; + } + if (count > 1) return { kind: "other", title: `Add ${count} swarm workers` }; + return { + kind: "other", + title: name.length > 0 ? `Add swarm worker @${name}` : "Add swarm worker", + }; + } + case "kill": + return { + kind: "other", + title: name.length > 0 ? `Stop swarm worker @${name}` : "Stop swarm worker", + }; + case "status": + return { kind: "other", title: "Check swarm status" }; + case "models": + return { kind: "other", title: "List swarm models" }; + case "model": { + const model = typeof input?.model === "string" ? input.model.trim() : ""; + if (name.length > 0 && model.length > 0) { + return { kind: "other", title: `Switch @${name} model to ${model}` }; + } + if (name.length > 0) return { kind: "other", title: `Switch swarm model for @${name}` }; + if (model.length > 0) return { kind: "other", title: `Switch swarm model to ${model}` }; + return { kind: "other", title: "Switch swarm model" }; + } + case "title": { + const title = typeof input?.title === "string" ? input.title.trim() : ""; + return { + kind: "other", + title: title.length > 0 ? `Set swarm title "${title}"` : "Set swarm title", + }; + } + case "channel": { + const op = typeof input?.op === "string" ? input.op.trim() : ""; + const channel = cleanChannel(input?.channel); + if (op.length > 0 && channel.length > 0) { + return { kind: "other", title: `Swarm channel ${op} #${channel}` }; + } + return { + kind: "other", + title: op.length > 0 ? `Swarm channel ${op}` : "Manage swarm channels", + }; + } + case "join": { + const swarm = typeof input?.swarm === "string" ? input.swarm.trim() : ""; + return { + kind: "other", + title: swarm.length > 0 ? `Join swarm ${swarm}` : "Join swarm", + }; + } + default: + return { kind: "other", title: "Run swarm" }; + } + } + case "post_message": { + const channel = cleanChannel(input?.channel); + return { + kind: "other", + title: + channel.length > 0 && channel !== "main" ? `Post to #${channel}` : "Post to swarm board", + }; + } + case "read_board": { + if (input?.status === true) return { kind: "other", title: "Read swarm status" }; + const channel = cleanChannel(input?.channel); + return { + kind: "other", + title: + channel.length > 0 && channel !== "main" && channel !== "*" + ? `Read #${channel}` + : "Read swarm board", + }; + } + case "swarm_wait": + return { kind: "think", title: "Wait for swarm board" }; + } +} + +function normalizeAntigravitySwarmToolPresentation(toolCall: AcpToolCallState): AcpToolCallState { + const swarm = identifyAntigravitySwarmToolCall(toolCall); + if (swarm === undefined || swarm.mcp) return toolCall; + const legacyTool = + toolCall.title === undefined + ? undefined + : LEGACY_SWARM_TITLE_TO_TOOL.get(toolCall.title.trim()); + if (legacyTool === undefined) return toolCall; + const presentation = formatSwarmToolPresentation( + swarm.tool, + swarm.action, + toolCall.data.rawInput, + ); + const existingMeta = Predicate.isObject(toolCall.data.meta) ? toolCall.data.meta : {}; + const existingAntigravity = Predicate.isObject(existingMeta.antigravity) + ? existingMeta.antigravity + : {}; + return { + ...toolCall, + kind: presentation.kind, + title: boundText(presentation.title), + data: { + ...toolCall.data, + meta: { + ...existingMeta, + antigravity: { + ...existingAntigravity, + swarm: { + tool: swarm.tool, + ...(swarm.action === undefined ? {} : { action: swarm.action }), + }, + }, + }, + }, + }; +} + +export function antigravitySwarmAddChildSessionId(toolCall: AcpToolCallState): string | null { + const output = toolCall.data.rawOutput; + if (!Predicate.isObject(output) || typeof output.conversation_id !== "string") return null; + const id = output.conversation_id.trim(); + return id.length > 0 ? id : null; +} + +export function antigravitySwarmAddModel(toolCall: AcpToolCallState): string | null { + const output = toolCall.data.rawOutput; + if (Predicate.isObject(output) && typeof output.model === "string" && output.model.trim()) { + return output.model.trim(); + } + const input = toolCall.data.rawInput; + if (Predicate.isObject(input) && typeof input.model === "string" && input.model.trim()) { + return input.model.trim(); + } + return null; +} + +/** Classifies native Antigravity subagent and `swarm` worker launch tool calls. */ export function classifyAntigravitySubagentToolCall( toolCall: AcpToolCallState, rawPayload?: unknown, ): "subagent" | "mcp" | undefined { - if ( - (toolCall.kind !== undefined && toolCall.kind !== "other") || - toolCall.title === undefined || - !ANTIGRAVITY_SUBAGENT_TITLES.has(toolCall.title) - ) + if (toolCall.kind !== undefined && toolCall.kind !== "other") return undefined; + const swarm = identifyAntigravitySwarmToolCall(toolCall, rawPayload); + if (swarm !== undefined) { + if (swarm.tool !== "swarm") return undefined; + if (swarm.mcp) return "mcp"; + return swarm.action?.toLowerCase() === "add" ? "subagent" : undefined; + } + if (toolCall.title === undefined || !ANTIGRAVITY_SUBAGENT_TITLES.has(toolCall.title)) { return undefined; - const update = Predicate.isObject(rawPayload) ? rawPayload.update : undefined; - const meta = Predicate.isObject(update) ? update._meta : toolCall.data.meta; + } + const meta = readToolMeta(toolCall, rawPayload); return Predicate.isObject(meta) && meta.is_mcp_tool_call === true ? "mcp" : "subagent"; } diff --git a/apps/server/src/provider/acp/AntigravitySwarm.test.ts b/apps/server/src/provider/acp/AntigravitySwarm.test.ts new file mode 100644 index 0000000000000..6cc53d3f6676e --- /dev/null +++ b/apps/server/src/provider/acp/AntigravitySwarm.test.ts @@ -0,0 +1,204 @@ +import * as Schema from "effect/Schema"; +import { describe, expect, it } from "vite-plus/test"; + +import { + ANTIGRAVITY_SWARM_CAPABILITIES_META, + ANTIGRAVITY_SWARM_NOTIFICATION_METHOD, + AntigravitySwarmNotification, + agentAdvertisesAntigravitySwarm, + makeAntigravitySwarmTracker, +} from "./AntigravitySwarm.ts"; + +describe("AntigravitySwarm", () => { + it("detects advertised swarm capability on initialize responses", () => { + expect(ANTIGRAVITY_SWARM_NOTIFICATION_METHOD).toBe("_antigravity/swarm"); + expect(ANTIGRAVITY_SWARM_CAPABILITIES_META).toEqual({ antigravity: { swarm: true } }); + expect(agentAdvertisesAntigravitySwarm({ _meta: { antigravity: { swarm: true } } })).toBe(true); + expect( + agentAdvertisesAntigravitySwarm({ _meta: { antigravity: { swarm: { enabled: true } } } }), + ).toBe(true); + expect( + agentAdvertisesAntigravitySwarm({ _meta: { antigravity: { swarm: { enabled: false } } } }), + ).toBe(false); + expect(agentAdvertisesAntigravitySwarm({ _meta: { antigravity: { swarm: false } } })).toBe( + false, + ); + expect(agentAdvertisesAntigravitySwarm({ _meta: { antigravity: { tier: true } } })).toBe(false); + expect(agentAdvertisesAntigravitySwarm(undefined)).toBe(false); + }); + + it("tracks multi-round worker lifecycles, board reports, helpers, and coordinator wakes", () => { + const decode = Schema.decodeUnknownSync(AntigravitySwarmNotification); + const tracker = makeAntigravitySwarmTracker(); + + const launched = tracker.applyNotification( + decode({ + sessionId: "root-1", + title: "API Audit", + head: 1, + activeWorkers: 2, + workingWorkers: 2, + waitingWorkers: 0, + members: [ + { + name: "alpha", + role: "worker", + conversationId: "worker-a", + toolCallId: "call-1", + brief: "Audit auth routes", + model: "model-pro", + modelLabel: "Model Pro", + state: "working", + addedBy: "coordinator", + }, + { + name: "helper", + role: "worker", + conversationId: "worker-h", + state: "working", + addedBy: "alpha", + }, + ], + posts: [ + { + seq: 1, + agent: "alpha", + kind: "brief", + text: "@helper Check rate limiter config", + }, + ], + }), + ); + + expect(launched.activeBackgroundWork).toBe(true); + expect(launched.subagents).toEqual([ + { + nativeTaskId: "swarm:worker-a", + childSessionId: "worker-a", + title: "@alpha", + prompt: "Audit auth routes", + model: "Model Pro", + status: "running", + result: null, + suppressNormalTool: true, + }, + { + nativeTaskId: "swarm:worker-h", + childSessionId: "worker-h", + title: "@helper via @alpha", + prompt: "@helper Check rate limiter config", + model: null, + status: "running", + result: null, + suppressNormalTool: true, + }, + ]); + expect( + tracker.partitionTaskIds("root-1", ["swarm:worker-a", "swarm:worker-h", "other-call"]), + ).toEqual({ + runningSwarmTaskIds: ["swarm:worker-a", "swarm:worker-h"], + unmanagedTaskIds: ["other-call"], + }); + + // Workers report and park while coordinator still has a pending doorbell wake. + const handoff = tracker.applyNotification( + decode({ + sessionId: "root-1", + head: 3, + activeWorkers: 0, + workingWorkers: 0, + waitingWorkers: 2, + coordinatorPendingWake: true, + members: [ + { + name: "alpha", + role: "worker", + conversationId: "worker-a", + state: "waiting", + }, + { + name: "helper", + role: "worker", + conversationId: "worker-h", + state: "waiting", + }, + ], + posts: [ + { seq: 2, agent: "alpha", text: "@coordinator Auth routes look solid." }, + { seq: 3, agent: "helper", text: "@alpha Rate limiter uses token bucket." }, + ], + }), + ); + + expect(handoff.activeBackgroundWork).toBe(true); + expect(handoff.subagents[0]).toMatchObject({ + status: "idle", + result: "Auth routes look solid.", + }); + expect(handoff.subagents[1]).toMatchObject({ + status: "idle", + result: "@alpha Rate limiter uses token bucket.", + }); + expect(tracker.partitionTaskIds("root-1", ["swarm:worker-a", "swarm:worker-h"])).toEqual({ + runningSwarmTaskIds: [], + unmanagedTaskIds: [], + }); + + // Coordinator processes wake, then wakes @alpha for round 2 while killing @helper cleanly. + const round2 = tracker.applyNotification( + decode({ + sessionId: "root-1", + head: 4, + activeWorkers: 1, + workingWorkers: 1, + waitingWorkers: 0, + coordinatorPendingWake: false, + members: [ + { name: "alpha", role: "worker", conversationId: "worker-a", state: "working" }, + { name: "helper", role: "worker", conversationId: "worker-h", state: "killed" }, + ], + }), + ); + + expect(round2.activeBackgroundWork).toBe(true); + expect(round2.subagents[0]).toMatchObject({ status: "running", result: null }); + expect(round2.subagents[1]).toMatchObject({ + status: "completed", + result: "@alpha Rate limiter uses token bucket.", + }); + + // A never-reporting worker killed mid-turn maps to cancelled; a failed worker maps to failed. + const terminal = tracker.applyNotification( + decode({ + sessionId: "root-1", + head: 4, + activeWorkers: 0, + workingWorkers: 0, + waitingWorkers: 0, + members: [ + { + name: "alpha", + role: "worker", + conversationId: "worker-a", + state: "failed", + failure: "quota exhausted", + }, + { + name: "scratch", + role: "narrator", + conversationId: "worker-n", + state: "killed", + }, + ], + }), + ); + + expect(terminal.activeBackgroundWork).toBe(false); + expect(terminal.subagents[0]).toMatchObject({ status: "failed", result: "quota exhausted" }); + expect(terminal.subagents[1]).toMatchObject({ + title: "@scratch (narrator)", + status: "cancelled", + result: null, + }); + }); +}); diff --git a/apps/server/src/provider/acp/AntigravitySwarm.ts b/apps/server/src/provider/acp/AntigravitySwarm.ts new file mode 100644 index 0000000000000..9f706f07dcb0e --- /dev/null +++ b/apps/server/src/provider/acp/AntigravitySwarm.ts @@ -0,0 +1,331 @@ +import type { AcpAdapterV2SubagentUpdate } from "@t3tools/provider-acp/server/adapter"; +import * as Schema from "effect/Schema"; + +export const ANTIGRAVITY_SWARM_CAPABILITIES_META = { + antigravity: { + swarm: true, + }, +} as const; + +export const ANTIGRAVITY_SWARM_NOTIFICATION_METHOD = "_antigravity/swarm"; + +const ANTIGRAVITY_SWARM_TASK_PREFIX = "swarm:"; + +export const AntigravitySwarmMember = Schema.Struct({ + name: Schema.String, + role: Schema.String, + conversationId: Schema.String, + toolCallId: Schema.optional(Schema.String), + brief: Schema.optional(Schema.String), + model: Schema.optional(Schema.String), + modelLabel: Schema.optional(Schema.String), + state: Schema.String, + failure: Schema.optional(Schema.String), + workspace: Schema.optional(Schema.String), + addedBy: Schema.optional(Schema.String), +}); +export type AntigravitySwarmMember = Schema.Schema.Type; + +export const AntigravitySwarmPost = Schema.Struct({ + seq: Schema.Number, + time: Schema.optional(Schema.String), + agent: Schema.String, + channel: Schema.optional(Schema.String), + kind: Schema.optional(Schema.String), + text: Schema.String, +}); +export type AntigravitySwarmPost = Schema.Schema.Type; + +export const AntigravitySwarmNotification = Schema.Struct({ + sessionId: Schema.String, + title: Schema.optional(Schema.String), + head: Schema.Number, + channels: Schema.optional(Schema.Array(Schema.String)), + activeWorkers: Schema.Number, + workingWorkers: Schema.Number, + waitingWorkers: Schema.Number, + coordinatorPendingWake: Schema.optional(Schema.Boolean), + members: Schema.Array(AntigravitySwarmMember), + posts: Schema.optional(Schema.Array(AntigravitySwarmPost)), +}); +export type AntigravitySwarmNotification = Schema.Schema.Type; + +const MAX_BOARD_REPORT_CHARS = 8_000; + +interface TrackedSwarmMember { + nativeTaskId: string; + name: string; + conversationId: string; + toolCallId: string | null; + status: AcpAdapterV2SubagentUpdate["status"]; + latestReport: string | null; + lastBrief: string; + sawIdleOrReport: boolean; +} + +interface TrackedSwarmSession { + busy: boolean; + readonly membersByConversationId: Map; + readonly membersByName: Map; + readonly latestPostsByAgent: Map; + readonly briefsByMention: Map; +} + +function nonEmpty(value: string | undefined): string | undefined { + const trimmed = value?.trim(); + return trimmed !== undefined && trimmed.length > 0 ? trimmed : undefined; +} + +function cleanBoardReport(text: string): string | null { + const withoutCoordinatorPrefix = text.trim().replace(/^@(?:coordinator|all)\b[:,\s-]*/i, ""); + const normalized = (withoutCoordinatorPrefix.length > 0 ? withoutCoordinatorPrefix : text).trim(); + if (normalized.length === 0) return null; + return normalized.length <= MAX_BOARD_REPORT_CHARS + ? normalized + : `${normalized.slice(0, MAX_BOARD_REPORT_CHARS - 1)}…`; +} + +function extractMentionedNames(text: string): ReadonlyArray { + const names: Array = []; + for (const match of text.matchAll(/(?:^|\s)@([a-z0-9][a-z0-9_-]*)\b/gi)) { + const name = match[1]?.toLowerCase(); + if (name !== undefined && name !== "coordinator" && name !== "all") { + names.push(name); + } + } + return names; +} + +function formatSwarmMemberTitle(member: AntigravitySwarmMember): string { + const handle = `@${member.name.replace(/^@/, "")}`; + const roleSuffix = + member.role !== "worker" && member.role.trim().length > 0 ? ` (${member.role.trim()})` : ""; + const addedBy = nonEmpty(member.addedBy)?.replace(/^@/, ""); + const parentSuffix = addedBy !== undefined && addedBy !== "coordinator" ? ` via @${addedBy}` : ""; + return `${handle}${roleSuffix}${parentSuffix}`; +} + +function mapSwarmMemberStatus( + state: string, + sawIdleOrReport: boolean, +): AcpAdapterV2SubagentUpdate["status"] { + switch (state.trim().toLowerCase()) { + case "working": + return "running"; + case "waiting": + case "stopped": + return "idle"; + case "failed": + return "failed"; + case "killed": + return sawIdleOrReport ? "completed" : "cancelled"; + default: + return "idle"; + } +} + +export function agentAdvertisesAntigravitySwarm(agentCapabilities: unknown): boolean { + if (typeof agentCapabilities !== "object" || agentCapabilities === null) return false; + const meta = (agentCapabilities as { readonly _meta?: unknown })._meta; + if (typeof meta !== "object" || meta === null) return false; + const antigravity = (meta as { readonly antigravity?: unknown }).antigravity; + if (typeof antigravity !== "object" || antigravity === null) return false; + const swarm = (antigravity as { readonly swarm?: unknown }).swarm; + if (swarm === true) return true; + if (typeof swarm === "object" && swarm !== null) { + const enabled = (swarm as { readonly enabled?: unknown }).enabled; + return enabled !== false; + } + return false; +} + +export function swarmWorkerConversationIdFromTaskId(nativeTaskId: string): string | undefined { + return nativeTaskId.startsWith(ANTIGRAVITY_SWARM_TASK_PREFIX) + ? nativeTaskId.slice(ANTIGRAVITY_SWARM_TASK_PREFIX.length) + : undefined; +} + +export interface AntigravitySwarmMutation { + readonly sessionId: string; + readonly activeBackgroundWork: boolean; + readonly subagents: ReadonlyArray; +} + +export interface AntigravitySwarmTracker { + readonly applyNotification: ( + notification: AntigravitySwarmNotification, + ) => AntigravitySwarmMutation; + readonly hasLiveSwarm: (sessionId: string) => boolean; + readonly partitionTaskIds: ( + sessionId: string, + nativeTaskIds: ReadonlyArray, + ) => { + readonly runningSwarmTaskIds: ReadonlyArray; + readonly unmanagedTaskIds: ReadonlyArray; + }; +} + +export function makeAntigravitySwarmTracker(): AntigravitySwarmTracker { + const sessions = new Map(); + + const sessionFor = (sessionId: string): TrackedSwarmSession => { + let session = sessions.get(sessionId); + if (session === undefined) { + session = { + busy: false, + membersByConversationId: new Map(), + membersByName: new Map(), + latestPostsByAgent: new Map(), + briefsByMention: new Map(), + }; + sessions.set(sessionId, session); + } + return session; + }; + + return { + applyNotification(notification) { + const session = sessionFor(notification.sessionId); + + for (const post of notification.posts ?? []) { + const author = post.agent.trim().toLowerCase(); + if (post.kind === "brief") { + const cleaned = cleanBoardReport(post.text); + if (cleaned !== null) { + for (const mentioned of extractMentionedNames(post.text)) { + if (!session.briefsByMention.has(mentioned)) { + session.briefsByMention.set(mentioned, cleaned); + } + } + } + continue; + } + if (author === "coordinator" || author.length === 0) continue; + const report = cleanBoardReport(post.text); + if (report === null) continue; + session.latestPostsByAgent.set(author, report); + const tracked = session.membersByName.get(author); + if (tracked !== undefined) { + tracked.latestReport = report; + tracked.sawIdleOrReport = true; + } + } + + const subagents: Array = []; + let runningMemberCount = 0; + + for (const member of notification.members) { + const conversationId = nonEmpty(member.conversationId); + if (conversationId === undefined || member.role === "coordinator") continue; + const nameKey = member.name.trim().toLowerCase(); + const callId = nonEmpty(member.toolCallId) ?? null; + + let tracked = session.membersByConversationId.get(conversationId); + const nativeTaskId = `${ANTIGRAVITY_SWARM_TASK_PREFIX}${conversationId}`; + if (tracked === undefined) { + tracked = { + nativeTaskId, + name: member.name, + conversationId, + toolCallId: callId, + status: "running", + latestReport: session.latestPostsByAgent.get(nameKey) ?? null, + lastBrief: "", + sawIdleOrReport: session.latestPostsByAgent.has(nameKey), + }; + session.membersByConversationId.set(conversationId, tracked); + session.membersByName.set(nameKey, tracked); + } else if (tracked.toolCallId === null && callId !== null) { + tracked.toolCallId = callId; + } + + const latestPost = session.latestPostsByAgent.get(nameKey) ?? tracked.latestReport; + if (latestPost !== null) { + tracked.latestReport = latestPost; + tracked.sawIdleOrReport = true; + } + + const nextStatus = mapSwarmMemberStatus(member.state, tracked.sawIdleOrReport); + if (nextStatus === "idle") { + tracked.sawIdleOrReport = true; + } + if (nextStatus === "running" || nextStatus === "pending") { + runningMemberCount += 1; + } + tracked.status = nextStatus; + + const brief = + nonEmpty(member.brief) ?? + nonEmpty(tracked.lastBrief) ?? + session.briefsByMention.get(nameKey) ?? + `Swarm ${member.role} @${member.name}`; + tracked.lastBrief = brief; + + const model = nonEmpty(member.modelLabel) ?? nonEmpty(member.model) ?? null; + const failureText = nonEmpty(member.failure) ?? null; + const result = + nextStatus === "running" + ? null + : nextStatus === "failed" + ? (failureText ?? tracked.latestReport ?? "Swarm worker execution failed.") + : tracked.latestReport; + + subagents.push({ + nativeTaskId: tracked.nativeTaskId, + childSessionId: conversationId, + title: formatSwarmMemberTitle(member), + prompt: brief, + model, + status: nextStatus, + result, + suppressNormalTool: true, + }); + } + + session.busy = + runningMemberCount > 0 || + notification.workingWorkers > 0 || + notification.activeWorkers > 0 || + notification.coordinatorPendingWake === true; + + return { + sessionId: notification.sessionId, + activeBackgroundWork: session.busy, + subagents, + }; + }, + + hasLiveSwarm(sessionId) { + return sessions.has(sessionId); + }, + + partitionTaskIds(sessionId, nativeTaskIds) { + const session = sessions.get(sessionId); + if (session === undefined) { + return { runningSwarmTaskIds: [], unmanagedTaskIds: nativeTaskIds }; + } + const managedStatus = new Map(); + for (const member of session.membersByConversationId.values()) { + managedStatus.set(member.nativeTaskId, member.status); + if (member.toolCallId !== null) { + managedStatus.set(member.toolCallId, member.status); + } + managedStatus.set( + `${ANTIGRAVITY_SWARM_TASK_PREFIX}${member.conversationId}`, + member.status, + ); + } + const runningSwarmTaskIds: Array = []; + const unmanagedTaskIds: Array = []; + for (const id of nativeTaskIds) { + const status = managedStatus.get(id); + if (status === undefined) { + unmanagedTaskIds.push(id); + } else if (status === "running" || status === "pending") { + runningSwarmTaskIds.push(id); + } + } + return { runningSwarmTaskIds, unmanagedTaskIds }; + }, + }; +} diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index e214a51586f4c..b2de500dfeb5e 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -258,6 +258,25 @@ export interface AcpAdapterV2ExtensionContext { readonly status: "completed" | "failed" | "cancelled"; readonly result: string | null; }) => Effect.Effect; + /** + * Projects a provider-native subagent lifecycle update delivered out-of-band (for example an ACP + * swarm roster notification). When `allowReopenFromIdle` is true, a parked `"idle"` worker that + * wakes up again transitions back to `"running"` on its existing child thread. + */ + readonly upsertSubagent: (notice: { + readonly sessionId: string; + readonly subagent: AcpAdapterV2SubagentUpdate; + readonly allowReopenFromIdle?: boolean | undefined; + }) => Effect.Effect; + /** + * Reports whether the session has active out-of-turn background coordination (for example running + * swarm workers or a queued coordinator doorbell wake) that must defer turn settlement and keep + * the session alive across idle timeouts. + */ + readonly setExternalBackgroundWork: (notice: { + readonly sessionId: string; + readonly active: boolean; + }) => Effect.Effect; readonly applyBackgroundTaskMutation: (mutation: { readonly sessionId: string; readonly taskId: string; @@ -1908,6 +1927,9 @@ interface ActiveAcpSubagent { // ACP has no interrupted tool status; keep forced interruption across late updates. readonly interruptedToolIds: Set; readonly toolSessionIds: Map; + thoughtSegmentIndex: number; + thoughtText: string; + thoughtStartedAt: DateTime.Utc | null; } interface AcpNativeChildSession { @@ -2607,6 +2629,18 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const stoppedRunQuarantine = yield* Ref.make(false); // Native subagents can outlive interrupts; carry lineage forward to finish their original turn items. const carryoverSubagents = yield* Ref.make(null); + // Parked (idle) swarm workers retain their child thread lineage so later wakes or kills + // update the same worker subagent across turns. + const dormantSubagentsByChildSessionId = yield* Ref.make< + ReadonlyMap + >(new Map()); + const pendingExtensionSubagents = yield* Ref.make< + ReadonlyArray<{ + readonly subagent: AcpAdapterV2SubagentUpdate; + readonly allowReopenFromIdle: boolean; + }> + >([]); + let externalBackgroundWorkActive = false; const handledBackgroundTaskIdsInActiveTurn = yield* Ref.make>( new Set(), ); @@ -3479,21 +3513,114 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( }); }); + const writeSubagentThought = Effect.fnUntraced(function* ( + subagent: ActiveAcpSubagent, + completed: boolean, + ) { + if (subagent.thoughtText.length === 0) return; + const now = yield* DateTime.now; + const startedAt = subagent.thoughtStartedAt ?? now; + subagent.thoughtStartedAt = startedAt; + const baseId = subagent.task.nativeTaskRef?.nativeId ?? String(subagent.task.id); + const nativeItemId = `${baseId}:reasoning:${subagent.thoughtSegmentIndex}`; + const ordinal = resolveSubagentChildOrdinal(subagent, nativeItemId); + yield* emitProviderEvent({ + type: "turn_item.updated", + driver, + turnItem: { + id: providerTurnItemId(nativeItemId), + threadId: subagent.childThreadId, + runId: null, + nodeId: subagent.childRootNodeId, + providerThreadId: subagent.task.providerThreadId, + providerTurnId: null, + nativeItemRef: { driver, nativeId: nativeItemId, strength: "weak" }, + parentItemId: null, + ordinal, + status: completed ? "completed" : "running", + title: null, + startedAt, + completedAt: completed ? now : null, + updatedAt: now, + type: "reasoning", + text: subagent.thoughtText, + streaming: !completed, + }, + }); + if (completed) { + subagent.thoughtSegmentIndex += 1; + subagent.thoughtText = ""; + subagent.thoughtStartedAt = null; + } + }); + + const appendSubagentThought = Effect.fnUntraced(function* ( + subagent: ActiveAcpSubagent, + text: string, + mode: "append" | "replace", + ) { + if (text.length === 0) return; + subagent.thoughtText = mode === "replace" ? text : `${subagent.thoughtText}${text}`; + yield* writeSubagentThought(subagent, false); + }); + const projectSubagentNotification = Effect.fnUntraced(function* ( subagent: ActiveAcpSubagent, notification: EffectAcpSchema.SessionNotification, owner: ActiveAcpTurn, - ) { + ): Effect.fn.Return { const update = notification.update; - if (update.sessionUpdate === "agent_message_chunk") { + if (update.sessionUpdate === "tool_call" || update.sessionUpdate === "tool_call_update") { + yield* writeSubagentThought(subagent, true); + const nativeTaskId = subagent.task.nativeTaskRef?.nativeId ?? String(subagent.task.id); + for (const event of parseSessionUpdateEvent(notification).events) { + if (event._tag !== "ToolCallUpdated") continue; + const toolCall = flavor.normalizeToolCall?.(event.toolCall) ?? event.toolCall; + const subagentUpdate = extractSubagentUpdate(toolCall); + if (subagentUpdate !== undefined) { + if ( + subagentUpdate.nativeTaskId === nativeTaskId || + subagentUpdate.childSessionId === notification.sessionId + ) { + yield* emitSubagent(owner, subagentUpdate); + } + continue; + } + yield* projectSubagentTool( + subagent, + notification.sessionId, + toolCall, + undefined, + owner, + ); + } + } else if (update.sessionUpdate === "agent_thought_chunk") { const text = acpContentBlockDisplayText(update.content); if (text !== undefined) { + yield* appendSubagentThought(subagent, text, "append"); + } + } else if (update.sessionUpdate === "agent_thought") { + if (update.content === undefined) return; + const text = (update.content ?? []) + .flatMap((content) => { + const display = acpContentBlockDisplayText(content); + return display === undefined ? [] : [display]; + }) + .join("\n"); + yield* appendSubagentThought(subagent, text, "replace"); + yield* writeSubagentThought(subagent, true); + } else if (update.sessionUpdate === "agent_message_chunk") { + const text = acpContentBlockDisplayText(update.content); + if (text !== undefined) { + yield* writeSubagentThought(subagent, true); yield* emitSubagentAssistant(subagent, text, "append", update.messageId); } } else if (update.sessionUpdate === "tool_call_content_chunk") { + yield* writeSubagentThought(subagent, true); yield* projectSubagentTool(subagent, notification.sessionId, update, undefined, owner); } else if (update.sessionUpdate === "agent_message") { if (update.content === undefined) return; + yield* writeSubagentThought(subagent, true); const text = (update.content ?? []) .flatMap((content) => { const display = acpContentBlockDisplayText(content); @@ -3619,6 +3746,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const emitSubagent = Effect.fnUntraced(function* ( context: ActiveAcpTurn, reported: AcpAdapterV2SubagentUpdate, + options?: { readonly allowReopenFromIdle?: boolean | undefined }, ) { // Providers with cancellation detection already classify their subagent failures. const update: AcpAdapterV2SubagentUpdate = @@ -3634,10 +3762,21 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( ? context.subagentsBySessionId.get(update.childSessionId) : undefined); const updateIsTerminal = acpSubagentStatusIsTerminal(update.status); + const reopeningIdle = + options?.allowReopenFromIdle === true && + existing?.task.status === "idle" && + !updateIsTerminal; + const upgradingIdleToFinal = + options?.allowReopenFromIdle === true && + existing?.task.status === "idle" && + updateIsTerminal && + (update.status !== "idle" || + (update.result !== null && update.result !== existing.task.result)); if ( existing !== undefined && acpSubagentStatusIsTerminal(existing.task.status) && - !updateIsTerminal + !updateIsTerminal && + !reopeningIdle ) { return; } @@ -3645,7 +3784,8 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( existing !== undefined && existing.task.status === update.status && updateIsTerminal && - existing.terminalStatusProjected + existing.terminalStatusProjected && + !upgradingIdleToFinal ) { return; } @@ -3677,6 +3817,12 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const turnItemOrdinal = existing?.turnItemOrdinal ?? (yield* resolveItemOrdinal(context, nativeTaskId)); const taskStatus = update.status; + if (reopeningIdle && existing !== undefined) { + yield* flushSubagentAssistant(existing); + yield* writeSubagentThought(existing, true); + existing.terminalStatusProjected = false; + existing.assistantText = ""; + } const task: OrchestrationV2Subagent = { ...(existing?.task ?? { id: nodeId, @@ -3695,9 +3841,21 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( result: null, startedAt: now, }), + ...(existing !== undefined && + options?.allowReopenFromIdle === true && + update.title !== null && + existing.task.title === null + ? { title: update.title } + : {}), + ...(existing !== undefined && + options?.allowReopenFromIdle === true && + update.prompt.trim().length > 0 && + existing.task.prompt.trim().length === 0 + ? { prompt: update.prompt } + : {}), model: update.model?.trim() || existing?.task.model || null, status: taskStatus, - result: update.result ?? existing?.task.result ?? null, + result: reopeningIdle ? null : (update.result ?? existing?.task.result ?? null), completedAt: acpSubagentStatusIsTerminal(taskStatus) ? now : null, updatedAt: now, }; @@ -3723,6 +3881,9 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( }, interruptedToolIds: new Set(), toolSessionIds: new Map(), + thoughtSegmentIndex: 0, + thoughtText: "", + thoughtStartedAt: null, }; subagent.task = task; context.subagents.set(nativeTaskId, subagent); @@ -3816,6 +3977,9 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( } yield* flushSubagentAssistant(subagent); + if (taskStatus !== "running") { + yield* writeSubagentThought(subagent, true); + } // A failed child's result explains the failure; it is not the child's reply. if ( taskStatus !== "running" && @@ -3907,6 +4071,8 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( }); if (acpSubagentStatusIsTerminal(taskStatus)) { subagent.terminalStatusProjected = true; + } else { + subagent.terminalStatusProjected = false; } }); @@ -4257,6 +4423,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( /Monitor\s+["']?[0-9a-f-]{8,}/i.test(text) && /ended/i.test(text); const hasDeferredBackgroundWork = (context: ActiveAcpTurn): boolean => { + if (externalBackgroundWorkActive) return true; if (flavor.wakeOnDetachedRequest && agentRequests.size > 0) return true; if (flavor.toolOutlivesPrompt !== undefined) { // A tool that never started has nothing to report later. @@ -5988,50 +6155,22 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const subagent = context.subagentsBySessionId.get(notification.sessionId); if ( update.sessionUpdate === "tool_call" || - update.sessionUpdate === "tool_call_update" + update.sessionUpdate === "tool_call_update" || + update.sessionUpdate === "tool_call_content_chunk" ) { - if (subagent === undefined) return; - const nativeTaskId = - subagent.task.nativeTaskRef?.nativeId ?? String(subagent.task.id); - for (const event of parseSessionUpdateEvent(notification).events) { - if (event._tag !== "ToolCallUpdated") continue; - const toolCall = flavor.normalizeToolCall?.(event.toolCall) ?? event.toolCall; - const subagentUpdate = extractSubagentUpdate(toolCall); - if (subagentUpdate !== undefined) { - if ( - subagentUpdate.nativeTaskId === nativeTaskId || - subagentUpdate.childSessionId === notification.sessionId - ) { - yield* emitSubagent(context, subagentUpdate); - } - continue; - } - yield* projectSubagentTool( - subagent, - notification.sessionId, - toolCall, - undefined, - context, - ); + if (subagent !== undefined) { + yield* projectSubagentNotification(subagent, notification, context); } return; } - if (update.sessionUpdate === "tool_call_content_chunk") { - if (subagent !== undefined) - yield* projectSubagentTool( - subagent, - notification.sessionId, - update, - undefined, - context, - ); - return; - } - const isDisplayableAssistantUpdate = + const isProjectableChildUpdate = + (update.sessionUpdate === "agent_thought_chunk" && + acpContentBlockDisplayText(update.content) !== undefined) || + (update.sessionUpdate === "agent_thought" && update.content !== undefined) || (update.sessionUpdate === "agent_message_chunk" && acpContentBlockDisplayText(update.content) !== undefined) || (update.sessionUpdate === "agent_message" && update.content !== undefined); - if (!isDisplayableAssistantUpdate) { + if (!isProjectableChildUpdate) { return; } if (subagent !== undefined) { @@ -6039,8 +6178,10 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( return; } const buffered = context.pendingSubagentNotifications.get(notification.sessionId) ?? []; - buffered.push(notification); - context.pendingSubagentNotifications.set(notification.sessionId, buffered); + if (buffered.length < 256) { + buffered.push(notification); + context.pendingSubagentNotifications.set(notification.sessionId, buffered); + } return; } // The activeSessionId yield may let idle/prompt settlement finalize this context. @@ -6886,6 +7027,104 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( ); }); + const applyExtensionSubagentToTurn = Effect.fnUntraced(function* ( + context: ActiveAcpTurn, + update: AcpAdapterV2SubagentUpdate, + allowReopenFromIdle: boolean, + ) { + if (update.childSessionId !== null && allowReopenFromIdle) { + const knownInTurn = + context.subagents.get(update.nativeTaskId) ?? + context.subagentsBySessionId.get(update.childSessionId); + if (knownInTurn === undefined) { + const dormant = (yield* Ref.get(dormantSubagentsByChildSessionId)).get( + update.childSessionId, + ); + if (dormant !== undefined) { + const nativeId = dormant.task.nativeTaskRef?.nativeId ?? update.nativeTaskId; + context.subagents.set(nativeId, dormant); + context.subagentsBySessionId.set(update.childSessionId, dormant); + yield* Ref.update(dormantSubagentsByChildSessionId, (current) => { + const next = new Map(current); + next.delete(update.childSessionId!); + return next; + }); + } + } + } + yield* emitSubagent(context, update, { allowReopenFromIdle }); + if (hasDeferredBackgroundWork(context)) { + context.backgroundFinalizeGeneration += 1; + } else { + yield* rearmDeferredFinalize(context); + } + }); + + const upsertSubagentFromExtension = Effect.fnUntraced(function* (notice: { + readonly sessionId: string; + readonly subagent: AcpAdapterV2SubagentUpdate; + readonly allowReopenFromIdle?: boolean | undefined; + }) { + const allowReopenFromIdle = notice.allowReopenFromIdle === true; + const update = notice.subagent; + const context = yield* Ref.get(activeTurn); + if ( + context !== null && + !context.finalized && + !context.interrupted && + context.nativeThreadId === notice.sessionId + ) { + yield* applyExtensionSubagentToTurn(context, update, allowReopenFromIdle); + return; + } + if (acpSubagentStatusIsTerminal(update.status)) { + if (update.childSessionId !== null) { + const dormant = (yield* Ref.get(dormantSubagentsByChildSessionId)).get( + update.childSessionId, + ); + if (dormant !== undefined) { + const nextResult = update.result ?? dormant.task.result; + if (dormant.task.status !== update.status || dormant.task.result !== nextResult) { + yield* projectCarryoverSubagentStatus(dormant, update.status, nextResult); + } + if (update.status !== "idle") { + yield* Ref.update(dormantSubagentsByChildSessionId, (current) => { + const next = new Map(current); + next.delete(update.childSessionId!); + return next; + }); + } + return; + } + const carryover = yield* Ref.get(carryoverSubagents); + yield* updateCarryoverSubagentStatus( + update.childSessionId, + update.status, + update.result, + { + project: + carryover !== null && + carryover.sessionId === notice.sessionId && + carryover.projectsLateTerminals, + }, + ); + } + return; + } + if (postSettleContinuationEnabled && !(yield* Ref.get(loadingSessionId))) { + yield* Ref.update(pendingExtensionSubagents, (current) => [ + ...current.filter( + (entry) => + entry.subagent.nativeTaskId !== update.nativeTaskId && + (update.childSessionId === null || + entry.subagent.childSessionId !== update.childSessionId), + ), + { subagent: update, allowReopenFromIdle }, + ]); + yield* offerContinuationRun(notice.sessionId); + } + }); + applyFinalizedActiveTurnSubagentTerminal = Effect.fnUntraced(function* ( context: ActiveAcpTurn, notification: EffectAcpSchema.SessionNotification, @@ -7633,6 +7872,38 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( yield* finishSubagentFromNotice(notice); }), ).pipe(Effect.asVoid), + upsertSubagent: (notice) => + runRuntimeCallbackAtGeneration( + handlerGeneration, + Effect.gen(function* () { + if (yield* Ref.get(stoppedRunQuarantine)) return; + if ((yield* Ref.get(activeSessionId)) !== notice.sessionId) return; + yield* upsertSubagentFromExtension(notice); + }), + ).pipe(Effect.asVoid), + setExternalBackgroundWork: (notice) => + runRuntimeCallbackAtGeneration( + handlerGeneration, + Effect.gen(function* () { + if (yield* Ref.get(stoppedRunQuarantine)) return; + if ((yield* Ref.get(activeSessionId)) !== notice.sessionId) return; + externalBackgroundWorkActive = notice.active; + const context = yield* Ref.get(activeTurn); + if ( + context === null || + context.finalized || + context.interrupted || + context.nativeThreadId !== notice.sessionId + ) { + return; + } + if (notice.active) { + context.backgroundFinalizeGeneration += 1; + } else { + yield* rearmDeferredFinalize(context); + } + }), + ).pipe(Effect.asVoid), markSessionCompacted: (sessionId) => runRuntimeCallbackAtGeneration( handlerGeneration, @@ -7979,6 +8250,9 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( yield* Ref.set(midTurnUnreportedCompletedTaskIds, new Set()); yield* Ref.set(handledBackgroundTaskIdsInActiveTurn, new Set()); yield* Ref.set(carryoverSubagents, null); + yield* Ref.set(dormantSubagentsByChildSessionId, new Map()); + yield* Ref.set(pendingExtensionSubagents, []); + externalBackgroundWorkActive = false; yield* Ref.set(suppressPostSettleMonitorPrompt, false); yield* Ref.set(lastTurnRoute, null); }), @@ -8540,6 +8814,9 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( yield* Ref.set(detachedBackgroundCommands, new Map()); yield* Ref.set(midTurnUnreportedCompletedTaskIds, new Set()); yield* Ref.set(carryoverSubagents, null); + yield* Ref.set(dormantSubagentsByChildSessionId, new Map()); + yield* Ref.set(pendingExtensionSubagents, []); + externalBackgroundWorkActive = false; yield* Ref.set(lastTurnRoute, null); }), ); @@ -8715,6 +8992,22 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const subagentsRequiringCarryover = [...context.subagents.values()].filter( acpSubagentHasPendingBackgroundWork, ); + if (settledStatus === "completed" && !directStopQuarantine) { + const idleChildren = [...context.subagents.values()].filter( + (subagent) => subagent.task.status === "idle" && subagent.childSessionId !== null, + ); + if (idleChildren.length > 0) { + yield* Ref.update(dormantSubagentsByChildSessionId, (current) => { + const next = new Map(current); + for (const subagent of idleChildren) { + if (subagent.childSessionId !== null) { + next.set(subagent.childSessionId, subagent); + } + } + return next; + }); + } + } if (subagentsRequiringCarryover.length > 0 && !directStopQuarantine) { const sessionId = yield* Ref.get(activeSessionId); if (sessionId !== null) { @@ -8785,6 +9078,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const promptInactivityPaused = Effect.fn("AcpAdapterV2.promptInactivityPaused")(function* ( context: ActiveAcpTurn, ) { + if (externalBackgroundWorkActive) return true; if (openAgentRequests.size > 0) return true; if ((yield* Ref.get(pendingRuntimeRequests)).size > 0) return true; for (const tool of context.tools.values()) { @@ -9490,6 +9784,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( } yield* Ref.set(activeTurn, context); yield* Ref.set(stoppedRunQuarantine, false); + const queuedExtensionSubagents = yield* Ref.getAndSet(pendingExtensionSubagents, []); const runningTurn = providerTurnPayload(context, "running", null); yield* Ref.update(providerTurns, (current) => { const updated = new Map(current); @@ -9518,6 +9813,13 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( driver, providerThread: activeProviderThread, }); + for (const queued of queuedExtensionSubagents) { + yield* applyExtensionSubagentToTurn( + context, + queued.subagent, + queued.allowReopenFromIdle, + ); + } yield* rememberSnapshotMessage({ createdBy: turnInput.message.createdBy, creationSource: turnInput.message.creationSource, @@ -9881,6 +10183,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( agentRequests.size > 0) ) return true; + if (externalBackgroundWorkActive) return true; if ((yield* Ref.get(wakeBuffer)).length > 0) return true; if ((yield* Ref.get(midTurnUnreportedCompletedTaskIds)).size > 0) return true; if (yield* Ref.get(continuationRequested)) return true; From d801c601c9e1337b51e1fa5a21c9f75a8dd78b0b Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 14:50:18 +0000 Subject: [PATCH 02/11] fix(antigravity): expect the swarm client capability and tidy swarm imports The driver test still expected the old initialize capabilities, so CI failed once the adapter started advertising _meta.antigravity.swarm. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/provider/Drivers/AntigravityDriver.test.ts | 1 + apps/server/src/provider/acp/AntigravityChildWork.ts | 3 +-- apps/server/src/provider/acp/AntigravitySwarm.test.ts | 4 ---- 3 files changed, 2 insertions(+), 6 deletions(-) diff --git a/apps/server/src/provider/Drivers/AntigravityDriver.test.ts b/apps/server/src/provider/Drivers/AntigravityDriver.test.ts index 3c0135f419c66..1e3cab3c5f61b 100644 --- a/apps/server/src/provider/Drivers/AntigravityDriver.test.ts +++ b/apps/server/src/provider/Drivers/AntigravityDriver.test.ts @@ -417,6 +417,7 @@ it.layer(layerTest)("AntigravityDriver", (it) => { terminal: false, session: { notices: {}, compaction: {} }, elicitation: { form: {} }, + _meta: { antigravity: { swarm: true } }, }, ]); diff --git a/apps/server/src/provider/acp/AntigravityChildWork.ts b/apps/server/src/provider/acp/AntigravityChildWork.ts index d23dd67ed58ef..012ec0a6553bd 100644 --- a/apps/server/src/provider/acp/AntigravityChildWork.ts +++ b/apps/server/src/provider/acp/AntigravityChildWork.ts @@ -15,6 +15,7 @@ import * as Schema from "effect/Schema"; import { antigravityManagedPath, antigravityProfileRoot } from "./AntigravityProfilePaths.ts"; import { boundAntigravityToolText, isCutAntigravityToolText } from "./AntigravityProtocol.ts"; +import { swarmWorkerConversationIdFromTaskId } from "./AntigravitySwarm.ts"; // Field numbers from the runtime's trajectory protos (exa.cortex_pb). const STEP_METADATA = 5; @@ -46,8 +47,6 @@ interface AntigravityChildLaunch { readonly prompt: string; } -import { swarmWorkerConversationIdFromTaskId } from "./AntigravitySwarm.ts"; - const LaunchInput = Schema.Struct({ Role: Schema.String, Prompt: Schema.String }); const SwarmAddInput = Schema.Struct({ action: Schema.String, diff --git a/apps/server/src/provider/acp/AntigravitySwarm.test.ts b/apps/server/src/provider/acp/AntigravitySwarm.test.ts index 6cc53d3f6676e..3ff70e718e7e3 100644 --- a/apps/server/src/provider/acp/AntigravitySwarm.test.ts +++ b/apps/server/src/provider/acp/AntigravitySwarm.test.ts @@ -2,8 +2,6 @@ import * as Schema from "effect/Schema"; import { describe, expect, it } from "vite-plus/test"; import { - ANTIGRAVITY_SWARM_CAPABILITIES_META, - ANTIGRAVITY_SWARM_NOTIFICATION_METHOD, AntigravitySwarmNotification, agentAdvertisesAntigravitySwarm, makeAntigravitySwarmTracker, @@ -11,8 +9,6 @@ import { describe("AntigravitySwarm", () => { it("detects advertised swarm capability on initialize responses", () => { - expect(ANTIGRAVITY_SWARM_NOTIFICATION_METHOD).toBe("_antigravity/swarm"); - expect(ANTIGRAVITY_SWARM_CAPABILITIES_META).toEqual({ antigravity: { swarm: true } }); expect(agentAdvertisesAntigravitySwarm({ _meta: { antigravity: { swarm: true } } })).toBe(true); expect( agentAdvertisesAntigravitySwarm({ _meta: { antigravity: { swarm: { enabled: true } } } }), From 071ee81617acf74dec15c32066e1d969fb912a41 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 15:01:05 +0000 Subject: [PATCH 03/11] fix(antigravity): keep swarm worker state consistent across turns and sessions - Track external background work per session, so a resumed or forked session does not inherit a busy flag from the one before it. - Drop a queued between-turn update once the worker reports a terminal state, so the next turn cannot replay it as running. - Reset a reopened worker's accumulated reply so round two does not append to round one. - Cap legacy swarm add launches so an untrusted worker count cannot allocate without bound. Co-Authored-By: Claude Opus 5.5 --- .../Adapters/AntigravityAdapterV2.test.ts | 45 +++++++++++++------ .../provider/acp/AntigravityChildWork.test.ts | 2 + .../src/provider/acp/AntigravityChildWork.ts | 5 ++- packages/provider-acp/src/server/adapter.ts | 26 ++++++++--- 4 files changed, 57 insertions(+), 21 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts index 34fcdd427ffc7..82fe3443986ce 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts @@ -2662,10 +2662,10 @@ describe("AntigravityAdapterV2 native swarm protocol", () => { } else { yield* onSwarmNotification!({ sessionId: rootSessionId, - head: 4, + head: 5, activeWorkers: 1, workingWorkers: 1, - waitingWorkers: 1, + waitingWorkers: 0, members: [ { name: "alpha", @@ -2674,13 +2674,6 @@ describe("AntigravityAdapterV2 native swarm protocol", () => { brief: "Inspect frontend", state: "working", }, - { - name: "beta", - role: "worker", - conversationId: betaSessionId, - brief: "Inspect backend", - state: "waiting", - }, ], }); yield* onSessionUpdate!({ @@ -2884,6 +2877,31 @@ describe("AntigravityAdapterV2 native swarm protocol", () => { ), ); + // Between turns @beta wakes and is killed; turn 2 must not replay the queued running update. + yield* onSwarmNotification!({ + sessionId: rootSessionId, + head: 4, + activeWorkers: 1, + workingWorkers: 1, + waitingWorkers: 1, + members: [ + { name: "alpha", role: "worker", conversationId: alphaSessionId, state: "waiting" }, + { name: "beta", role: "worker", conversationId: betaSessionId, state: "working" }, + ], + }); + yield* onSwarmNotification!({ + sessionId: rootSessionId, + head: 4, + activeWorkers: 0, + workingWorkers: 0, + waitingWorkers: 1, + members: [ + { name: "alpha", role: "worker", conversationId: alphaSessionId, state: "waiting" }, + { name: "beta", role: "worker", conversationId: betaSessionId, state: "killed" }, + ], + posts: [{ seq: 4, agent: "beta", text: "@coordinator Backend wrap-up." }], + }); + // Turn 2 wakes @alpha again on the exact same child thread, then kills @alpha after reporting. const turn2Input = makeTurnInput({ instanceId, @@ -2913,16 +2931,15 @@ describe("AntigravityAdapterV2 native swarm protocol", () => { yield* onSwarmNotification!({ sessionId: rootSessionId, - head: 5, + head: 6, activeWorkers: 0, workingWorkers: 0, - waitingWorkers: 1, + waitingWorkers: 0, coordinatorPendingWake: false, members: [ { name: "alpha", role: "worker", conversationId: alphaSessionId, state: "killed" }, - { name: "beta", role: "worker", conversationId: betaSessionId, state: "waiting" }, ], - posts: [{ seq: 5, agent: "alpha", text: "@coordinator Follow-up complete." }], + posts: [{ seq: 6, agent: "alpha", text: "@coordinator Follow-up complete." }], }); yield* onSessionUpdate!({ sessionId: rootSessionId, @@ -2933,6 +2950,8 @@ describe("AntigravityAdapterV2 native swarm protocol", () => { assert.equal(collected.filter((event) => event.type === "turn.terminal").length, 2); assert.equal(subagentsByTitle().get("@alpha")?.status, "completed"); assert.equal(subagentsByTitle().get("@alpha")?.result, "Follow-up complete."); + assert.equal(subagentsByTitle().get("@beta")?.status, "completed"); + assert.equal(subagentsByTitle().get("@beta")?.result, "Backend wrap-up."); yield* Fiber.interrupt(reader); }).pipe(Effect.provide(layerSession), Effect.scoped), diff --git a/apps/server/src/provider/acp/AntigravityChildWork.test.ts b/apps/server/src/provider/acp/AntigravityChildWork.test.ts index 35e9e2dabd4f2..d7a936244dc34 100644 --- a/apps/server/src/provider/acp/AntigravityChildWork.test.ts +++ b/apps/server/src/provider/acp/AntigravityChildWork.test.ts @@ -642,6 +642,8 @@ it.layer(NodeServices.layer)("readAntigravityChildWork", (it) => { ]); expect(batchChildren[0]?.steps?.[0]?.text).toBe("shard-1 finished"); + expect(antigravitySubagentLaunches({ action: "add", name: "w", n: 1e9 })).toHaveLength(64); + const direct = yield* read(profile, `swarm:${workerOne}`); expect(direct).toHaveLength(1); expect(direct[0]?.role).toBe("@shard-1"); diff --git a/apps/server/src/provider/acp/AntigravityChildWork.ts b/apps/server/src/provider/acp/AntigravityChildWork.ts index 012ec0a6553bd..78803da9ebfc6 100644 --- a/apps/server/src/provider/acp/AntigravityChildWork.ts +++ b/apps/server/src/provider/acp/AntigravityChildWork.ts @@ -62,6 +62,9 @@ const decodeLaunchInput = Schema.decodeUnknownOption( ); const decodeSwarmAddInput = Schema.decodeUnknownOption(SwarmAddInput); +// The tool input is untrusted; a huge `n` must not allocate a launch per requested worker. +const MAX_SWARM_ADD_LAUNCHES = 64; + function swarmAddLaunches(input: unknown): ReadonlyArray | undefined { const decoded = Option.getOrUndefined(decodeSwarmAddInput(input)); if (decoded === undefined || decoded.action.trim().toLowerCase() !== "add") return undefined; @@ -70,7 +73,7 @@ function swarmAddLaunches(input: unknown): ReadonlyArray const tasks = decoded.tasks ?? []; const requestedCount = decoded.n !== undefined && Number.isFinite(decoded.n) ? Math.trunc(decoded.n) : 0; - const count = Math.max(tasks.length, requestedCount, 1); + const count = Math.min(Math.max(tasks.length, requestedCount, 1), MAX_SWARM_ADD_LAUNCHES); const roleSuffix = decoded.role !== undefined && decoded.role.trim().length > 0 && decoded.role !== "worker" ? ` (${decoded.role.trim()})` diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index b2de500dfeb5e..1ee6a0ea2df36 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -2640,7 +2640,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( readonly allowReopenFromIdle: boolean; }> >([]); - let externalBackgroundWorkActive = false; + const externalBackgroundWorkSessionIds = new Set(); const handledBackgroundTaskIdsInActiveTurn = yield* Ref.make>( new Set(), ); @@ -3822,6 +3822,8 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( yield* writeSubagentThought(existing, true); existing.terminalStatusProjected = false; existing.assistantText = ""; + existing.assistantMessages.clear(); + existing.pendingAssistantMessages.clear(); } const task: OrchestrationV2Subagent = { ...(existing?.task ?? { @@ -4423,7 +4425,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( /Monitor\s+["']?[0-9a-f-]{8,}/i.test(text) && /ended/i.test(text); const hasDeferredBackgroundWork = (context: ActiveAcpTurn): boolean => { - if (externalBackgroundWorkActive) return true; + if (externalBackgroundWorkSessionIds.has(context.nativeThreadId)) return true; if (flavor.wakeOnDetachedRequest && agentRequests.size > 0) return true; if (flavor.toolOutlivesPrompt !== undefined) { // A tool that never started has nothing to report later. @@ -7078,6 +7080,14 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( return; } if (acpSubagentStatusIsTerminal(update.status)) { + yield* Ref.update(pendingExtensionSubagents, (current) => + current.filter( + (entry) => + entry.subagent.nativeTaskId !== update.nativeTaskId && + (update.childSessionId === null || + entry.subagent.childSessionId !== update.childSessionId), + ), + ); if (update.childSessionId !== null) { const dormant = (yield* Ref.get(dormantSubagentsByChildSessionId)).get( update.childSessionId, @@ -7887,7 +7897,8 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( Effect.gen(function* () { if (yield* Ref.get(stoppedRunQuarantine)) return; if ((yield* Ref.get(activeSessionId)) !== notice.sessionId) return; - externalBackgroundWorkActive = notice.active; + if (notice.active) externalBackgroundWorkSessionIds.add(notice.sessionId); + else externalBackgroundWorkSessionIds.delete(notice.sessionId); const context = yield* Ref.get(activeTurn); if ( context === null || @@ -8252,7 +8263,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( yield* Ref.set(carryoverSubagents, null); yield* Ref.set(dormantSubagentsByChildSessionId, new Map()); yield* Ref.set(pendingExtensionSubagents, []); - externalBackgroundWorkActive = false; + externalBackgroundWorkSessionIds.clear(); yield* Ref.set(suppressPostSettleMonitorPrompt, false); yield* Ref.set(lastTurnRoute, null); }), @@ -8816,7 +8827,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( yield* Ref.set(carryoverSubagents, null); yield* Ref.set(dormantSubagentsByChildSessionId, new Map()); yield* Ref.set(pendingExtensionSubagents, []); - externalBackgroundWorkActive = false; + externalBackgroundWorkSessionIds.clear(); yield* Ref.set(lastTurnRoute, null); }), ); @@ -9078,7 +9089,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const promptInactivityPaused = Effect.fn("AcpAdapterV2.promptInactivityPaused")(function* ( context: ActiveAcpTurn, ) { - if (externalBackgroundWorkActive) return true; + if (externalBackgroundWorkSessionIds.has(context.nativeThreadId)) return true; if (openAgentRequests.size > 0) return true; if ((yield* Ref.get(pendingRuntimeRequests)).size > 0) return true; for (const tool of context.tools.values()) { @@ -10183,7 +10194,8 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( agentRequests.size > 0) ) return true; - if (externalBackgroundWorkActive) return true; + if (rootSessionId !== null && externalBackgroundWorkSessionIds.has(rootSessionId)) + return true; if ((yield* Ref.get(wakeBuffer)).length > 0) return true; if ((yield* Ref.get(midTurnUnreportedCompletedTaskIds)).size > 0) return true; if (yield* Ref.get(continuationRequested)) return true; From d21dc36f7c4b2789eca195fcdca7fb03531a439d Mon Sep 17 00:00:00 2001 From: "Patrick C. Toulme" <135739773+patrick-toulme@users.noreply.github.com> Date: Sat, 21 Nov 2026 20:58:26 +0000 Subject: [PATCH 04/11] fix(antigravity): handle swarm worker approvals, lifecycle, and local CLI parity - Avoid holding root reply settlement open or offering empty continuation runs on child worker permission and elicitation requests, and auto-cancel open child approvals when a worker stops or its tool leaves pending - Preserve worker attribution on command approval details and accept verified swarm worker worktree roots under workspaceWrite policies - Honor coordinatorWorking, hadActivity, stopped states, and housekeeping roles (@monitor, @narrator), buffer opening worker frames across re-wakes and session loads, and scope swarm tracker state per session with teardown cleanup - Share the native swarm protocol tracker with the local agy ACP registry provider --- .../Adapters/AntigravityAdapterV2.test.ts | 496 ++++++++++++++++++ .../Adapters/AntigravityAdapterV2.ts | 92 ++-- .../src/provider/acp/AntigravityAcpSupport.ts | 3 +- .../src/provider/acp/AntigravitySwarm.test.ts | 235 ++++++--- .../src/provider/acp/AntigravitySwarm.ts | 339 +----------- .../src/server/adapter.ts | 65 ++- packages/provider-acp/package.json | 4 + packages/provider-acp/src/server/adapter.ts | 272 ++++++++-- .../src/server/antigravitySwarm.ts | 488 +++++++++++++++++ .../provider-acp/src/server/clientPolicy.ts | 9 + .../provider-acp/src/server/runtimeModel.ts | 58 +- 11 files changed, 1578 insertions(+), 483 deletions(-) create mode 100644 packages/provider-acp/src/server/antigravitySwarm.ts diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts index 82fe3443986ce..b4a90c0b7d3f5 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts @@ -2956,4 +2956,500 @@ describe("AntigravityAdapterV2 native swarm protocol", () => { yield* Fiber.interrupt(reader); }).pipe(Effect.provide(layerSession), Effect.scoped), ); + + it.effect( + "settles worker approvals without root reply stalls, cancels withdrawn worker approvals, allows worker worktree writes, and ignores monitor pulses", + () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const workspace = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-ag-swarm-perm-", + }); + const worktree = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-ag-swarm-wt-" }); + const outside = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-ag-swarm-out-" }); + + type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"]; + let onSessionUpdate: Parameters[0] | undefined; + let onRequestPermission: + | Parameters[0] + | undefined; + let onSwarmNotification: + | ((payload: unknown) => Effect.Effect) + | undefined; + let onOutgoingResponse: ((requestId: string) => Effect.Effect) | undefined; + let continuationOffers = 0; + + const rootSessionId = "22222222-2222-4000-8000-000000000001"; + const alphaSessionId = "22222222-2222-4000-8000-00000000000a"; + const monitorSessionId = "22222222-2222-4000-8000-00000000000m"; + + const continuationRequests = { + offer: () => + Effect.sync(() => { + continuationOffers += 1; + return true; + }), + } as unknown as NonNullable< + Parameters[0]["continuationRequests"] + >; + + const instanceId = ProviderInstanceId.make("antigravity-swarm-perm"); + const adapter = yield* makeAntigravityAdapterV2({ + instanceId, + continuationRequests, + selfInvocation: yield* resolveSelfInvocation(), + withProcess: (_stop, task) => task, + defaultModel: Effect.undefined, + makeRuntime: (runtimeInput) => + Effect.sync(() => { + onOutgoingResponse = runtimeInput.onOutgoingResponse; + return { + start: () => + Effect.succeed({ + initializeResult: { + protocolVersion: 1, + agentInfo: { name: "Antigravity ACP Server", version: "1.5.14" }, + agentCapabilities: { + loadSession: true, + _meta: { antigravity: { swarm: true } }, + }, + }, + sessionId: rootSessionId, + resumed: false, + sessionSetupResult: { + sessionId: rootSessionId, + modes: { + currentModeId: "default", + availableModes: [ + { id: "default", name: "Default" }, + { id: "auto_edit", name: "Accept Edits" }, + { id: "yolo", name: "Full Access" }, + ], + }, + models: { + currentModelId: "test-model", + availableModels: [{ modelId: "test-model", name: "Test Model" }], + }, + configOptions: [], + }, + } as unknown as AcpSessionRuntime.AcpSessionRuntimeStartResult), + getEvents: () => Stream.empty, + drainEvents: Effect.void, + getSessionId: Effect.succeed(rootSessionId), + getConfigOptions: Effect.succeed([]), + getModeState: Effect.succeed({ + currentModeId: "default", + availableModes: [ + { id: "default", name: "Default" }, + { id: "auto_edit", name: "Accept Edits" }, + { id: "yolo", name: "Full Access" }, + ], + }), + getModelState: Effect.succeed({ + currentModelId: "test-model", + availableModels: [{ modelId: "test-model", name: "Test Model" }], + }), + setConfigOption: () => Effect.succeed({ configOptions: [] }), + setMode: () => Effect.void, + setModel: () => Effect.void, + prompt: ( + _payload: Parameters[0], + promptOptions: Parameters[1], + ) => + Effect.gen(function* () { + if (promptOptions?.dispatched !== undefined) { + yield* Deferred.succeed(promptOptions.dispatched, undefined); + } + yield* onSwarmNotification!({ + sessionId: rootSessionId, + head: 1, + activeWorkers: 1, + workingWorkers: 1, + waitingWorkers: 0, + members: [ + { + name: "alpha", + role: "worker", + conversationId: alphaSessionId, + brief: "Run checks", + workspace: worktree, + workspaces: [worktree], + state: "working", + }, + ], + }); + yield* onSessionUpdate!({ + sessionId: rootSessionId, + update: { + sessionUpdate: "agent_message_chunk", + content: { type: "text", text: "Started @alpha." }, + }, + }); + yield* onSessionUpdate!({ + sessionId: rootSessionId, + update: { sessionUpdate: "usage_update", used: 100, size: 100_000 }, + }); + return { stopReason: "end_turn" as const }; + }), + cancel: () => Effect.void, + closeSession: () => Effect.void, + extRequest: () => Effect.die("unused"), + extNotification: () => Effect.void, + handleSessionUpdate: ( + handler: Parameters[0], + ) => + Effect.sync(() => { + onSessionUpdate = handler; + }), + handleRequestPermission: ( + handler: Parameters[0], + ) => + Effect.sync(() => { + onRequestPermission = handler; + }), + handleReadTextFile: () => Effect.void, + handleWriteTextFile: () => Effect.void, + handleCreateTerminal: () => Effect.void, + handleTerminalOutput: () => Effect.void, + handleWaitForTerminalExit: () => Effect.void, + handleKillTerminalCommand: () => Effect.void, + handleReleaseTerminal: () => Effect.void, + handleElicitation: () => Effect.void, + handleElicitationComplete: () => Effect.void, + handleExtRequest: () => Effect.void, + handleExtNotification: ( + method: string, + _schema: unknown, + handler: (payload: unknown) => Effect.Effect, + ) => + Effect.sync(() => { + if (method === "_antigravity/swarm") { + onSwarmNotification = handler; + } + }), + } as unknown as RuntimeService; + }), + }); + + const threadId = ThreadId.make("thread-ag-swarm-perm"); + const modelSelection = { instanceId, model: "antigravity-default" } as const; + const supervisedPolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "approval-required", + interactionMode: "default", + cwd: workspace, + }); + const session = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make("ps-ag-swarm-perm"), + modelSelection, + runtimePolicy: supervisedPolicy, + }); + + const eventQueue = yield* Queue.unbounded(); + const collected: Array = []; + const reader = yield* session.events.pipe( + Stream.runForEach((event) => + Effect.sync(() => { + collected.push(event); + }).pipe(Effect.andThen(Queue.offer(eventQueue, event))), + ), + Effect.forkScoped, + ); + const takeUntil = (predicate: (event: ProviderAdapter.ProviderAdapterV2Event) => boolean) => + Effect.gen(function* () { + while (true) { + const event = yield* Queue.take(eventQueue); + if (predicate(event)) return event; + } + }); + + const providerThread = yield* session.ensureThread({ + threadId, + modelSelection, + runtimePolicy: supervisedPolicy, + }); + + // Turn 1: worker asks for command permission after root prompt settled; user approves; + // worker parks without a coordinator wake. Turn must settle at 3 s without waiting 2 min. + const turn1 = makeTurnInput({ + instanceId, + threadId, + providerThread, + modelSelection, + runtimePolicy: supervisedPolicy, + now: yield* DateTime.now, + }); + yield* session.startTurn(turn1); + yield* Effect.yieldNow; + + const permOptions: ReadonlyArray = [ + { optionId: "allow_once", name: "Allow", kind: "allow_once" }, + { optionId: "allow_always", name: "Always Allow", kind: "allow_always" }, + { optionId: "reject_once", name: "Deny", kind: "reject_once" }, + ]; + const childMeta = { + antigravity: { + childSessionId: alphaSessionId, + role: "worker", + workspace: worktree, + workspaces: [worktree], + swarm: { + workerSessionId: alphaSessionId, + workerName: "alpha", + role: "worker", + workspace: worktree, + }, + }, + }; + + const sendPermission = ( + request: EffectAcpSchema.RequestPermissionRequest, + requestId: string, + ) => + onRequestPermission!(request, { requestId, method: "session/request_permission" }).pipe( + Effect.tap(() => onOutgoingResponse?.(requestId) ?? Effect.void), + ); + + const firstApproval = yield* sendPermission( + { + sessionId: rootSessionId, + _meta: childMeta, + options: permOptions, + toolCall: { + toolCallId: "alpha-cmd-1", + kind: "execute", + status: "pending", + title: "[@alpha] pnpm test", + rawInput: { CommandLine: "pnpm test" }, + _meta: childMeta, + }, + }, + "child-perm-1", + ).pipe(Effect.forkScoped({ startImmediately: true })); + + const openApprovalEvent = yield* takeUntil( + (event) => + event.type === "turn_item.updated" && + event.turnItem.type === "approval_request" && + event.turnItem.status === "waiting", + ); + if ( + openApprovalEvent.type !== "turn_item.updated" || + openApprovalEvent.turnItem.type !== "approval_request" + ) { + return assert.fail("expected an open command approval for @alpha"); + } + assert.equal(openApprovalEvent.turnItem.prompt, "[@alpha] pnpm test"); + assert.isTrue( + openApprovalEvent.turnItem.options?.some((opt) => opt.decision === "acceptForSession") === + true, + "worker approval card should expose session-wide approval when allow_always is offered", + ); + + const respondFiber = yield* session + .respondToRuntimeRequest({ + requestId: openApprovalEvent.turnItem.requestId, + decision: "accept", + }) + .pipe(Effect.forkScoped); + assert.deepEqual(yield* Fiber.join(firstApproval), { + outcome: { outcome: "selected", optionId: "allow_once" }, + }); + yield* Fiber.join(respondFiber); + + // Worker finishes quietly without triggering a root reply or usage_update. + yield* onSwarmNotification!({ + sessionId: rootSessionId, + head: 1, + activeWorkers: 0, + workingWorkers: 0, + waitingWorkers: 1, + coordinatorWorking: false, + coordinatorPendingWake: false, + members: [ + { name: "alpha", role: "worker", conversationId: alphaSessionId, state: "waiting" }, + ], + }); + yield* TestClock.adjust("4 seconds"); + yield* Effect.yieldNow; + assert.equal( + collected.filter((event) => event.type === "turn.terminal").length, + 1, + "worker approval must not hold replyOpen for the 2-minute quiet fallback", + ); + + // Turn 2: an unanswered worker approval is withdrawn when the worker fails; the card + // cancels automatically and the turn settles promptly. + const workspaceWritePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "approval-required", + approvalPolicy: "never", + sandboxPolicy: { type: "workspaceWrite" }, + interactionMode: "default", + cwd: workspace, + }); + yield* session.startTurn({ + ...turn1, + runId: RunId.make("run-perm-2"), + runOrdinal: 2, + providerTurnOrdinal: 2, + attemptId: RunAttemptId.make("attempt-perm-2"), + rootNodeId: NodeId.make("root-perm-2"), + runtimePolicy: supervisedPolicy, + }); + yield* Effect.yieldNow; + + const withdrawnApproval = yield* sendPermission( + { + sessionId: rootSessionId, + _meta: childMeta, + options: permOptions, + toolCall: { + toolCallId: "alpha-cmd-2", + kind: "execute", + status: "pending", + title: "[@alpha] pnpm lint", + rawInput: { CommandLine: "pnpm lint" }, + _meta: childMeta, + }, + }, + "child-perm-2", + ).pipe(Effect.forkScoped({ startImmediately: true })); + const withdrawnCard = yield* takeUntil( + (event) => + event.type === "turn_item.updated" && + event.turnItem.type === "approval_request" && + event.turnItem.status === "waiting", + ); + assert.equal( + withdrawnCard.type === "turn_item.updated" && + withdrawnCard.turnItem.type === "approval_request" + ? withdrawnCard.turnItem.prompt + : undefined, + "[@alpha] pnpm lint", + ); + + yield* onSwarmNotification!({ + sessionId: rootSessionId, + head: 1, + activeWorkers: 0, + workingWorkers: 0, + waitingWorkers: 0, + coordinatorWorking: false, + coordinatorPendingWake: false, + members: [ + { + name: "alpha", + role: "worker", + conversationId: alphaSessionId, + state: "failed", + failure: "worker aborted", + }, + ], + }); + assert.deepEqual(yield* Fiber.join(withdrawnApproval), { + outcome: { outcome: "cancelled" }, + }); + yield* TestClock.adjust("4 seconds"); + yield* Effect.yieldNow; + assert.equal( + collected.filter((event) => event.type === "turn.terminal").length, + 2, + "cancelling a withdrawn worker approval must allow the turn to settle", + ); + + // Turn 3 switches policy to workspaceWrite (auto-approve workspace edits), finishes, and + // verifies between-turn worktree edit approval + monitor daemon isolation. + yield* session.startTurn({ + ...turn1, + runId: RunId.make("run-perm-3"), + runOrdinal: 3, + providerTurnOrdinal: 3, + attemptId: RunAttemptId.make("attempt-perm-3"), + rootNodeId: NodeId.make("root-perm-3"), + runtimePolicy: workspaceWritePolicy, + }); + yield* Effect.yieldNow; + yield* onSwarmNotification!({ + sessionId: rootSessionId, + head: 1, + activeWorkers: 0, + workingWorkers: 0, + waitingWorkers: 1, + members: [ + { + name: "alpha", + role: "worker", + conversationId: alphaSessionId, + workspace: worktree, + workspaces: [worktree], + state: "waiting", + }, + ], + }); + yield* TestClock.adjust("4 seconds"); + yield* Effect.yieldNow; + assert.equal(collected.filter((event) => event.type === "turn.terminal").length, 3); + const offersBeforeIdleChecks = continuationOffers; + + // Periodic @monitor daemon tick neither blocks idle eviction nor wakes a continuation run. + yield* onSwarmNotification!({ + sessionId: rootSessionId, + head: 1, + activeWorkers: 0, + workingWorkers: 0, + waitingWorkers: 1, + members: [ + { name: "alpha", role: "worker", conversationId: alphaSessionId, state: "waiting" }, + { name: "monitor", role: "worker", conversationId: monitorSessionId, state: "working" }, + ], + }); + assert.isFalse(yield* session.hasPendingBackgroundWork ?? Effect.succeed(true)); + assert.equal(continuationOffers, offersBeforeIdleChecks); + + // Detached worktree edit is auto-allowed and outside edit is auto-denied without offering + // an empty parent continuation run. + const worktreeEdit = yield* sendPermission( + { + sessionId: rootSessionId, + _meta: childMeta, + options: permOptions, + toolCall: { + toolCallId: "alpha-edit-1", + kind: "edit", + status: "pending", + title: "Edit file", + locations: [{ path: path.join(worktree, "src", "index.ts") }], + _meta: childMeta, + }, + }, + "child-edit-1", + ); + assert.deepEqual(worktreeEdit, { + outcome: { outcome: "selected", optionId: "allow_once" }, + }); + const outsideEdit = yield* sendPermission( + { + sessionId: rootSessionId, + _meta: childMeta, + options: permOptions, + toolCall: { + toolCallId: "alpha-edit-2", + kind: "edit", + status: "pending", + title: "Edit outside file", + locations: [{ path: path.join(outside, "escape.ts") }], + _meta: childMeta, + }, + }, + "child-edit-2", + ); + assert.deepEqual(outsideEdit, { + outcome: { outcome: "selected", optionId: "reject_once" }, + }); + assert.equal(continuationOffers, offersBeforeIdleChecks); + + yield* Fiber.interrupt(reader); + }).pipe(Effect.provide(layerSession), Effect.scoped), + ); }); diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts index 414d412535d4b..0c718e27d2b44 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts @@ -53,10 +53,9 @@ import { } from "../../provider/acp/AntigravityProtocol.ts"; import { ANTIGRAVITY_SWARM_CAPABILITIES_META, - ANTIGRAVITY_SWARM_NOTIFICATION_METHOD, - AntigravitySwarmNotification, agentAdvertisesAntigravitySwarm, makeAntigravitySwarmTracker, + registerAntigravitySwarmExtension, } from "../../provider/acp/AntigravitySwarm.ts"; import { isAntigravitySignInRequiredError } from "../../provider/antigravityAuthSupport.ts"; import { @@ -165,7 +164,6 @@ export function makeAntigravityAcpAdapterFlavor( ): AcpAdapterV2Flavor { const { profileDirectory } = options; const swarmTracker = makeAntigravitySwarmTracker(); - let nativeSwarmProtocol = false; const antigravityClientFileRoots = (cwd: string | null) => cwd === null ? [options.host.paths.attachmentsDir] : [cwd, options.host.paths.attachmentsDir]; const makeRuntime = Effect.fn("AntigravityAdapterV2.makeRuntime")( @@ -186,6 +184,28 @@ export function makeAntigravityAcpAdapterFlavor( // Served reads are reported from the read handler, so they take turns with agent updates. const updates = yield* Semaphore.make(1); let projectUpdate: Parameters[0] | undefined; + let activeRuntimeSessionId: string | undefined; + const rememberStartedSession = (started: AcpSessionRuntime.AcpSessionRuntimeStartResult) => + Effect.sync(() => { + if ( + activeRuntimeSessionId !== undefined && + activeRuntimeSessionId !== started.sessionId + ) { + swarmTracker.clearSession(activeRuntimeSessionId); + } + activeRuntimeSessionId = started.sessionId; + swarmTracker.setSessionProtocol( + started.sessionId, + agentAdvertisesAntigravitySwarm(started.initializeResult.agentCapabilities), + ); + }); + yield* Effect.addFinalizer(() => + Effect.sync(() => { + if (activeRuntimeSessionId !== undefined) { + swarmTracker.clearSession(activeRuntimeSessionId); + } + }), + ); return { ...runtime, handleReadTextFile: (handler) => @@ -218,17 +238,24 @@ export function makeAntigravityAcpAdapterFlavor( ); }, start: () => - runtime.start().pipe( - Effect.tap((started) => - Effect.sync(() => { - nativeSwarmProtocol = agentAdvertisesAntigravitySwarm( - started.initializeResult.agentCapabilities, - ); - }).pipe( - Effect.andThen(options.onSessionStarted?.(started, input.cwd) ?? Effect.void), + runtime + .start() + .pipe( + Effect.tap((started) => + rememberStartedSession(started).pipe( + Effect.andThen(options.onSessionStarted?.(started, input.cwd) ?? Effect.void), + ), ), ), - ), + loadSession: (...args) => + runtime.loadSession(...args).pipe(Effect.tap(rememberStartedSession)), + resumeSession: (...args) => + runtime.resumeSession(...args).pipe(Effect.tap(rememberStartedSession)), + closeSession: (sessionId) => + Effect.sync(() => { + const target = sessionId ?? activeRuntimeSessionId; + if (target !== undefined) swarmTracker.clearSession(target); + }).pipe(Effect.andThen(runtime.closeSession(sessionId))), } satisfies typeof runtime; }, Effect.provideService(SecureRandom.SecureRandom, options.random), @@ -298,7 +325,10 @@ export function makeAntigravityAcpAdapterFlavor( request, }), }, - permissionDisposition: antigravityPermissionDisposition, + permissionDisposition: (policy, request) => + antigravityPermissionDisposition(policy, request, { + extraWritableRoots: swarmTracker.childPermissionWorkspaces(request), + }), approvalOptions: antigravityApprovalOptions, extractPermissionQuestion: (request) => { const question = extractAntigravityUserInputQuestion(request); @@ -310,37 +340,11 @@ export function makeAntigravityAcpAdapterFlavor( }, normalizeToolCall: normalizeAntigravityToolCall, clientCapabilitiesMeta: ANTIGRAVITY_SWARM_CAPABILITIES_META, - registerExtensions: (context) => - context.runtime.handleExtNotification( - ANTIGRAVITY_SWARM_NOTIFICATION_METHOD, - AntigravitySwarmNotification, - (notification) => - Effect.gen(function* () { - nativeSwarmProtocol = true; - const mutation = swarmTracker.applyNotification(notification); - if (mutation.activeBackgroundWork) { - yield* context.setExternalBackgroundWork({ - sessionId: mutation.sessionId, - active: true, - }); - } - for (const subagent of mutation.subagents) { - yield* context.upsertSubagent({ - sessionId: mutation.sessionId, - subagent, - allowReopenFromIdle: true, - }); - } - if (!mutation.activeBackgroundWork) { - yield* context.setExternalBackgroundWork({ - sessionId: mutation.sessionId, - active: false, - }); - } - }), - ), - extractSubagentUpdate: (toolCall) => - extractAntigravitySubagentUpdate(toolCall, { nativeSwarmProtocol }), + registerExtensions: (context) => registerAntigravitySwarmExtension(swarmTracker, context), + extractSubagentUpdate: (toolCall, sessionId) => + extractAntigravitySubagentUpdate(toolCall, { + nativeSwarmProtocol: sessionId !== undefined && swarmTracker.usesNativeProtocol(sessionId), + }), supportsImagePrompts: true, compactViaAdvertisedCommand: true, requiresSignIn: isAntigravitySignInRequiredError, diff --git a/apps/server/src/provider/acp/AntigravityAcpSupport.ts b/apps/server/src/provider/acp/AntigravityAcpSupport.ts index 7434e23b5eda9..04365467945f6 100644 --- a/apps/server/src/provider/acp/AntigravityAcpSupport.ts +++ b/apps/server/src/provider/acp/AntigravityAcpSupport.ts @@ -184,8 +184,9 @@ export function antigravitySessionMode( export function antigravityPermissionDisposition( policy: AcpRuntimePolicy, request: EffectAcpSchema.RequestPermissionRequest, + options?: { readonly extraWritableRoots?: ReadonlyArray | undefined }, ) { - const disposition = acpPermissionDisposition(policy, request); + const disposition = acpPermissionDisposition(policy, request, options); // agy's Auto has already reviewed what it sends; the user decides unless the sandbox forbids it. return policy.runtimeMode === "auto" && disposition !== "deny" ? "ask" : disposition; } diff --git a/apps/server/src/provider/acp/AntigravitySwarm.test.ts b/apps/server/src/provider/acp/AntigravitySwarm.test.ts index 3ff70e718e7e3..ac57f09dd8890 100644 --- a/apps/server/src/provider/acp/AntigravitySwarm.test.ts +++ b/apps/server/src/provider/acp/AntigravitySwarm.test.ts @@ -1,3 +1,5 @@ +import { acpPermissionDisposition } from "@t3tools/provider-acp/server/clientPolicy"; +import { parsePermissionRequest } from "@t3tools/provider-acp/server/runtimeModel"; import * as Schema from "effect/Schema"; import { describe, expect, it } from "vite-plus/test"; @@ -23,10 +25,14 @@ describe("AntigravitySwarm", () => { expect(agentAdvertisesAntigravitySwarm(undefined)).toBe(false); }); - it("tracks multi-round worker lifecycles, board reports, helpers, and coordinator wakes", () => { + it("tracks multi-round lifecycles, monitor exclusion, hadActivity, coordinatorWorking, and session cleanup", () => { const decode = Schema.decodeUnknownSync(AntigravitySwarmNotification); const tracker = makeAntigravitySwarmTracker(); + tracker.setSessionProtocol("root-1", true); + expect(tracker.usesNativeProtocol("root-1")).toBe(true); + expect(tracker.usesNativeProtocol("root-2")).toBe(false); + const launched = tracker.applyNotification( decode({ sessionId: "root-1", @@ -45,6 +51,7 @@ describe("AntigravitySwarm", () => { model: "model-pro", modelLabel: "Model Pro", state: "working", + workspaces: ["/tmp/fork-a", "/tmp/fork-b"], addedBy: "coordinator", }, { @@ -54,10 +61,17 @@ describe("AntigravitySwarm", () => { state: "working", addedBy: "alpha", }, + { + name: "monitor", + role: "worker", + conversationId: "worker-m", + state: "working", + }, ], posts: [ { seq: 1, + time: "2026-11-21T12:00:00Z", agent: "alpha", kind: "brief", text: "@helper Check rate limiter config", @@ -69,108 +83,105 @@ describe("AntigravitySwarm", () => { expect(launched.activeBackgroundWork).toBe(true); expect(launched.subagents).toEqual([ { - nativeTaskId: "swarm:worker-a", - childSessionId: "worker-a", - title: "@alpha", - prompt: "Audit auth routes", - model: "Model Pro", - status: "running", - result: null, - suppressNormalTool: true, + subagent: { + nativeTaskId: "swarm:worker-a", + childSessionId: "worker-a", + title: "@alpha", + prompt: "Audit auth routes", + model: "Model Pro", + status: "running", + result: null, + suppressNormalTool: true, + }, + wakeContinuation: true, }, { - nativeTaskId: "swarm:worker-h", - childSessionId: "worker-h", - title: "@helper via @alpha", - prompt: "@helper Check rate limiter config", - model: null, - status: "running", - result: null, - suppressNormalTool: true, + subagent: { + nativeTaskId: "swarm:worker-h", + childSessionId: "worker-h", + title: "@helper via @alpha", + prompt: "@helper Check rate limiter config", + model: null, + status: "running", + result: null, + suppressNormalTool: true, + }, + wakeContinuation: true, + }, + { + subagent: { + nativeTaskId: "swarm:worker-m", + childSessionId: "worker-m", + title: "@monitor (monitor)", + prompt: "Swarm monitor @monitor", + model: null, + status: "running", + result: null, + suppressNormalTool: true, + }, + wakeContinuation: false, }, ]); expect( - tracker.partitionTaskIds("root-1", ["swarm:worker-a", "swarm:worker-h", "other-call"]), + tracker.partitionTaskIds("root-1", [ + "swarm:worker-a", + "swarm:worker-h", + "swarm:worker-m", + "other-call", + ]), ).toEqual({ runningSwarmTaskIds: ["swarm:worker-a", "swarm:worker-h"], unmanagedTaskIds: ["other-call"], }); - // Workers report and park while coordinator still has a pending doorbell wake. + // Workers park while out-of-turn coordinator is actively synthesizing (`coordinatorWorking`). const handoff = tracker.applyNotification( decode({ sessionId: "root-1", - head: 3, + head: 4, activeWorkers: 0, workingWorkers: 0, waitingWorkers: 2, - coordinatorPendingWake: true, + coordinatorWorking: true, + coordinatorPendingWake: false, members: [ - { - name: "alpha", - role: "worker", - conversationId: "worker-a", - state: "waiting", - }, - { - name: "helper", - role: "worker", - conversationId: "worker-h", - state: "waiting", - }, + { name: "alpha", role: "worker", conversationId: "worker-a", state: "waiting" }, + { name: "helper", role: "worker", conversationId: "worker-h", state: "waiting" }, + { name: "monitor", role: "monitor", conversationId: "worker-m", state: "working" }, ], posts: [ { seq: 2, agent: "alpha", text: "@coordinator Auth routes look solid." }, { seq: 3, agent: "helper", text: "@alpha Rate limiter uses token bucket." }, + { + seq: 4, + agent: "monitor", + text: "archived #old", + control: { op: "archive", channel: "old" }, + }, ], }), ); expect(handoff.activeBackgroundWork).toBe(true); - expect(handoff.subagents[0]).toMatchObject({ + expect(handoff.subagents[0]?.subagent).toMatchObject({ status: "idle", result: "Auth routes look solid.", }); - expect(handoff.subagents[1]).toMatchObject({ + expect(handoff.subagents[1]?.subagent).toMatchObject({ status: "idle", result: "@alpha Rate limiter uses token bucket.", }); - expect(tracker.partitionTaskIds("root-1", ["swarm:worker-a", "swarm:worker-h"])).toEqual({ - runningSwarmTaskIds: [], - unmanagedTaskIds: [], - }); - // Coordinator processes wake, then wakes @alpha for round 2 while killing @helper cleanly. - const round2 = tracker.applyNotification( - decode({ - sessionId: "root-1", - head: 4, - activeWorkers: 1, - workingWorkers: 1, - waitingWorkers: 0, - coordinatorPendingWake: false, - members: [ - { name: "alpha", role: "worker", conversationId: "worker-a", state: "working" }, - { name: "helper", role: "worker", conversationId: "worker-h", state: "killed" }, - ], - }), - ); - - expect(round2.activeBackgroundWork).toBe(true); - expect(round2.subagents[0]).toMatchObject({ status: "running", result: null }); - expect(round2.subagents[1]).toMatchObject({ - status: "completed", - result: "@alpha Rate limiter uses token bucket.", - }); - - // A never-reporting worker killed mid-turn maps to cancelled; a failed worker maps to failed. - const terminal = tracker.applyNotification( + // Periodic @monitor tick alone does NOT mark the session busy; hadActivity marks killed workers completed. + const settled = tracker.applyNotification( decode({ sessionId: "root-1", head: 4, activeWorkers: 0, workingWorkers: 0, waitingWorkers: 0, + coordinatorWorking: false, + coordinatorPendingWake: false, members: [ { name: "alpha", @@ -179,22 +190,112 @@ describe("AntigravitySwarm", () => { state: "failed", failure: "quota exhausted", }, + { + name: "helper", + role: "worker", + conversationId: "worker-h", + state: "killed", + }, + { + name: "resumed-done", + role: "worker", + conversationId: "worker-r", + state: "killed", + hadActivity: true, + }, { name: "scratch", role: "narrator", conversationId: "worker-n", state: "killed", }, + { + name: "monitor", + role: "monitor", + conversationId: "worker-m", + state: "working", + }, ], }), ); - expect(terminal.activeBackgroundWork).toBe(false); - expect(terminal.subagents[0]).toMatchObject({ status: "failed", result: "quota exhausted" }); - expect(terminal.subagents[1]).toMatchObject({ + expect(settled.activeBackgroundWork).toBe(false); + expect(settled.subagents[0]?.subagent).toMatchObject({ + status: "failed", + result: "quota exhausted", + }); + expect(settled.subagents[1]?.subagent).toMatchObject({ + status: "completed", + result: "@alpha Rate limiter uses token bucket.", + }); + expect(settled.subagents[2]?.subagent).toMatchObject({ + status: "completed", + result: null, + }); + expect(settled.subagents[3]?.subagent).toMatchObject({ title: "@scratch (narrator)", status: "cancelled", result: null, }); + expect(settled.subagents[4]?.wakeContinuation).toBe(false); + + tracker.clearSession("root-1"); + expect(tracker.hasLiveSwarm("root-1")).toBe(false); + expect(tracker.usesNativeProtocol("root-1")).toBe(false); + }); + + it("preserves worker attribution on command approvals and honors worker worktree roots in workspaceWrite", () => { + const parsed = parsePermissionRequest({ + sessionId: "root-1", + toolCall: { + toolCallId: "worker-cmd-1", + kind: "execute", + title: "[@alpha] pnpm test", + rawInput: { CommandLine: "pnpm test" }, + }, + options: [{ optionId: "allow", name: "Allow", kind: "allow_once" }], + _meta: { + antigravity: { + childSessionId: "worker-a", + swarm: { workerSessionId: "worker-a", workerName: "alpha" }, + }, + }, + }); + expect(parsed.detail).toBe("[@alpha] pnpm test"); + + const baseRequest = { + sessionId: "root-1", + toolCall: { + toolCallId: "worker-edit-1", + kind: "edit" as const, + title: "[@alpha] Edit /tmp/isolated-worktree/file.ts", + locations: [{ path: "/tmp/isolated-worktree/file.ts" }], + }, + options: [{ optionId: "allow", name: "Allow", kind: "allow_once" as const }], + }; + const policy = { + runtimeMode: "full-access" as const, + cwd: "/tmp/main-workspace", + sandboxPolicy: { type: "workspaceWrite" }, + }; + const tracker = makeAntigravitySwarmTracker(); + const childWorktreeRequest = { + ...baseRequest, + _meta: { + antigravity: { + childSessionId: "worker-a", + workspaces: ["/tmp/isolated-worktree"], + }, + }, + }; + // Generic ACP servers cannot expand writable roots via _meta.antigravity.workspaces. + expect(acpPermissionDisposition(policy, baseRequest)).toBe("deny"); + expect(acpPermissionDisposition(policy, childWorktreeRequest)).toBe("deny"); + // Antigravity adapters pass their verified worker worktree roots explicitly. + expect( + acpPermissionDisposition(policy, childWorktreeRequest, { + extraWritableRoots: tracker.childPermissionWorkspaces(childWorktreeRequest), + }), + ).toBe("allow"); }); }); diff --git a/apps/server/src/provider/acp/AntigravitySwarm.ts b/apps/server/src/provider/acp/AntigravitySwarm.ts index 9f706f07dcb0e..7d85517e511d6 100644 --- a/apps/server/src/provider/acp/AntigravitySwarm.ts +++ b/apps/server/src/provider/acp/AntigravitySwarm.ts @@ -1,331 +1,8 @@ -import type { AcpAdapterV2SubagentUpdate } from "@t3tools/provider-acp/server/adapter"; -import * as Schema from "effect/Schema"; - -export const ANTIGRAVITY_SWARM_CAPABILITIES_META = { - antigravity: { - swarm: true, - }, -} as const; - -export const ANTIGRAVITY_SWARM_NOTIFICATION_METHOD = "_antigravity/swarm"; - -const ANTIGRAVITY_SWARM_TASK_PREFIX = "swarm:"; - -export const AntigravitySwarmMember = Schema.Struct({ - name: Schema.String, - role: Schema.String, - conversationId: Schema.String, - toolCallId: Schema.optional(Schema.String), - brief: Schema.optional(Schema.String), - model: Schema.optional(Schema.String), - modelLabel: Schema.optional(Schema.String), - state: Schema.String, - failure: Schema.optional(Schema.String), - workspace: Schema.optional(Schema.String), - addedBy: Schema.optional(Schema.String), -}); -export type AntigravitySwarmMember = Schema.Schema.Type; - -export const AntigravitySwarmPost = Schema.Struct({ - seq: Schema.Number, - time: Schema.optional(Schema.String), - agent: Schema.String, - channel: Schema.optional(Schema.String), - kind: Schema.optional(Schema.String), - text: Schema.String, -}); -export type AntigravitySwarmPost = Schema.Schema.Type; - -export const AntigravitySwarmNotification = Schema.Struct({ - sessionId: Schema.String, - title: Schema.optional(Schema.String), - head: Schema.Number, - channels: Schema.optional(Schema.Array(Schema.String)), - activeWorkers: Schema.Number, - workingWorkers: Schema.Number, - waitingWorkers: Schema.Number, - coordinatorPendingWake: Schema.optional(Schema.Boolean), - members: Schema.Array(AntigravitySwarmMember), - posts: Schema.optional(Schema.Array(AntigravitySwarmPost)), -}); -export type AntigravitySwarmNotification = Schema.Schema.Type; - -const MAX_BOARD_REPORT_CHARS = 8_000; - -interface TrackedSwarmMember { - nativeTaskId: string; - name: string; - conversationId: string; - toolCallId: string | null; - status: AcpAdapterV2SubagentUpdate["status"]; - latestReport: string | null; - lastBrief: string; - sawIdleOrReport: boolean; -} - -interface TrackedSwarmSession { - busy: boolean; - readonly membersByConversationId: Map; - readonly membersByName: Map; - readonly latestPostsByAgent: Map; - readonly briefsByMention: Map; -} - -function nonEmpty(value: string | undefined): string | undefined { - const trimmed = value?.trim(); - return trimmed !== undefined && trimmed.length > 0 ? trimmed : undefined; -} - -function cleanBoardReport(text: string): string | null { - const withoutCoordinatorPrefix = text.trim().replace(/^@(?:coordinator|all)\b[:,\s-]*/i, ""); - const normalized = (withoutCoordinatorPrefix.length > 0 ? withoutCoordinatorPrefix : text).trim(); - if (normalized.length === 0) return null; - return normalized.length <= MAX_BOARD_REPORT_CHARS - ? normalized - : `${normalized.slice(0, MAX_BOARD_REPORT_CHARS - 1)}…`; -} - -function extractMentionedNames(text: string): ReadonlyArray { - const names: Array = []; - for (const match of text.matchAll(/(?:^|\s)@([a-z0-9][a-z0-9_-]*)\b/gi)) { - const name = match[1]?.toLowerCase(); - if (name !== undefined && name !== "coordinator" && name !== "all") { - names.push(name); - } - } - return names; -} - -function formatSwarmMemberTitle(member: AntigravitySwarmMember): string { - const handle = `@${member.name.replace(/^@/, "")}`; - const roleSuffix = - member.role !== "worker" && member.role.trim().length > 0 ? ` (${member.role.trim()})` : ""; - const addedBy = nonEmpty(member.addedBy)?.replace(/^@/, ""); - const parentSuffix = addedBy !== undefined && addedBy !== "coordinator" ? ` via @${addedBy}` : ""; - return `${handle}${roleSuffix}${parentSuffix}`; -} - -function mapSwarmMemberStatus( - state: string, - sawIdleOrReport: boolean, -): AcpAdapterV2SubagentUpdate["status"] { - switch (state.trim().toLowerCase()) { - case "working": - return "running"; - case "waiting": - case "stopped": - return "idle"; - case "failed": - return "failed"; - case "killed": - return sawIdleOrReport ? "completed" : "cancelled"; - default: - return "idle"; - } -} - -export function agentAdvertisesAntigravitySwarm(agentCapabilities: unknown): boolean { - if (typeof agentCapabilities !== "object" || agentCapabilities === null) return false; - const meta = (agentCapabilities as { readonly _meta?: unknown })._meta; - if (typeof meta !== "object" || meta === null) return false; - const antigravity = (meta as { readonly antigravity?: unknown }).antigravity; - if (typeof antigravity !== "object" || antigravity === null) return false; - const swarm = (antigravity as { readonly swarm?: unknown }).swarm; - if (swarm === true) return true; - if (typeof swarm === "object" && swarm !== null) { - const enabled = (swarm as { readonly enabled?: unknown }).enabled; - return enabled !== false; - } - return false; -} - -export function swarmWorkerConversationIdFromTaskId(nativeTaskId: string): string | undefined { - return nativeTaskId.startsWith(ANTIGRAVITY_SWARM_TASK_PREFIX) - ? nativeTaskId.slice(ANTIGRAVITY_SWARM_TASK_PREFIX.length) - : undefined; -} - -export interface AntigravitySwarmMutation { - readonly sessionId: string; - readonly activeBackgroundWork: boolean; - readonly subagents: ReadonlyArray; -} - -export interface AntigravitySwarmTracker { - readonly applyNotification: ( - notification: AntigravitySwarmNotification, - ) => AntigravitySwarmMutation; - readonly hasLiveSwarm: (sessionId: string) => boolean; - readonly partitionTaskIds: ( - sessionId: string, - nativeTaskIds: ReadonlyArray, - ) => { - readonly runningSwarmTaskIds: ReadonlyArray; - readonly unmanagedTaskIds: ReadonlyArray; - }; -} - -export function makeAntigravitySwarmTracker(): AntigravitySwarmTracker { - const sessions = new Map(); - - const sessionFor = (sessionId: string): TrackedSwarmSession => { - let session = sessions.get(sessionId); - if (session === undefined) { - session = { - busy: false, - membersByConversationId: new Map(), - membersByName: new Map(), - latestPostsByAgent: new Map(), - briefsByMention: new Map(), - }; - sessions.set(sessionId, session); - } - return session; - }; - - return { - applyNotification(notification) { - const session = sessionFor(notification.sessionId); - - for (const post of notification.posts ?? []) { - const author = post.agent.trim().toLowerCase(); - if (post.kind === "brief") { - const cleaned = cleanBoardReport(post.text); - if (cleaned !== null) { - for (const mentioned of extractMentionedNames(post.text)) { - if (!session.briefsByMention.has(mentioned)) { - session.briefsByMention.set(mentioned, cleaned); - } - } - } - continue; - } - if (author === "coordinator" || author.length === 0) continue; - const report = cleanBoardReport(post.text); - if (report === null) continue; - session.latestPostsByAgent.set(author, report); - const tracked = session.membersByName.get(author); - if (tracked !== undefined) { - tracked.latestReport = report; - tracked.sawIdleOrReport = true; - } - } - - const subagents: Array = []; - let runningMemberCount = 0; - - for (const member of notification.members) { - const conversationId = nonEmpty(member.conversationId); - if (conversationId === undefined || member.role === "coordinator") continue; - const nameKey = member.name.trim().toLowerCase(); - const callId = nonEmpty(member.toolCallId) ?? null; - - let tracked = session.membersByConversationId.get(conversationId); - const nativeTaskId = `${ANTIGRAVITY_SWARM_TASK_PREFIX}${conversationId}`; - if (tracked === undefined) { - tracked = { - nativeTaskId, - name: member.name, - conversationId, - toolCallId: callId, - status: "running", - latestReport: session.latestPostsByAgent.get(nameKey) ?? null, - lastBrief: "", - sawIdleOrReport: session.latestPostsByAgent.has(nameKey), - }; - session.membersByConversationId.set(conversationId, tracked); - session.membersByName.set(nameKey, tracked); - } else if (tracked.toolCallId === null && callId !== null) { - tracked.toolCallId = callId; - } - - const latestPost = session.latestPostsByAgent.get(nameKey) ?? tracked.latestReport; - if (latestPost !== null) { - tracked.latestReport = latestPost; - tracked.sawIdleOrReport = true; - } - - const nextStatus = mapSwarmMemberStatus(member.state, tracked.sawIdleOrReport); - if (nextStatus === "idle") { - tracked.sawIdleOrReport = true; - } - if (nextStatus === "running" || nextStatus === "pending") { - runningMemberCount += 1; - } - tracked.status = nextStatus; - - const brief = - nonEmpty(member.brief) ?? - nonEmpty(tracked.lastBrief) ?? - session.briefsByMention.get(nameKey) ?? - `Swarm ${member.role} @${member.name}`; - tracked.lastBrief = brief; - - const model = nonEmpty(member.modelLabel) ?? nonEmpty(member.model) ?? null; - const failureText = nonEmpty(member.failure) ?? null; - const result = - nextStatus === "running" - ? null - : nextStatus === "failed" - ? (failureText ?? tracked.latestReport ?? "Swarm worker execution failed.") - : tracked.latestReport; - - subagents.push({ - nativeTaskId: tracked.nativeTaskId, - childSessionId: conversationId, - title: formatSwarmMemberTitle(member), - prompt: brief, - model, - status: nextStatus, - result, - suppressNormalTool: true, - }); - } - - session.busy = - runningMemberCount > 0 || - notification.workingWorkers > 0 || - notification.activeWorkers > 0 || - notification.coordinatorPendingWake === true; - - return { - sessionId: notification.sessionId, - activeBackgroundWork: session.busy, - subagents, - }; - }, - - hasLiveSwarm(sessionId) { - return sessions.has(sessionId); - }, - - partitionTaskIds(sessionId, nativeTaskIds) { - const session = sessions.get(sessionId); - if (session === undefined) { - return { runningSwarmTaskIds: [], unmanagedTaskIds: nativeTaskIds }; - } - const managedStatus = new Map(); - for (const member of session.membersByConversationId.values()) { - managedStatus.set(member.nativeTaskId, member.status); - if (member.toolCallId !== null) { - managedStatus.set(member.toolCallId, member.status); - } - managedStatus.set( - `${ANTIGRAVITY_SWARM_TASK_PREFIX}${member.conversationId}`, - member.status, - ); - } - const runningSwarmTaskIds: Array = []; - const unmanagedTaskIds: Array = []; - for (const id of nativeTaskIds) { - const status = managedStatus.get(id); - if (status === undefined) { - unmanagedTaskIds.push(id); - } else if (status === "running" || status === "pending") { - runningSwarmTaskIds.push(id); - } - } - return { runningSwarmTaskIds, unmanagedTaskIds }; - }, - }; -} +export { + ANTIGRAVITY_SWARM_CAPABILITIES_META, + AntigravitySwarmNotification, + agentAdvertisesAntigravitySwarm, + makeAntigravitySwarmTracker, + registerAntigravitySwarmExtension, + swarmWorkerConversationIdFromTaskId, +} from "@t3tools/provider-acp/server/antigravitySwarm"; diff --git a/packages/provider-acp-registry/src/server/adapter.ts b/packages/provider-acp-registry/src/server/adapter.ts index 8eb5dbb30b8cc..2b1624441fa84 100644 --- a/packages/provider-acp-registry/src/server/adapter.ts +++ b/packages/provider-acp-registry/src/server/adapter.ts @@ -48,6 +48,12 @@ import { import * as AcpRegistrySupport from "./AcpRegistrySupport.ts"; import * as AcpRegistryRuntimeCoordinator from "./AcpRegistryRuntimeCoordinator.ts"; import * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime"; +import { + ANTIGRAVITY_SWARM_CAPABILITIES_META, + makeAntigravitySwarmTracker, + registerAntigravitySwarmExtension, +} from "@t3tools/provider-acp/server/antigravitySwarm"; +import { acpPermissionDisposition } from "@t3tools/provider-acp/server/clientPolicy"; import { makeAcpNativeLoggerFactory } from "@t3tools/provider-acp/server/nativeLogging"; import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers"; import { mergeProviderInstanceEnvironment } from "@t3tools/provider-core/server/instanceEnvironment"; @@ -257,6 +263,7 @@ export const makeAcpRegistryAdapterV2 = Effect.fn("makeAcpRegistryAdapterV2")(fu ? yield* makeKimiPromptOutcomeWatch(options.environment.KIMI_CODE_HOME) : undefined; const copilotRouting = isCopilot ? makeCopilotSubagentRouting() : undefined; + const antigravitySwarm = isAntigravityCli ? makeAntigravitySwarmTracker() : undefined; // Copilot CLI 1.0.105 rejects stdio MCP servers from the client, and Command Code cannot // start the stdio bridge on Windows (it spawns MCP commands through cmd.exe, which splits // the unquoted "T3 Code (Beta).exe" path). Both take T3's MCP endpoint over ACP HTTP. @@ -273,7 +280,23 @@ export const makeAcpRegistryAdapterV2 = Effect.fn("makeAcpRegistryAdapterV2")(fu : AcpProviderCapabilitiesV2, customModels: readCustomModelEntries(options.settings.customModels).map((entry) => entry.slug), compactViaAdvertisedCommand: true, - ...(isAntigravityCli ? { wakeOnDetachedRequest: true, replyEndsWithUsageUpdate: true } : {}), + ...(antigravitySwarm === undefined + ? {} + : { + wakeOnDetachedRequest: true, + replyEndsWithUsageUpdate: true, + subagentsIdleOnTurnCompletion: true, + clientCapabilitiesMeta: ANTIGRAVITY_SWARM_CAPABILITIES_META, + permissionDisposition: ( + policy: Parameters[0], + request: Parameters[1], + ) => + acpPermissionDisposition(policy, request, { + extraWritableRoots: antigravitySwarm.childPermissionWorkspaces(request), + }), + registerExtensions: (context: Parameters[1]) => + registerAntigravitySwarmExtension(antigravitySwarm, context), + }), promptFailure: (cause) => acpRegistryPromptFailure(isVibe ? "mistral-vibe" : registryAgentId, cause), ...(isDroid @@ -343,7 +366,45 @@ export const makeAcpRegistryAdapterV2 = Effect.fn("makeAcpRegistryAdapterV2")(fu alwaysSetModel: true, }), mcpOverHttp: useHttpMcpServers, - makeRuntime: options.makeRuntime ?? makeAcpRegistryRuntime(runtimeOptions, catalog), + makeRuntime: + options.makeRuntime ?? + (antigravitySwarm === undefined + ? makeAcpRegistryRuntime(runtimeOptions, catalog) + : (runtimeInput) => + Effect.gen(function* () { + const rt = yield* makeAcpRegistryRuntime(runtimeOptions, catalog)(runtimeInput); + let activeRuntimeSessionId: string | undefined; + const rememberSession = (started: AcpSessionRuntime.AcpSessionRuntimeStartResult) => + Effect.sync(() => { + if ( + activeRuntimeSessionId !== undefined && + activeRuntimeSessionId !== started.sessionId + ) { + antigravitySwarm.clearSession(activeRuntimeSessionId); + } + activeRuntimeSessionId = started.sessionId; + }); + yield* Effect.addFinalizer(() => + Effect.sync(() => { + if (activeRuntimeSessionId !== undefined) { + antigravitySwarm.clearSession(activeRuntimeSessionId); + } + }), + ); + return { + ...rt, + start: () => rt.start().pipe(Effect.tap(rememberSession)), + loadSession: (...args: Parameters) => + rt.loadSession(...args).pipe(Effect.tap(rememberSession)), + resumeSession: (...args: Parameters) => + rt.resumeSession(...args).pipe(Effect.tap(rememberSession)), + closeSession: (sessionId?: string) => + Effect.sync(() => { + const target = sessionId ?? activeRuntimeSessionId; + if (target !== undefined) antigravitySwarm.clearSession(target); + }).pipe(Effect.andThen(rt.closeSession(sessionId))), + }; + })), ...(runtimeCoordinator === undefined ? {} : { diff --git a/packages/provider-acp/package.json b/packages/provider-acp/package.json index 83f556e4c44e7..1210f6191ab4d 100644 --- a/packages/provider-acp/package.json +++ b/packages/provider-acp/package.json @@ -11,6 +11,10 @@ "types": "./src/server/adapter.ts", "import": "./src/server/adapter.ts" }, + "./server/antigravitySwarm": { + "types": "./src/server/antigravitySwarm.ts", + "import": "./src/server/antigravitySwarm.ts" + }, "./server/clientPolicy": { "types": "./src/server/clientPolicy.ts", "import": "./src/server/clientPolicy.ts" diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index 1ee6a0ea2df36..829d6d3812994 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -80,6 +80,8 @@ import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderS import * as McpProviderSession from "@t3tools/provider-core/server/mcpSession"; import { applyAcpAgentTerminalUpdate, + extractAcpChildRequestTarget, + type AcpChildRequestTarget, acpContentBlockDisplayText, embeddedTerminalIdsFromSessionUpdate, extractMcpToolCallIdentity, @@ -244,6 +246,8 @@ export interface AcpAdapterV2UserInputRequest { readonly nativeItemId: string; readonly nativeRequestId: string; readonly questions: ReadonlyArray; + readonly childSessionId?: string | null | undefined; + readonly childToolCallId?: string | null | undefined; } export interface AcpAdapterV2ExtensionContext { @@ -267,6 +271,7 @@ export interface AcpAdapterV2ExtensionContext { readonly sessionId: string; readonly subagent: AcpAdapterV2SubagentUpdate; readonly allowReopenFromIdle?: boolean | undefined; + readonly wakeContinuation?: boolean | undefined; }) => Effect.Effect; /** * Reports whether the session has active out-of-turn background coordination (for example running @@ -626,6 +631,7 @@ export interface AcpAdapterV2Flavor { ) => AcpSubagentSessionEvent | undefined; readonly extractSubagentUpdate?: ( toolCall: AcpToolCallState, + sessionId?: string, ) => AcpAdapterV2SubagentUpdate | undefined; readonly isProvisionalSubagentTool?: (toolCall: AcpToolCallState) => boolean; readonly normalizeToolCall?: (toolCall: AcpToolCallState) => AcpToolCallState; @@ -1978,6 +1984,8 @@ type PendingRuntimeRequest = { readonly runtimeRequest: OrchestrationV2RuntimeRequest; readonly node: OrchestrationV2ExecutionNode; readonly turnItem: OrchestrationV2TurnItem; + readonly childSessionId?: string | null | undefined; + readonly childToolCallId?: string | null | undefined; } & ( | { readonly type: "approval"; @@ -2280,14 +2288,15 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( let rootForegroundWork: "running" | "idle" | undefined; const agentRequests = new Set(); const nativeChildren = new Map(); - const extractSubagentUpdate = (tool: AcpToolCallState) => - flavor.extractSubagentSessionEvent !== undefined && !followsAgentWorkState - ? undefined - : flavor.extractSubagentUpdate?.(tool); - let turnAttached = yield* Deferred.make(); const activeSessionId = yield* Ref.make(null); // session/load replays history before activeSessionId names the loaded session. const loadingSessionId = yield* Ref.make(null); + let currentExtractSessionId: string | undefined; + const extractSubagentUpdate = (tool: AcpToolCallState, sessionId?: string) => + flavor.extractSubagentSessionEvent !== undefined && !followsAgentWorkState + ? undefined + : flavor.extractSubagentUpdate?.(tool, sessionId ?? currentExtractSessionId); + let turnAttached = yield* Deferred.make(); const contextUsageBySessionId = yield* Ref.make( new Map(), ); @@ -2641,6 +2650,11 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( }> >([]); const externalBackgroundWorkSessionIds = new Set(); + const knownExtensionChildSessions = new Set(); + const pendingBetweenTurnChildNotifications = new Map< + string, + Array + >(); const handledBackgroundTaskIdsInActiveTurn = yield* Ref.make>( new Set(), ); @@ -3575,6 +3589,12 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const nativeTaskId = subagent.task.nativeTaskRef?.nativeId ?? String(subagent.task.id); for (const event of parseSessionUpdateEvent(notification).events) { if (event._tag !== "ToolCallUpdated") continue; + if (event.toolCall.status !== undefined && event.toolCall.status !== "pending") { + yield* cancelPendingChildRuntimeRequests( + notification.sessionId, + event.toolCall.toolCallId, + ); + } const toolCall = flavor.normalizeToolCall?.(event.toolCall) ?? event.toolCall; const subagentUpdate = extractSubagentUpdate(toolCall); if (subagentUpdate !== undefined) { @@ -4076,6 +4096,12 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( } else { subagent.terminalStatusProjected = false; } + if ( + subagent.childSessionId !== null && + (taskStatus === "idle" || acpSubagentStatusIsTerminal(taskStatus)) + ) { + yield* cancelPendingChildRuntimeRequests(subagent.childSessionId); + } }); const nativeChild = (sessionId: string) => { @@ -5786,8 +5812,13 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( } }); + let cancelPendingChildRuntimeRequests: ( + childSessionId: string, + childToolCallId?: string | null, + ) => Effect.Effect = () => Effect.void; + const holdingAgentRequest = - (generation: number) => + (generation: number, options?: { readonly opensRootReply?: boolean | undefined }) => (effect: Effect.Effect) => Effect.suspend(() => !followsAgentWorkState && @@ -5811,8 +5842,14 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const context = yield* Ref.get(activeTurn); if (context !== null) yield* settleIdleWork(context); if (context !== null && flavor.wakeOnDetachedRequest) { - // The agent goes on with its reply once the request is answered. - if (flavor.replyEndsWithUsageUpdate === true) context.replyOpen = true; + // Child/worker approvals do not open a root reply or emit a root + // `usage_update`, so only root-owned requests open `replyOpen`. + if ( + flavor.replyEndsWithUsageUpdate === true && + options?.opensRootReply !== false + ) { + context.replyOpen = true; + } yield* rearmDeferredFinalize(context); } }), @@ -6079,6 +6116,12 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( ) { for (const event of parseSessionUpdateEvent(notification).events) { if (event._tag !== "ToolCallUpdated") continue; + if (event.toolCall.status !== undefined && event.toolCall.status !== "pending") { + yield* cancelPendingChildRuntimeRequests( + notification.sessionId, + event.toolCall.toolCallId, + ); + } const toolCall = flavor.normalizeToolCall?.(event.toolCall) ?? event.toolCall; const subagentUpdate = extractSubagentUpdate(toolCall); if (subagentUpdate === undefined) continue; @@ -6146,14 +6189,37 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( if (wakeOutcome.stopProcessing) { return; } + const currentRootSessionId = yield* Ref.get(activeSessionId); + if ( + currentRootSessionId !== null && + notification.sessionId !== currentRootSessionId && + !(yield* Ref.get(loadingSessionId)) && + (knownExtensionChildSessions.has(notification.sessionId) || + (yield* Ref.get(dormantSubagentsByChildSessionId)).has(notification.sessionId)) + ) { + const queued = pendingBetweenTurnChildNotifications.get(notification.sessionId) ?? []; + if (queued.length < 128) { + queued.push(notification); + pendingBetweenTurnChildNotifications.set(notification.sessionId, queued); + } + return; + } yield* recordLoadedHistory(notification, true); return; } if (context.finalized) return; const rootSessionId = yield* Ref.get(activeSessionId); + currentExtractSessionId = rootSessionId ?? undefined; if (notification.sessionId !== rootSessionId) { if (context.finalized) return; - if (flavor.extractSubagentUpdate === undefined) return; + const isKnownExtensionChild = knownExtensionChildSessions.has(notification.sessionId); + if ( + flavor.extractSubagentUpdate === undefined && + !isKnownExtensionChild && + !context.subagentsBySessionId.has(notification.sessionId) + ) { + return; + } const subagent = context.subagentsBySessionId.get(notification.sessionId); if ( update.sessionUpdate === "tool_call" || @@ -6162,6 +6228,13 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( ) { if (subagent !== undefined) { yield* projectSubagentNotification(subagent, notification, context); + } else if (isKnownExtensionChild) { + const buffered = + context.pendingSubagentNotifications.get(notification.sessionId) ?? []; + if (buffered.length < 256) { + buffered.push(notification); + context.pendingSubagentNotifications.set(notification.sessionId, buffered); + } } return; } @@ -6539,6 +6612,11 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( ...(parsed.detail === undefined ? {} : { prompt: parsed.detail }), ...(approvalOptions === undefined ? {} : { options: approvalOptions }), }; + const childTarget = extractAcpChildRequestTarget({ + meta: params._meta, + toolCallMeta: params.toolCall._meta, + fallbackToolCallId: params.toolCall.toolCallId, + }); yield* Ref.update(pendingRuntimeRequests, (current) => { const updated = new Map(current); updated.set(String(requestId), { @@ -6551,6 +6629,8 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( runtimeRequest, node, turnItem, + childSessionId: childTarget?.childSessionId ?? null, + childToolCallId: childTarget?.toolCallId ?? null, }); return updated; }); @@ -6676,6 +6756,8 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( runtimeRequest, node, turnItem, + childSessionId: request.childSessionId ?? null, + childToolCallId: request.childToolCallId ?? null, }); return updated; }); @@ -6765,22 +6847,10 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( ), ); - const cancelPendingRuntimeRequests = Effect.fnUntraced(function* ( - options: { readonly stopMcpCalls: boolean } = { stopMcpCalls: true }, + const cancelRuntimeRequestList = Effect.fnUntraced(function* ( + requests: ReadonlyArray, ) { - const waiting = turnAttached; - turnAttached = yield* Deferred.make(); - yield* Deferred.succeed(waiting, false); - // session/cancel does not end the agent's MCP calls; T3 runs them, so it stops them. - if (options.stopMcpCalls && runtimeMcpBridge !== undefined) { - yield* runtimeMcpBridge.stopCalls; - } - const requests = yield* Ref.modify(pendingRuntimeRequests, (current) => [ - [...current.values()], - new Map(), - ]); if (requests.length === 0) return; - const now = yield* DateTime.now; yield* Effect.forEach( requests, @@ -6825,6 +6895,48 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( ); }); + cancelPendingChildRuntimeRequests = Effect.fnUntraced(function* ( + childSessionId: string, + childToolCallId?: string | null, + ) { + const matched = yield* Ref.modify(pendingRuntimeRequests, (current) => { + const removed: Array = []; + let updated: Map | undefined; + for (const [key, req] of current) { + if (req.childSessionId !== childSessionId) continue; + if ( + childToolCallId !== undefined && + childToolCallId !== null && + req.childToolCallId !== childToolCallId + ) { + continue; + } + removed.push(req); + updated ??= new Map(current); + updated.delete(key); + } + return [removed, updated ?? current] as const; + }); + yield* cancelRuntimeRequestList(matched); + }); + + const cancelPendingRuntimeRequests = Effect.fnUntraced(function* ( + options: { readonly stopMcpCalls: boolean } = { stopMcpCalls: true }, + ) { + const waiting = turnAttached; + turnAttached = yield* Deferred.make(); + yield* Deferred.succeed(waiting, false); + // session/cancel does not end the agent's MCP calls; T3 runs them, so it stops them. + if (options.stopMcpCalls && runtimeMcpBridge !== undefined) { + yield* runtimeMcpBridge.stopCalls; + } + const requests = yield* Ref.modify(pendingRuntimeRequests, (current) => [ + [...current.values()], + new Map(), + ]); + yield* cancelRuntimeRequestList(requests); + }); + const mutateCarryoverSubagentStatus = Effect.fnUntraced(function* ( subagent: ActiveAcpSubagent, status: OrchestrationV2Subagent["status"], @@ -7066,9 +7178,14 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( readonly sessionId: string; readonly subagent: AcpAdapterV2SubagentUpdate; readonly allowReopenFromIdle?: boolean | undefined; + readonly wakeContinuation?: boolean | undefined; }) { const allowReopenFromIdle = notice.allowReopenFromIdle === true; + const wakeContinuation = notice.wakeContinuation !== false; const update = notice.subagent; + if (update.childSessionId !== null) { + knownExtensionChildSessions.add(update.childSessionId); + } const context = yield* Ref.get(activeTurn); if ( context !== null && @@ -7089,6 +7206,8 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( ), ); if (update.childSessionId !== null) { + pendingBetweenTurnChildNotifications.delete(update.childSessionId); + yield* cancelPendingChildRuntimeRequests(update.childSessionId); const dormant = (yield* Ref.get(dormantSubagentsByChildSessionId)).get( update.childSessionId, ); @@ -7121,7 +7240,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( } return; } - if (postSettleContinuationEnabled && !(yield* Ref.get(loadingSessionId))) { + if (postSettleContinuationEnabled && wakeContinuation) { yield* Ref.update(pendingExtensionSubagents, (current) => [ ...current.filter( (entry) => @@ -7131,7 +7250,9 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( ), { subagent: update, allowReopenFromIdle }, ]); - yield* offerContinuationRun(notice.sessionId); + if (!(yield* Ref.get(loadingSessionId))) { + yield* offerContinuationRun(notice.sessionId); + } } }); @@ -7552,8 +7673,13 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( projectAcpRuntimeSessionUpdate(handlerGeneration, rawNotification), ); } - yield* targetRuntime.handleRequestPermission((nativeParams, requestContext) => - Effect.gen(function* () { + yield* targetRuntime.handleRequestPermission((nativeParams, requestContext) => { + const childTarget: AcpChildRequestTarget | undefined = extractAcpChildRequestTarget({ + meta: nativeParams._meta, + toolCallMeta: nativeParams.toolCall._meta, + fallbackToolCallId: nativeParams.toolCall.toolCallId, + }); + return Effect.gen(function* () { if ( postSettleContinuationEnabled && flavor.wakeOnDetachedRequest && @@ -7563,7 +7689,9 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( } const trackedTurn = yield* Ref.get(activeTurn); const params = - trackedTurn !== null && nativeParams.sessionId === (yield* Ref.get(activeSessionId)) + trackedTurn !== null && + childTarget === undefined && + nativeParams.sessionId === (yield* Ref.get(activeSessionId)) ? withTrackedPermissionToolCall( nativeParams, trackedTurn.tools.get(nativeParams.toolCall.toolCallId), @@ -7580,6 +7708,8 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( nativeRequestId: params.toolCall.toolCallId, nativeSessionId: params.sessionId, questions: [permissionQuestion.question], + childSessionId: childTarget?.childSessionId ?? null, + childToolCallId: childTarget?.toolCallId ?? null, }), transportRequestId, ); @@ -7598,6 +7728,39 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( policy: ProviderAdapter.ProviderAdapterV2RuntimePolicy, request: EffectAcpSchema.RequestPermissionRequest = params, ) => (flavor.permissionDisposition ?? acpPermissionDisposition)(policy, request); + // Auto-allowed or auto-denied child worker permissions do not need an empty parent + // continuation run when no turn is currently open. + if ( + childTarget !== undefined && + trackedTurn === null && + dispositionFor(latestRuntimePolicy) !== "ask" + ) { + const direct = yield* runRuntimeCallbackAtGeneration( + handlerGeneration, + Effect.gen(function* () { + const disposition = dispositionFor(latestRuntimePolicy); + if (disposition === "ask") return undefined; + const optionId = + disposition === "allow" + ? selectAutoApprovedPermissionOption(answerableParams) + : selectPermissionOptionId(answerableParams, "decline"); + const nativeResponseAcknowledgement = yield* Deferred.make< + void, + EffectAcpErrors.AcpError + >(); + yield* registerNativeResponseAcknowledgement( + handlerGeneration, + transportRequestId, + nativeResponseAcknowledgement, + ); + return optionId === undefined + ? ({ outcome: { outcome: "cancelled" } } as const) + : ({ outcome: { outcome: "selected", optionId } } as const); + }), + ); + if (Option.isNone(direct)) return yield* Effect.never; + if (direct.value !== undefined) return direct.value; + } if ( (followsAgentWorkState && dispositionFor(latestRuntimePolicy) === "ask") || (postSettleContinuationEnabled && flavor.wakeOnDetachedRequest) @@ -7735,11 +7898,20 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( cause, }), ), - holdingAgentRequest(handlerGeneration), - ), - ); - yield* targetRuntime.handleElicitation((params, requestContext) => - Effect.gen(function* () { + holdingAgentRequest(handlerGeneration, { + opensRootReply: childTarget === undefined, + }), + ); + }); + yield* targetRuntime.handleElicitation((params, requestContext) => { + const childElicitation = extractAcpChildRequestTarget({ + meta: params._meta, + fallbackToolCallId: + "toolCallId" in params && typeof params.toolCallId === "string" + ? params.toolCallId + : undefined, + }); + return Effect.gen(function* () { const transportRequestId = requestContext.requestId; if ( params.mode === "form" && @@ -7851,6 +8023,8 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( nativeItemId: nativeRequestId, nativeRequestId, questions: form.questions, + childSessionId: childElicitation?.childSessionId ?? null, + childToolCallId: childElicitation?.toolCallId ?? null, }; }), transportRequestId, @@ -7861,8 +8035,12 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( : form.respond(userInput.answers); yield* userInput.acknowledgeNativeResponse; return response; - }).pipe(holdingAgentRequest(handlerGeneration)), - ); + }).pipe( + holdingAgentRequest(handlerGeneration, { + opensRootReply: childElicitation === undefined, + }), + ); + }); if (flavor.registerExtensions !== undefined) { yield* flavor.registerExtensions({ runtime: targetRuntime, @@ -7887,7 +8065,9 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( handlerGeneration, Effect.gen(function* () { if (yield* Ref.get(stoppedRunQuarantine)) return; - if ((yield* Ref.get(activeSessionId)) !== notice.sessionId) return; + const expectedSessionId = + (yield* Ref.get(activeSessionId)) ?? (yield* Ref.get(loadingSessionId)); + if (expectedSessionId !== notice.sessionId) return; yield* upsertSubagentFromExtension(notice); }), ).pipe(Effect.asVoid), @@ -7896,7 +8076,9 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( handlerGeneration, Effect.gen(function* () { if (yield* Ref.get(stoppedRunQuarantine)) return; - if ((yield* Ref.get(activeSessionId)) !== notice.sessionId) return; + const expectedSessionId = + (yield* Ref.get(activeSessionId)) ?? (yield* Ref.get(loadingSessionId)); + if (expectedSessionId !== notice.sessionId) return; if (notice.active) externalBackgroundWorkSessionIds.add(notice.sessionId); else externalBackgroundWorkSessionIds.delete(notice.sessionId); const context = yield* Ref.get(activeTurn); @@ -8264,6 +8446,9 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( yield* Ref.set(dormantSubagentsByChildSessionId, new Map()); yield* Ref.set(pendingExtensionSubagents, []); externalBackgroundWorkSessionIds.clear(); + knownExtensionChildSessions.clear(); + pendingBetweenTurnChildNotifications.clear(); + currentExtractSessionId = undefined; yield* Ref.set(suppressPostSettleMonitorPrompt, false); yield* Ref.set(lastTurnRoute, null); }), @@ -9824,6 +10009,11 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( driver, providerThread: activeProviderThread, }); + const queuedChildNotifications = new Map(pendingBetweenTurnChildNotifications); + pendingBetweenTurnChildNotifications.clear(); + for (const [childId, frames] of queuedChildNotifications) { + context.pendingSubagentNotifications.set(childId, frames); + } for (const queued of queuedExtensionSubagents) { yield* applyExtensionSubagentToTurn( context, @@ -9831,6 +10021,14 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( queued.allowReopenFromIdle, ); } + for (const [childId, frames] of context.pendingSubagentNotifications) { + const subagent = context.subagentsBySessionId.get(childId); + if (subagent === undefined) continue; + context.pendingSubagentNotifications.delete(childId); + for (const frame of frames) { + yield* projectSubagentNotification(subagent, frame, context); + } + } yield* rememberSnapshotMessage({ createdBy: turnInput.message.createdBy, creationSource: turnInput.message.creationSource, diff --git a/packages/provider-acp/src/server/antigravitySwarm.ts b/packages/provider-acp/src/server/antigravitySwarm.ts new file mode 100644 index 0000000000000..4d499541698c9 --- /dev/null +++ b/packages/provider-acp/src/server/antigravitySwarm.ts @@ -0,0 +1,488 @@ +import type * as EffectAcpSchema from "effect-acp/compat"; +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; + +import type { AcpAdapterV2ExtensionContext, AcpAdapterV2SubagentUpdate } from "./adapter.ts"; +import { unknownRecord } from "./clientPolicy.ts"; + +export const ANTIGRAVITY_SWARM_CAPABILITIES_META = { + antigravity: { + swarm: true, + }, +} as const; + +const ANTIGRAVITY_SWARM_NOTIFICATION_METHOD = "_antigravity/swarm"; + +const ANTIGRAVITY_SWARM_TASK_PREFIX = "swarm:"; + +const HOUSEKEEPING_SWARM_ROLES = new Set(["monitor", "narrator"]); + +export const AntigravitySwarmMember = Schema.Struct({ + name: Schema.String, + role: Schema.String, + conversationId: Schema.String, + toolCallId: Schema.optional(Schema.String), + brief: Schema.optional(Schema.String), + model: Schema.optional(Schema.String), + modelLabel: Schema.optional(Schema.String), + state: Schema.String, + hadActivity: Schema.optional(Schema.Boolean), + failure: Schema.optional(Schema.String), + workspace: Schema.optional(Schema.String), + workspaces: Schema.optional(Schema.Array(Schema.String)), + addedBy: Schema.optional(Schema.String), +}); +export type AntigravitySwarmMember = Schema.Schema.Type; + +const AntigravitySwarmControl = Schema.Struct({ + op: Schema.String, + channel: Schema.optional(Schema.String), + topic: Schema.optional(Schema.String), + channels: Schema.optional(Schema.Array(Schema.String)), + members: Schema.optional(Schema.Array(Schema.String)), +}); + +export const AntigravitySwarmPost = Schema.Struct({ + seq: Schema.Number, + time: Schema.optional(Schema.String), + agent: Schema.String, + channel: Schema.optional(Schema.String), + kind: Schema.optional(Schema.String), + text: Schema.String, + control: Schema.optional(AntigravitySwarmControl), +}); +export type AntigravitySwarmPost = Schema.Schema.Type; + +export const AntigravitySwarmNotification = Schema.Struct({ + sessionId: Schema.String, + title: Schema.optional(Schema.String), + head: Schema.Number, + channels: Schema.optional(Schema.Array(Schema.String)), + activeWorkers: Schema.Number, + workingWorkers: Schema.Number, + waitingWorkers: Schema.Number, + coordinatorWorking: Schema.optional(Schema.Boolean), + coordinatorPendingWake: Schema.optional(Schema.Boolean), + members: Schema.Array(AntigravitySwarmMember), + posts: Schema.optional(Schema.Array(AntigravitySwarmPost)), +}); +export type AntigravitySwarmNotification = Schema.Schema.Type; + +const MAX_BOARD_REPORT_CHARS = 8_000; + +interface TrackedSwarmMember { + nativeTaskId: string; + name: string; + role: string; + conversationId: string; + toolCallId: string | null; + status: AcpAdapterV2SubagentUpdate["status"]; + latestReport: string | null; + lastBrief: string; + sawIdleOrReport: boolean; + readonly workspaces: Set; +} + +interface TrackedSwarmSession { + busy: boolean; + readonly membersByConversationId: Map; + readonly membersByName: Map; + readonly latestPostsByAgent: Map; + readonly briefsByMention: Map; +} + +function nonEmpty(value: string | undefined): string | undefined { + const trimmed = value?.trim(); + return trimmed !== undefined && trimmed.length > 0 ? trimmed : undefined; +} + +function resolveMemberRole(name: string, rawRole: string): string { + const trimmedRole = rawRole.trim().toLowerCase(); + if (trimmedRole.length > 0 && trimmedRole !== "worker") { + return trimmedRole; + } + const normalizedName = name.trim().replace(/^@/, "").toLowerCase(); + const match = /^(narrator|monitor)(?:-\d+)?$/.exec(normalizedName); + return match?.[1] ?? (trimmedRole || "worker"); +} + +function isHousekeepingRole(role: string): boolean { + return HOUSEKEEPING_SWARM_ROLES.has(role); +} + +function cleanBoardReport(text: string): string | null { + const withoutCoordinatorPrefix = text.trim().replace(/^@(?:coordinator|all)\b[:,\s-]*/i, ""); + const normalized = (withoutCoordinatorPrefix.length > 0 ? withoutCoordinatorPrefix : text).trim(); + if (normalized.length === 0) return null; + return normalized.length <= MAX_BOARD_REPORT_CHARS + ? normalized + : `${normalized.slice(0, MAX_BOARD_REPORT_CHARS - 1)}…`; +} + +function extractMentionedNames(text: string): ReadonlyArray { + const names: Array = []; + for (const match of text.matchAll(/(?:^|\s)@([a-z0-9][a-z0-9_-]*)\b/gi)) { + const name = match[1]?.toLowerCase(); + if (name !== undefined && name !== "coordinator" && name !== "all") { + names.push(name); + } + } + return names; +} + +function formatSwarmMemberTitle(member: AntigravitySwarmMember, role: string): string { + const handle = `@${member.name.replace(/^@/, "")}`; + const roleSuffix = role !== "worker" && role.length > 0 ? ` (${role})` : ""; + const addedBy = nonEmpty(member.addedBy)?.replace(/^@/, ""); + const parentSuffix = addedBy !== undefined && addedBy !== "coordinator" ? ` via @${addedBy}` : ""; + return `${handle}${roleSuffix}${parentSuffix}`; +} + +function mapSwarmMemberStatus( + state: string, + sawIdleOrReport: boolean, +): AcpAdapterV2SubagentUpdate["status"] { + switch (state.trim().toLowerCase()) { + case "working": + return "running"; + case "waiting": + case "stopped": + return "idle"; + case "failed": + return "failed"; + case "killed": + return sawIdleOrReport ? "completed" : "cancelled"; + default: + return "idle"; + } +} + +export function agentAdvertisesAntigravitySwarm(agentCapabilities: unknown): boolean { + if (typeof agentCapabilities !== "object" || agentCapabilities === null) return false; + const meta = (agentCapabilities as { readonly _meta?: unknown })._meta; + if (typeof meta !== "object" || meta === null) return false; + const antigravity = (meta as { readonly antigravity?: unknown }).antigravity; + if (typeof antigravity !== "object" || antigravity === null) return false; + const swarm = (antigravity as { readonly swarm?: unknown }).swarm; + if (swarm === true) return true; + if (typeof swarm === "object" && swarm !== null) { + const enabled = (swarm as { readonly enabled?: unknown }).enabled; + return enabled !== false; + } + return false; +} + +export function swarmWorkerConversationIdFromTaskId(nativeTaskId: string): string | undefined { + return nativeTaskId.startsWith(ANTIGRAVITY_SWARM_TASK_PREFIX) + ? nativeTaskId.slice(ANTIGRAVITY_SWARM_TASK_PREFIX.length) + : undefined; +} + +export interface AntigravitySwarmSubagentEntry { + readonly subagent: AcpAdapterV2SubagentUpdate; + readonly wakeContinuation: boolean; +} + +export interface AntigravitySwarmMutation { + readonly sessionId: string; + readonly activeBackgroundWork: boolean; + readonly subagents: ReadonlyArray; +} + +export interface AntigravitySwarmTracker { + readonly applyNotification: ( + notification: AntigravitySwarmNotification, + ) => AntigravitySwarmMutation; + readonly setSessionProtocol: (sessionId: string, supported: boolean) => void; + readonly usesNativeProtocol: (sessionId: string) => boolean; + readonly clearSession: (sessionId: string) => void; + readonly hasLiveSwarm: (sessionId: string) => boolean; + readonly childPermissionWorkspaces: ( + request: EffectAcpSchema.RequestPermissionRequest, + ) => ReadonlyArray; + readonly partitionTaskIds: ( + sessionId: string, + nativeTaskIds: ReadonlyArray, + ) => { + readonly runningSwarmTaskIds: ReadonlyArray; + readonly unmanagedTaskIds: ReadonlyArray; + }; +} + +export function registerAntigravitySwarmExtension( + tracker: AntigravitySwarmTracker, + context: AcpAdapterV2ExtensionContext, +) { + return context.runtime.handleExtNotification( + ANTIGRAVITY_SWARM_NOTIFICATION_METHOD, + AntigravitySwarmNotification, + (notification) => + Effect.gen(function* () { + const mutation = tracker.applyNotification(notification); + if (mutation.activeBackgroundWork) { + yield* context.setExternalBackgroundWork({ + sessionId: mutation.sessionId, + active: true, + }); + } + for (const entry of mutation.subagents) { + yield* context.upsertSubagent({ + sessionId: mutation.sessionId, + subagent: entry.subagent, + allowReopenFromIdle: true, + wakeContinuation: entry.wakeContinuation, + }); + } + if (!mutation.activeBackgroundWork) { + yield* context.setExternalBackgroundWork({ + sessionId: mutation.sessionId, + active: false, + }); + } + }), + ); +} + +export function makeAntigravitySwarmTracker(): AntigravitySwarmTracker { + const sessions = new Map(); + const nativeProtocolSessions = new Set(); + + const sessionFor = (sessionId: string): TrackedSwarmSession => { + let session = sessions.get(sessionId); + if (session === undefined) { + session = { + busy: false, + membersByConversationId: new Map(), + membersByName: new Map(), + latestPostsByAgent: new Map(), + briefsByMention: new Map(), + }; + sessions.set(sessionId, session); + } + return session; + }; + + return { + setSessionProtocol(sessionId, supported) { + if (supported) nativeProtocolSessions.add(sessionId); + else nativeProtocolSessions.delete(sessionId); + }, + + usesNativeProtocol(sessionId) { + return nativeProtocolSessions.has(sessionId) || sessions.has(sessionId); + }, + + clearSession(sessionId) { + sessions.delete(sessionId); + nativeProtocolSessions.delete(sessionId); + }, + + applyNotification(notification) { + nativeProtocolSessions.add(notification.sessionId); + const session = sessionFor(notification.sessionId); + + for (const post of notification.posts ?? []) { + if (post.control !== undefined) continue; + const author = post.agent.trim().toLowerCase(); + if (post.kind === "brief") { + const cleaned = cleanBoardReport(post.text); + if (cleaned !== null) { + for (const mentioned of extractMentionedNames(post.text)) { + if (!session.briefsByMention.has(mentioned)) { + session.briefsByMention.set(mentioned, cleaned); + } + } + } + continue; + } + if (author === "coordinator" || author.length === 0) continue; + const report = cleanBoardReport(post.text); + if (report === null) continue; + session.latestPostsByAgent.set(author, report); + const tracked = session.membersByName.get(author); + if (tracked !== undefined) { + tracked.latestReport = report; + tracked.sawIdleOrReport = true; + } + } + + const subagents: Array = []; + let runningWorkerCount = 0; + + for (const member of notification.members) { + const conversationId = nonEmpty(member.conversationId); + const role = resolveMemberRole(member.name, member.role); + if (conversationId === undefined || role === "coordinator") continue; + const housekeeping = isHousekeepingRole(role); + const nameKey = member.name.trim().toLowerCase(); + const callId = nonEmpty(member.toolCallId) ?? null; + + let tracked = session.membersByConversationId.get(conversationId); + const nativeTaskId = `${ANTIGRAVITY_SWARM_TASK_PREFIX}${conversationId}`; + if (tracked === undefined) { + tracked = { + nativeTaskId, + name: member.name, + role, + conversationId, + toolCallId: callId, + status: "running", + latestReport: session.latestPostsByAgent.get(nameKey) ?? null, + lastBrief: "", + sawIdleOrReport: member.hadActivity === true || session.latestPostsByAgent.has(nameKey), + workspaces: new Set(), + }; + session.membersByConversationId.set(conversationId, tracked); + session.membersByName.set(nameKey, tracked); + } else { + tracked.role = role; + if (tracked.toolCallId === null && callId !== null) { + tracked.toolCallId = callId; + } + if (member.hadActivity === true) { + tracked.sawIdleOrReport = true; + } + } + const primaryWorkspace = nonEmpty(member.workspace); + if (primaryWorkspace !== undefined) tracked.workspaces.add(primaryWorkspace); + for (const extraWorkspace of member.workspaces ?? []) { + const trimmed = nonEmpty(extraWorkspace); + if (trimmed !== undefined) tracked.workspaces.add(trimmed); + } + + const latestPost = session.latestPostsByAgent.get(nameKey) ?? tracked.latestReport; + if (latestPost !== null) { + tracked.latestReport = latestPost; + tracked.sawIdleOrReport = true; + } + + const nextStatus = mapSwarmMemberStatus(member.state, tracked.sawIdleOrReport); + if (nextStatus === "idle") { + tracked.sawIdleOrReport = true; + } + if (!housekeeping && (nextStatus === "running" || nextStatus === "pending")) { + runningWorkerCount += 1; + } + tracked.status = nextStatus; + + const brief = + nonEmpty(member.brief) ?? + nonEmpty(tracked.lastBrief) ?? + session.briefsByMention.get(nameKey) ?? + `Swarm ${role} @${member.name}`; + tracked.lastBrief = brief; + + const model = nonEmpty(member.modelLabel) ?? nonEmpty(member.model) ?? null; + const failureText = nonEmpty(member.failure) ?? null; + const result = + nextStatus === "running" + ? null + : nextStatus === "failed" + ? (failureText ?? tracked.latestReport ?? "Swarm worker execution failed.") + : tracked.latestReport; + + subagents.push({ + subagent: { + nativeTaskId: tracked.nativeTaskId, + childSessionId: conversationId, + title: formatSwarmMemberTitle(member, role), + prompt: brief, + model, + status: nextStatus, + result, + suppressNormalTool: true, + }, + // Periodic `@monitor` / `@narrator` checks never wake empty parent continuation runs. + wakeContinuation: !housekeeping, + }); + } + + session.busy = + runningWorkerCount > 0 || + notification.workingWorkers > 0 || + notification.activeWorkers > 0 || + notification.coordinatorWorking === true || + notification.coordinatorPendingWake === true; + + return { + sessionId: notification.sessionId, + activeBackgroundWork: session.busy, + subagents, + }; + }, + + hasLiveSwarm(sessionId) { + return sessions.has(sessionId); + }, + + childPermissionWorkspaces(request) { + const roots = new Set(); + for (const container of [ + unknownRecord(request._meta), + unknownRecord(request.toolCall._meta), + ]) { + const antigravity = unknownRecord(container?.antigravity); + if (antigravity === undefined) continue; + const primary = + typeof antigravity.workspace === "string" ? nonEmpty(antigravity.workspace) : undefined; + if (primary !== undefined) roots.add(primary); + if (Array.isArray(antigravity.workspaces)) { + for (const entry of antigravity.workspaces) { + if (typeof entry !== "string") continue; + const trimmed = nonEmpty(entry); + if (trimmed !== undefined) roots.add(trimmed); + } + } + const childSessionId = + typeof antigravity.childSessionId === "string" + ? nonEmpty(antigravity.childSessionId) + : undefined; + if (childSessionId !== undefined) { + const tracked = sessions + .get(request.sessionId) + ?.membersByConversationId.get(childSessionId); + if (tracked !== undefined) { + for (const workspace of tracked.workspaces) roots.add(workspace); + } + } + } + return [...roots]; + }, + + partitionTaskIds(sessionId, nativeTaskIds) { + const session = sessions.get(sessionId); + if (session === undefined) { + return { runningSwarmTaskIds: [], unmanagedTaskIds: nativeTaskIds }; + } + const managedStatus = new Map< + string, + { readonly status: AcpAdapterV2SubagentUpdate["status"]; readonly housekeeping: boolean } + >(); + for (const member of session.membersByConversationId.values()) { + const entry = { + status: member.status, + housekeeping: isHousekeepingRole(member.role), + }; + managedStatus.set(member.nativeTaskId, entry); + if (member.toolCallId !== null) { + managedStatus.set(member.toolCallId, entry); + } + managedStatus.set(`${ANTIGRAVITY_SWARM_TASK_PREFIX}${member.conversationId}`, entry); + } + const runningSwarmTaskIds: Array = []; + const unmanagedTaskIds: Array = []; + for (const id of nativeTaskIds) { + const entry = managedStatus.get(id); + if (entry === undefined) { + unmanagedTaskIds.push(id); + } else if ( + !entry.housekeeping && + (entry.status === "running" || entry.status === "pending") + ) { + runningSwarmTaskIds.push(id); + } + } + return { runningSwarmTaskIds, unmanagedTaskIds }; + }, + }; +} diff --git a/packages/provider-acp/src/server/clientPolicy.ts b/packages/provider-acp/src/server/clientPolicy.ts index 022d96dd956f6..cdec5b919061f 100644 --- a/packages/provider-acp/src/server/clientPolicy.ts +++ b/packages/provider-acp/src/server/clientPolicy.ts @@ -72,6 +72,7 @@ function acpCanonicalPathForContainment(path: string): string | undefined { interface AcpPolicyOperation { readonly kind: string | null | undefined; readonly locations: ReadonlyArray<{ readonly path: string }> | null | undefined; + readonly extraWritableRoots?: ReadonlyArray | undefined; } function acpPolicyRequiresApproval(runtimePolicy: AcpRuntimePolicy): boolean { @@ -102,6 +103,7 @@ function acpWorkspaceWriteAllowsMutation( runtimePolicy: AcpRuntimePolicy, sandboxPolicy: Record, locations: AcpPolicyOperation["locations"], + extraWritableRoots?: ReadonlyArray, ): boolean { const cwd = typeof runtimePolicy.cwd === "string" && runtimePolicy.cwd.trim().length > 0 @@ -115,6 +117,7 @@ function acpWorkspaceWriteAllowsMutation( const writableRoots = [ ...(Array.isArray(sandboxPolicy.writableRoots) ? sandboxPolicy.writableRoots : []), ...(runtimePolicy.workspace?.extraRoots ?? []), + ...(extraWritableRoots ?? []), ]; for (const writableRoot of writableRoots) { if (typeof writableRoot !== "string") continue; @@ -164,6 +167,7 @@ function acpOperationDisposition( runtimePolicy, sandboxPolicy ?? {}, operation.locations, + operation.extraWritableRoots, ) ? "allow" : "deny"; @@ -194,10 +198,15 @@ function isAcpMutationKind(toolKind: string): boolean { export function acpPermissionDisposition( runtimePolicy: AcpRuntimePolicy, request: EffectAcpSchema.RequestPermissionRequest, + options?: { readonly extraWritableRoots?: ReadonlyArray | undefined }, ): AcpPermissionDisposition { + const extraWritableRoots = options?.extraWritableRoots; return acpOperationDisposition(runtimePolicy, { kind: request.toolCall.kind, locations: request.toolCall.locations, + ...(extraWritableRoots === undefined || extraWritableRoots.length === 0 + ? {} + : { extraWritableRoots }), }); } diff --git a/packages/provider-acp/src/server/runtimeModel.ts b/packages/provider-acp/src/server/runtimeModel.ts index e01ca47772f9e..589556f39c4b2 100644 --- a/packages/provider-acp/src/server/runtimeModel.ts +++ b/packages/provider-acp/src/server/runtimeModel.ts @@ -1287,6 +1287,43 @@ export function withTrackedPermissionToolCall( }; } +export interface AcpChildRequestTarget { + readonly childSessionId: string; + readonly toolCallId: string | null; + readonly workerLabel: string | null; +} + +export function extractAcpChildRequestTarget(input: { + readonly meta?: unknown; + readonly toolCallMeta?: unknown; + readonly fallbackToolCallId?: string | undefined; +}): AcpChildRequestTarget | undefined { + const fromMeta = (candidate: unknown) => { + if (!isRecord(candidate)) return undefined; + const antigravity = candidate.antigravity; + return isRecord(antigravity) ? antigravity : undefined; + }; + const ag = fromMeta(input.meta) ?? fromMeta(input.toolCallMeta); + if (ag === undefined) return undefined; + const swarm = isRecord(ag.swarm) ? ag.swarm : undefined; + const childSessionId = + (typeof ag.childSessionId === "string" && ag.childSessionId.trim()) || + (typeof swarm?.workerSessionId === "string" && swarm.workerSessionId.trim()) || + ""; + if (childSessionId.length === 0) return undefined; + const toolCallId = + (typeof ag.workerToolCallId === "string" && ag.workerToolCallId.trim()) || + (typeof input.fallbackToolCallId === "string" && input.fallbackToolCallId.trim()) || + null; + const workerName = + (typeof swarm?.workerName === "string" && swarm.workerName.trim().replace(/^@/, "")) || + (typeof ag.agentName === "string" && ag.agentName.trim().replace(/^@/, "")) || + ""; + const role = typeof ag.role === "string" ? ag.role.trim() : ""; + const workerLabel = workerName.length > 0 ? `@${workerName}` : role.length > 0 ? role : null; + return { childSessionId, toolCallId, workerLabel }; +} + export function parsePermissionRequest( params: EffectAcpSchema.RequestPermissionRequest, ): AcpPermissionRequest { @@ -1300,15 +1337,34 @@ export function parsePermissionRequest( rawOutput: params.toolCall.rawOutput, content: params.toolCall.content, locations: params.toolCall.locations, + _meta: params.toolCall._meta, }, { fallbackStatus: "pending" }, ); const kind = normalizeToolKind(params.toolCall.kind) ?? "unknown"; - const detail = + const childTarget = extractAcpChildRequestTarget({ + meta: params._meta, + toolCallMeta: params.toolCall._meta, + fallbackToolCallId: params.toolCall.toolCallId, + }); + const rawCommandLine = + isRecord(params.toolCall.rawInput) && typeof params.toolCall.rawInput.CommandLine === "string" + ? params.toolCall.rawInput.CommandLine.trim() || undefined + : undefined; + const baseDetail = toolCall?.command ?? + rawCommandLine ?? toolCall?.title ?? toolCall?.detail ?? (typeof params.sessionId === "string" ? `Session ${params.sessionId}` : undefined); + const actorPrefix = + childTarget?.workerLabel !== null && childTarget?.workerLabel !== undefined + ? `[${childTarget.workerLabel}] ` + : undefined; + const detail = + baseDetail !== undefined && actorPrefix !== undefined && !baseDetail.startsWith(actorPrefix) + ? `${actorPrefix}${baseDetail}` + : baseDetail; return { kind, ...(detail ? { detail } : {}), From 97162fe4ed7f5716606462da8104a3aa3cc48862 Mon Sep 17 00:00:00 2001 From: "Patrick C. Toulme" <135739773+patrick-toulme@users.noreply.github.com> Date: Sat, 21 Nov 2026 23:12:18 +0000 Subject: [PATCH 05/11] fix(antigravity): tighten swarm worktree validation and session scoping - Restrict childPermissionWorkspaces to non-root workspaces recorded for tracked swarm members - Keep child approvals pending while tool status is requiresAction - Scope queued extension subagent updates by root session ID and prefer loadingSessionId during load - Fall back to toolCall._meta.antigravity when top-level _meta.antigravity lacks a child target --- .../src/provider/acp/AntigravitySwarm.test.ts | 65 ++++++++++++++++++- packages/provider-acp/src/server/adapter.ts | 41 ++++++++---- .../src/server/antigravitySwarm.ts | 46 ++++++------- .../provider-acp/src/server/runtimeModel.ts | 47 +++++++------- 4 files changed, 138 insertions(+), 61 deletions(-) diff --git a/apps/server/src/provider/acp/AntigravitySwarm.test.ts b/apps/server/src/provider/acp/AntigravitySwarm.test.ts index ac57f09dd8890..f38d07288e234 100644 --- a/apps/server/src/provider/acp/AntigravitySwarm.test.ts +++ b/apps/server/src/provider/acp/AntigravitySwarm.test.ts @@ -263,6 +263,26 @@ describe("AntigravitySwarm", () => { }); expect(parsed.detail).toBe("[@alpha] pnpm test"); + // Falls back to toolCall._meta.antigravity when top-level _meta.antigravity lacks childSessionId. + const fallbackParsed = parsePermissionRequest({ + sessionId: "root-1", + _meta: { antigravity: {} }, + toolCall: { + toolCallId: "worker-cmd-2", + kind: "execute", + title: "pnpm lint", + rawInput: { CommandLine: "pnpm lint" }, + _meta: { + antigravity: { + childSessionId: "worker-a", + swarm: { workerSessionId: "worker-a", workerName: "alpha" }, + }, + }, + }, + options: [{ optionId: "allow", name: "Allow", kind: "allow_once" }], + }); + expect(fallbackParsed.detail).toBe("[@alpha] pnpm lint"); + const baseRequest = { sessionId: "root-1", toolCall: { @@ -284,18 +304,57 @@ describe("AntigravitySwarm", () => { _meta: { antigravity: { childSessionId: "worker-a", - workspaces: ["/tmp/isolated-worktree"], + workspaces: ["/tmp/isolated-worktree", "/"], }, }, }; - // Generic ACP servers cannot expand writable roots via _meta.antigravity.workspaces. + // Untracked metadata roots never widen workspaceWrite. expect(acpPermissionDisposition(policy, baseRequest)).toBe("deny"); expect(acpPermissionDisposition(policy, childWorktreeRequest)).toBe("deny"); - // Antigravity adapters pass their verified worker worktree roots explicitly. + expect( + acpPermissionDisposition(policy, childWorktreeRequest, { + extraWritableRoots: tracker.childPermissionWorkspaces(childWorktreeRequest), + }), + ).toBe("deny"); + + // Once the session records worker-a's worktree (while rejecting root "/" paths), + // edits inside the tracked worktree are allowed and outside paths remain denied. + tracker.applyNotification({ + sessionId: "root-1", + head: 1, + activeWorkers: 1, + workingWorkers: 1, + waitingWorkers: 0, + members: [ + { + name: "alpha", + role: "worker", + conversationId: "worker-a", + workspaces: ["/tmp/isolated-worktree", "/"], + state: "working", + }, + ], + }); + expect(tracker.childPermissionWorkspaces(childWorktreeRequest)).toEqual([ + "/tmp/isolated-worktree", + ]); expect( acpPermissionDisposition(policy, childWorktreeRequest, { extraWritableRoots: tracker.childPermissionWorkspaces(childWorktreeRequest), }), ).toBe("allow"); + expect( + acpPermissionDisposition( + policy, + { + ...childWorktreeRequest, + toolCall: { + ...childWorktreeRequest.toolCall, + locations: [{ path: "/tmp/other-dir/escape.ts" }], + }, + }, + { extraWritableRoots: tracker.childPermissionWorkspaces(childWorktreeRequest) }, + ), + ).toBe("deny"); }); }); diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index 829d6d3812994..4f3fe1f19d327 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -2645,6 +2645,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( >(new Map()); const pendingExtensionSubagents = yield* Ref.make< ReadonlyArray<{ + readonly sessionId: string; readonly subagent: AcpAdapterV2SubagentUpdate; readonly allowReopenFromIdle: boolean; }> @@ -3589,7 +3590,11 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const nativeTaskId = subagent.task.nativeTaskRef?.nativeId ?? String(subagent.task.id); for (const event of parseSessionUpdateEvent(notification).events) { if (event._tag !== "ToolCallUpdated") continue; - if (event.toolCall.status !== undefined && event.toolCall.status !== "pending") { + if ( + event.toolCall.status !== undefined && + event.toolCall.status !== "pending" && + event.toolCall.status !== "requiresAction" + ) { yield* cancelPendingChildRuntimeRequests( notification.sessionId, event.toolCall.toolCallId, @@ -6116,7 +6121,11 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( ) { for (const event of parseSessionUpdateEvent(notification).events) { if (event._tag !== "ToolCallUpdated") continue; - if (event.toolCall.status !== undefined && event.toolCall.status !== "pending") { + if ( + event.toolCall.status !== undefined && + event.toolCall.status !== "pending" && + event.toolCall.status !== "requiresAction" + ) { yield* cancelPendingChildRuntimeRequests( notification.sessionId, event.toolCall.toolCallId, @@ -7200,9 +7209,10 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( yield* Ref.update(pendingExtensionSubagents, (current) => current.filter( (entry) => - entry.subagent.nativeTaskId !== update.nativeTaskId && - (update.childSessionId === null || - entry.subagent.childSessionId !== update.childSessionId), + entry.sessionId !== notice.sessionId || + (entry.subagent.nativeTaskId !== update.nativeTaskId && + (update.childSessionId === null || + entry.subagent.childSessionId !== update.childSessionId)), ), ); if (update.childSessionId !== null) { @@ -7244,11 +7254,12 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( yield* Ref.update(pendingExtensionSubagents, (current) => [ ...current.filter( (entry) => - entry.subagent.nativeTaskId !== update.nativeTaskId && - (update.childSessionId === null || - entry.subagent.childSessionId !== update.childSessionId), + entry.sessionId !== notice.sessionId || + (entry.subagent.nativeTaskId !== update.nativeTaskId && + (update.childSessionId === null || + entry.subagent.childSessionId !== update.childSessionId)), ), - { subagent: update, allowReopenFromIdle }, + { sessionId: notice.sessionId, subagent: update, allowReopenFromIdle }, ]); if (!(yield* Ref.get(loadingSessionId))) { yield* offerContinuationRun(notice.sessionId); @@ -8066,7 +8077,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( Effect.gen(function* () { if (yield* Ref.get(stoppedRunQuarantine)) return; const expectedSessionId = - (yield* Ref.get(activeSessionId)) ?? (yield* Ref.get(loadingSessionId)); + (yield* Ref.get(loadingSessionId)) ?? (yield* Ref.get(activeSessionId)); if (expectedSessionId !== notice.sessionId) return; yield* upsertSubagentFromExtension(notice); }), @@ -8077,7 +8088,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( Effect.gen(function* () { if (yield* Ref.get(stoppedRunQuarantine)) return; const expectedSessionId = - (yield* Ref.get(activeSessionId)) ?? (yield* Ref.get(loadingSessionId)); + (yield* Ref.get(loadingSessionId)) ?? (yield* Ref.get(activeSessionId)); if (expectedSessionId !== notice.sessionId) return; if (notice.active) externalBackgroundWorkSessionIds.add(notice.sessionId); else externalBackgroundWorkSessionIds.delete(notice.sessionId); @@ -9980,7 +9991,13 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( } yield* Ref.set(activeTurn, context); yield* Ref.set(stoppedRunQuarantine, false); - const queuedExtensionSubagents = yield* Ref.getAndSet(pendingExtensionSubagents, []); + const queuedExtensionSubagents = yield* Ref.modify( + pendingExtensionSubagents, + (current) => [ + current.filter((entry) => entry.sessionId === requestedSessionId), + current.filter((entry) => entry.sessionId !== requestedSessionId), + ], + ); const runningTurn = providerTurnPayload(context, "running", null); yield* Ref.update(providerTurns, (current) => { const updated = new Map(current); diff --git a/packages/provider-acp/src/server/antigravitySwarm.ts b/packages/provider-acp/src/server/antigravitySwarm.ts index 4d499541698c9..4626b1da7b0f7 100644 --- a/packages/provider-acp/src/server/antigravitySwarm.ts +++ b/packages/provider-acp/src/server/antigravitySwarm.ts @@ -91,6 +91,14 @@ interface TrackedSwarmSession { readonly briefsByMention: Map; } +function isNonRootWorkspacePath(candidate: string): boolean { + const normalized = candidate.replaceAll("\\", "/").replace(/\/+$/, ""); + if (normalized.length === 0) return false; + if (/^[a-z]:$/i.test(normalized)) return false; + if (/^\/\/[^/]+(?:\/[^/]+)?$/.test(normalized)) return false; + return true; +} + function nonEmpty(value: string | undefined): string | undefined { const trimmed = value?.trim(); return trimmed !== undefined && trimmed.length > 0 ? trimmed : undefined; @@ -343,11 +351,11 @@ export function makeAntigravitySwarmTracker(): AntigravitySwarmTracker { tracked.sawIdleOrReport = true; } } - const primaryWorkspace = nonEmpty(member.workspace); - if (primaryWorkspace !== undefined) tracked.workspaces.add(primaryWorkspace); for (const extraWorkspace of member.workspaces ?? []) { const trimmed = nonEmpty(extraWorkspace); - if (trimmed !== undefined) tracked.workspaces.add(trimmed); + if (trimmed !== undefined && isNonRootWorkspacePath(trimmed)) { + tracked.workspaces.add(trimmed); + } } const latestPost = session.latestPostsByAgent.get(nameKey) ?? tracked.latestReport; @@ -416,6 +424,8 @@ export function makeAntigravitySwarmTracker(): AntigravitySwarmTracker { }, childPermissionWorkspaces(request) { + const session = sessions.get(request.sessionId); + if (session === undefined) return []; const roots = new Set(); for (const container of [ unknownRecord(request._meta), @@ -423,27 +433,19 @@ export function makeAntigravitySwarmTracker(): AntigravitySwarmTracker { ]) { const antigravity = unknownRecord(container?.antigravity); if (antigravity === undefined) continue; - const primary = - typeof antigravity.workspace === "string" ? nonEmpty(antigravity.workspace) : undefined; - if (primary !== undefined) roots.add(primary); - if (Array.isArray(antigravity.workspaces)) { - for (const entry of antigravity.workspaces) { - if (typeof entry !== "string") continue; - const trimmed = nonEmpty(entry); - if (trimmed !== undefined) roots.add(trimmed); - } - } + const swarm = unknownRecord(antigravity.swarm); const childSessionId = - typeof antigravity.childSessionId === "string" + (typeof antigravity.childSessionId === "string" ? nonEmpty(antigravity.childSessionId) - : undefined; - if (childSessionId !== undefined) { - const tracked = sessions - .get(request.sessionId) - ?.membersByConversationId.get(childSessionId); - if (tracked !== undefined) { - for (const workspace of tracked.workspaces) roots.add(workspace); - } + : undefined) ?? + (typeof swarm?.workerSessionId === "string" + ? nonEmpty(swarm.workerSessionId) + : undefined); + if (childSessionId === undefined) continue; + const tracked = session.membersByConversationId.get(childSessionId); + if (tracked === undefined) continue; + for (const workspace of tracked.workspaces) { + if (isNonRootWorkspacePath(workspace)) roots.add(workspace); } } return [...roots]; diff --git a/packages/provider-acp/src/server/runtimeModel.ts b/packages/provider-acp/src/server/runtimeModel.ts index 589556f39c4b2..3b9d04e7d30ab 100644 --- a/packages/provider-acp/src/server/runtimeModel.ts +++ b/packages/provider-acp/src/server/runtimeModel.ts @@ -1298,30 +1298,29 @@ export function extractAcpChildRequestTarget(input: { readonly toolCallMeta?: unknown; readonly fallbackToolCallId?: string | undefined; }): AcpChildRequestTarget | undefined { - const fromMeta = (candidate: unknown) => { - if (!isRecord(candidate)) return undefined; - const antigravity = candidate.antigravity; - return isRecord(antigravity) ? antigravity : undefined; - }; - const ag = fromMeta(input.meta) ?? fromMeta(input.toolCallMeta); - if (ag === undefined) return undefined; - const swarm = isRecord(ag.swarm) ? ag.swarm : undefined; - const childSessionId = - (typeof ag.childSessionId === "string" && ag.childSessionId.trim()) || - (typeof swarm?.workerSessionId === "string" && swarm.workerSessionId.trim()) || - ""; - if (childSessionId.length === 0) return undefined; - const toolCallId = - (typeof ag.workerToolCallId === "string" && ag.workerToolCallId.trim()) || - (typeof input.fallbackToolCallId === "string" && input.fallbackToolCallId.trim()) || - null; - const workerName = - (typeof swarm?.workerName === "string" && swarm.workerName.trim().replace(/^@/, "")) || - (typeof ag.agentName === "string" && ag.agentName.trim().replace(/^@/, "")) || - ""; - const role = typeof ag.role === "string" ? ag.role.trim() : ""; - const workerLabel = workerName.length > 0 ? `@${workerName}` : role.length > 0 ? role : null; - return { childSessionId, toolCallId, workerLabel }; + for (const candidate of [input.meta, input.toolCallMeta]) { + if (!isRecord(candidate)) continue; + const ag = candidate.antigravity; + if (!isRecord(ag)) continue; + const swarm = isRecord(ag.swarm) ? ag.swarm : undefined; + const childSessionId = + (typeof ag.childSessionId === "string" && ag.childSessionId.trim()) || + (typeof swarm?.workerSessionId === "string" && swarm.workerSessionId.trim()) || + ""; + if (childSessionId.length === 0) continue; + const toolCallId = + (typeof ag.workerToolCallId === "string" && ag.workerToolCallId.trim()) || + (typeof input.fallbackToolCallId === "string" && input.fallbackToolCallId.trim()) || + null; + const workerName = + (typeof swarm?.workerName === "string" && swarm.workerName.trim().replace(/^@/, "")) || + (typeof ag.agentName === "string" && ag.agentName.trim().replace(/^@/, "")) || + ""; + const role = typeof ag.role === "string" ? ag.role.trim() : ""; + const workerLabel = workerName.length > 0 ? `@${workerName}` : role.length > 0 ? role : null; + return { childSessionId, toolCallId, workerLabel }; + } + return undefined; } export function parsePermissionRequest( From 77a235251f8395ab98ba2b2376dda9c58584c9b5 Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Sat, 21 Nov 2026 15:25:09 -0800 Subject: [PATCH 06/11] fix(antigravity): keep between-turn worker reports and bound swarm writable roots - A worker first seen between turns that finishes before the next turn now keeps its queued registration with the terminal status, so the next turn still shows the worker and its report. - Agent-reported swarm worktree roots that contain the session cwd no longer widen workspaceWrite. This replaces the tracker's root-path check with one rule in the shared policy. Co-Authored-By: Claude Opus 5.5 --- .../Adapters/AntigravityAdapterV2.test.ts | 23 ++++++++- .../src/provider/acp/AntigravitySwarm.test.ts | 9 ++-- packages/provider-acp/src/server/adapter.ts | 50 ++++++++++++------- .../src/server/antigravitySwarm.ts | 16 +----- .../provider-acp/src/server/clientPolicy.ts | 31 +++++++----- 5 files changed, 78 insertions(+), 51 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts index b4a90c0b7d3f5..ec331214e7657 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts @@ -2544,6 +2544,7 @@ describe("AntigravityAdapterV2 native swarm protocol", () => { const rootSessionId = "11111111-1111-4000-8000-000000000001"; const alphaSessionId = "11111111-1111-4000-8000-00000000000a"; const betaSessionId = "11111111-1111-4000-8000-00000000000b"; + const gammaSessionId = "11111111-1111-4000-8000-00000000000c"; const continuationRequests = { offer: () => Effect.succeed(true), @@ -2878,6 +2879,7 @@ describe("AntigravityAdapterV2 native swarm protocol", () => { ); // Between turns @beta wakes and is killed; turn 2 must not replay the queued running update. + // New worker @gamma spawns and finishes in the same gap; turn 2 must still show its report. yield* onSwarmNotification!({ sessionId: rootSessionId, head: 4, @@ -2887,6 +2889,13 @@ describe("AntigravityAdapterV2 native swarm protocol", () => { members: [ { name: "alpha", role: "worker", conversationId: alphaSessionId, state: "waiting" }, { name: "beta", role: "worker", conversationId: betaSessionId, state: "working" }, + { + name: "gamma", + role: "worker", + conversationId: gammaSessionId, + brief: "Inspect docs", + state: "working", + }, ], }); yield* onSwarmNotification!({ @@ -2898,8 +2907,18 @@ describe("AntigravityAdapterV2 native swarm protocol", () => { members: [ { name: "alpha", role: "worker", conversationId: alphaSessionId, state: "waiting" }, { name: "beta", role: "worker", conversationId: betaSessionId, state: "killed" }, + { + name: "gamma", + role: "worker", + conversationId: gammaSessionId, + brief: "Inspect docs", + state: "killed", + }, + ], + posts: [ + { seq: 4, agent: "beta", text: "@coordinator Backend wrap-up." }, + { seq: 5, agent: "gamma", text: "@coordinator Docs wrap-up." }, ], - posts: [{ seq: 4, agent: "beta", text: "@coordinator Backend wrap-up." }], }); // Turn 2 wakes @alpha again on the exact same child thread, then kills @alpha after reporting. @@ -2952,6 +2971,8 @@ describe("AntigravityAdapterV2 native swarm protocol", () => { assert.equal(subagentsByTitle().get("@alpha")?.result, "Follow-up complete."); assert.equal(subagentsByTitle().get("@beta")?.status, "completed"); assert.equal(subagentsByTitle().get("@beta")?.result, "Backend wrap-up."); + assert.equal(subagentsByTitle().get("@gamma")?.status, "completed"); + assert.equal(subagentsByTitle().get("@gamma")?.result, "Docs wrap-up."); yield* Fiber.interrupt(reader); }).pipe(Effect.provide(layerSession), Effect.scoped), diff --git a/apps/server/src/provider/acp/AntigravitySwarm.test.ts b/apps/server/src/provider/acp/AntigravitySwarm.test.ts index f38d07288e234..f6d0d56c315f2 100644 --- a/apps/server/src/provider/acp/AntigravitySwarm.test.ts +++ b/apps/server/src/provider/acp/AntigravitySwarm.test.ts @@ -317,8 +317,8 @@ describe("AntigravitySwarm", () => { }), ).toBe("deny"); - // Once the session records worker-a's worktree (while rejecting root "/" paths), - // edits inside the tracked worktree are allowed and outside paths remain denied. + // Once the session records worker-a's worktree, edits inside it are allowed. Reported roots + // that contain the session cwd ("/" and "/tmp") never widen workspaceWrite. tracker.applyNotification({ sessionId: "root-1", head: 1, @@ -330,14 +330,11 @@ describe("AntigravitySwarm", () => { name: "alpha", role: "worker", conversationId: "worker-a", - workspaces: ["/tmp/isolated-worktree", "/"], + workspaces: ["/tmp/isolated-worktree", "/", "/tmp"], state: "working", }, ], }); - expect(tracker.childPermissionWorkspaces(childWorktreeRequest)).toEqual([ - "/tmp/isolated-worktree", - ]); expect( acpPermissionDisposition(policy, childWorktreeRequest, { extraWritableRoots: tracker.childPermissionWorkspaces(childWorktreeRequest), diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index 4f3fe1f19d327..d2413b82eaabb 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -7205,23 +7205,26 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( yield* applyExtensionSubagentToTurn(context, update, allowReopenFromIdle); return; } + const isSameQueuedWorker = (entry: { + sessionId: string; + subagent: AcpAdapterV2SubagentUpdate; + }) => + entry.sessionId === notice.sessionId && + (entry.subagent.nativeTaskId === update.nativeTaskId || + (update.childSessionId !== null && + entry.subagent.childSessionId === update.childSessionId)); if (acpSubagentStatusIsTerminal(update.status)) { - yield* Ref.update(pendingExtensionSubagents, (current) => - current.filter( - (entry) => - entry.sessionId !== notice.sessionId || - (entry.subagent.nativeTaskId !== update.nativeTaskId && - (update.childSessionId === null || - entry.subagent.childSessionId !== update.childSessionId)), - ), - ); + const queued = yield* Ref.modify(pendingExtensionSubagents, (current) => [ + current.find(isSameQueuedWorker), + current.filter((entry) => !isSameQueuedWorker(entry)), + ]); if (update.childSessionId !== null) { - pendingBetweenTurnChildNotifications.delete(update.childSessionId); yield* cancelPendingChildRuntimeRequests(update.childSessionId); const dormant = (yield* Ref.get(dormantSubagentsByChildSessionId)).get( update.childSessionId, ); if (dormant !== undefined) { + pendingBetweenTurnChildNotifications.delete(update.childSessionId); const nextResult = update.result ?? dormant.task.result; if (dormant.task.status !== update.status || dormant.task.result !== nextResult) { yield* projectCarryoverSubagentStatus(dormant, update.status, nextResult); @@ -7236,7 +7239,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( return; } const carryover = yield* Ref.get(carryoverSubagents); - yield* updateCarryoverSubagentStatus( + const handledByCarryover = yield* updateCarryoverSubagentStatus( update.childSessionId, update.status, update.result, @@ -7247,18 +7250,29 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( carryover.projectsLateTerminals, }, ); + if (!handledByCarryover && queued !== undefined) { + // A worker first seen between turns exists only in the queue; keep its final state + // and buffered frames so the next turn still projects it. + yield* Ref.update(pendingExtensionSubagents, (current) => [ + ...current, + { + ...queued, + subagent: { + ...queued.subagent, + status: update.status, + result: update.result ?? queued.subagent.result, + }, + }, + ]); + return; + } + pendingBetweenTurnChildNotifications.delete(update.childSessionId); } return; } if (postSettleContinuationEnabled && wakeContinuation) { yield* Ref.update(pendingExtensionSubagents, (current) => [ - ...current.filter( - (entry) => - entry.sessionId !== notice.sessionId || - (entry.subagent.nativeTaskId !== update.nativeTaskId && - (update.childSessionId === null || - entry.subagent.childSessionId !== update.childSessionId)), - ), + ...current.filter((entry) => !isSameQueuedWorker(entry)), { sessionId: notice.sessionId, subagent: update, allowReopenFromIdle }, ]); if (!(yield* Ref.get(loadingSessionId))) { diff --git a/packages/provider-acp/src/server/antigravitySwarm.ts b/packages/provider-acp/src/server/antigravitySwarm.ts index 4626b1da7b0f7..6e355fd11a3c3 100644 --- a/packages/provider-acp/src/server/antigravitySwarm.ts +++ b/packages/provider-acp/src/server/antigravitySwarm.ts @@ -91,14 +91,6 @@ interface TrackedSwarmSession { readonly briefsByMention: Map; } -function isNonRootWorkspacePath(candidate: string): boolean { - const normalized = candidate.replaceAll("\\", "/").replace(/\/+$/, ""); - if (normalized.length === 0) return false; - if (/^[a-z]:$/i.test(normalized)) return false; - if (/^\/\/[^/]+(?:\/[^/]+)?$/.test(normalized)) return false; - return true; -} - function nonEmpty(value: string | undefined): string | undefined { const trimmed = value?.trim(); return trimmed !== undefined && trimmed.length > 0 ? trimmed : undefined; @@ -353,9 +345,7 @@ export function makeAntigravitySwarmTracker(): AntigravitySwarmTracker { } for (const extraWorkspace of member.workspaces ?? []) { const trimmed = nonEmpty(extraWorkspace); - if (trimmed !== undefined && isNonRootWorkspacePath(trimmed)) { - tracked.workspaces.add(trimmed); - } + if (trimmed !== undefined) tracked.workspaces.add(trimmed); } const latestPost = session.latestPostsByAgent.get(nameKey) ?? tracked.latestReport; @@ -444,9 +434,7 @@ export function makeAntigravitySwarmTracker(): AntigravitySwarmTracker { if (childSessionId === undefined) continue; const tracked = session.membersByConversationId.get(childSessionId); if (tracked === undefined) continue; - for (const workspace of tracked.workspaces) { - if (isNonRootWorkspacePath(workspace)) roots.add(workspace); - } + for (const workspace of tracked.workspaces) roots.add(workspace); } return [...roots]; }, diff --git a/packages/provider-acp/src/server/clientPolicy.ts b/packages/provider-acp/src/server/clientPolicy.ts index cdec5b919061f..86d5d234f70fd 100644 --- a/packages/provider-acp/src/server/clientPolicy.ts +++ b/packages/provider-acp/src/server/clientPolicy.ts @@ -110,22 +110,29 @@ function acpWorkspaceWriteAllowsMutation( ? (resolveAcpPermissionPath(runtimePolicy.cwd, process.cwd()) ?? null) : null; const roots: Array = []; - if (cwd !== null) { - const canonicalCwd = acpCanonicalPathForContainment(cwd); - if (canonicalCwd !== undefined) roots.push(canonicalCwd); - } - const writableRoots = [ + const canonicalCwd = cwd === null ? undefined : acpCanonicalPathForContainment(cwd); + if (canonicalCwd !== undefined) roots.push(canonicalCwd); + const canonicalizeRoot = (writableRoot: unknown) => { + if (typeof writableRoot !== "string") return undefined; + const resolved = resolveAcpPermissionPath(writableRoot, cwd); + return resolved === undefined ? undefined : acpCanonicalPathForContainment(resolved); + }; + for (const writableRoot of [ ...(Array.isArray(sandboxPolicy.writableRoots) ? sandboxPolicy.writableRoots : []), ...(runtimePolicy.workspace?.extraRoots ?? []), - ...(extraWritableRoots ?? []), - ]; - for (const writableRoot of writableRoots) { - if (typeof writableRoot !== "string") continue; - const resolved = resolveAcpPermissionPath(writableRoot, cwd); - if (resolved === undefined) continue; - const canonicalRoot = acpCanonicalPathForContainment(resolved); + ]) { + const canonicalRoot = canonicalizeRoot(writableRoot); if (canonicalRoot !== undefined) roots.push(canonicalRoot); } + // Agent-reported roots (swarm worker worktrees) may sit beside the workspace, never above it. + if (canonicalCwd !== undefined) { + for (const writableRoot of extraWritableRoots ?? []) { + const canonicalRoot = canonicalizeRoot(writableRoot); + if (canonicalRoot !== undefined && !acpPathIsWithinRoot(canonicalCwd, canonicalRoot)) { + roots.push(canonicalRoot); + } + } + } if (roots.length === 0) return false; if (locations === undefined || locations === null || locations.length === 0) { From 70f8d6068b5d648008acabfa8ce4e16ffcf9b593 Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Sat, 21 Nov 2026 15:45:05 -0800 Subject: [PATCH 07/11] fix(antigravity): settle swarm turns after housekeeping pulses and process exits - Report housekeeping (@monitor, @narrator) pulses as idle so they never hold a turn open, and report finished workers once so later rosters do not re-create them in a new turn. - A process exit now fails a turn held only by swarm work and clears the external work marker, so local agy turns cannot hang after a crash. - After Stop, a stopped worker's permission request is cancelled instead of auto-approved, and buffered child frames are dropped. Co-Authored-By: Claude Opus 5.5 --- .../Adapters/AcpRegistryAdapterV2.test.ts | 68 ++++++++++++ .../src/provider/acp/AntigravitySwarm.test.ts | 100 ++++++++++-------- packages/provider-acp/src/server/adapter.ts | 13 ++- .../src/server/antigravitySwarm.ts | 8 +- 4 files changed, 140 insertions(+), 49 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts index 55b313a9d3adc..7abd44071e4e5 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts @@ -523,6 +523,74 @@ describe("AcpRegistryAdapterV2", () => { }).pipe(Effect.provide(layerTest)), ); + it.effect("fails an agy swarm turn held by running workers when the process exits", () => + Effect.gen(function* () { + const update = (sessionUpdate: Record) => + claudeFrames.update(CLAUDE_ROOT_SESSION, sessionUpdate); + const session = yield* openClaudeReplaySession( + [ + { + type: "expect_outbound", + frame: { kind: "request", method: "initialize", params: "" }, + }, + { + type: "emit_inbound", + frame: { + kind: "response", + method: "initialize", + result: { + protocolVersion: 1, + agentInfo: { name: "Antigravity ACP Server", version: "1.5.14" }, + agentCapabilities: { loadSession: true, _meta: { antigravity: { swarm: true } } }, + authMethods: [], + }, + }, + }, + claudeFrames.open[2], + claudeFrames.open[3], + claudeFrames.prompt(1)[0], + { + type: "emit_inbound", + frame: { + kind: "notification", + method: "_antigravity/swarm", + params: { + sessionId: CLAUDE_ROOT_SESSION, + head: 1, + activeWorkers: 1, + workingWorkers: 1, + waitingWorkers: 0, + members: [ + { name: "alpha", role: "worker", conversationId: "worker-a", state: "working" }, + ], + }, + }, + }, + { + type: "emit_inbound", + frame: { + kind: "response", + method: "session/prompt", + result: { stopReason: "end_turn" }, + }, + }, + update({ sessionUpdate: "usage_update", used: 100, size: 1000 }), + claudeMarker("workers running"), + ], + undefined, + true, + { source: "local", commandPath: "/root/.local/bin/agy", commandArgs: ["acp"] }, + ); + yield* session.runtime.startTurn(session.turnInput(1)); + yield* session.throughMarker("workers running"); + assert.isTrue(yield* session.runtime.hasPendingBackgroundWork!); + yield* session.terminate(); + const terminal = yield* session.terminal; + assert.equal(terminal.status, "failed"); + assert.isFalse(yield* session.runtime.hasPendingBackgroundWork!); + }).pipe(Effect.provide(layerTest)), + ); + it.effect.each(["approval-required", "full-access"] as const)( "continues an agy permission request after the prompt settles (%s)", (runtimeMode) => diff --git a/apps/server/src/provider/acp/AntigravitySwarm.test.ts b/apps/server/src/provider/acp/AntigravitySwarm.test.ts index f6d0d56c315f2..0b502d9bb9ea4 100644 --- a/apps/server/src/provider/acp/AntigravitySwarm.test.ts +++ b/apps/server/src/provider/acp/AntigravitySwarm.test.ts @@ -115,7 +115,8 @@ describe("AntigravitySwarm", () => { title: "@monitor (monitor)", prompt: "Swarm monitor @monitor", model: null, - status: "running", + // Housekeeping pulses never hold the turn open, so they report idle. + status: "idle", result: null, suppressNormalTool: true, }, @@ -173,51 +174,50 @@ describe("AntigravitySwarm", () => { }); // Periodic @monitor tick alone does NOT mark the session busy; hadActivity marks killed workers completed. - const settled = tracker.applyNotification( - decode({ - sessionId: "root-1", - head: 4, - activeWorkers: 0, - workingWorkers: 0, - waitingWorkers: 0, - coordinatorWorking: false, - coordinatorPendingWake: false, - members: [ - { - name: "alpha", - role: "worker", - conversationId: "worker-a", - state: "failed", - failure: "quota exhausted", - }, - { - name: "helper", - role: "worker", - conversationId: "worker-h", - state: "killed", - }, - { - name: "resumed-done", - role: "worker", - conversationId: "worker-r", - state: "killed", - hadActivity: true, - }, - { - name: "scratch", - role: "narrator", - conversationId: "worker-n", - state: "killed", - }, - { - name: "monitor", - role: "monitor", - conversationId: "worker-m", - state: "working", - }, - ], - }), - ); + const settledNotification = decode({ + sessionId: "root-1", + head: 4, + activeWorkers: 0, + workingWorkers: 0, + waitingWorkers: 0, + coordinatorWorking: false, + coordinatorPendingWake: false, + members: [ + { + name: "alpha", + role: "worker", + conversationId: "worker-a", + state: "failed", + failure: "quota exhausted", + }, + { + name: "helper", + role: "worker", + conversationId: "worker-h", + state: "killed", + }, + { + name: "resumed-done", + role: "worker", + conversationId: "worker-r", + state: "killed", + hadActivity: true, + }, + { + name: "scratch", + role: "narrator", + conversationId: "worker-n", + state: "killed", + }, + { + name: "monitor", + role: "monitor", + conversationId: "worker-m", + state: "working", + }, + ], + }); + const settled = tracker.applyNotification(settledNotification); expect(settled.activeBackgroundWork).toBe(false); expect(settled.subagents[0]?.subagent).toMatchObject({ @@ -238,6 +238,14 @@ describe("AntigravitySwarm", () => { result: null, }); expect(settled.subagents[4]?.wakeContinuation).toBe(false); + expect(settled.subagents[4]?.subagent.status).toBe("idle"); + + // Finished workers are reported once; a later roster that still lists them does not re-emit them. + expect( + tracker + .applyNotification(settledNotification) + .subagents.map((entry) => entry.subagent.childSessionId), + ).toEqual(["worker-m"]); tracker.clearSession("root-1"); expect(tracker.hasLiveSwarm("root-1")).toBe(false); diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index d2413b82eaabb..42a902d63b728 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -2806,12 +2806,16 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( // An open prompt fails with its transport. A turn held open for a running tool // has no prompt, so nothing else ends it. const held = yield* Ref.get(activeTurn); + const heldByExternalWork = + held !== null && externalBackgroundWorkSessionIds.has(held.nativeThreadId); + // The exited process can no longer report its external work ending. + externalBackgroundWorkSessionIds.clear(); if ( - flavor.toolOutlivesPrompt === undefined || + (flavor.toolOutlivesPrompt === undefined && !heldByExternalWork) || held === null || !held.promptSettled || held.finalized || - !hasDeferredBackgroundWork(held) + (!heldByExternalWork && !hasDeferredBackgroundWork(held)) ) return; for (const tool of held.tools.values()) { @@ -7763,6 +7767,9 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const direct = yield* runRuntimeCallbackAtGeneration( handlerGeneration, Effect.gen(function* () { + if (yield* Ref.get(stoppedRunQuarantine)) { + return { outcome: { outcome: "cancelled" } } as const; + } const disposition = dispositionFor(latestRuntimePolicy); if (disposition === "ask") return undefined; const optionId = @@ -9038,6 +9045,8 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( yield* Ref.set(dormantSubagentsByChildSessionId, new Map()); yield* Ref.set(pendingExtensionSubagents, []); externalBackgroundWorkSessionIds.clear(); + knownExtensionChildSessions.clear(); + pendingBetweenTurnChildNotifications.clear(); yield* Ref.set(lastTurnRoute, null); }), ); diff --git a/packages/provider-acp/src/server/antigravitySwarm.ts b/packages/provider-acp/src/server/antigravitySwarm.ts index 6e355fd11a3c3..bc280ecd60d4f 100644 --- a/packages/provider-acp/src/server/antigravitySwarm.ts +++ b/packages/provider-acp/src/server/antigravitySwarm.ts @@ -361,7 +361,12 @@ export function makeAntigravitySwarmTracker(): AntigravitySwarmTracker { if (!housekeeping && (nextStatus === "running" || nextStatus === "pending")) { runningWorkerCount += 1; } + // Rosters keep listing finished workers; re-emitting one would re-create it in a later turn. + const alreadyReported = + tracked.status === nextStatus && + (nextStatus === "completed" || nextStatus === "failed" || nextStatus === "cancelled"); tracked.status = nextStatus; + if (alreadyReported) continue; const brief = nonEmpty(member.brief) ?? @@ -386,7 +391,8 @@ export function makeAntigravitySwarmTracker(): AntigravitySwarmTracker { title: formatSwarmMemberTitle(member, role), prompt: brief, model, - status: nextStatus, + // Housekeeping pulses never hold the turn open. + status: housekeeping && nextStatus === "running" ? "idle" : nextStatus, result, suppressNormalTool: true, }, From a08445f7b3432cb8c558a0f7f6853b66abcdf130 Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Sat, 21 Nov 2026 16:15:43 -0800 Subject: [PATCH 08/11] fix(antigravity): address swarm review findings - Never take a worker permission's kind from the root turn's tool table. - Queue a worker's first terminal report even with no earlier running update. - A recreated worker with a reused name no longer inherits the old report. - Close open child tools when a worker ends, keep a parked worker's buffered frames, and merge queued child frames with live ones at turn start. - Coalesce child reasoning updates like the assistant stream. - Re-read the swarm roster after the classic-child disk read, and read the worker tool id from either metadata record. Co-Authored-By: Claude Opus 5.5 --- .../Adapters/AntigravityAdapterV2.test.ts | 14 ++++ .../Adapters/AntigravityAdapterV2.ts | 4 +- .../src/provider/acp/AntigravitySwarm.test.ts | 29 ++++++++ packages/provider-acp/src/server/adapter.ts | 72 ++++++++++++++----- .../src/server/antigravitySwarm.ts | 7 ++ .../provider-acp/src/server/runtimeModel.ts | 8 ++- 6 files changed, 114 insertions(+), 20 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts index ec331214e7657..0359e1724e600 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts @@ -2545,6 +2545,7 @@ describe("AntigravityAdapterV2 native swarm protocol", () => { const alphaSessionId = "11111111-1111-4000-8000-00000000000a"; const betaSessionId = "11111111-1111-4000-8000-00000000000b"; const gammaSessionId = "11111111-1111-4000-8000-00000000000c"; + const deltaSessionId = "11111111-1111-4000-8000-00000000000d"; const continuationRequests = { offer: () => Effect.succeed(true), @@ -2862,6 +2863,8 @@ describe("AntigravityAdapterV2 native swarm protocol", () => { } return map; }; + // The native `swarm add` tool call must not create a subagent beside the roster workers. + assert.deepEqual([...subagentsByTitle().keys()].sort(), ["@alpha", "@beta"]); const alphaAfterTurn1 = subagentsByTitle().get("@alpha"); const betaAfterTurn1 = subagentsByTitle().get("@beta"); assert.equal(alphaAfterTurn1?.status, "idle"); @@ -2880,6 +2883,7 @@ describe("AntigravityAdapterV2 native swarm protocol", () => { // Between turns @beta wakes and is killed; turn 2 must not replay the queued running update. // New worker @gamma spawns and finishes in the same gap; turn 2 must still show its report. + // @delta is first seen already finished, with no running update before it. yield* onSwarmNotification!({ sessionId: rootSessionId, head: 4, @@ -2914,10 +2918,18 @@ describe("AntigravityAdapterV2 native swarm protocol", () => { brief: "Inspect docs", state: "killed", }, + { + name: "delta", + role: "worker", + conversationId: deltaSessionId, + brief: "Inspect CI", + state: "killed", + }, ], posts: [ { seq: 4, agent: "beta", text: "@coordinator Backend wrap-up." }, { seq: 5, agent: "gamma", text: "@coordinator Docs wrap-up." }, + { seq: 6, agent: "delta", text: "@coordinator CI wrap-up." }, ], }); @@ -2973,6 +2985,8 @@ describe("AntigravityAdapterV2 native swarm protocol", () => { assert.equal(subagentsByTitle().get("@beta")?.result, "Backend wrap-up."); assert.equal(subagentsByTitle().get("@gamma")?.status, "completed"); assert.equal(subagentsByTitle().get("@gamma")?.result, "Docs wrap-up."); + assert.equal(subagentsByTitle().get("@delta")?.status, "completed"); + assert.equal(subagentsByTitle().get("@delta")?.result, "CI wrap-up."); yield* Fiber.interrupt(reader); }).pipe(Effect.provide(layerSession), Effect.scoped), diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts index 0c718e27d2b44..b705ecc94eaf6 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts @@ -367,7 +367,9 @@ export function makeAntigravityAcpAdapterFlavor( rootSessionId: sessionId, toolCallIds: unmanagedTaskIds, }); - return [...new Set([...runningSwarmTaskIds, ...diskAtWork])]; + // Swarm notifications can land during the disk read; use the latest roster. + const running = swarmTracker.partitionTaskIds(sessionId, nativeTaskIds).runningSwarmTaskIds; + return [...new Set([...running, ...diskAtWork])]; }, ), ...(profileDirectory === undefined diff --git a/apps/server/src/provider/acp/AntigravitySwarm.test.ts b/apps/server/src/provider/acp/AntigravitySwarm.test.ts index 0b502d9bb9ea4..9b757a5d5c068 100644 --- a/apps/server/src/provider/acp/AntigravitySwarm.test.ts +++ b/apps/server/src/provider/acp/AntigravitySwarm.test.ts @@ -247,6 +247,35 @@ describe("AntigravitySwarm", () => { .subagents.map((entry) => entry.subagent.childSessionId), ).toEqual(["worker-m"]); + // A new @helper incarnation does not inherit the old one's report. + const recreated = tracker.applyNotification( + decode({ + sessionId: "root-1", + head: 5, + activeWorkers: 1, + workingWorkers: 1, + waitingWorkers: 0, + members: [ + { name: "helper", role: "worker", conversationId: "worker-h2", state: "working" }, + ], + }), + ); + expect(recreated.subagents[0]?.subagent).toMatchObject({ status: "running", result: null }); + const recreatedKilled = tracker.applyNotification( + decode({ + sessionId: "root-1", + head: 5, + activeWorkers: 0, + workingWorkers: 0, + waitingWorkers: 0, + members: [{ name: "helper", role: "worker", conversationId: "worker-h2", state: "killed" }], + }), + ); + expect(recreatedKilled.subagents[0]?.subagent).toMatchObject({ + status: "cancelled", + result: null, + }); + tracker.clearSession("root-1"); expect(tracker.hasLiveSwarm("root-1")).toBe(false); expect(tracker.usesNativeProtocol("root-1")).toBe(false); diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index 42a902d63b728..5b1a96e05df3d 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -1934,6 +1934,7 @@ interface ActiveAcpSubagent { readonly interruptedToolIds: Set; readonly toolSessionIds: Map; thoughtSegmentIndex: number; + thoughtFlushPending: boolean; thoughtText: string; thoughtStartedAt: DateTime.Utc | null; } @@ -3566,6 +3567,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( streaming: !completed, }, }); + subagent.thoughtFlushPending = false; if (completed) { subagent.thoughtSegmentIndex += 1; subagent.thoughtText = ""; @@ -3579,8 +3581,18 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( mode: "append" | "replace", ) { if (text.length === 0) return; + const continuing = mode === "append" && subagent.thoughtText.length > 0; subagent.thoughtText = mode === "replace" ? text : `${subagent.thoughtText}${text}`; - yield* writeSubagentThought(subagent, false); + if (!continuing) return yield* writeSubagentThought(subagent, false); + // Coalesce follow-up chunks like the assistant stream; each write carries the whole text. + if (subagent.thoughtFlushPending) return; + subagent.thoughtFlushPending = true; + const segment = subagent.thoughtSegmentIndex; + yield* Effect.suspend(() => + subagent.thoughtFlushPending && subagent.thoughtSegmentIndex === segment + ? writeSubagentThought(subagent, false) + : Effect.void, + ).pipe(Effect.delay(ACP_SUBAGENT_TEXT_FLUSH_INTERVAL), Effect.forkIn(sessionScope)); }); const projectSubagentNotification = Effect.fnUntraced(function* ( @@ -3913,6 +3925,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( interruptedToolIds: new Set(), toolSessionIds: new Map(), thoughtSegmentIndex: 0, + thoughtFlushPending: false, thoughtText: "", thoughtStartedAt: null, }; @@ -7179,6 +7192,18 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( } } } + if ( + update.status === "completed" || + update.status === "failed" || + update.status === "cancelled" + ) { + const ended = + context.subagents.get(update.nativeTaskId) ?? + (update.childSessionId === null + ? undefined + : context.subagentsBySessionId.get(update.childSessionId)); + if (ended !== undefined) yield* terminalizeSubagentTools(ended); + } yield* emitSubagent(context, update, { allowReopenFromIdle }); if (hasDeferredBackgroundWork(context)) { context.backgroundFinalizeGeneration += 1; @@ -7228,7 +7253,10 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( update.childSessionId, ); if (dormant !== undefined) { - pendingBetweenTurnChildNotifications.delete(update.childSessionId); + // A parked worker keeps its buffered frames for the turn that wakes it. + if (update.status !== "idle") { + pendingBetweenTurnChildNotifications.delete(update.childSessionId); + } const nextResult = update.result ?? dormant.task.result; if (dormant.task.status !== update.status || dormant.task.result !== nextResult) { yield* projectCarryoverSubagentStatus(dormant, update.status, nextResult); @@ -7254,19 +7282,24 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( carryover.projectsLateTerminals, }, ); - if (!handledByCarryover && queued !== undefined) { - // A worker first seen between turns exists only in the queue; keep its final state + if ( + !handledByCarryover && + (queued !== undefined || (postSettleContinuationEnabled && wakeContinuation)) + ) { + // A worker first seen between turns has no other lineage; keep its final state // and buffered frames so the next turn still projects it. yield* Ref.update(pendingExtensionSubagents, (current) => [ ...current, - { - ...queued, - subagent: { - ...queued.subagent, - status: update.status, - result: update.result ?? queued.subagent.result, - }, - }, + queued === undefined + ? { sessionId: notice.sessionId, subagent: update, allowReopenFromIdle } + : { + ...queued, + subagent: { + ...queued.subagent, + status: update.status, + result: update.result ?? queued.subagent.result, + }, + }, ]); return; } @@ -7806,11 +7839,13 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const context = followsAgentWorkState ? yield* Ref.get(activeTurn) : yield* activeContext; - // Kiro sends the tool's kind on its `tool_call` and leaves it - // off the permission request for that call; take it from the - // tool already seen under the same id so policy can tell a - // read from a write. - const knownKind = context?.tools.get(params.toolCall.toolCallId)?.kind; + // Kiro leaves the kind off the permission request; take it from the tool + // seen under the same id so policy can tell a read from a write. Worker + // tool ids live in their own session, so a root tool's kind never applies. + const knownKind = + childTarget === undefined + ? context?.tools.get(params.toolCall.toolCallId)?.kind + : undefined; const disposition = dispositionFor( context?.input.runtimePolicy ?? latestRuntimePolicy, params.toolCall.kind == null && knownKind !== undefined @@ -10052,7 +10087,8 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const queuedChildNotifications = new Map(pendingBetweenTurnChildNotifications); pendingBetweenTurnChildNotifications.clear(); for (const [childId, frames] of queuedChildNotifications) { - context.pendingSubagentNotifications.set(childId, frames); + const live = context.pendingSubagentNotifications.get(childId) ?? []; + context.pendingSubagentNotifications.set(childId, [...frames, ...live]); } for (const queued of queuedExtensionSubagents) { yield* applyExtensionSubagentToTurn( diff --git a/packages/provider-acp/src/server/antigravitySwarm.ts b/packages/provider-acp/src/server/antigravitySwarm.ts index bc280ecd60d4f..1606e21af9e68 100644 --- a/packages/provider-acp/src/server/antigravitySwarm.ts +++ b/packages/provider-acp/src/server/antigravitySwarm.ts @@ -280,6 +280,7 @@ export function makeAntigravitySwarmTracker(): AntigravitySwarmTracker { applyNotification(notification) { nativeProtocolSessions.add(notification.sessionId); const session = sessionFor(notification.sessionId); + const postedNow = new Set(); for (const post of notification.posts ?? []) { if (post.control !== undefined) continue; @@ -299,6 +300,7 @@ export function makeAntigravitySwarmTracker(): AntigravitySwarmTracker { const report = cleanBoardReport(post.text); if (report === null) continue; session.latestPostsByAgent.set(author, report); + postedNow.add(author); const tracked = session.membersByName.get(author); if (tracked !== undefined) { tracked.latestReport = report; @@ -320,6 +322,11 @@ export function makeAntigravitySwarmTracker(): AntigravitySwarmTracker { let tracked = session.membersByConversationId.get(conversationId); const nativeTaskId = `${ANTIGRAVITY_SWARM_TASK_PREFIX}${conversationId}`; if (tracked === undefined) { + // A recreated worker reuses its name; reports from the old incarnation are not its own. + const previous = session.membersByName.get(nameKey); + if (previous !== undefined && !postedNow.has(nameKey)) { + session.latestPostsByAgent.delete(nameKey); + } tracked = { nativeTaskId, name: member.name, diff --git a/packages/provider-acp/src/server/runtimeModel.ts b/packages/provider-acp/src/server/runtimeModel.ts index 3b9d04e7d30ab..80598ac23e8a6 100644 --- a/packages/provider-acp/src/server/runtimeModel.ts +++ b/packages/provider-acp/src/server/runtimeModel.ts @@ -1308,8 +1308,14 @@ export function extractAcpChildRequestTarget(input: { (typeof swarm?.workerSessionId === "string" && swarm.workerSessionId.trim()) || ""; if (childSessionId.length === 0) continue; + const workerToolCallId = [input.meta, input.toolCallMeta] + .map((record) => (isRecord(record) && isRecord(record.antigravity) ? record.antigravity : {})) + .map((record) => + typeof record.workerToolCallId === "string" ? record.workerToolCallId.trim() : "", + ) + .find((id) => id.length > 0); const toolCallId = - (typeof ag.workerToolCallId === "string" && ag.workerToolCallId.trim()) || + workerToolCallId || (typeof input.fallbackToolCallId === "string" && input.fallbackToolCallId.trim()) || null; const workerName = From 47d157dcaee2213e57ec2bb8367cc7f1099305a1 Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Sat, 21 Nov 2026 16:26:45 -0800 Subject: [PATCH 09/11] fix(antigravity): drain parked worker frames on wake and throttle child thoughts in place - Project a re-woken parked worker's buffered frames: after the wake for a running worker, before closing tools for an ended one. - Throttle child reasoning updates in the same fiber instead of a delayed write, so no write can land after the segment completes. - Do not queue finished workers that a session load replays. Co-Authored-By: Claude Opus 5.5 --- .../Adapters/AntigravityAdapterV2.test.ts | 17 +++++++ packages/provider-acp/src/server/adapter.ts | 47 +++++++++++++------ 2 files changed, 49 insertions(+), 15 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts index 0359e1724e600..ec2243fbef65c 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts @@ -2884,6 +2884,14 @@ describe("AntigravityAdapterV2 native swarm protocol", () => { // Between turns @beta wakes and is killed; turn 2 must not replay the queued running update. // New worker @gamma spawns and finishes in the same gap; turn 2 must still show its report. // @delta is first seen already finished, with no running update before it. + // Parked @alpha streams a note; it must show once turn 2 wakes @alpha. + yield* onSessionUpdate!({ + sessionId: alphaSessionId, + update: { + sessionUpdate: "agent_message_chunk", + content: { type: "text", text: "Parked note." }, + }, + }); yield* onSwarmNotification!({ sessionId: rootSessionId, head: 4, @@ -2987,6 +2995,15 @@ describe("AntigravityAdapterV2 native swarm protocol", () => { assert.equal(subagentsByTitle().get("@gamma")?.result, "Docs wrap-up."); assert.equal(subagentsByTitle().get("@delta")?.status, "completed"); assert.equal(subagentsByTitle().get("@delta")?.result, "CI wrap-up."); + assert.isTrue( + collected.some( + (event) => + event.type === "turn_item.updated" && + event.turnItem.threadId === alphaAfterTurn1?.childThreadId && + event.turnItem.type === "assistant_message" && + event.turnItem.text.includes("Parked note."), + ), + ); yield* Fiber.interrupt(reader); }).pipe(Effect.provide(layerSession), Effect.scoped), diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index 5b1a96e05df3d..3f0cd19f38e82 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -1934,7 +1934,7 @@ interface ActiveAcpSubagent { readonly interruptedToolIds: Set; readonly toolSessionIds: Map; thoughtSegmentIndex: number; - thoughtFlushPending: boolean; + thoughtEmittedAt: number; thoughtText: string; thoughtStartedAt: DateTime.Utc | null; } @@ -3567,7 +3567,6 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( streaming: !completed, }, }); - subagent.thoughtFlushPending = false; if (completed) { subagent.thoughtSegmentIndex += 1; subagent.thoughtText = ""; @@ -3583,16 +3582,16 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( if (text.length === 0) return; const continuing = mode === "append" && subagent.thoughtText.length > 0; subagent.thoughtText = mode === "replace" ? text : `${subagent.thoughtText}${text}`; - if (!continuing) return yield* writeSubagentThought(subagent, false); - // Coalesce follow-up chunks like the assistant stream; each write carries the whole text. - if (subagent.thoughtFlushPending) return; - subagent.thoughtFlushPending = true; - const segment = subagent.thoughtSegmentIndex; - yield* Effect.suspend(() => - subagent.thoughtFlushPending && subagent.thoughtSegmentIndex === segment - ? writeSubagentThought(subagent, false) - : Effect.void, - ).pipe(Effect.delay(ACP_SUBAGENT_TEXT_FLUSH_INTERVAL), Effect.forkIn(sessionScope)); + const now = yield* Clock.currentTimeMillis; + // Each write carries the whole text, so throttle follow-up chunks; the write that + // completes the segment carries the rest. + if ( + continuing && + now - subagent.thoughtEmittedAt < Duration.toMillis(ACP_SUBAGENT_TEXT_FLUSH_INTERVAL) + ) + return; + subagent.thoughtEmittedAt = now; + yield* writeSubagentThought(subagent, false); }); const projectSubagentNotification = Effect.fnUntraced(function* ( @@ -3925,7 +3924,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( interruptedToolIds: new Set(), toolSessionIds: new Map(), thoughtSegmentIndex: 0, - thoughtFlushPending: false, + thoughtEmittedAt: 0, thoughtText: "", thoughtStartedAt: null, }; @@ -7192,19 +7191,34 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( } } } + // A re-woken parked worker is attached above; emitSubagent drains only new ones. + const drainAttachedFrames = Effect.fnUntraced(function* () { + if (update.childSessionId === null) return; + const attached = context.subagentsBySessionId.get(update.childSessionId); + const frames = context.pendingSubagentNotifications.get(update.childSessionId); + if (attached === undefined || frames === undefined) return; + context.pendingSubagentNotifications.delete(update.childSessionId); + for (const frame of frames) { + yield* projectSubagentNotification(attached, frame, context); + } + }); if ( update.status === "completed" || update.status === "failed" || update.status === "cancelled" ) { + yield* drainAttachedFrames(); const ended = context.subagents.get(update.nativeTaskId) ?? (update.childSessionId === null ? undefined : context.subagentsBySessionId.get(update.childSessionId)); if (ended !== undefined) yield* terminalizeSubagentTools(ended); + yield* emitSubagent(context, update, { allowReopenFromIdle }); + } else { + yield* emitSubagent(context, update, { allowReopenFromIdle }); + yield* drainAttachedFrames(); } - yield* emitSubagent(context, update, { allowReopenFromIdle }); if (hasDeferredBackgroundWork(context)) { context.backgroundFinalizeGeneration += 1; } else { @@ -7284,7 +7298,10 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( ); if ( !handledByCarryover && - (queued !== undefined || (postSettleContinuationEnabled && wakeContinuation)) + (queued !== undefined || + (postSettleContinuationEnabled && + wakeContinuation && + !(yield* Ref.get(loadingSessionId)))) ) { // A worker first seen between turns has no other lineage; keep its final state // and buffered frames so the next turn still projects it. From bb81e05756d97ca075b51d9bfbc0567dee0838a4 Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Sat, 21 Nov 2026 16:51:31 -0800 Subject: [PATCH 10/11] fix(antigravity): keep worker identity and replay order consistent - Resolve a worker permission's writable roots from the same single worker that approval routing targets. - At turn start, skip a queued worker update when a live update for that worker already landed in the new turn. - Close tools replayed for a worker first seen as finished. Co-Authored-By: Claude Opus 5.5 --- .../src/provider/acp/AntigravitySwarm.test.ts | 33 +++++++++++++++++ packages/provider-acp/src/server/adapter.ts | 21 ++++++++++- .../src/server/antigravitySwarm.ts | 35 ++++++------------- 3 files changed, 64 insertions(+), 25 deletions(-) diff --git a/apps/server/src/provider/acp/AntigravitySwarm.test.ts b/apps/server/src/provider/acp/AntigravitySwarm.test.ts index 9b757a5d5c068..2d0b56fcda723 100644 --- a/apps/server/src/provider/acp/AntigravitySwarm.test.ts +++ b/apps/server/src/provider/acp/AntigravitySwarm.test.ts @@ -377,6 +377,39 @@ describe("AntigravitySwarm", () => { extraWritableRoots: tracker.childPermissionWorkspaces(childWorktreeRequest), }), ).toBe("allow"); + // Roots come only from the one worker the request targets, even if tool metadata names another. + tracker.applyNotification({ + sessionId: "root-1", + head: 2, + activeWorkers: 2, + workingWorkers: 2, + waitingWorkers: 0, + members: [ + { + name: "alpha", + role: "worker", + conversationId: "worker-a", + workspaces: ["/tmp/isolated-worktree"], + state: "working", + }, + { + name: "beta", + role: "worker", + conversationId: "worker-b", + workspaces: ["/tmp/beta-worktree"], + state: "working", + }, + ], + }); + expect( + tracker.childPermissionWorkspaces({ + ...childWorktreeRequest, + toolCall: { + ...childWorktreeRequest.toolCall, + _meta: { antigravity: { childSessionId: "worker-b" } }, + }, + }), + ).not.toContain("/tmp/beta-worktree"); expect( acpPermissionDisposition( policy, diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index 3f0cd19f38e82..57cc1a7c06ab2 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -2653,6 +2653,8 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( >([]); const externalBackgroundWorkSessionIds = new Set(); const knownExtensionChildSessions = new Set(); + // Workers a live extension update touched in a turn, so turn start skips older queued ones. + const liveExtensionWorkers = new WeakMap>(); const pendingBetweenTurnChildNotifications = new Map< string, Array @@ -7208,13 +7210,17 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( update.status === "cancelled" ) { yield* drainAttachedFrames(); - const ended = + const findEnded = () => context.subagents.get(update.nativeTaskId) ?? (update.childSessionId === null ? undefined : context.subagentsBySessionId.get(update.childSessionId)); + const ended = findEnded(); if (ended !== undefined) yield* terminalizeSubagentTools(ended); yield* emitSubagent(context, update, { allowReopenFromIdle }); + // A worker first seen as finished is created above, which replays its buffered tools. + const created = ended === undefined ? findEnded() : undefined; + if (created !== undefined) yield* terminalizeSubagentTools(created); } else { yield* emitSubagent(context, update, { allowReopenFromIdle }); yield* drainAttachedFrames(); @@ -7245,6 +7251,10 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( !context.interrupted && context.nativeThreadId === notice.sessionId ) { + const touched = liveExtensionWorkers.get(context) ?? new Set(); + touched.add(update.nativeTaskId); + if (update.childSessionId !== null) touched.add(update.childSessionId); + liveExtensionWorkers.set(context, touched); yield* applyExtensionSubagentToTurn(context, update, allowReopenFromIdle); return; } @@ -10108,6 +10118,15 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( context.pendingSubagentNotifications.set(childId, [...frames, ...live]); } for (const queued of queuedExtensionSubagents) { + // A live update for this worker in this turn is newer than the queued one. + const touched = liveExtensionWorkers.get(context); + if ( + touched !== undefined && + (touched.has(queued.subagent.nativeTaskId) || + (queued.subagent.childSessionId !== null && + touched.has(queued.subagent.childSessionId))) + ) + continue; yield* applyExtensionSubagentToTurn( context, queued.subagent, diff --git a/packages/provider-acp/src/server/antigravitySwarm.ts b/packages/provider-acp/src/server/antigravitySwarm.ts index 1606e21af9e68..e8f51337fa3c8 100644 --- a/packages/provider-acp/src/server/antigravitySwarm.ts +++ b/packages/provider-acp/src/server/antigravitySwarm.ts @@ -3,7 +3,7 @@ import * as Effect from "effect/Effect"; import * as Schema from "effect/Schema"; import type { AcpAdapterV2ExtensionContext, AcpAdapterV2SubagentUpdate } from "./adapter.ts"; -import { unknownRecord } from "./clientPolicy.ts"; +import { extractAcpChildRequestTarget } from "./runtimeModel.ts"; export const ANTIGRAVITY_SWARM_CAPABILITIES_META = { antigravity: { @@ -427,29 +427,16 @@ export function makeAntigravitySwarmTracker(): AntigravitySwarmTracker { }, childPermissionWorkspaces(request) { - const session = sessions.get(request.sessionId); - if (session === undefined) return []; - const roots = new Set(); - for (const container of [ - unknownRecord(request._meta), - unknownRecord(request.toolCall._meta), - ]) { - const antigravity = unknownRecord(container?.antigravity); - if (antigravity === undefined) continue; - const swarm = unknownRecord(antigravity.swarm); - const childSessionId = - (typeof antigravity.childSessionId === "string" - ? nonEmpty(antigravity.childSessionId) - : undefined) ?? - (typeof swarm?.workerSessionId === "string" - ? nonEmpty(swarm.workerSessionId) - : undefined); - if (childSessionId === undefined) continue; - const tracked = session.membersByConversationId.get(childSessionId); - if (tracked === undefined) continue; - for (const workspace of tracked.workspaces) roots.add(workspace); - } - return [...roots]; + // Same worker resolution as approval routing, so policy and cancellation agree. + const target = extractAcpChildRequestTarget({ + meta: request._meta, + toolCallMeta: request.toolCall._meta, + }); + if (target === undefined) return []; + const tracked = sessions + .get(request.sessionId) + ?.membersByConversationId.get(target.childSessionId); + return tracked === undefined ? [] : [...tracked.workspaces]; }, partitionTaskIds(sessionId, nativeTaskIds) { From 050b991605d8d031af4ab555ea500f5e0dacad37 Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Sat, 21 Nov 2026 17:18:47 -0800 Subject: [PATCH 11/11] fix(antigravity): keep each woken worker reply and hand off buffered frames first - A reopened worker's reply without a message id starts a new message instead of replacing the previous round's reply. - Move buffered child frames into a new turn before it is published, so a live update cannot finish a worker before its older frames replay. Co-Authored-By: Claude Opus 5.5 --- .../Adapters/AntigravityAdapterV2.test.ts | 19 +++++++++++++++++++ packages/provider-acp/src/server/adapter.ts | 18 +++++++++++------- 2 files changed, 30 insertions(+), 7 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts index ec2243fbef65c..0789e9184673b 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts @@ -2783,6 +2783,13 @@ describe("AntigravityAdapterV2 native swarm protocol", () => { rawOutput: { combinedOutput: "ok" }, }, }); + yield* onSessionUpdate!({ + sessionId: alphaSessionId, + update: { + sessionUpdate: "agent_message_chunk", + content: { type: "text", text: "Round one note." }, + }, + }); // Turn stays open past deferred-finalize debounce and protects the session from idle eviction. yield* TestClock.adjust("5 seconds"); @@ -3004,6 +3011,18 @@ describe("AntigravityAdapterV2 native swarm protocol", () => { event.turnItem.text.includes("Parked note."), ), ); + // The woken round's reply is a new message; it does not replace round one's. + const alphaReplies = new Map(); + for (const event of collected) { + if ( + event.type === "turn_item.updated" && + event.turnItem.threadId === alphaAfterTurn1?.childThreadId && + event.turnItem.type === "assistant_message" + ) { + alphaReplies.set(event.turnItem.id, event.turnItem.text); + } + } + assert.includeMembers([...alphaReplies.values()], ["Round one note.", "Parked note."]); yield* Fiber.interrupt(reader); }).pipe(Effect.provide(layerSession), Effect.scoped), diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index 57cc1a7c06ab2..0f6db613d142d 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -1935,6 +1935,8 @@ interface ActiveAcpSubagent { readonly toolSessionIds: Map; thoughtSegmentIndex: number; thoughtEmittedAt: number; + /** Bumped on each reopen so a reply without a message id starts a new message. */ + replyRound: number; thoughtText: string; thoughtStartedAt: DateTime.Utc | null; } @@ -3464,7 +3466,8 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( messageId?: string | null, ) { if (text.length === 0 && mode === "append") return; - const nativeItemId = `${subagent.task.nativeTaskRef?.nativeId ?? subagent.task.id}:message:${messageId ?? "result"}`; + const fallbackId = subagent.replyRound === 0 ? "result" : `result-${subagent.replyRound}`; + const nativeItemId = `${subagent.task.nativeTaskRef?.nativeId ?? subagent.task.id}:message:${messageId ?? fallbackId}`; const previous = subagent.assistantMessages.get(nativeItemId); const messageText = mode === "replace" ? text : `${previous ?? ""}${text}`; subagent.assistantMessages.set(nativeItemId, messageText); @@ -3866,6 +3869,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( existing.assistantText = ""; existing.assistantMessages.clear(); existing.pendingAssistantMessages.clear(); + existing.replyRound += 1; } const task: OrchestrationV2Subagent = { ...(existing?.task ?? { @@ -3926,6 +3930,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( interruptedToolIds: new Set(), toolSessionIds: new Map(), thoughtSegmentIndex: 0, + replyRound: 0, thoughtEmittedAt: 0, thoughtText: "", thoughtStartedAt: null, @@ -10074,6 +10079,11 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( } } } + // Hand buffered child frames over before live frames can reach the published turn. + for (const [childId, frames] of pendingBetweenTurnChildNotifications) { + context.pendingSubagentNotifications.set(childId, frames); + } + pendingBetweenTurnChildNotifications.clear(); yield* Ref.set(activeTurn, context); yield* Ref.set(stoppedRunQuarantine, false); const queuedExtensionSubagents = yield* Ref.modify( @@ -10111,12 +10121,6 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( driver, providerThread: activeProviderThread, }); - const queuedChildNotifications = new Map(pendingBetweenTurnChildNotifications); - pendingBetweenTurnChildNotifications.clear(); - for (const [childId, frames] of queuedChildNotifications) { - const live = context.pendingSubagentNotifications.get(childId) ?? []; - context.pendingSubagentNotifications.set(childId, [...frames, ...live]); - } for (const queued of queuedExtensionSubagents) { // A live update for this worker in this turn is newer than the queued one. const touched = liveExtensionWorkers.get(context);