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/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts index fca472c6c433e..0789e9184673b 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts @@ -2505,3 +2505,1022 @@ 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 gammaSessionId = "11111111-1111-4000-8000-00000000000c"; + const deltaSessionId = "11111111-1111-4000-8000-00000000000d"; + + 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: 5, + activeWorkers: 1, + workingWorkers: 1, + waitingWorkers: 0, + members: [ + { + name: "alpha", + role: "worker", + conversationId: alphaSessionId, + brief: "Inspect frontend", + state: "working", + }, + ], + }); + 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" }, + }, + }); + 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"); + 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; + }; + // 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"); + 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.", + ), + ); + + // 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, + activeWorkers: 1, + workingWorkers: 1, + waitingWorkers: 1, + 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!({ + 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" }, + { + name: "gamma", + role: "worker", + conversationId: gammaSessionId, + 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." }, + ], + }); + + // 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: 6, + activeWorkers: 0, + workingWorkers: 0, + waitingWorkers: 0, + coordinatorPendingWake: false, + members: [ + { name: "alpha", role: "worker", conversationId: alphaSessionId, state: "killed" }, + ], + posts: [{ seq: 6, 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."); + 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."); + 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."), + ), + ); + // 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), + ); + + 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 3f629c813b615..b705ecc94eaf6 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts @@ -40,14 +40,23 @@ 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, + agentAdvertisesAntigravitySwarm, + makeAntigravitySwarmTracker, + registerAntigravitySwarmExtension, +} from "../../provider/acp/AntigravitySwarm.ts"; import { isAntigravitySignInRequiredError } from "../../provider/antigravityAuthSupport.ts"; import { AcpProviderCapabilitiesV2, @@ -106,15 +115,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 +139,18 @@ const extractAntigravitySubagentUpdate: NonNullable cwd === null ? [options.host.paths.attachmentsDir] : [cwd, options.host.paths.attachmentsDir]; const makeRuntime = Effect.fn("AntigravityAdapterV2.makeRuntime")( @@ -166,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) => @@ -201,10 +241,21 @@ export function makeAntigravityAcpAdapterFlavor( runtime .start() .pipe( - Effect.tap( - (started) => options.onSessionStarted?.(started, input.cwd) ?? Effect.void, + 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), @@ -274,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); @@ -285,7 +339,12 @@ export function makeAntigravityAcpAdapterFlavor( }; }, normalizeToolCall: normalizeAntigravityToolCall, - extractSubagentUpdate: extractAntigravitySubagentUpdate, + clientCapabilitiesMeta: ANTIGRAVITY_SWARM_CAPABILITIES_META, + registerExtensions: (context) => registerAntigravitySwarmExtension(swarmTracker, context), + extractSubagentUpdate: (toolCall, sessionId) => + extractAntigravitySubagentUpdate(toolCall, { + nativeSwarmProtocol: sessionId !== undefined && swarmTracker.usesNativeProtocol(sessionId), + }), supportsImagePrompts: true, compactViaAdvertisedCommand: true, requiresSignIn: isAntigravitySignInRequiredError, @@ -294,17 +353,30 @@ 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, + }); + // 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 ? {} : { 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/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/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/AntigravityChildWork.test.ts b/apps/server/src/provider/acp/AntigravityChildWork.test.ts index e0336da84ac64..d7a936244dc34 100644 --- a/apps/server/src/provider/acp/AntigravityChildWork.test.ts +++ b/apps/server/src/provider/acp/AntigravityChildWork.test.ts @@ -541,6 +541,115 @@ 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"); + + 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"); + }), + ); + 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..78803da9ebfc6 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; @@ -47,16 +48,64 @@ interface AntigravityChildLaunch { } 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); + +// 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; + 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.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()})` + : ""; + + 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 +113,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 +630,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 +727,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 +761,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 +955,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..2d0b56fcda723 --- /dev/null +++ b/apps/server/src/provider/acp/AntigravitySwarm.test.ts @@ -0,0 +1,427 @@ +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"; + +import { + AntigravitySwarmNotification, + agentAdvertisesAntigravitySwarm, + makeAntigravitySwarmTracker, +} from "./AntigravitySwarm.ts"; + +describe("AntigravitySwarm", () => { + it("detects advertised swarm capability on initialize responses", () => { + 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 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", + 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", + workspaces: ["/tmp/fork-a", "/tmp/fork-b"], + addedBy: "coordinator", + }, + { + name: "helper", + role: "worker", + conversationId: "worker-h", + 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", + }, + ], + }), + ); + + expect(launched.activeBackgroundWork).toBe(true); + expect(launched.subagents).toEqual([ + { + 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, + }, + { + 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, + // Housekeeping pulses never hold the turn open, so they report idle. + status: "idle", + result: null, + suppressNormalTool: true, + }, + wakeContinuation: false, + }, + ]); + expect( + 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 park while out-of-turn coordinator is actively synthesizing (`coordinatorWorking`). + const handoff = tracker.applyNotification( + decode({ + sessionId: "root-1", + head: 4, + activeWorkers: 0, + workingWorkers: 0, + waitingWorkers: 2, + coordinatorWorking: true, + coordinatorPendingWake: false, + members: [ + { 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]?.subagent).toMatchObject({ + status: "idle", + result: "Auth routes look solid.", + }); + expect(handoff.subagents[1]?.subagent).toMatchObject({ + status: "idle", + result: "@alpha Rate limiter uses token bucket.", + }); + + // Periodic @monitor tick alone does NOT mark the session busy; hadActivity marks killed workers completed. + 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({ + 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); + 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"]); + + // 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); + }); + + 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"); + + // 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: { + 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", "/"], + }, + }, + }; + // Untracked metadata roots never widen workspaceWrite. + expect(acpPermissionDisposition(policy, baseRequest)).toBe("deny"); + expect(acpPermissionDisposition(policy, childWorktreeRequest)).toBe("deny"); + expect( + acpPermissionDisposition(policy, childWorktreeRequest, { + extraWritableRoots: tracker.childPermissionWorkspaces(childWorktreeRequest), + }), + ).toBe("deny"); + + // 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, + activeWorkers: 1, + workingWorkers: 1, + waitingWorkers: 0, + members: [ + { + name: "alpha", + role: "worker", + conversationId: "worker-a", + workspaces: ["/tmp/isolated-worktree", "/", "/tmp"], + state: "working", + }, + ], + }); + expect( + acpPermissionDisposition(policy, childWorktreeRequest, { + 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, + { + ...childWorktreeRequest, + toolCall: { + ...childWorktreeRequest.toolCall, + locations: [{ path: "/tmp/other-dir/escape.ts" }], + }, + }, + { extraWritableRoots: tracker.childPermissionWorkspaces(childWorktreeRequest) }, + ), + ).toBe("deny"); + }); +}); diff --git a/apps/server/src/provider/acp/AntigravitySwarm.ts b/apps/server/src/provider/acp/AntigravitySwarm.ts new file mode 100644 index 0000000000000..7d85517e511d6 --- /dev/null +++ b/apps/server/src/provider/acp/AntigravitySwarm.ts @@ -0,0 +1,8 @@ +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 e214a51586f4c..0f6db613d142d 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 { @@ -258,6 +262,26 @@ 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; + readonly wakeContinuation?: 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; @@ -607,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; @@ -1908,6 +1933,12 @@ interface ActiveAcpSubagent { // ACP has no interrupted tool status; keep forced interruption across late updates. readonly interruptedToolIds: Set; 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; } interface AcpNativeChildSession { @@ -1956,6 +1987,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"; @@ -2258,14 +2291,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(), ); @@ -2607,6 +2641,26 @@ 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 sessionId: string; + readonly subagent: AcpAdapterV2SubagentUpdate; + readonly allowReopenFromIdle: boolean; + }> + >([]); + 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 + >(); const handledBackgroundTaskIdsInActiveTurn = yield* Ref.make>( new Set(), ); @@ -2757,12 +2811,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()) { @@ -3408,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); @@ -3479,21 +3538,134 @@ 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; + const continuing = mode === "append" && subagent.thoughtText.length > 0; + subagent.thoughtText = mode === "replace" ? text : `${subagent.thoughtText}${text}`; + 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* ( 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; + if ( + event.toolCall.status !== undefined && + event.toolCall.status !== "pending" && + event.toolCall.status !== "requiresAction" + ) { + yield* cancelPendingChildRuntimeRequests( + notification.sessionId, + event.toolCall.toolCallId, + ); + } + 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 +3791,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 +3807,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 +3829,8 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( existing !== undefined && existing.task.status === update.status && updateIsTerminal && - existing.terminalStatusProjected + existing.terminalStatusProjected && + !upgradingIdleToFinal ) { return; } @@ -3677,6 +3862,15 @@ 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 = ""; + existing.assistantMessages.clear(); + existing.pendingAssistantMessages.clear(); + existing.replyRound += 1; + } const task: OrchestrationV2Subagent = { ...(existing?.task ?? { id: nodeId, @@ -3695,9 +3889,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 +3929,11 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( }, interruptedToolIds: new Set(), toolSessionIds: new Map(), + thoughtSegmentIndex: 0, + replyRound: 0, + thoughtEmittedAt: 0, + thoughtText: "", + thoughtStartedAt: null, }; subagent.task = task; context.subagents.set(nativeTaskId, subagent); @@ -3816,6 +4027,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 +4121,14 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( }); if (acpSubagentStatusIsTerminal(taskStatus)) { subagent.terminalStatusProjected = true; + } else { + subagent.terminalStatusProjected = false; + } + if ( + subagent.childSessionId !== null && + (taskStatus === "idle" || acpSubagentStatusIsTerminal(taskStatus)) + ) { + yield* cancelPendingChildRuntimeRequests(subagent.childSessionId); } }); @@ -4257,6 +4479,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 (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. @@ -5617,8 +5840,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 && @@ -5642,8 +5870,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); } }), @@ -5910,6 +6144,16 @@ 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" && + event.toolCall.status !== "requiresAction" + ) { + yield* cancelPendingChildRuntimeRequests( + notification.sessionId, + event.toolCall.toolCallId, + ); + } const toolCall = flavor.normalizeToolCall?.(event.toolCall) ?? event.toolCall; const subagentUpdate = extractSubagentUpdate(toolCall); if (subagentUpdate === undefined) continue; @@ -5977,61 +6221,63 @@ 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" || - 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; + 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); } - yield* projectSubagentTool( - subagent, - notification.sessionId, - toolCall, - undefined, - 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 +6285,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. @@ -6396,6 +6644,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), { @@ -6408,6 +6661,8 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( runtimeRequest, node, turnItem, + childSessionId: childTarget?.childSessionId ?? null, + childToolCallId: childTarget?.toolCallId ?? null, }); return updated; }); @@ -6533,6 +6788,8 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( runtimeRequest, node, turnItem, + childSessionId: request.childSessionId ?? null, + childToolCallId: request.childToolCallId ?? null, }); return updated; }); @@ -6622,22 +6879,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, @@ -6682,6 +6927,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"], @@ -6886,6 +7173,183 @@ 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; + }); + } + } + } + // 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 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(); + } + 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; + 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 && + !context.finalized && + !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; + } + 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)) { + const queued = yield* Ref.modify(pendingExtensionSubagents, (current) => [ + current.find(isSameQueuedWorker), + current.filter((entry) => !isSameQueuedWorker(entry)), + ]); + if (update.childSessionId !== null) { + yield* cancelPendingChildRuntimeRequests(update.childSessionId); + const dormant = (yield* Ref.get(dormantSubagentsByChildSessionId)).get( + update.childSessionId, + ); + if (dormant !== undefined) { + // 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); + } + 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); + const handledByCarryover = yield* updateCarryoverSubagentStatus( + update.childSessionId, + update.status, + update.result, + { + project: + carryover !== null && + carryover.sessionId === notice.sessionId && + carryover.projectsLateTerminals, + }, + ); + if ( + !handledByCarryover && + (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. + yield* Ref.update(pendingExtensionSubagents, (current) => [ + ...current, + queued === undefined + ? { sessionId: notice.sessionId, subagent: update, allowReopenFromIdle } + : { + ...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) => !isSameQueuedWorker(entry)), + { sessionId: notice.sessionId, subagent: update, allowReopenFromIdle }, + ]); + if (!(yield* Ref.get(loadingSessionId))) { + yield* offerContinuationRun(notice.sessionId); + } + } + }); + applyFinalizedActiveTurnSubagentTerminal = Effect.fnUntraced(function* ( context: ActiveAcpTurn, notification: EffectAcpSchema.SessionNotification, @@ -7303,8 +7767,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 && @@ -7314,7 +7783,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), @@ -7331,6 +7802,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, ); @@ -7349,6 +7822,42 @@ 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* () { + if (yield* Ref.get(stoppedRunQuarantine)) { + return { outcome: { outcome: "cancelled" } } as const; + } + 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) @@ -7362,11 +7871,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 @@ -7486,11 +7997,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" && @@ -7602,6 +8122,8 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( nativeItemId: nativeRequestId, nativeRequestId, questions: form.questions, + childSessionId: childElicitation?.childSessionId ?? null, + childToolCallId: childElicitation?.toolCallId ?? null, }; }), transportRequestId, @@ -7612,8 +8134,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, @@ -7633,6 +8159,43 @@ 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; + const expectedSessionId = + (yield* Ref.get(loadingSessionId)) ?? (yield* Ref.get(activeSessionId)); + if (expectedSessionId !== notice.sessionId) return; + yield* upsertSubagentFromExtension(notice); + }), + ).pipe(Effect.asVoid), + setExternalBackgroundWork: (notice) => + runRuntimeCallbackAtGeneration( + handlerGeneration, + Effect.gen(function* () { + if (yield* Ref.get(stoppedRunQuarantine)) return; + const expectedSessionId = + (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); + 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 +8542,12 @@ 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, []); + externalBackgroundWorkSessionIds.clear(); + knownExtensionChildSessions.clear(); + pendingBetweenTurnChildNotifications.clear(); + currentExtractSessionId = undefined; yield* Ref.set(suppressPostSettleMonitorPrompt, false); yield* Ref.set(lastTurnRoute, null); }), @@ -8540,6 +9109,11 @@ 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, []); + externalBackgroundWorkSessionIds.clear(); + knownExtensionChildSessions.clear(); + pendingBetweenTurnChildNotifications.clear(); yield* Ref.set(lastTurnRoute, null); }), ); @@ -8715,6 +9289,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 +9375,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const promptInactivityPaused = Effect.fn("AcpAdapterV2.promptInactivityPaused")(function* ( context: ActiveAcpTurn, ) { + 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()) { @@ -9488,8 +10079,20 @@ 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( + 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); @@ -9518,6 +10121,30 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( driver, providerThread: activeProviderThread, }); + 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, + 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, @@ -9881,6 +10508,8 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( agentRequests.size > 0) ) 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; diff --git a/packages/provider-acp/src/server/antigravitySwarm.ts b/packages/provider-acp/src/server/antigravitySwarm.ts new file mode 100644 index 0000000000000..e8f51337fa3c8 --- /dev/null +++ b/packages/provider-acp/src/server/antigravitySwarm.ts @@ -0,0 +1,478 @@ +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 { extractAcpChildRequestTarget } from "./runtimeModel.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); + const postedNow = new Set(); + + 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); + postedNow.add(author); + 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) { + // 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, + 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; + } + } + 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; + } + // 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) ?? + 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, + // Housekeeping pulses never hold the turn open. + status: housekeeping && nextStatus === "running" ? "idle" : 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) { + // 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) { + 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..86d5d234f70fd 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,27 +103,36 @@ function acpWorkspaceWriteAllowsMutation( runtimePolicy: AcpRuntimePolicy, sandboxPolicy: Record, locations: AcpPolicyOperation["locations"], + extraWritableRoots?: ReadonlyArray, ): boolean { const cwd = typeof runtimePolicy.cwd === "string" && runtimePolicy.cwd.trim().length > 0 ? (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 ?? []), - ]; - 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) { @@ -164,6 +174,7 @@ function acpOperationDisposition( runtimePolicy, sandboxPolicy ?? {}, operation.locations, + operation.extraWritableRoots, ) ? "allow" : "deny"; @@ -194,10 +205,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..80598ac23e8a6 100644 --- a/packages/provider-acp/src/server/runtimeModel.ts +++ b/packages/provider-acp/src/server/runtimeModel.ts @@ -1287,6 +1287,48 @@ 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 { + 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 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 = + workerToolCallId || + (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( params: EffectAcpSchema.RequestPermissionRequest, ): AcpPermissionRequest { @@ -1300,15 +1342,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 } : {}),