Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -992,12 +992,32 @@ describe("AntigravityAdapterV2 html_render pages", () => {
* A session whose prompt reports one running command and returns end_turn, as agy 1.5.11 does
* for `run_command` once `WaitMsBeforeAsync` passes. The test sends every later frame.
*/
const invokeSubagentLaunch = {
sessionUpdate: "tool_call",
toolCallId: "call_research",
kind: "other",
title: "Run invoke_subagent",
status: "completed",
rawInput: { TypeName: "research", Role: "Researcher", Prompt: "Read it" },
} as const satisfies EffectAcpSchema.SessionUpdate;

// agy 1.5.13 completes `swarm` add at once; the worker keeps running as a detached child.
const swarmWorkerLaunch = {
sessionUpdate: "tool_call",
toolCallId: "call_research",
kind: "other",
title: "Run swarm",
status: "completed",
rawInput: { action: "add", name: "worker-a", brief: "Read it" },
} as const satisfies EffectAcpSchema.SessionUpdate;

const openSessionWithRunningCommand = Effect.fn("openSessionWithRunningCommand")(function* (
commandInput: Record<string, unknown>,
/** The prompt launches one agy 1.5 subagent instead; its records live below this profile. */
detachedChildProfile?: string,
/** agy 1.5.11 answers a steered prompt once the next one arrives, which runs to `releaseSteer`. */
steering?: { readonly agentVersion: string; readonly holdsFirstPrompt: boolean },
detachedLaunch: EffectAcpSchema.SessionUpdate = invokeSubagentLaunch,
) {
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const path = yield* Path.Path;
Expand Down Expand Up @@ -1077,14 +1097,7 @@ const openSessionWithRunningCommand = Effect.fn("openSessionWithRunningCommand")
yield* send(
detachedChildProfile === undefined
? { sessionUpdate: "tool_call", ...command, status: "in_progress" }
: {
sessionUpdate: "tool_call",
toolCallId: "call_research",
kind: "other",
title: "Run invoke_subagent",
status: "completed",
rawInput: { TypeName: "research", Role: "Researcher", Prompt: "Read it" },
},
: detachedLaunch,
);
yield* send({
sessionUpdate: "agent_message_chunk",
Expand Down Expand Up @@ -1551,9 +1564,10 @@ describe("AntigravityAdapterV2 work after the prompt ends", () => {
// Files as agy 1.5.12 wrote them: the launch sits in the child's inbox, and the child's report
// lands in the parent's inbox with no session update. Only the agent's own reply follows.
it.effect.each([
{ reports: "after the prompt ends", duringPrompt: false },
{ reports: "while the prompt runs", duringPrompt: true },
])("keeps a detached subagent running until it reports $reports", ({ duringPrompt }) =>
{ reports: "after the prompt ends", duringPrompt: false, tool: "invoke_subagent" },
{ reports: "while the prompt runs", duringPrompt: true, tool: "invoke_subagent" },
{ reports: "after the prompt ends", duringPrompt: false, tool: "swarm" },
])("keeps a detached $tool child running until it reports $reports", ({ duringPrompt, tool }) =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
Expand All @@ -1571,22 +1585,45 @@ describe("AntigravityAdapterV2 work after the prompt ends", () => {
yield* write(records("mock-session-1", "subagents"), "child-1.json", {});
yield* write(records("child-1", "messages"), "launch.json", {
sender: "mock-session-1",
sourceMetadata: { tool: { toolCall: { id: "call_research", name: "invoke_subagent" } } },
});
const report = write(records("mock-session-1", "messages"), "report.json", {
sender: "child-1",
sourceMetadata: { tool: { toolCall: { id: "call_research", name: tool } } },
});
// A swarm worker reports on the parent's board, not in its inbox.
const report =
tool === "swarm"
? write(records("mock-session-1", "swarm"), "members.json", {
members: { "worker-a": { conversation_id: "child-1" } },
}).pipe(
Effect.andThen(
fileSystem.writeFileString(
path.join(records("mock-session-1", "swarm"), "board.jsonl"),
`${JSON.stringify({ seq: 1, agent: "coordinator", text: "@worker-a Read it" })}\n${JSON.stringify({ seq: 2, agent: "worker-a", text: "@coordinator Done" })}\n`,
),
),
)
: write(records("mock-session-1", "messages"), "report.json", { sender: "child-1" });
if (duringPrompt) yield* report;

const { usage, offers, send, startTurn, until, throughPromptSettled } =
yield* openSessionWithRunningCommand({}, profile);
yield* openSessionWithRunningCommand(
{},
profile,
undefined,
tool === "swarm" ? swarmWorkerLaunch : invokeSubagentLaunch,
);
yield* startTurn(1, false);
const statuses = (events: ReadonlyArray<ProviderAdapter.ProviderAdapterV2Event>) =>
events.flatMap((event) =>
event.type === "subagent.updated" ? [event.subagent.status] : [],
);
const prompt = yield* throughPromptSettled;
assert.equal(statuses(prompt).at(-1), duringPrompt ? "idle" : "running");
const launched = prompt.find((event) => event.type === "subagent.updated");
assert.deepInclude(
launched?.type === "subagent.updated" ? launched.subagent : {},
tool === "swarm"
? { title: "worker-a", prompt: "Read it" }
: { title: "Researcher", prompt: "Read it" },
);
if (!duringPrompt) {
yield* TestClock.adjust("10 minutes");
yield* report;
Expand Down
11 changes: 11 additions & 0 deletions apps/server/src/provider/acp/AntigravityChildWork.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -537,6 +537,17 @@ it.layer(NodeServices.layer)("readAntigravityChildWork", (it) => {
toolCallIds: ["call_alive", "call_killed"],
}),
).toEqual(["call_alive"]);

// An unreadable swarm board leaves the other records' verdicts alone.
yield* writeJson([ROOT, ".system_generated", "swarm", "board.jsonl"], { agent: "x" });
yield* writeJson([ROOT, ".system_generated", "swarm", "members.json"], { members: 1 });
expect(
yield* readAntigravityChildrenAtWork({
profileDirectory: profile,
rootSessionId: ROOT,
toolCallIds: ["call_alive", "call_killed"],
}),
).toEqual(["call_alive"]);
}),
);

Expand Down
68 changes: 58 additions & 10 deletions apps/server/src/provider/acp/AntigravityChildWork.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,11 +51,16 @@ const LaunchInput = Schema.Struct({ Role: Schema.String, Prompt: Schema.String }
const decodeLaunchInput = Schema.decodeUnknownOption(
Schema.Union([Schema.Struct({ Subagents: Schema.NonEmptyArray(LaunchInput) }), LaunchInput]),
);
const decodeSwarmAdd = Schema.decodeUnknownOption(
Schema.Struct({ action: Schema.Literal("add"), name: Schema.String, brief: Schema.String }),
);

/** `invoke_subagent` arguments, from the permission prompt or the persisted record. */
/** `invoke_subagent` or `swarm` add arguments, from the tool call or the persisted record. */
export function antigravitySubagentLaunches(
input: unknown,
): ReadonlyArray<AntigravityChildLaunch> | undefined {
const swarmAdd = Option.getOrUndefined(decodeSwarmAdd(input));
if (swarmAdd !== undefined) return [{ role: swarmAdd.name, prompt: swarmAdd.brief }];
return Option.getOrUndefined(
Option.map(decodeLaunchInput(input), (decoded) =>
("Subagents" in decoded ? decoded.Subagents : [decoded]).map((entry) => ({
Expand Down Expand Up @@ -580,7 +585,7 @@ 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;
}
Expand Down Expand Up @@ -610,7 +615,7 @@ async function readDetachedSubagent(profileRoot: string, rootSessionId: string,

/**
* agy 1.5 records detached children under `subagents/` instead of a SQLite `INVOKE_SUBAGENT` step;
* the child's own inbox carries the parent's launching `invoke_subagent` tool call id.
* the child's own inbox carries the parent's launching `invoke_subagent` or `swarm` tool call id.
*/
async function findDetachedInvokeRecord(
profileRoot: string,
Expand Down Expand Up @@ -651,11 +656,50 @@ async function findDetachedInvokeRecord(
return matches.length === 1 ? match : undefined;
}

const decodeSwarmMembers = Schema.decodeUnknownOption(
Schema.fromJsonString(
Schema.Struct({
members: Schema.Record(Schema.String, Schema.Struct({ conversation_id: Schema.String })),
}),
),
);
const decodeBoardEntry = Schema.decodeUnknownOption(
Schema.fromJsonString(Schema.Struct({ agent: Schema.String })),
);

/**
* Swarm workers report on the parent's board, and the parent's inbox only gets a notice it sent
* itself. Returns the conversation ids of members that have posted. Throws past a bound.
*/
async function readSwarmBoardPosters(profileRoot: string, rootSessionId: string) {
const directory = ["antigravity-acp", "brain", rootSessionId, ".system_generated", "swarm"];
const members = await antigravityManagedPath(profileRoot, [...directory, "members.json"], "file");
const board = await antigravityManagedPath(profileRoot, [...directory, "board.jsonl"], "file");
if (members === undefined || board === undefined) return new Set<string>();
if (members.info.size > MAX_STEP_BYTES || board.info.size > MAX_SCAN_BYTES)
throw new Error("Swarm board too large");
const roster = Option.getOrThrow(
decodeSwarmMembers(await NodeFSP.readFile(members.path, "utf8")),
);
const posters = new Set(
(await NodeFSP.readFile(board.path, "utf8"))
.split("\n")
.flatMap((line) =>
Option.toArray(Option.map(decodeBoardEntry(line), (entry) => entry.agent)),
),
);
return new Set(
Object.entries(roster.members).flatMap(([name, member]) =>
posters.has(name) ? [member.conversation_id] : [],
),
);
}

/**
* agy 1.5 children outlive their `invoke_subagent` call and the agent reports no end for them:
* a child is done, or waits for guidance, once its message is in the parent's inbox or its record
* says it was killed. Returns the launching tool call ids of children with neither; none when the
* records prove nothing.
* agy 1.5 children outlive their `invoke_subagent` or `swarm` call and the agent reports no end
* for them: a child is done, or waits for guidance, once its message is in the parent's inbox or
* on its swarm board, or its record says it was killed. Returns the launching tool call ids of
* children with none of these; none when the records prove nothing.
*/
export const readAntigravityChildrenAtWork = Effect.fn("readAntigravityChildrenAtWork")(
function* (input: {
Expand All @@ -671,9 +715,13 @@ export const readAntigravityChildrenAtWork = Effect.fn("readAntigravityChildrenA
? undefined
: await listDetachedChildIds(profileRoot, input.rootSessionId);
if (profileRoot === undefined || childIds === undefined) return [];
const reported = new Set(
(await readInbox(profileRoot, input.rootSessionId)).map((message) => message.sender),
);
const reported = new Set([
...(await readInbox(profileRoot, input.rootSessionId)).map((message) => message.sender),
// An unreadable board proves no report, so it holds swarm workers and touches no others.
...(await readSwarmBoardPosters(profileRoot, input.rootSessionId).catch(
() => new Set<string>(),
)),
]);
const atWork: Array<string> = [];
for (const childId of childIds) {
if (reported.has(childId)) continue;
Expand Down
2 changes: 2 additions & 0 deletions apps/server/src/provider/acp/AntigravityProtocol.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,8 @@ describe("native Antigravity subagent tools", () => {
"start_subagent",
"Run command",
"Running manage_task",
// Only a `swarm` add starts a worker.
"Run swarm",
]) {
expect(classifyAntigravitySubagentToolCall({ ...toolCall, title }, {})).toBeUndefined();
}
Expand Down
8 changes: 7 additions & 1 deletion apps/server/src/provider/acp/AntigravityProtocol.ts
Original file line number Diff line number Diff line change
Expand Up @@ -532,6 +532,12 @@ const ANTIGRAVITY_SUBAGENT_TITLES = new Set([
"Run invoke_subagent",
]);

// agy 1.5.13 `swarm` add starts a worker that runs detached, like an `invoke_subagent` child.
const isAntigravitySwarmWorkerLaunch = (toolCall: AcpToolCallState) =>
toolCall.title === "Run swarm" &&
Predicate.isObject(toolCall.data.rawInput) &&
toolCall.data.rawInput.action === "add";

/** The ACP agent reports subagent calls as ordinary tools without child IDs or models. */
export function classifyAntigravitySubagentToolCall(
toolCall: AcpToolCallState,
Expand All @@ -540,7 +546,7 @@ export function classifyAntigravitySubagentToolCall(
if (
(toolCall.kind !== undefined && toolCall.kind !== "other") ||
toolCall.title === undefined ||
!ANTIGRAVITY_SUBAGENT_TITLES.has(toolCall.title)
!(ANTIGRAVITY_SUBAGENT_TITLES.has(toolCall.title) || isAntigravitySwarmWorkerLaunch(toolCall))
)
return undefined;
const update = Predicate.isObject(rawPayload) ? rawPayload.update : undefined;
Expand Down
Loading