From 8378d53f6a0b5954aae4889a2bf1b61db0ecf8a9 Mon Sep 17 00:00:00 2001 From: "Patrick C. Toulme" <135739773+patrick-toulme@users.noreply.github.com> Date: Tue, 24 Nov 2026 22:00:51 -0800 Subject: [PATCH] fix(antigravity): /swarm workers show as subagents Antigravity /swarm workers showed only as raw swarm and read_board tool rows. Project each swarm worker as a subagent from the swarm add call and the on-disk swarm roster, and format swarm board tool titles. Carved down from #40368 to the parts released agy builds use. Co-authored-by: Julius Marminge Co-Authored-By: Claude Opus 5.5 --- .../Adapters/AntigravityAdapterV2.ts | 6 +- .../provider/acp/AntigravityChildWork.test.ts | 105 +++++++ .../src/provider/acp/AntigravityChildWork.ts | 170 ++++++++++- .../provider/acp/AntigravityProtocol.test.ts | 62 ++++ .../src/provider/acp/AntigravityProtocol.ts | 271 +++++++++++++++++- 5 files changed, 590 insertions(+), 24 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts index 9534a50829fa1..b8174495e28c7 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts @@ -40,6 +40,8 @@ import { readAntigravityClientTextFile } from "../../provider/acp/AntigravityCli import { watchAntigravityPromptOutcome } from "../../provider/acp/AntigravityTurnOutcome.ts"; import { antigravityApprovalOptions, + antigravitySwarmAddChildSessionId, + antigravitySwarmAddModel, antigravityToolOutlivesPrompt, antigravityCommandOutlivesPrompt, antigravitySubagentOutput, @@ -130,9 +132,9 @@ const extractAntigravitySubagentUpdate: NonNullable { }), ); + 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); + }), + ); + 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..c7b64311fb53b 100644 --- a/apps/server/src/provider/acp/AntigravityChildWork.ts +++ b/apps/server/src/provider/acp/AntigravityChildWork.ts @@ -47,16 +47,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 +112,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 +629,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, @@ -619,7 +728,7 @@ async function findDetachedInvokeRecord( ): Promise { 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 +739,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 +933,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 902ad272aa548..a96f1e3ceaf45 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 aedf7da7bce3a..a80a899360604 100644 --- a/apps/server/src/provider/acp/AntigravityProtocol.ts +++ b/apps/server/src/provider/acp/AntigravityProtocol.ts @@ -638,7 +638,7 @@ export function normalizeAntigravityToolCall( ...(exitCode !== undefined ? { exitCode } : {}), }; } - return { + const normalized: AcpToolCallState = { ...toolCall, ...(kind !== undefined ? { kind } : {}), ...(command !== undefined ? { command } : {}), @@ -650,6 +650,7 @@ export function normalizeAntigravityToolCall( : {}), data, }; + return normalizeAntigravitySwarmToolPresentation(normalized); } const ANTIGRAVITY_SUBAGENT_TITLES = new Set([ @@ -661,19 +662,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) + ); +} + +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"; }