diff --git a/apps/mobile/src/features/threads/ThreadWorkflowGroup.tsx b/apps/mobile/src/features/threads/ThreadWorkflowGroup.tsx index 336a904fff5ba..472bc59bdb37a 100644 --- a/apps/mobile/src/features/threads/ThreadWorkflowGroup.tsx +++ b/apps/mobile/src/features/threads/ThreadWorkflowGroup.tsx @@ -24,6 +24,8 @@ import { ListSection } from "../../components/ui/ListSection"; import { RowPressable } from "../../components/ui/RowPressable"; import { cn } from "../../lib/cn"; import { useEnvironmentServerConfig, useThreadShell } from "../../state/entities"; +import { useEnvironmentQuery } from "../../state/query"; +import { threadFamilies } from "../../state/threads"; import { SUBAGENT_TONE_TEXT_CLASS, SubagentStatusDot } from "./SubagentStatusDot"; import { SubagentStopButton } from "./SubagentStopButton"; import { @@ -61,6 +63,15 @@ export function ThreadWorkflowGroup(props: { const open = rail.find((item) => item.key === selected); const label = group.workflow.workflowName ?? group.workflow.title; const statusLabel = resolveSubagentRowPresentation(props.subagent, false, m).statusLabel; + // The shell omits idle subagent threads. One read of the workflow's thread family carries + // every member's row, since members share the coordinator's root thread. + const coordinatorThreadId = props.subagent.childThreadId; + const family = useEnvironmentQuery( + open !== undefined && coordinatorThreadId !== null + ? threadFamilies.familyAtom(props.environmentId, ThreadId.make(coordinatorThreadId)) + : null, + ); + const familyThreadIds = new Set(family.data?.threads.map((row) => row.id)); return ( @@ -150,6 +161,7 @@ export function ThreadWorkflowGroup(props: { key={member.id} environmentId={props.environmentId} member={member} + inFamily={member.childThreadId !== null && familyThreadIds.has(member.childThreadId)} provider={provider} onOpen={props.onOpen} /> @@ -163,6 +175,7 @@ export function ThreadWorkflowGroup(props: { function WorkflowMemberRow(props: { readonly environmentId: EnvironmentId; readonly member: RuntimeSubagent; + readonly inFamily: boolean; readonly provider: ServerProvider | undefined; readonly onOpen: (threadId: ThreadId) => void; }) { @@ -173,7 +186,7 @@ function WorkflowMemberRow(props: { const shell = useThreadShell( threadId === null ? null : scopeThreadRef(props.environmentId, threadId), ); - const canOpen = threadId !== null && shell !== null; + const canOpen = threadId !== null && (shell !== null || props.inFamily); const presentation = resolveSubagentRowPresentation( { title: member.title, diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts index 9924d6c831833..e39620f2184af 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts @@ -1364,6 +1364,7 @@ const openSessionWithRunningCommand = Effect.fn("openSessionWithRunningCommand") const usage = { sessionUpdate: "usage_update", used: 9000, size: 1048576 } as const; const offers: Array = []; const scheduledFinalizes = yield* Queue.unbounded(); + const workflowReads = yield* Queue.unbounded(); const instanceId = ProviderInstanceId.make("antigravity-wake-test"); const threadId = ThreadId.make("thread-antigravity-wake"); const selfInvocation = yield* resolveSelfInvocation(); @@ -1463,6 +1464,7 @@ const openSessionWithRunningCommand = Effect.fn("openSessionWithRunningCommand") : { continuationRequests: adapterOptions.continuationRequests }), testHooks: { onDeferredFinalizeScheduled: (debounce) => Queue.offer(scheduledFinalizes, debounce), + afterNativeWorkflowRead: () => Queue.offer(workflowReads, undefined), }, }); const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ @@ -1497,7 +1499,11 @@ const openSessionWithRunningCommand = Effect.fn("openSessionWithRunningCommand") runtimePolicy, }); const now = yield* DateTime.now; - const startTurn = (ordinal: number, continuation: boolean) => + const startTurn = ( + ordinal: number, + continuation: boolean, + extra?: Pick, + ) => session.startTurn({ appThread: { createdBy: "user", @@ -1539,6 +1545,7 @@ const openSessionWithRunningCommand = Effect.fn("openSessionWithRunningCommand") }, modelSelection, runtimePolicy, + ...extra, }); return { @@ -1548,6 +1555,7 @@ const openSessionWithRunningCommand = Effect.fn("openSessionWithRunningCommand") usage, offers, scheduledFinalizes, + workflowReads, send, startTurn, until, @@ -1575,6 +1583,106 @@ const openSessionWithRunningCommand = Effect.fn("openSessionWithRunningCommand") }; }); +// Frames and files as agy 1.5.14 wrote them for `/swarm`: the coordinator's `swarm` calls +// arrive as `Run swarm`, and workers report only on the board below its session. +const openSwarmSession = Effect.fn("openSwarmSession")(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const profile = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-antigravity-swarm-", + }); + const brain = (conversationId: string, ...rest: ReadonlyArray) => + path.join(profile, "antigravity-acp", "brain", conversationId, ".system_generated", ...rest); + const writeLines = (file: string, values: ReadonlyArray) => + fileSystem + .makeDirectory(path.dirname(file), { recursive: true }) + .pipe( + Effect.andThen( + fileSystem.writeFileString( + file, + values.map((value) => JSON.stringify(value)).join("\n") + "\n", + ), + ), + ); + yield* fileSystem.makeDirectory(brain("mock-session-1", "swarm"), { recursive: true }); + yield* fileSystem.writeFileString( + brain("mock-session-1", "swarm", "members.json"), + JSON.stringify({ + title: "Compute 6*7", + members: { + coordinator: { conversation_id: "mock-session-1", role: "coordinator" }, + "mul-a": { conversation_id: "worker-1", role: "worker", model: "gemini-test-low" }, + }, + }), + ); + const brief = { + seq: 1, + agent: "coordinator", + text: "@mul-a Compute 6*7.", + time: "2026-11-23 17:23:18", + kind: "brief", + }; + yield* writeLines(brain("mock-session-1", "swarm", "board.jsonl"), [brief]); + const transcript = brain("worker-1", "logs", "transcript.jsonl"); + yield* writeLines(transcript, [ + { step_index: 0, type: "SYSTEM_MESSAGE", status: "DONE" }, + { step_index: 1, type: "PLANNER_RESPONSE", status: "DONE", tool_calls: [{ name: "x" }] }, + ]); + const swarmCall = (toolCallId: string, rawInput: Record) => + ({ + sessionUpdate: "tool_call", + toolCallId, + kind: "other", + title: "Run swarm", + status: "completed", + rawInput, + }) as const; + const opened = yield* openSessionWithRunningCommand({}, undefined, undefined, { + profileDirectory: profile, + initialToolCalls: [ + swarmCall("call_title", { action: "title", title: "Compute 6*7" }), + swarmCall("call_add", { action: "add", name: "mul-a", brief: "Compute 6*7." }), + ], + }); + const parked = [ + { step_index: 0, type: "SYSTEM_MESSAGE", status: "DONE" }, + { + step_index: 1, + type: "PLANNER_RESPONSE", + status: "DONE", + tool_calls: [{ name: "post_message" }, { name: "swarm_wait" }], + }, + { step_index: 2, type: "GENERIC", status: "DONE" }, + { step_index: 3, type: "GENERIC", status: "DONE" }, + ]; + const workflows = (events: ReadonlyArray) => + events.flatMap((event) => + event.type === "subagent.updated" && event.subagent.workflow !== undefined + ? [event.subagent] + : [], + ); + // The watch reads files off the test clock: step to its next poll and wait for that read. + const readAfterPoll = Effect.gen(function* () { + yield* Queue.clear(opened.workflowReads); + yield* TestClock.adjust("2 seconds"); + yield* Queue.take(opened.workflowReads); + }); + return { + ...opened, + readAfterPoll, + brain, + brief, + transcript, + writeLines, + swarmCall, + parked, + workflows, + board: brain("mock-session-1", "swarm", "board.jsonl"), + roster: brain("mock-session-1", "swarm", "members.json"), + fileSystem, + }; +}); + describe("AntigravityAdapterV2 work after the prompt ends", () => { // agy sets `IsDaemon` on a command it does not wait for. When it exits, the agent replies // with no prompt open. @@ -2429,6 +2537,248 @@ describe("AntigravityAdapterV2 work after the prompt ends", () => { }).pipe(Effect.provide(layerSession)), ); + it.effect("shows a swarm as one workflow that runs until its workers park", () => + Effect.gen(function* () { + const swarm = yield* openSwarmSession(); + const { startTurn, until, throughPromptSettled, scheduledFinalizes, send, workflows } = swarm; + yield* startTurn(1, false); + const settled = yield* throughPromptSettled; + // The first board read can land before or after the reply settles. + const prompt = + workflows(settled).length > 0 + ? settled + : [...settled, ...(yield* until((event) => workflows([event]).length > 0))]; + const running = workflows(prompt).at(-1); + assert.equal(running?.status, "running"); + assert.equal(running?.workflow?.name, "Compute 6*7"); + assert.deepEqual( + running?.workflow?.agents.map(({ label, state, prompt: brief }) => [label, state, brief]), + [["mul-a", "running", "Compute 6*7."]], + ); + assert.isFalse( + JSON.stringify(prompt).includes("Run swarm"), + "swarm calls fold into the workflow instead of showing as tools", + ); + assert.isTrue( + prompt.some( + (event) => + event.type === "message.updated" && + event.message.threadId === running?.childThreadId && + event.message.workflowScript === true, + ), + "the swarm's thread opens on its plan, like a workflow", + ); + + yield* swarm.writeLines(swarm.board, [ + swarm.brief, + { seq: 2, agent: "mul-a", text: "@coordinator [done] 42", time: "2026-11-23 17:23:21" }, + ]); + yield* swarm.writeLines(swarm.transcript, swarm.parked); + // One poll reads the parked worker; the idle swarm then schedules the turn's end. + yield* TestClock.adjust("2 seconds"); + const parkedRun = yield* until((event) => workflows([event]).at(-1)?.status === "completed"); + yield* Queue.take(scheduledFinalizes); + yield* TestClock.adjust("5 seconds"); + const run = [...parkedRun, ...(yield* until((event) => event.type === "turn.terminal"))]; + const terminal = run.at(-1); + assert.equal(terminal?.type === "turn.terminal" && terminal.status, "completed"); + const done = workflows(run).at(-1); + assert.equal(done?.status, "completed"); + assert.deepEqual( + done?.workflow?.agents.map(({ state, result }) => [state, result]), + [["completed", "@coordinator [done] 42"]], + ); + const memberThread = done?.workflow?.agents[0]?.childThreadId; + assert.isTrue( + run.some( + (event) => + event.type === "message.updated" && + event.message.threadId === memberThread && + event.message.text === "@coordinator [done] 42", + ), + "the worker's result reaches its own thread", + ); + + // A later turn that checks on the swarm takes its card and announces its worker threads, + // so that run routes their updates. + yield* startTurn(2, false); + yield* send(swarm.swarmCall("call_status", { action: "status" })); + const later = yield* until((event) => workflows([event]).length > 0); + assert.equal(workflows(later).at(-1)?.runId, "run-antigravity-wake-2"); + const announced = yield* until( + (event) => event.type === "app_thread.created" && event.appThread.id === memberThread, + ); + assert.isNotEmpty(announced); + }).pipe(Effect.provide(layerSession)), + ); + + it.effect("the Swarm toggle sends a plain message as /swarm with its app context", () => + Effect.gen(function* () { + const opened = yield* openSessionWithRunningCommand({}); + yield* opened.startTurn(1, false, { + modelSelection: { + instanceId: ProviderInstanceId.make("antigravity-wake-test"), + model: "gemini-test-low", + options: [{ id: "swarm", value: true }], + }, + appContext: [{ key: "mcp_app_item-1", text: "Created Jira issue PROJ-42" }], + }); + yield* opened.throughPromptSettled; + const sent = opened.prompts[0]!.prompt.flatMap((block) => + block.type === "text" ? [block.text] : [], + ); + assert.isTrue( + sent.some((text) => text.startsWith("/swarm chart the throughput")), + "the message runs as a swarm", + ); + assert.isTrue( + sent.some((text) => text.includes("Created Jira issue PROJ-42")), + "the swarm gets the context the plain message would", + ); + }).pipe(Effect.provide(layerSession)), + ); + + it.effect("rewrites the swarm's plan when briefs arrive after its title", () => + Effect.gen(function* () { + const swarm = yield* openSwarmSession(); + const { startTurn, until, workflows } = swarm; + yield* swarm.writeLines(swarm.board, []); + yield* startTurn(1, false); + const plan = (events: ReadonlyArray) => + events.flatMap((event) => + event.type === "message.updated" && event.message.workflowScript === true + ? [event.message.text] + : [], + ); + const first = yield* until((event) => plan([event]).length > 0); + assert.equal(plan(first).at(-1), "Compute 6*7"); + yield* swarm.writeLines(swarm.board, [swarm.brief]); + yield* TestClock.adjust("2 seconds"); + const rewritten = yield* until((event) => plan([event]).length > 0); + assert.equal(plan(rewritten).at(-1), "@mul-a Compute 6*7."); + // A brief that scrolls out of the board's tail stays on the plan and the worker. + yield* swarm.writeLines(swarm.board, []); + yield* swarm.writeLines(swarm.transcript, [ + ...swarm.parked.slice(0, 1), + { + step_index: 1, + type: "PLANNER_RESPONSE", + status: "DONE", + input_tokens: 5, + tool_calls: [{ name: "y" }], + }, + ]); + yield* TestClock.adjust("2 seconds"); + const kept = yield* until((event) => workflows([event]).at(-1)?.workflow?.totalTokens === 5); + assert.equal(workflows(kept).at(-1)?.prompt, "@mul-a Compute 6*7."); + assert.equal(workflows(kept).at(-1)?.workflow?.agents[0]?.prompt, "Compute 6*7."); + }).pipe(Effect.provide(layerSession)), + ); + + it.effect("a turn after Stop waits for a swarm still at work, through unreadable polls", () => + Effect.gen(function* () { + const swarm = yield* openSwarmSession(); + const { startTurn, until, workflows, fileSystem, session, providerThread } = swarm; + yield* startTurn(1, false); + const started = yield* until((event) => workflows([event]).at(-1)?.status === "running"); + const turn = started.find((event) => event.type === "provider_turn.updated"); + if (turn?.type !== "provider_turn.updated") return assert.fail("the turn must start"); + yield* session.interruptTurn({ providerThread, providerTurnId: turn.providerTurn.id }); + yield* until((event) => event.type === "turn.terminal"); + // Turn 2 makes no swarm call; the workers still work, so the turn stays open. + yield* startTurn(2, false); + yield* swarm.releaseSteer; + yield* until((event) => workflows([event]).at(-1)?.runId === "run-antigravity-wake-2"); + // One unreadable poll must not end the watch while the swarm holds the turn. + const roster = yield* fileSystem.readFileString(swarm.roster); + yield* fileSystem.writeFileString(swarm.roster, "{"); + yield* swarm.readAfterPoll; + yield* fileSystem.writeFileString(swarm.roster, roster); + yield* swarm.writeLines(swarm.transcript, swarm.parked); + yield* TestClock.adjust("2 seconds"); + yield* until((event) => workflows([event]).at(-1)?.status === "completed"); + yield* Queue.take(swarm.scheduledFinalizes); + yield* TestClock.adjust("5 seconds"); + const terminal = (yield* until((event) => event.type === "turn.terminal")).at(-1); + assert.equal(terminal?.type === "turn.terminal" && terminal.status, "completed"); + }).pipe(Effect.provide(layerSession)), + ); + + it.effect("a worker still adding steps keeps holding the turn past the stall limit", () => + Effect.gen(function* () { + const swarm = yield* openSwarmSession(); + const { startTurn, until, workflows } = swarm; + yield* startTurn(1, false); + yield* until((event) => workflows([event]).at(-1)?.status === "running"); + // Each step leaves the shown workflow unchanged, but proves the worker is at work. + for (const step of [2, 3]) { + yield* swarm.writeLines(swarm.transcript, [ + ...swarm.parked.slice(0, 1), + { step_index: 1, type: "PLANNER_RESPONSE", status: "DONE", tool_calls: [{ name: "x" }] }, + { step_index: step, type: "GENERIC", status: "DONE" }, + ]); + yield* TestClock.adjust("8 minutes"); + yield* swarm.readAfterPoll; + } + yield* swarm.writeLines(swarm.transcript, swarm.parked); + yield* swarm.readAfterPoll; + const done = yield* until((event) => workflows([event]).length > 0); + assert.equal(workflows(done).at(-1)?.status, "completed", "the swarm finished, not stalled"); + }).pipe(Effect.provide(layerSession)), + ); + + it.effect("a swarm whose records stop changing stops holding the turn", () => + Effect.gen(function* () { + const swarm = yield* openSwarmSession(); + const { startTurn, until, workflows } = swarm; + yield* startTurn(1, false); + yield* until((event) => workflows([event]).at(-1)?.status === "running"); + // A worker whose transcript cannot be read stays queued with nothing on the board changing. + yield* swarm.readAfterPoll; + yield* TestClock.adjust("15 minutes"); + yield* swarm.readAfterPoll; + yield* until((event) => workflows([event]).at(-1)?.status === "idle"); + yield* TestClock.adjust("5 seconds"); + const terminal = (yield* until((event) => event.type === "turn.terminal")).at(-1); + assert.equal(terminal?.type === "turn.terminal" && terminal.status, "completed"); + }).pipe(Effect.provide(layerSession)), + ); + + it.effect("a swarm whose records stay unreadable stops holding the turn", () => + Effect.gen(function* () { + const swarm = yield* openSwarmSession(); + const { startTurn, until, workflows, fileSystem } = swarm; + yield* startTurn(1, false); + yield* until((event) => workflows([event]).at(-1)?.status === "running"); + const roster = yield* fileSystem.readFileString(swarm.roster); + yield* fileSystem.writeFileString(swarm.roster, "{"); + // The first unreadable read starts the minute; one a minute later ends it. + yield* swarm.readAfterPoll; + yield* TestClock.adjust("59 seconds"); + yield* swarm.readAfterPoll; + const released = yield* until( + (event) => + event.type === "subagent.updated" && + event.subagent.title === "mul-a" && + event.subagent.status === "idle", + ); + assert.equal(workflows(released).at(-1)?.status, "idle"); + // Records readable again with the worker still at work bring the hold back, keeping the + // brief that has since left the board's tail. + yield* fileSystem.writeFileString(swarm.roster, roster); + yield* swarm.writeLines(swarm.board, []); + yield* TestClock.adjust("2 seconds"); + const resumed = yield* until((event) => workflows([event]).at(-1)?.status === "running"); + assert.equal(workflows(resumed).at(-1)?.prompt, "@mul-a Compute 6*7."); + yield* swarm.writeLines(swarm.transcript, swarm.parked); + yield* TestClock.adjust("2 seconds"); + yield* until((event) => workflows([event]).at(-1)?.status === "completed"); + yield* TestClock.adjust("5 seconds"); + const terminal = (yield* until((event) => event.type === "turn.terminal")).at(-1); + assert.equal(terminal?.type === "turn.terminal" && terminal.status, "completed"); + }).pipe(Effect.provide(layerSession)), + ); + it.effect.each([ // session/cancel ends the agent's commands, so only Stop may send it. { ending: "Stop", cancels: 1, status: "interrupted" }, diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts index c20afa04e31b8..68e22aa3da9f4 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts @@ -5,6 +5,7 @@ import { type OrchestrationV2ProviderCapabilities, type ProviderSetupError, } from "@t3tools/contracts"; +import { getModelSelectionBooleanOptionValue } from "@t3tools/shared/model"; import type { SelfInvocation } from "@t3tools/shared/nodeRuntime"; import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Effect from "effect/Effect"; @@ -37,6 +38,13 @@ import { readAntigravityPendingReply, } from "../../provider/acp/AntigravityChildWork.ts"; import { readAntigravityClientTextFile } from "../../provider/acp/AntigravityClientFiles.ts"; +import { + antigravitySwarmPrompt, + antigravitySwarmTaskId, + isAntigravitySwarmToolCall, + readAntigravitySwarm, +} from "../../provider/acp/AntigravitySwarm.ts"; +import { ANTIGRAVITY_SWARM_OPTION } from "../../provider/AntigravityProvider.ts"; import { watchAntigravityPromptOutcome } from "../../provider/acp/AntigravityTurnOutcome.ts"; import { antigravityApprovalOptions, @@ -292,6 +300,19 @@ export function makeAntigravityAcpAdapterFlavor( }; }, normalizeToolCall: normalizeAntigravityToolCall, + // The Swarm toggle is T3's, not an agent option: it starts each message with `/swarm`. + ownedModelOptionIds: [ANTIGRAVITY_SWARM_OPTION.id], + rewriteKeepsUserMessage: true, + rewriteUserText: (text, turnInput) => + Effect.succeed( + antigravitySwarmPrompt( + text, + getModelSelectionBooleanOptionValue( + turnInput.modelSelection, + ANTIGRAVITY_SWARM_OPTION.id, + ), + ), + ), extractSubagentUpdate: extractAntigravitySubagentUpdate, supportsImagePrompts: true, compactViaAdvertisedCommand: true, @@ -317,6 +338,24 @@ export function makeAntigravityAcpAdapterFlavor( profileDirectory, sessionId, }), + nativeWorkflow: { + isTool: isAntigravitySwarmToolCall, + read: (sessionId: string) => + readAntigravitySwarm({ profileDirectory, sessionId }).pipe( + Effect.map((swarm) => + swarm === undefined + ? undefined + : { + nativeTaskId: antigravitySwarmTaskId(sessionId), + title: swarm.workflow.name ?? "Swarm", + prompt: swarm.prompt, + workflow: swarm.workflow, + active: swarm.active, + progress: swarm.progress, + }, + ), + ), + }, }), }; } diff --git a/apps/server/src/orchestration-v2/NativeChildWorkQuery.test.ts b/apps/server/src/orchestration-v2/NativeChildWorkQuery.test.ts index 1b7c95336629f..f9eeac5ee592f 100644 --- a/apps/server/src/orchestration-v2/NativeChildWorkQuery.test.ts +++ b/apps/server/src/orchestration-v2/NativeChildWorkQuery.test.ts @@ -136,3 +136,89 @@ it.layer( }), ); }); + +const memberThreadId = ThreadId.make("thread-swarm-member"); +const swarmThreadId = ThreadId.make("thread-swarm"); +// A swarm worker's thread hangs off the swarm thread, whose workflow names the worker's session. +const swarmRecords = (threadId: string) => + threadId === memberThreadId + ? { + thread: { + id: memberThreadId, + creationSource: "provider", + lineage: { parentThreadId: swarmThreadId, relationshipToParent: "subagent" }, + forkedFrom: { type: "node", nodeId: "member-node" }, + }, + } + : threadId === swarmThreadId + ? { + thread: { id: swarmThreadId, lineage: { parentThreadId: "thread-root" } }, + subagents: [ + { + id: "member-node", + childThreadId: memberThreadId, + driver: "antigravity", + providerInstanceId: instanceId, + runId: null, + prompt: "Read it", + }, + ], + } + : { + subagents: [ + { + childThreadId: swarmThreadId, + driver: "antigravity", + providerInstanceId: instanceId, + workflow: { + phases: [], + agents: [ + { + index: 0, + label: "reader", + state: "completed", + agentId: CHILD, + childThreadId: memberThreadId, + prompt: "Read README.md and report the marker", + }, + ], + }, + }, + ], + }; + +it.layer( + Layer.mergeAll( + NodeServices.layer, + NodeCrypto.layer, + ServerConfig.layerTest(process.cwd(), { prefix: "native-swarm-work-" }).pipe( + Layer.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), + ), + ), +)("NativeChildWorkQuery swarm", (it) => { + it.effect("reads a swarm worker's own transcript", () => + Effect.gen(function* () { + const { stateDir } = yield* ServerConfig.ServerConfig; + const { profile } = yield* resolveAntigravityInstanceDirectories(stateDir, instanceId); + yield* makeProfile({ profile, steps: () => [] }); + const children = yield* Effect.gen(function* () { + const query = yield* NativeChildWorkQuery.NativeChildWorkQuery; + return (yield* query.getNativeChildWork({ threadId: memberThreadId })).children; + }).pipe( + Effect.provide( + NativeChildWorkQuery.layer.pipe( + Layer.provide( + Layer.mock(ThreadManagement.ThreadManagementService)({ + getThreadRecords: (threadId) => Effect.succeed(swarmRecords(threadId) as never), + }), + ), + ), + ), + ); + expect(children.map(({ conversationId, role }) => [conversationId, role])).toEqual([ + [CHILD, "reader"], + ]); + expect(children[0]?.steps?.at(-1)?.text).toBe("marker 4242 found"); + }), + ); +}); diff --git a/apps/server/src/orchestration-v2/NativeChildWorkQuery.ts b/apps/server/src/orchestration-v2/NativeChildWorkQuery.ts index 389ae6c408273..37019e3fbb3b8 100644 --- a/apps/server/src/orchestration-v2/NativeChildWorkQuery.ts +++ b/apps/server/src/orchestration-v2/NativeChildWorkQuery.ts @@ -1,5 +1,7 @@ import { isProviderNativeSubagentThread, + type OrchestrationV2Subagent, + type ThreadId, OrchestrationV2GetNativeChildWorkError, type OrchestrationV2GetNativeChildWorkInput, type OrchestrationV2GetNativeChildWorkResult, @@ -11,7 +13,10 @@ import * as Layer from "effect/Layer"; import * as Path from "effect/Path"; import * as ServerConfig from "../config.ts"; -import { readAntigravityChildWork } from "../provider/acp/AntigravityChildWork.ts"; +import { + readAntigravityChildWork, + readAntigravitySwarmMemberWork, +} from "../provider/acp/AntigravityChildWork.ts"; import { resolveAntigravityInstanceDirectories } from "../provider/antigravityAuthSupport.ts"; import * as ThreadManagement from "./ThreadManagementService.ts"; @@ -36,6 +41,42 @@ const make = Effect.gen(function* () { const digest = yield* Digest.Digest; const path = yield* Path.Path; + const profileOf = (providerInstanceId: OrchestrationV2Subagent["providerInstanceId"]) => + resolveAntigravityInstanceDirectories(stateDir, providerInstanceId).pipe( + Effect.provideService(Digest.Digest, digest), + Effect.provideService(Path.Path, path), + Effect.map((directories) => directories.profile), + ); + + // A swarm worker's thread hangs off the swarm's thread; the workflow record names its session. + const swarmMemberWork = Effect.fn("NativeChildWorkQuery.swarmMemberWork")(function* ( + memberThreadId: ThreadId, + swarmThreadId: ThreadId, + member: OrchestrationV2Subagent, + ) { + const { thread: swarmThread } = yield* threads.getThreadRecords(swarmThreadId, []); + const rootThreadId = swarmThread.lineage.parentThreadId; + if (rootThreadId === null) return NO_CHILDREN; + const { subagents } = yield* threads.getThreadRecords(rootThreadId, ["subagents"]); + const swarm = subagents.find( + (candidate) => + candidate.childThreadId === swarmThreadId && + candidate.driver === "antigravity" && + candidate.providerInstanceId === member.providerInstanceId, + ); + const agent = swarm?.workflow?.agents.find( + (candidate) => candidate.childThreadId === memberThreadId, + ); + if (agent?.agentId === undefined) return NO_CHILDREN; + const children = yield* readAntigravitySwarmMemberWork({ + profileDirectory: yield* profileOf(member.providerInstanceId), + conversationId: agent.agentId, + role: agent.label, + prompt: agent.prompt ?? member.prompt, + }); + return { children }; + }); + const getNativeChildWork = Effect.fn("NativeChildWorkQuery.getNativeChildWork")( function* (input: OrchestrationV2GetNativeChildWorkInput) { const { thread } = yield* threads.getThreadRecords(input.threadId, []); @@ -53,6 +94,9 @@ const make = Effect.gen(function* () { (candidate) => candidate.id === subagentId && candidate.childThreadId === thread.id, ); const nativeTaskId = subagent?.nativeTaskRef?.nativeId; + if (subagent?.driver === "antigravity" && subagent.runId === null) { + return yield* swarmMemberWork(thread.id, parentThreadId, subagent); + } if ( subagent?.driver !== "antigravity" || subagent.origin !== "provider_native" || @@ -93,12 +137,8 @@ const make = Effect.gen(function* () { if (!rootSessionId || providerThread?.providerInstanceId !== subagent.providerInstanceId) { return NO_CHILDREN; } - const directories = yield* resolveAntigravityInstanceDirectories( - stateDir, - subagent.providerInstanceId, - ).pipe(Effect.provideService(Digest.Digest, digest), Effect.provideService(Path.Path, path)); const children = yield* readAntigravityChildWork({ - profileDirectory: directories.profile, + profileDirectory: yield* profileOf(subagent.providerInstanceId), rootSessionId, nativeTaskId, launch: { title: subagent.title, prompt: subagent.prompt }, diff --git a/apps/server/src/provider/AntigravityProvider.test.ts b/apps/server/src/provider/AntigravityProvider.test.ts index 88589d1c9a773..3c00b4828f564 100644 --- a/apps/server/src/provider/AntigravityProvider.test.ts +++ b/apps/server/src/provider/AntigravityProvider.test.ts @@ -289,14 +289,20 @@ describe("Antigravity model catalog", () => { ["plain", null], ]), ); - const thinkingOf = (slug: string) => - models.find((model) => model.slug === slug)?.capabilities?.optionDescriptors?.[0]; + const descriptorOf = (slug: string, id: string) => + models + .find((model) => model.slug === slug) + ?.capabilities?.optionDescriptors?.find((descriptor) => descriptor.id === id); + const thinkingOf = (slug: string) => descriptorOf(slug, "thinking_level"); expect(thinkingOf("gemini")).toMatchObject({ id: "thinking_level", currentValue: "high" }); expect(thinkingOf("claude")).toMatchObject({ id: "thinking_level", currentValue: "low" }); expect(thinkingOf("plain")).toBeUndefined(); expect(thinkingOf("unseen")).toMatchObject({ id: "thinking_level" }); expect(thinkingOf("unseen")).not.toHaveProperty("currentValue"); + for (const { slug } of models) { + expect(descriptorOf(slug, "swarm")).toMatchObject({ type: "boolean", label: "Swarm" }); + } }); }); diff --git a/apps/server/src/provider/AntigravityProvider.ts b/apps/server/src/provider/AntigravityProvider.ts index f5e18f6bece9d..f785757cadf22 100644 --- a/apps/server/src/provider/AntigravityProvider.ts +++ b/apps/server/src/provider/AntigravityProvider.ts @@ -44,7 +44,6 @@ import { resolveUsageLimitsAfterProbe } from "@t3tools/provider-core/server/usag import { antigravityThinkingConfig } from "./acp/AntigravityAcpSupport.ts"; -const EMPTY_MODEL_CAPABILITIES = createModelCapabilities({ optionDescriptors: [] }); const MAX_WORKSPACE_SNAPSHOTS = 32; const HEALTH_CHECK_TIMEOUT_MS = 90_000; const SIGN_IN_MESSAGE = "Sign in with Google to use Antigravity."; @@ -65,14 +64,25 @@ type ThinkingConfig = NonNullable>; /** Thinking options each model reported when selected; `null` means it has none. */ export type AntigravityThinkingLevels = ReadonlyMap; +/** Sends each message as `/swarm`, so the agent runs it with a team of workers. */ +export const ANTIGRAVITY_SWARM_OPTION = { + id: "swarm", + label: "Swarm", + type: "boolean", +} as const; + function thinkingCapabilities(config: ThinkingConfig | null | undefined, observed: boolean) { const descriptor = config ? acpProviderOptionDescriptors({ configOptions: [config], modeState: undefined })[0] : undefined; - if (descriptor?.type !== "select") return EMPTY_MODEL_CAPABILITIES; + if (descriptor?.type !== "select") { + return createModelCapabilities({ optionDescriptors: [ANTIGRAVITY_SWARM_OPTION] }); + } // Another model's selected level is not this model's default. const { currentValue: _currentValue, ...unobserved } = descriptor; - return createModelCapabilities({ optionDescriptors: [observed ? descriptor : unobserved] }); + return createModelCapabilities({ + optionDescriptors: [observed ? descriptor : unobserved, ANTIGRAVITY_SWARM_OPTION], + }); } export function buildAntigravityModelsFromSession( diff --git a/apps/server/src/provider/acp/AntigravityChildWork.ts b/apps/server/src/provider/acp/AntigravityChildWork.ts index aa0932cf0f41a..62e960fcf9c0f 100644 --- a/apps/server/src/provider/acp/AntigravityChildWork.ts +++ b/apps/server/src/provider/acp/AntigravityChildWork.ts @@ -820,3 +820,37 @@ export const readAntigravityChildrenAtWork = Effect.fn("readAntigravityChildrenA }).pipe(Effect.orElseSucceed((): ReadonlyArray => [])); }, ); + +/** A swarm worker's own transcript; the board, not a launching tool call, proves it belongs. */ +export const readAntigravitySwarmMemberWork = Effect.fn("readAntigravitySwarmMemberWork")( + function* (input: { + readonly profileDirectory: string; + readonly conversationId: string; + readonly role: string; + readonly prompt: string; + }) { + if (!NATIVE_ID.test(input.conversationId)) return []; + return yield* Effect.tryPromise({ + try: async (): Promise> => { + const profileRoot = await antigravityProfileRoot(input.profileDirectory); + if (profileRoot === undefined) return []; + const transcript = await readChildTranscript( + profileRoot, + { conversationId: input.conversationId }, + input.prompt, + TRANSCRIPT_BYTE_CAP, + ).catch(() => undefined); + return [ + { + conversationId: input.conversationId, + role: input.role, + prompt: input.prompt, + steps: transcript?.steps ?? null, + truncated: transcript?.truncated ?? false, + }, + ]; + }, + catch: (cause) => new AntigravityChildWorkReadError({ cause }), + }); + }, +); 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..c6ab2815ebf85 --- /dev/null +++ b/apps/server/src/provider/acp/AntigravitySwarm.test.ts @@ -0,0 +1,250 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { expect, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Path from "effect/Path"; + +import { antigravitySwarmPrompt, readAntigravitySwarm } from "./AntigravitySwarm.ts"; + +const COORDINATOR = "e1eca26b-11b5-41f8-9d9b-bb8a692b2125"; +const ADD_A = "a82657e1-5a66-4505-aecc-6844eec6d066"; +const ADD_B = "60c330fe-87ec-457b-9fba-9e062cfc58d7"; + +const member = (conversationId: string, role: string, extra: object = {}) => ({ + conversation_id: conversationId, + role, + model: "gemini-3.8-flash-low", + wake_mode: "mentions", + killed: false, + ...extra, +}); + +// Shapes captured from a real `agy` 1.5.14 `/swarm` run. +const writeSwarm = Effect.fn("writeSwarm")(function* (input: { + readonly members: Record; + readonly board: ReadonlyArray; + readonly transcripts: Record>; +}) { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const profile = yield* fs.makeTempDirectoryScoped({ prefix: "t3-agy-swarm-" }); + const brain = path.join(profile, "antigravity-acp", "brain"); + const swarm = path.join(brain, COORDINATOR, ".system_generated", "swarm"); + yield* fs.makeDirectory(swarm, { recursive: true }); + yield* fs.writeFileString( + path.join(swarm, "members.json"), + JSON.stringify({ title: "simple arithmetic addition", members: input.members }), + ); + yield* fs.writeFileString( + path.join(swarm, "board.jsonl"), + input.board.map((post) => JSON.stringify(post)).join("\n") + "\n", + ); + for (const [conversationId, steps] of Object.entries(input.transcripts)) { + const logs = path.join(brain, conversationId, ".system_generated", "logs"); + yield* fs.makeDirectory(logs, { recursive: true }); + yield* fs.writeFileString( + path.join(logs, "transcript.jsonl"), + steps.map((step) => JSON.stringify(step)).join("\n") + "\n", + ); + } + return profile; +}); + +const briefs = [ + { + seq: 1, + agent: "coordinator", + text: "@add-a Compute 2 + 3. Post @coordinator [done] 5 to the board.", + time: "2026-11-23 17:23:18", + kind: "brief", + }, + { + seq: 2, + agent: "coordinator", + text: "@add-b Compute 4 + 5. Post @coordinator [done] 9 to the board.", + time: "2026-11-23 17:23:18", + kind: "brief", + }, +]; + +const started = { + step_index: 0, + type: "SYSTEM_MESSAGE", + status: "DONE", + created_at: "2026-11-23T16:23:18Z", +}; + +const parked = [ + started, + { + step_index: 1, + type: "PLANNER_RESPONSE", + status: "DONE", + created_at: "2026-11-23T16:23:18Z", + input_tokens: 100, + output_tokens: 20, + tool_calls: [{ name: "post_message" }, { name: "swarm_wait" }], + }, + { step_index: 2, type: "GENERIC", status: "DONE", created_at: "2026-11-23T16:23:21Z" }, + { step_index: 3, type: "GENERIC", status: "DONE", created_at: "2026-11-23T16:23:21Z" }, +]; + +const working = [ + started, + { + step_index: 1, + type: "PLANNER_RESPONSE", + status: "DONE", + created_at: "2026-11-23T16:23:19Z", + tool_calls: [{ name: "run_command" }], + }, +]; + +it.layer(NodeServices.layer)("readAntigravitySwarm", (it) => { + it.effect("shows each worker with its brief, state and [done] result", () => + Effect.gen(function* () { + const profileDirectory = yield* writeSwarm({ + members: { + "add-a": member(ADD_A, "worker"), + "add-b": member(ADD_B, "worker"), + coordinator: member(COORDINATOR, "coordinator"), + narrator: member("bb91cb60-3240-44a0-a20d-966af04a49a3", "narrator"), + }, + board: [ + ...briefs, + { seq: 3, agent: "add-a", text: "@coordinator [done] 5", time: "2026-11-23 17:23:21" }, + ], + // A large result after the parking batch pushes its planner step out of a short tail. + transcripts: { + [ADD_A]: parked.map((step) => + step.step_index === 2 ? { ...step, content: "x".repeat(70_000) } : step, + ), + [ADD_B]: working, + }, + }); + const swarm = yield* readAntigravitySwarm({ profileDirectory, sessionId: COORDINATOR }); + expect(swarm?.active).toBe(true); + expect(swarm?.workflow.name).toBe("simple arithmetic addition"); + expect( + swarm?.workflow.agents.map(({ label, state, prompt, result, model, totalTokens }) => ({ + label, + state, + prompt, + result, + model, + totalTokens, + })), + ).toEqual([ + { + label: "add-a", + state: "completed", + prompt: "Compute 2 + 3. Post @coordinator [done] 5 to the board.", + result: "@coordinator [done] 5", + model: "gemini-3.8-flash-low", + totalTokens: 120, + }, + { + label: "add-b", + state: "running", + prompt: "Compute 4 + 5. Post @coordinator [done] 9 to the board.", + result: undefined, + model: "gemini-3.8-flash-low", + totalTokens: 0, + }, + ]); + }), + ); + + it.effect("ends when every worker parked, failed or was killed", () => + Effect.gen(function* () { + const profileDirectory = yield* writeSwarm({ + members: { + coordinator: member(COORDINATOR, "coordinator"), + "add-a": member(ADD_A, "worker"), + "add-b": member(ADD_B, "worker", { killed: true }), + }, + board: briefs, + transcripts: { + [ADD_A]: [ + ...working, + { + step_index: 2, + type: "ERROR_MESSAGE", + status: "DONE", + error: "RESOURCE_EXHAUSTED", + }, + ], + [ADD_B]: working, + }, + }); + const swarm = yield* readAntigravitySwarm({ profileDirectory, sessionId: COORDINATOR }); + expect(swarm?.active).toBe(false); + expect(swarm?.workflow.agents.map(({ state, result }) => ({ state, result }))).toEqual([ + { state: "failed", result: "RESOURCE_EXHAUSTED" }, + { state: "completed", result: undefined }, + ]); + }), + ); + + it.effect("leaves usage out when a count is not a valid number", () => + Effect.gen(function* () { + const profileDirectory = yield* writeSwarm({ + members: { + coordinator: member(COORDINATOR, "coordinator"), + "add-a": member(ADD_A, "worker"), + }, + board: briefs, + transcripts: { + [ADD_A]: [ + started, + { step_index: 1, type: "PLANNER_RESPONSE", input_tokens: -1, output_tokens: 5 }, + ], + }, + }); + const swarm = yield* readAntigravitySwarm({ profileDirectory, sessionId: COORDINATOR }); + expect(swarm?.workflow.agents[0]?.totalTokens).toBeUndefined(); + expect(swarm?.workflow.totalTokens).toBeUndefined(); + }), + ); + + it.effect("a worker past the shown 64 that has not started keeps the swarm active", () => + Effect.gen(function* () { + const finished = Object.fromEntries( + Array.from({ length: 64 }, (_, index) => [`w-${index}`, member(ADD_A, "worker")]), + ); + const profileDirectory = yield* writeSwarm({ + members: { + coordinator: member(COORDINATOR, "coordinator"), + ...finished, + "zz-late": member("cccccccc-0000-0000-0000-000000000000", "worker"), + }, + board: [], + transcripts: { [ADD_A]: parked }, + }); + const swarm = yield* readAntigravitySwarm({ profileDirectory, sessionId: COORDINATOR }); + expect(swarm?.workflow.agents).toHaveLength(64); + expect(swarm?.active).toBe(true); + }), + ); + + it.effect("reads only the swarm this session coordinates", () => + Effect.gen(function* () { + const profileDirectory = yield* writeSwarm({ + members: { coordinator: member(ADD_A, "coordinator") }, + board: [], + transcripts: {}, + }); + expect( + yield* readAntigravitySwarm({ profileDirectory, sessionId: COORDINATOR }), + ).toBeUndefined(); + expect(yield* readAntigravitySwarm({ profileDirectory, sessionId: ADD_B })).toBeUndefined(); + }), + ); +}); + +it("starts a message as /swarm only when the toggle is on and no command is typed", () => { + expect(antigravitySwarmPrompt("fix the tests", true)).toBe("/swarm fix the tests"); + expect(antigravitySwarmPrompt("fix the tests", false)).toBe("fix the tests"); + expect(antigravitySwarmPrompt("/goal ship it", true)).toBe("/goal ship it"); + expect(antigravitySwarmPrompt(" ", true)).toBe(" "); +}); diff --git a/apps/server/src/provider/acp/AntigravitySwarm.ts b/apps/server/src/provider/acp/AntigravitySwarm.ts new file mode 100644 index 0000000000000..3706e2779d5db --- /dev/null +++ b/apps/server/src/provider/acp/AntigravitySwarm.ts @@ -0,0 +1,400 @@ +// @effect-diagnostics nodeBuiltinImport:off -- reads the native swarm board files without following links. +import * as NodeFS from "node:fs"; +import * as NodeFSP from "node:fs/promises"; + +import type { + OrchestrationV2SubagentWorkflow, + OrchestrationV2WorkflowAgent, +} from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; + +import { antigravityManagedPath, antigravityProfileRoot } from "./AntigravityProfilePaths.ts"; + +const NATIVE_ID = /^[A-Za-z0-9-]{1,64}$/; +const MAX_ROSTER_BYTES = 256 * 1024; +const BOARD_TAIL_BYTES = 512 * 1024; +const TRANSCRIPT_TAIL_BYTES = [64 * 1024, 1024 * 1024]; +const MAX_MEMBERS = 64; +const TEXT_CAP = 4_000; +// The swarm's own helpers, not task workers; the board view leaves them out the same way. +const SUPPORT_ROLE = /^(narrator|monitor)(-\d+)?$/; +// Workers open a final result with `[done]`, after the @mention that wakes its reader. +const DONE_MARK = /^(?:@[A-Za-z0-9._-]+\s+)*\[done\]/i; + +/** With the Swarm toggle on, a message the user did not start with a command runs as `/swarm`. */ +export function antigravitySwarmPrompt(text: string, swarm: boolean | undefined): string { + const trimmed = text.trimStart(); + return swarm === true && trimmed !== "" && !trimmed.startsWith("/") ? `/swarm ${text}` : text; +} + +/** Native task id T3 gives a swarm, so its record survives every turn of the coordinator thread. */ +export const antigravitySwarmTaskId = (sessionId: string) => `swarm:${sessionId}`; + +const SwarmToolInput = Schema.Struct({ action: Schema.String }); +const decodeSwarmToolInput = Schema.decodeUnknownOption(SwarmToolInput); + +/** The coordinator's `swarm` tool. ACP reports it as `Run swarm` with the action as input. */ +export function isAntigravitySwarmToolCall(toolCall: { + readonly kind?: string; + readonly title?: string; + readonly data: Record; +}): boolean { + if (toolCall.kind !== undefined && toolCall.kind !== "other") return false; + if (toolCall.title !== "Run swarm" && toolCall.title !== "Run swarm?") return false; + return Option.isSome(decodeSwarmToolInput(toolCall.data.rawInput)); +} + +const Member = Schema.Struct({ + conversation_id: Schema.optional(Schema.String), + role: Schema.optional(Schema.String), + model: Schema.optional(Schema.String), + applied_model: Schema.optional(Schema.String), + desired_model: Schema.optional(Schema.String), + desired_state: Schema.optional(Schema.String), + phase: Schema.optional(Schema.String), + killed: Schema.optional(Schema.Boolean), +}); +const decodeRoster = Schema.decodeUnknownOption( + Schema.fromJsonString( + Schema.Struct({ + title: Schema.optional(Schema.String), + members: Schema.Record(Schema.String, Member), + }), + ), +); +const Post = Schema.Struct({ + seq: Schema.Int, + agent: Schema.String, + text: Schema.String, + time: Schema.optional(Schema.String), + kind: Schema.optional(Schema.String), +}); +type Post = typeof Post.Type; +const decodePost = Schema.decodeUnknownOption(Schema.fromJsonString(Post)); +const Step = Schema.Struct({ + step_index: Schema.optional(Schema.Number), + type: Schema.String, + status: Schema.optional(Schema.String), + error: Schema.optional(Schema.String), + created_at: Schema.optional(Schema.String), + input_tokens: Schema.optional(Schema.Unknown), + output_tokens: Schema.optional(Schema.Unknown), + tool_calls: Schema.optional(Schema.Array(Schema.Struct({ name: Schema.String }))), +}); +type Step = typeof Step.Type; +const decodeStep = Schema.decodeUnknownOption(Schema.fromJsonString(Step)); + +async function readTail( + path: string, + maxBytes: number, +): Promise<{ readonly text: string; readonly whole: boolean } | undefined> { + const handle = await NodeFSP.open( + path, + NodeFS.constants.O_RDONLY | (NodeFS.constants.O_NOFOLLOW ?? 0), + ); + try { + const stat = await handle.stat(); + if (!stat.isFile()) return undefined; + const start = Math.max(0, stat.size - maxBytes); + // One byte before the window tells a record boundary from a cut record. + const readStart = Math.max(0, start - 1); + const buffer = Buffer.alloc(stat.size - readStart); + const { bytesRead } = await handle.read(buffer, 0, buffer.length, readStart); + const bytes = buffer.subarray(0, bytesRead); + if (start === 0) return { text: bytes.toString("utf8"), whole: true }; + const newline = bytes.indexOf(0x0a); + return { text: newline === -1 ? "" : bytes.toString("utf8", newline + 1), whole: false }; + } finally { + await handle.close(); + } +} + +const brainFile = (conversationId: string, ...rest: ReadonlyArray) => [ + "antigravity-acp", + "brain", + conversationId, + ".system_generated", + ...rest, +]; + +function lines(text: string, decode: (line: string) => Option.Option): ReadonlyArray { + return text.split("\n").flatMap((line) => Option.toArray(decode(line))); +} + +// Board and transcript times are the runtime's local wall clock without a zone. +function epochMillis(value: string | undefined): number | undefined { + if (value === undefined) return undefined; + const millis = Date.parse(value.includes("T") ? value : value.replace(" ", "T")); + return Number.isFinite(millis) ? millis : undefined; +} + +const tokenCount = (value: unknown) => + value === undefined + ? 0 + : typeof value === "number" && Number.isSafeInteger(value) && value >= 0 + ? value + : undefined; + +const capText = (value: string) => + value.length <= TEXT_CAP ? value : `${value.slice(0, TEXT_CAP)}…`; + +/** Whether the member's newest turn has ended: a final reply, or a batch that parked in `swarm_wait`. */ +function turnEnded(steps: ReadonlyArray): boolean { + let results = 0; + for (let index = steps.length - 1; index >= 0; index -= 1) { + const step = steps[index]; + if (step === undefined) return false; + if (step.type === "GENERIC") { + results += 1; + continue; + } + if (step.type !== "PLANNER_RESPONSE") return false; + const calls = step.tool_calls ?? []; + if (calls.length === 0) return results === 0; + const wait = calls.findIndex((call) => call.name === "swarm_wait"); + if (wait < 0 || results < calls.length) return false; + return steps[index + 1 + wait]?.status === "DONE"; + } + return false; +} + +interface MemberActivity { + readonly ended: boolean; + readonly failed: string | undefined; + readonly startedAt: number | undefined; + readonly lastAt: number | undefined; + /** The newest step's index: it moves whenever the worker does anything. */ + readonly lastStep: number | undefined; + /** Only when the whole transcript was read; a tail would undercount. */ + readonly usage: { readonly totalTokens: number; readonly toolCalls: number } | undefined; +} + +async function readActivity( + profileRoot: string, + conversationId: string, +): Promise { + const file = await antigravityManagedPath( + profileRoot, + brainFile(conversationId, "logs", "transcript.jsonl"), + "file", + ); + if (file === undefined) return undefined; + let tail: Awaited>; + let steps: ReadonlyArray = []; + // A large tool result can push the planner step that called it out of a short tail. + for (const bytes of TRANSCRIPT_TAIL_BYTES) { + tail = await readTail(file.path, bytes).catch(() => undefined); + if (tail === undefined) return undefined; + steps = lines(tail.text, decodeStep); + if (tail.whole || steps.some((step) => step.type !== "GENERIC")) break; + } + if (tail === undefined) return undefined; + const last = steps.at(-1); + // An invalid count makes the total unknown, not smaller. + let tokens: number | undefined = 0; + let toolCalls = 0; + for (const step of steps) { + const input = tokenCount(step.input_tokens); + const output = tokenCount(step.output_tokens); + tokens = + tokens === undefined || input === undefined || output === undefined + ? undefined + : tokens + input + output; + toolCalls += step.tool_calls?.length ?? 0; + } + return { + ended: turnEnded(steps), + failed: + last?.type === "ERROR_MESSAGE" + ? (last.error ?? "The agent stopped on a model error.") + : undefined, + startedAt: epochMillis(steps[0]?.created_at), + lastAt: epochMillis(last?.created_at), + lastStep: last?.step_index, + usage: tail.whole && tokens !== undefined ? { totalTokens: tokens, toolCalls } : undefined, + }; +} + +const memberModel = (member: typeof Member.Type) => + [member.model, member.applied_model, member.desired_model].find( + (model) => model !== undefined && model.trim() !== "", + ); + +const killed = (member: typeof Member.Type) => + member.killed === true || member.desired_state === "KILLED" || member.phase === "KILLED"; + +class AntigravitySwarmReadError extends Schema.TaggedError()( + "AntigravitySwarmReadError", + { cause: Schema.Defect() }, +) { + override get message(): string { + return "Could not read the Antigravity swarm board."; + } +} + +export interface AntigravitySwarmSnapshot { + readonly workflow: OrchestrationV2SubagentWorkflow; + /** The coordinator's brief to each worker, in the order they joined. */ + readonly prompt: string; + /** True while any worker still works; parked and killed workers do not count. */ + readonly active: boolean; + /** Changes whenever any worker records a step, shown or not: proof the swarm progresses. */ + readonly progress: string; +} + +/** + * Reads the coordinator session's swarm board: the roster, the board feed and each worker's + * transcript tail. Workers become workflow agents; the coordinator and helpers are left out. + * Returns undefined when this session coordinates no swarm or its records cannot be read. + */ +export const readAntigravitySwarm = Effect.fn("readAntigravitySwarm")(function* (input: { + readonly profileDirectory: string; + readonly sessionId: string; +}) { + if (!NATIVE_ID.test(input.sessionId)) return undefined; + const read = async (): Promise => { + const profileRoot = await antigravityProfileRoot(input.profileDirectory); + if (profileRoot === undefined) return undefined; + const rosterFile = await antigravityManagedPath( + profileRoot, + brainFile(input.sessionId, "swarm", "members.json"), + "file", + ); + if (rosterFile === undefined) return undefined; + // The cap holds at read time; a roster that outgrew it is not parsed cut. + const rosterText = await readTail(rosterFile.path, MAX_ROSTER_BYTES); + if (rosterText?.whole !== true) return undefined; + const roster = Option.getOrUndefined(decodeRoster(rosterText.text)); + if (roster === undefined) return undefined; + const coordinator = Object.entries(roster.members).find( + ([, member]) => member.role === "coordinator", + ); + // Only the swarm this session coordinates; a worker's own board view belongs to its coordinator. + if (coordinator === undefined || coordinator[1].conversation_id !== input.sessionId) { + return undefined; + } + const boardFile = await antigravityManagedPath( + profileRoot, + brainFile(input.sessionId, "swarm", "board.jsonl"), + "file", + ); + const board: ReadonlyArray = + boardFile === undefined + ? [] + : lines((await readTail(boardFile.path, BOARD_TAIL_BYTES))?.text ?? "", decodePost); + const coordinatorName = coordinator[0]; + const briefs = new Map(); + const results = new Map(); + for (const post of board) { + if (post.agent === coordinatorName && post.kind === "brief") { + const named = /^@([A-Za-z0-9._-]+)/.exec(post.text)?.[1]; + if (named !== undefined && !briefs.has(named)) briefs.set(named, post); + } else if (post.agent !== coordinatorName && DONE_MARK.test(post.text)) { + results.set(post.agent, post); + } + } + const workers = Object.entries(roster.members) + .filter( + ([name, member]) => + member.role !== "coordinator" && + !SUPPORT_ROLE.test(member.role ?? "") && + !(member.role === undefined && SUPPORT_ROLE.test(name)), + ) + .sort( + ([left], [right]) => + (briefs.get(left)?.seq ?? Number.MAX_SAFE_INTEGER) - + (briefs.get(right)?.seq ?? Number.MAX_SAFE_INTEGER) || left.localeCompare(right), + ); + let active = false; + // Every worker's newest step, so steps that change nothing shown still count as progress. + const progress: Array = []; + let totalTokens: number | undefined = 0; + let toolCalls = 0; + const agents: Array = []; + for (const [index, [name, member]] of workers.slice(0, MAX_MEMBERS).entries()) { + const conversationId = member.conversation_id; + const activity = + conversationId !== undefined && NATIVE_ID.test(conversationId) + ? await readActivity(profileRoot, conversationId).catch(() => undefined) + : undefined; + progress.push(`${name}:${activity?.lastStep ?? ""}`); + const brief = briefs.get(name); + const result = results.get(name); + const isKilled = killed(member); + const state: OrchestrationV2WorkflowAgent["state"] = + activity?.failed !== undefined + ? "failed" + : activity === undefined + ? isKilled + ? "completed" + : "queued" + : activity.ended || isKilled + ? "completed" + : "running"; + if (state === "running" || state === "queued") active = true; + if (activity?.usage === undefined) totalTokens = undefined; + else if (totalTokens !== undefined) { + totalTokens += activity.usage.totalTokens; + toolCalls += activity.usage.toolCalls; + } + const prompt = brief?.text.replace(/^@[A-Za-z0-9._-]+\s*/, "").trim(); + const resultText = (activity?.failed ?? result?.text)?.trim(); + const startedAt = activity?.startedAt ?? epochMillis(brief?.time); + const completedAt = + state === "failed" + ? activity?.lastAt + : state === "completed" + ? (epochMillis(result?.time) ?? activity?.lastAt) + : undefined; + const model = memberModel(member); + agents.push({ + index, + label: name, + ...(conversationId === undefined || conversationId === "" + ? {} + : { agentId: conversationId }), + state, + ...(model === undefined ? {} : { model }), + ...activity?.usage, + ...(startedAt === undefined ? {} : { startedAt }), + ...(completedAt === undefined ? {} : { completedAt }), + ...(prompt === undefined || prompt === "" ? {} : { prompt: capText(prompt) }), + ...(resultText === undefined || resultText === "" ? {} : { result: capText(resultText) }), + }); + } + // Workers past the cap are not shown, but one queued or at work keeps the swarm active. + for (const [, member] of workers.slice(MAX_MEMBERS)) { + if (killed(member)) continue; + const conversationId = member.conversation_id; + const activity = + conversationId !== undefined && NATIVE_ID.test(conversationId) + ? await readActivity(profileRoot, conversationId).catch(() => undefined) + : undefined; + progress.push(`${activity?.lastStep ?? ""}`); + if (activity === undefined || (!activity.ended && activity.failed === undefined)) { + active = true; + } + } + const title = roster.title?.trim(); + return { + workflow: { + ...(title === undefined || title === "" ? {} : { name: title }), + phases: [], + agents, + ...(agents.length === 0 || totalTokens === undefined ? {} : { totalTokens, toolCalls }), + }, + prompt: agents + .flatMap((agent) => (agent.prompt === undefined ? [] : [`@${agent.label} ${agent.prompt}`])) + .join("\n\n"), + active, + progress: progress.join(","), + }; + }; + // An unreadable board means no swarm view this poll; the next poll reads again. + return yield* Effect.tryPromise({ + try: read, + catch: (cause) => new AntigravitySwarmReadError({ cause }), + }).pipe(Effect.orElseSucceed((): AntigravitySwarmSnapshot | undefined => undefined)); +}); diff --git a/apps/web/src/components/chat/ComposerModelEffort.tsx b/apps/web/src/components/chat/ComposerModelEffort.tsx index b5d5a519a3410..e4f0376a3340d 100644 --- a/apps/web/src/components/chat/ComposerModelEffort.tsx +++ b/apps/web/src/components/chat/ComposerModelEffort.tsx @@ -38,14 +38,16 @@ import { type SelectDescriptor = Extract; type BooleanDescriptor = Extract; -/** Service tiers, Claude's Fast mode, and Ultracode sit in the footer, not the column. */ +/** Service tiers, Claude's Fast mode, and team modes (Ultracode, Swarm) sit in the footer. */ function splitSpeed( selects: ReadonlyArray, toggles: ReadonlyArray, ) { const speedSelect = selects.find((descriptor) => descriptor.id === "serviceTier") ?? null; const fastToggle = toggles.find((descriptor) => descriptor.id === "fastMode") ?? null; - const ultracodeToggle = toggles.find((descriptor) => descriptor.id === "ultracode") ?? null; + const ultracodeToggle = + toggles.find((descriptor) => descriptor.id === "ultracode" || descriptor.id === "swarm") ?? + null; return { speedSelect, fastToggle, diff --git a/docs/user/providers-antigravity.md b/docs/user/providers-antigravity.md index 614fda68f2c1d..be19c82638371 100644 --- a/docs/user/providers-antigravity.md +++ b/docs/user/providers-antigravity.md @@ -121,6 +121,19 @@ which children a batch started, the view says so. See [agent work](./thread-sidebar.md#inspect-agent-work) for where to inspect activity. +### Swarms + +Start a swarm with `/swarm `, or turn on **Swarm** in the model picker to send every +message as a swarm. The thread shows it as one workflow, titled with +the swarm's name, with a row for each worker: its brief, model, state, and the +result it posted. Open a worker to read its brief and result, and select **Work** +to see its recent steps. The run stays open while any worker is still working. + +Talk to the swarm through the thread; the coordinator relays your messages to +the workers. A message sent while the swarm works waits for the coordinator's turn +to end unless you steer it. **Stop** ends the coordinator's turn but does not remove workers; ask +the coordinator to remove them. The swarm's narrator and monitor are not shown. + ## Accounts and removal Add an Antigravity provider instance for each Google account in diff --git a/packages/client-runtime/src/modelTraits.ts b/packages/client-runtime/src/modelTraits.ts index da2387da30278..c56396322126e 100644 --- a/packages/client-runtime/src/modelTraits.ts +++ b/packages/client-runtime/src/modelTraits.ts @@ -134,7 +134,10 @@ export function buildTraitsTriggerDisplay( speedLabel ?? resolve(msg("Normal", { $context: "model speed tier" })); continue; } - if (descriptor.id === "ultracode" && descriptor.type === "boolean") { + if ( + (descriptor.id === "ultracode" || descriptor.id === "swarm") && + descriptor.type === "boolean" + ) { if (descriptor.currentValue === true) { ultracodeLabelIndex = labels.length; labels.push(descriptor.label); diff --git a/packages/client-runtime/src/state/subagentRuntime.test.ts b/packages/client-runtime/src/state/subagentRuntime.test.ts index 3512956af25fc..ae85009a1a939 100644 --- a/packages/client-runtime/src/state/subagentRuntime.test.ts +++ b/packages/client-runtime/src/state/subagentRuntime.test.ts @@ -210,6 +210,19 @@ describe("deriveWorkflowGroups over a dynamic workflow", () => { expect(groups[0]?.phases[0]?.title).toBe("Review"); }); + it("shows open members idle once their workflow goes idle", () => { + const [, open, done] = projectedSubagentsToRuntime([ + subagent({ + status: "idle", + workflow: { + phases: [], + agents: [member(), member({ index: 2, label: "beta", state: "completed" })], + }, + }), + ]); + expect([open?.status, done?.status]).toEqual(["idle", "completed"]); + }); + it("keeps unphased members with their workflow and excludes unrelated agents", () => { const runtime = projectedSubagentsToRuntime([ subagent({ id: "ordinary" }), diff --git a/packages/client-runtime/src/state/subagentRuntime.ts b/packages/client-runtime/src/state/subagentRuntime.ts index b6efb9cac132e..00f25dc00beab 100644 --- a/packages/client-runtime/src/state/subagentRuntime.ts +++ b/packages/client-runtime/src/state/subagentRuntime.ts @@ -141,9 +141,10 @@ function workflowMembersToRuntime( workflow: OrchestrationV2SubagentWorkflow, ): ReadonlyArray { return workflow.agents.map((agent) => { + // A workflow that stopped (or went idle with nothing left to watch) stops its open members. const status = (agent.state === "queued" || agent.state === "running") && - isTerminalSubagentStatus(coordinator.status) + (isTerminalSubagentStatus(coordinator.status) || coordinator.status === "idle") ? coordinator.status : agent.state === "queued" ? "pending" diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index c4b90adc0c3d1..2a17b0d39153a 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -16,6 +16,7 @@ import { type OrchestrationV2ProviderTurn, type OrchestrationV2RuntimeRequest, type OrchestrationV2Subagent, + type OrchestrationV2SubagentWorkflow, type OrchestrationV2TurnItem, type OrchestrationV2UserInputQuestion, type OrchestrationV2WebSearchResult, @@ -155,6 +156,12 @@ const ACP_BUSY_PROMPT_RETRY_INTERVAL: Duration.Input = "1 second"; // Agents such as omp advertise a loaded session's commands shortly after answering session/load. const ACP_LOADED_COMMANDS_WAIT: Duration.Input = "2 seconds"; const ACP_PROMPT_INACTIVITY_SLICE_MILLIS = 60_000; +const ACP_NATIVE_WORKFLOW_POLL = Duration.millis(1_500); +const ACP_NATIVE_WORKFLOW_UNREADABLE_MILLIS = 60_000; +// As long as an open prompt may go silent: a workflow whose records stop changing stops holding. +// Wall-clock on purpose: after a host sleep this can settle the turn early, and the next turn +// picks a swarm still at work back up from its records. +const ACP_NATIVE_WORKFLOW_STALL_MILLIS = 15 * 60_000; const ACP_HOST_SLEEP_TOLERANCE_MILLIS = 10_000; // pi-agent-core agents (oh-my-pi) end a turn while background work runs and reject @@ -440,6 +447,8 @@ export interface AcpAdapterV2Flavor { text: string, turnInput: ProviderAdapter.ProviderAdapterV2TurnInput, ) => Effect.Effect; + /** The rewrite only wraps the user's message, so it is treated as the message it wraps. */ + readonly rewriteKeepsUserMessage?: boolean; readonly driver: ProviderDriverKind; readonly capabilities: OrchestrationV2ProviderCapabilities; readonly supportsNativeGoals?: Effect.Effect; @@ -694,6 +703,15 @@ export interface AcpAdapterV2Flavor { * through `ACP_OPEN_REPLY_QUIET_LIMIT` instead of closing early. */ readonly hasPendingReply?: (sessionId: string) => Effect.Effect; + /** + * A team the agent runs from this session outside ACP (Antigravity `/swarm`), shown as one + * workflow subagent read from the agent's own records. `isTool` names the tool calls that + * manage it; they fold into the workflow instead of showing as tools. + */ + readonly nativeWorkflow?: { + readonly isTool: (toolCall: AcpToolCallState) => boolean; + readonly read: (sessionId: string) => Effect.Effect; + }; readonly assertComplete?: Effect.Effect; /** Interrupt the local prompt fiber before `session/cancel` (Grok wedged prompts). */ readonly interruptPromptOnCancel?: boolean; @@ -811,6 +829,18 @@ export interface AcpAdapterV2SubagentUpdate { readonly childSessionId: string | null; readonly result: string | null; readonly suppressNormalTool?: boolean; + readonly workflow?: OrchestrationV2SubagentWorkflow; +} + +export interface AcpNativeWorkflowSnapshot { + readonly nativeTaskId: string; + readonly title: string; + readonly prompt: string; + readonly workflow: OrchestrationV2SubagentWorkflow; + /** Any member still works; holds the turn open like a running subagent. */ + readonly active: boolean; + /** Changes whenever the team makes progress, shown or not; a stall clock reads it. */ + readonly progress?: string; } export interface AcpAdapterV2Options { @@ -834,6 +864,8 @@ export interface AcpAdapterV2Options { readonly afterPromptWireSettled?: () => Effect.Effect; readonly afterPromptSettledWithBackgroundWork?: () => Effect.Effect; readonly afterPromptCallback?: () => Effect.Effect; + /** The native workflow watch finished one read of the agent's records. */ + readonly afterNativeWorkflowRead?: () => Effect.Effect; readonly onNativeResponseLifecycle?: (event: { readonly generation?: number; readonly requestId?: string; @@ -1787,6 +1819,20 @@ interface ActiveAcpTurn { /** Clock millis of the prompt's last progress, for `promptInactivityTimeout`. */ lastProgressAt: number; inactivityWatchdog: Fiber.Fiber | undefined; + nativeWorkflowWatching: boolean; + /** The turn called a `nativeWorkflow` tool, so the workflow belongs to it even if unchanged. */ + nativeWorkflowToolSeen: boolean; + /** The watch has read the agent's records since the last native workflow call. */ + nativeWorkflowRead: boolean; + /** Counts native workflow calls, so a read that began before the latest call does not count. */ + nativeWorkflowCalls: number; + /** Native workflow member threads this turn has announced, so its run routes their updates. */ + readonly nativeWorkflowMembers: Set; + /** Clock millis when reads of a workflow this turn holds open began to fail, if they fail. */ + nativeWorkflowUnreadableSince: number | undefined; + /** Clock millis when the workflow's records last changed during this turn. */ + nativeWorkflowChangedAt: number | undefined; + nativeWorkflowProgress: string | undefined; } const PROMPT_OUTCOME_CHECK_TIMEOUT = Duration.seconds(5); @@ -3723,10 +3769,12 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( ? context.subagentsBySessionId.get(update.childSessionId) : undefined); const updateIsTerminal = acpSubagentStatusIsTerminal(update.status); + // A native workflow can take on more work after its members all parked. if ( existing !== undefined && acpSubagentStatusIsTerminal(existing.task.status) && - !updateIsTerminal + !updateIsTerminal && + update.workflow === undefined ) { return; } @@ -3734,7 +3782,8 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( existing !== undefined && existing.task.status === update.status && updateIsTerminal && - existing.terminalStatusProjected + existing.terminalStatusProjected && + update.workflow === undefined ) { return; } @@ -3766,6 +3815,9 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const turnItemOrdinal = existing?.turnItemOrdinal ?? (yield* resolveItemOrdinal(context, nativeTaskId)); const taskStatus = update.status; + const writesPrompt = + existing === undefined || + (update.workflow !== undefined && update.prompt !== existing.task.prompt); const task: OrchestrationV2Subagent = { ...(existing?.task ?? { id: nodeId, @@ -3785,6 +3837,9 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( startedAt: now, }), model: update.model?.trim() || existing?.task.model || null, + ...(update.workflow === undefined + ? {} + : { workflow: update.workflow, prompt: update.prompt }), status: taskStatus, result: update.result ?? existing?.task.result ?? null, completedAt: acpSubagentStatusIsTerminal(taskStatus) ? now : null, @@ -3841,6 +3896,8 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( creationSource: "provider", }), }); + } + if (writesPrompt) { const promptNativeItemId = `${nativeTaskId}:prompt`; const promptArtifacts = makeSubagentConversationArtifacts({ senderThreadId: context.input.threadId, @@ -3853,6 +3910,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( nativeItemRef: { driver, nativeId: promptNativeItemId, strength: "weak" }, role: "user", text: update.prompt, + ...(update.workflow === undefined ? {} : { workflowScript: true }), ordinal: 100, now, }); @@ -3999,6 +4057,380 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( } }); + // Last projected state per native workflow and member, across turns of this session. + const nativeWorkflowProjected = new Map>(); + + const projectNativeWorkflowMembers = Effect.fnUntraced(function* ( + context: ActiveAcpTurn, + coordinator: ActiveAcpSubagent, + workflow: OrchestrationV2SubagentWorkflow, + ) { + const parentThread = { ...context.input.appThread, id: coordinator.childThreadId }; + const providerInstanceId = context.input.modelSelection.instanceId; + for (const member of workflow.agents) { + const childThreadId = member.childThreadId; + if (childThreadId === undefined) continue; + const memberKey = `${coordinator.childThreadId}:agent:${member.label}`; + const status = + (member.state === "queued" || member.state === "running") && + coordinator.task.status !== "running" + ? coordinator.task.status + : member.state === "queued" + ? "pending" + : member.state; + const prompt = member.prompt ?? member.label; + const result = member.result ?? null; + const model = member.model ?? context.input.modelSelection.model; + const previous = nativeWorkflowProjected.get(memberKey); + const next = [status, model, prompt, result, member.startedAt, member.completedAt]; + if ( + previous !== undefined && + Equal.equals(previous, next) && + context.nativeWorkflowMembers.has(memberKey) + ) + continue; + const [, previousModel, previousPrompt, previousResult] = previous ?? []; + nativeWorkflowProjected.set(memberKey, next); + const now = yield* DateTime.now; + const nodeId = providerNodeId(memberKey); + const childRootNodeId = providerNodeId(`${memberKey}:thread-root`); + const nativeItemRef = { driver, nativeId: memberKey, strength: "strong" as const }; + // A later turn that takes the workflow over re-announces its members' threads. + if ( + previous === undefined || + previousModel !== model || + !context.nativeWorkflowMembers.has(memberKey) + ) { + context.nativeWorkflowMembers.add(memberKey); + yield* emitProviderEvent({ + type: "app_thread.created", + driver, + appThread: makeSubagentChildThread({ + parentThread, + childThreadId, + parentNodeId: nodeId, + activeProviderThreadId: null, + providerInstanceId, + modelSelection: { instanceId: providerInstanceId, model }, + title: member.label, + now, + createdBy: "agent", + creationSource: "provider", + }), + }); + } + for (const [role, text, ordinal, changed] of [ + ["user", prompt, 100, previousPrompt !== prompt], + ["assistant", result, 200, result !== null && previousResult !== result], + ] as const) { + if (!changed || text === null) continue; + const nativeId = `${memberKey}:${role}`; + const artifacts = makeSubagentConversationArtifacts({ + ...(role === "user" ? { senderThreadId: coordinator.childThreadId } : {}), + messageId: providerMessageId(nativeId), + turnItemId: providerTurnItemId(nativeId), + threadId: childThreadId, + rootNodeId: childRootNodeId, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: { driver, nativeId, strength: "weak" }, + role, + text, + ordinal, + now, + }); + yield* emitProviderEvent({ + type: "message.updated", + driver, + message: artifacts.message, + }); + yield* emitProviderEvent({ + type: "turn_item.updated", + driver, + turnItem: artifacts.turnItem, + }); + } + const startedAt = + member.startedAt === undefined ? now : DateTime.makeUnsafe(member.startedAt); + const completedAt = acpSubagentStatusIsTerminal(status) + ? member.completedAt === undefined + ? now + : DateTime.makeUnsafe(member.completedAt) + : null; + const nodeBase = { + runId: null, + status, + countsForRun: false, + providerThreadId: null, + providerTurnId: null, + nativeItemRef, + runtimeRequestId: null, + checkpointScopeId: null, + startedAt, + completedAt, + }; + yield* emitProviderEvent({ + type: "node.updated", + driver, + node: { + ...nodeBase, + id: nodeId, + threadId: coordinator.childThreadId, + parentNodeId: coordinator.childRootNodeId, + rootNodeId: coordinator.childRootNodeId, + kind: "subagent", + }, + }); + yield* emitProviderEvent({ + type: "node.updated", + driver, + node: { + ...nodeBase, + id: childRootNodeId, + threadId: childThreadId, + parentNodeId: null, + rootNodeId: childRootNodeId, + kind: "root_turn", + }, + }); + yield* emitProviderEvent({ + type: "subagent.updated", + driver, + subagent: { + id: nodeId, + threadId: coordinator.childThreadId, + runId: null, + parentNodeId: coordinator.childRootNodeId, + origin: "provider_native", + createdBy: "agent", + driver, + providerInstanceId, + providerThreadId: null, + childThreadId, + nativeTaskRef: nativeItemRef, + prompt, + title: member.label, + model, + status, + result, + startedAt, + completedAt, + updatedAt: now, + }, + }); + } + }); + + // A workflow whose records stay unreadable this long stops holding the turn open. + const heldNativeWorkflow = (context: ActiveAcpTurn) => + [...context.subagents.values()].find( + (subagent) => + subagent.task.workflow !== undefined && + acpSubagentStatusBlocksTurnSettlement(subagent.task.status), + ); + + const releaseUnreadableNativeWorkflow = Effect.fnUntraced(function* ( + context: ActiveAcpTurn, + ) { + const owns = [...context.subagents.values()].some( + (subagent) => subagent.task.workflow !== undefined, + ); + if (!owns) return; + const now = yield* Clock.currentTimeMillis; + // Recorded even after a stall released the hold, so the next readable read starts fresh. + context.nativeWorkflowUnreadableSince ??= now; + if (heldNativeWorkflow(context) === undefined) return; + if (now - context.nativeWorkflowUnreadableSince < ACP_NATIVE_WORKFLOW_UNREADABLE_MILLIS) { + return; + } + yield* releaseNativeWorkflowHold(context); + }); + + // The workflow goes idle with its workers, so the turn settles; a later read that shows + // it at work holds the turn again. + const releaseNativeWorkflowHold = Effect.fnUntraced(function* (context: ActiveAcpTurn) { + const held = heldNativeWorkflow(context); + if (held === undefined) return; + yield* runtimeCallbackPermit.withPermit( + Effect.gen(function* () { + if (context.finalized) return; + yield* emitSubagent(context, { + nativeTaskId: held.task.nativeTaskRef?.nativeId ?? held.task.id, + prompt: held.task.prompt, + title: held.task.title, + model: held.task.model, + status: "idle", + childSessionId: null, + result: null, + }); + // Workers still shown as working take the coordinator's idle status with it. + if (held.task.workflow !== undefined) { + yield* projectNativeWorkflowMembers(context, held, held.task.workflow); + } + yield* rearmDeferredFinalize(context); + }), + ); + }); + + /** Returns whether the session has a native workflow. */ + const syncNativeWorkflow = Effect.fnUntraced(function* (context: ActiveAcpTurn) { + if (flavor.nativeWorkflow === undefined) return false; + const read = yield* flavor.nativeWorkflow.read(context.nativeThreadId); + if (read === undefined) { + yield* releaseUnreadableNativeWorkflow(context); + return false; + } + const recovered = context.nativeWorkflowUnreadableSince !== undefined; + context.nativeWorkflowUnreadableSince = undefined; + // Records that read again after a failure count as a change for the stall clock. + if (recovered) context.nativeWorkflowChangedAt = undefined; + const { nativeTaskId } = read; + // A brief or result can scroll out of the board's tail; keep what an earlier poll saw. + const earlier = ( + nativeWorkflowProjected.get(nativeTaskId)?.[3] as + | OrchestrationV2SubagentWorkflow + | undefined + )?.agents; + const merged = { + ...read, + workflow: { + ...read.workflow, + agents: read.workflow.agents.map((member) => { + const seen = earlier?.find((candidate) => candidate.label === member.label); + return { + ...member, + ...(member.prompt === undefined && seen?.prompt !== undefined + ? { prompt: seen.prompt } + : {}), + ...(member.result === undefined && seen?.result !== undefined + ? { result: seen.result } + : {}), + }; + }), + }, + }; + // The plan lists every brief, so it is built from the members after the merge. + const briefs = merged.workflow.agents.flatMap((member) => + member.prompt === undefined ? [] : [`@${member.label} ${member.prompt}`], + ); + const snapshot = { + ...merged, + prompt: briefs.length === 0 ? merged.prompt : briefs.join("\n\n"), + }; + const owned = context.subagents.has(nativeTaskId); + const key = [snapshot.title, snapshot.prompt, snapshot.active, snapshot.workflow]; + const previous = nativeWorkflowProjected.get(nativeTaskId); + const changed = previous === undefined || !Equal.equals(previous, key); + const progressed = read.progress !== context.nativeWorkflowProgress; + context.nativeWorkflowProgress = read.progress; + const now = yield* Clock.currentTimeMillis; + if (changed || progressed || context.nativeWorkflowChangedAt === undefined) { + context.nativeWorkflowChangedAt = now; + } else if (now - context.nativeWorkflowChangedAt >= ACP_NATIVE_WORKFLOW_STALL_MILLIS) { + // Records that read fine but stop changing (a worker whose transcript cannot be + // read stays queued) must not hold the turn forever. + yield* releaseNativeWorkflowHold(context); + return true; + } + // A working swarm joins every turn; a finished one only a turn that manages it. + // One released as unreadable resumes once its records show it at work again. + const card = context.subagents.get(nativeTaskId); + const resumes = + snapshot.active && + card !== undefined && + !acpSubagentStatusBlocksTurnSettlement(card.task.status) && + context.nativeWorkflowUnreadableSince === undefined && + now - context.nativeWorkflowChangedAt < ACP_NATIVE_WORKFLOW_STALL_MILLIS; + const joins = owned + ? changed || resumes + : snapshot.active || context.nativeWorkflowToolSeen; + if (!joins) return true; + const coordinatorThreadId = + context.subagents.get(nativeTaskId)?.childThreadId ?? + idAllocator.derive.subagentThread({ + driver, + providerInstanceId: context.input.modelSelection.instanceId, + nativeThreadId: `${context.nativeThreadId}:task:${nativeTaskId}`, + }); + const workflow: OrchestrationV2SubagentWorkflow = { + ...snapshot.workflow, + agents: snapshot.workflow.agents.map((member) => ({ + ...member, + childThreadId: idAllocator.derive.subagentThread({ + driver, + providerInstanceId: context.input.modelSelection.instanceId, + nativeThreadId: `${coordinatorThreadId}:agent:${member.label}`, + }), + })), + }; + const results = workflow.agents.flatMap((member) => + member.result === undefined ? [] : [`${member.label}: ${member.result}`], + ); + yield* runtimeCallbackPermit.withPermit( + Effect.gen(function* () { + if (context.finalized) return; + // Members working on the board are the prompt's progress. + context.lastProgressAt = yield* Clock.currentTimeMillis; + yield* emitSubagent(context, { + nativeTaskId, + prompt: snapshot.prompt || snapshot.title, + title: snapshot.title, + model: null, + status: snapshot.active ? "running" : "completed", + childSessionId: null, + result: snapshot.active || results.length === 0 ? null : results.join("\n\n"), + workflow, + }); + const coordinator = context.subagents.get(nativeTaskId); + if (coordinator !== undefined) { + yield* projectNativeWorkflowMembers(context, coordinator, workflow); + } + nativeWorkflowProjected.set(nativeTaskId, key); + yield* rearmDeferredFinalize(context); + }), + ); + return true; + }); + + const watchNativeWorkflow = Effect.fnUntraced(function* (context: ActiveAcpTurn) { + if ( + flavor.nativeWorkflow === undefined || + context.nativeWorkflowWatching || + context.finalized + ) { + return; + } + context.nativeWorkflowWatching = true; + yield* Effect.gen(function* () { + while (!context.finalized) { + const calls = context.nativeWorkflowCalls; + const exists = yield* syncNativeWorkflow(context); + yield* options.testHooks?.afterNativeWorkflowRead?.() ?? Effect.void; + const owns = [...context.subagents.values()].some( + (subagent) => subagent.task.workflow !== undefined, + ); + if (calls === context.nativeWorkflowCalls && !context.nativeWorkflowRead) { + const waited = context.nativeWorkflowToolSeen || nativeWorkflowProjected.size > 0; + context.nativeWorkflowRead = true; + // The read held this turn open; it may settle now. + if (waited) yield* runtimeCallbackPermit.withPermit(rearmDeferredFinalize(context)); + } + // A turn that never touched a native workflow stops looking once none exists; one + // that shows a workflow keeps looking until it settles, so it sees a recovery. + if (!exists && !context.nativeWorkflowToolSeen && !owns) return; + yield* Effect.sleep(ACP_NATIVE_WORKFLOW_POLL); + } + }).pipe( + Effect.ensuring( + Effect.sync(() => { + context.nativeWorkflowWatching = false; + }), + ), + Effect.ignore, + Effect.forkIn(sessionScope), + ); + }); + const nativeChild = (sessionId: string) => { let child = nativeChildren.get(sessionId); if (child === undefined) { @@ -4350,6 +4782,13 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( ignoreTool?: (tool: AcpToolCallState) => boolean, ): boolean => { if (flavor.wakeOnDetachedRequest && agentRequests.size > 0) return true; + // A turn waits for the watch to read the agent's records after a native workflow call, + // and at its start once this session has one, so a swarm still at work holds it. + if ( + (context.nativeWorkflowToolSeen || nativeWorkflowProjected.size > 0) && + !context.nativeWorkflowRead + ) + return true; if (flavor.toolOutlivesPrompt !== undefined) { // A tool that never started has nothing to report later. for (const tool of context.tools.values()) { @@ -4389,8 +4828,11 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( if (flavor.subagentsOutlivingPrompt === undefined) return; const nativeTaskId = (subagent: ActiveAcpSubagent) => subagent.task.nativeTaskRef?.nativeId ?? String(subagent.task.id); - const running = [...context.subagents.values()].filter((subagent) => - acpSubagentStatusBlocksTurnSettlement(subagent.task.status), + // The native workflow watch owns its own status. + const running = [...context.subagents.values()].filter( + (subagent) => + subagent.task.workflow === undefined && + acpSubagentStatusBlocksTurnSettlement(subagent.task.status), ); if (running.length === 0) return; const atWork = yield* flavor.subagentsOutlivingPrompt({ @@ -4654,6 +5096,18 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( } } + // A call that failed has no workflow to show its error, so it stays a tool row. + if ( + flavor.nativeWorkflow?.isTool(toolCall) === true && + toolStatus(toolCall.status) !== "failed" + ) { + context.nativeWorkflowCalls += 1; + context.nativeWorkflowToolSeen = true; + context.nativeWorkflowRead = false; + yield* watchNativeWorkflow(context); + yield* rearmDeferredFinalize(context); + return; + } // Monitor TaskOutput resembles subagent hydration; do not invent a subagent. const subagentUpdate = hydratedRegisteredMonitor ? undefined @@ -9245,7 +9699,13 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( resolveAttachmentPath: host.resolveAttachmentPath, resolveExtractedTextPath: host.resolveExtractedTextPath, }); - const isNativeSlashCommand = userText.trimStart().startsWith("/"); + // A rewrite that keeps the user's message as the command's task (Antigravity's Swarm + // toggle) still carries the context and instructions that message would. + const isNativeSlashCommand = ( + flavor.rewriteKeepsUserMessage === true ? turnInput.message.text : userText + ) + .trimStart() + .startsWith("/"); const attachmentBlocks = yield* promptAttachmentBlocks( messageText, turnInput.message.attachments, @@ -9260,13 +9720,17 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( deliveredContext, isNativeSlashCommand, ); - const text = t3AcpPromptWithInstructions({ - prompt: messageText, + // A command a rewrite made keeps its first block; its instructions follow in another. + const commandFromRewrite = !isNativeSlashCommand && userText.trimStart().startsWith("/"); + const wrapped = t3AcpPromptWithInstructions({ + prompt: commandFromRewrite ? "" : messageText, state: instructionState, ...(previousInstructionState === undefined || compactionMarker !== undefined ? {} : { previousState: previousInstructionState }), }); + const instructionsBlock = commandFromRewrite && wrapped !== "" ? wrapped : undefined; + const text = commandFromRewrite ? messageText : wrapped; const sessionSetup = yield* Ref.get(activeSessionSetup); const runtimeInstructions = buildRuntimeInstructions({ agentFeedback: instructionState.hasT3Mcp ? (turnInput.agentFeedback ?? "off") : "off", @@ -9293,19 +9757,25 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( }); } if (appContextEntries.length > 0) { - prompt.unshift( - ...appContextEntries.map((entry) => ({ - type: "text" as const, - text: formatAcpAppContextEntry(entry), - })), - ); + const contextBlocks = appContextEntries.map((entry) => ({ + type: "text" as const, + text: formatAcpAppContextEntry(entry), + })); + if (commandFromRewrite) prompt.push(...contextBlocks); + else prompt.unshift(...contextBlocks); + } + if (instructionsBlock !== undefined) { + prompt.push({ type: "text", text: instructionsBlock }); } if (sendRuntimeInstructions) { prompt.push({ type: "text", text: runtimeInstructions }); } return { prompt, - instructionState: text === messageText ? undefined : instructionState, + instructionState: + text === messageText && instructionsBlock === undefined + ? undefined + : instructionState, runtimeInstructions: sendRuntimeInstructions ? runtimeInstructions : undefined, appContextEntries, compactionMarker, @@ -9848,6 +10318,14 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( nativePromptId: undefined, lastProgressAt: 0, inactivityWatchdog: undefined, + nativeWorkflowWatching: false, + nativeWorkflowToolSeen: false, + nativeWorkflowRead: false, + nativeWorkflowCalls: 0, + nativeWorkflowMembers: new Set(), + nativeWorkflowUnreadableSince: undefined, + nativeWorkflowChangedAt: undefined, + nativeWorkflowProgress: undefined, }; const carryover = yield* Ref.getAndSet(carryoverSubagents, null); let rehydratedCarryoverSubagents: ReadonlyArray = []; @@ -9865,6 +10343,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( } yield* Ref.set(activeTurn, context); yield* Ref.set(stoppedRunQuarantine, false); + yield* watchNativeWorkflow(context); const runningTurn = providerTurnPayload(context, "running", null); yield* emitProviderEvent({ type: "provider_turn.updated",