Skip to content
Open
Original file line number Diff line number Diff line change
Expand Up @@ -1248,6 +1248,75 @@ const openSessionWithRunningCommand = Effect.fn("openSessionWithRunningCommand")
});

describe("AntigravityAdapterV2 work after the prompt ends", () => {
// A swarm launch completes at once; only the board and the worker's transcript show the work.
it.effect("keeps the run open for swarm workers after the launch tool completes", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const profile = yield* fs.makeTempDirectoryScoped({ prefix: "t3-antigravity-swarm-" });
const brain = path.join(profile, "antigravity-acp", "brain");
const swarm = path.join(brain, "mock-session-1", ".system_generated", "swarm");
const logs = path.join(brain, "worker-1", ".system_generated", "logs");
const transcript = path.join(logs, "transcript.jsonl");
yield* fs.makeDirectory(swarm, { recursive: true });
yield* fs.makeDirectory(logs, { recursive: true });
yield* fs.writeFileString(
path.join(swarm, "members.json"),
JSON.stringify({
members: {
coordinator: { conversation_id: "mock-session-1", wake_mode: "working" },
worker: { conversation_id: "worker-1", wake_mode: "working" },
},
}),
);
yield* fs.writeFileString(
transcript,
JSON.stringify({ step_index: 0, type: "SYSTEM_MESSAGE", status: "DONE" }) + "\n",
);
const { offers, send, startTurn, throughPromptSettled, throughTerminal, usage } =
yield* openSessionWithRunningCommand({}, profile, undefined, {
initialToolCalls: [
{
sessionUpdate: "tool_call",
toolCallId: "call_swarm",
kind: "other",
title: "Run swarm",
status: "completed",
rawInput: { action: "add", name: "worker", brief: "Check the chart" },
},
],
});

yield* startTurn(1, false);
yield* throughPromptSettled;
yield* TestClock.adjust("10 minutes");
yield* fs.writeFileString(
transcript,
[
{
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" },
]
.map((step) => JSON.stringify(step))
.join("\n") + "\n",
);
yield* send({
sessionUpdate: "agent_message_chunk",
content: { type: "text", text: "The swarm checked the chart." },
});
yield* send(usage);
yield* TestClock.adjust("3 seconds");
const events = yield* throughTerminal;
assert.include(JSON.stringify(events), "The swarm checked the chart.");
assert.lengthOf(offers, 0, "the worker report stays in the original run");
}).pipe(Effect.provide(layerSession)),
);

// agy sets `IsDaemon` on a command it does not wait for. When it exits, the agent replies
// with no prompt open.
it.effect("continues in one run when a finished daemon wakes the agent", () =>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ import {
import {
ANTIGRAVITY_SUBAGENT_BATCH_TITLE,
antigravitySubagentLaunches,
antigravitySwarmAtWork,
describeAntigravitySubagentLaunches,
readAntigravityChildrenAtWork,
readAntigravityPendingReply,
Expand Down Expand Up @@ -299,6 +300,8 @@ export function makeAntigravityAcpAdapterFlavor(
: {
watchPromptOutcome: (sessionId: string) =>
watchAntigravityPromptOutcome(profileDirectory, sessionId),
detachedWorkOutlivingPrompt: (sessionId: string) =>
antigravitySwarmAtWork(profileDirectory, sessionId),
subagentsOutlivingPrompt: ({ sessionId, nativeTaskIds }) =>
readAntigravityChildrenAtWork({
profileDirectory,
Expand Down
71 changes: 71 additions & 0 deletions apps/server/src/provider/acp/AntigravityChildWork.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import * as Path from "effect/Path";
import {
ANTIGRAVITY_SUBAGENT_BATCH_TITLE,
antigravitySubagentLaunches,
antigravitySwarmAtWork,
describeAntigravitySubagentLaunches,
readAntigravityChildrenAtWork,
readAntigravityChildWork,
Expand Down Expand Up @@ -541,6 +542,76 @@ it.layer(NodeServices.layer)("readAntigravityChildWork", (it) => {
}),
);

it.effect("counts a parked swarm worker at work only while its calls or tasks run", () =>
Effect.gen(function* () {
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, ROOT, ".system_generated", "swarm");
const logs = path.join(brain, CHILD, ".system_generated", "logs");
yield* fs.makeDirectory(swarm, { recursive: true });
yield* fs.makeDirectory(logs, { recursive: true });
yield* fs.writeFileString(
path.join(swarm, "members.json"),
JSON.stringify({
members: {
coordinator: { conversation_id: ROOT, wake_mode: "mentions" },
writer: { conversation_id: CHILD, wake_mode: "mentions" },
},
}),
);
const writeSteps = (steps: ReadonlyArray<object>) =>
fs.writeFileString(
path.join(logs, "transcript.jsonl"),
[{ step_index: 0, type: "SYSTEM_MESSAGE", status: "DONE" }, ...steps]
.map((step, index) => JSON.stringify({ ...step, step_index: index }))
.join("\n") + "\n",
);
// agy 1.5.13 parks a worker with swarm_wait after the call it ran beside it.
const parked = (sibling: string, siblingStatus: string) => [
{
type: "PLANNER_RESPONSE",
status: "DONE",
tool_calls: [{ name: sibling }, { name: "swarm_wait" }],
},
{ type: "GENERIC", status: siblingStatus },
{ type: "GENERIC", status: "DONE" },
];
// A long command moves to a background task and the worker's reply ends without a call.
const task = `${CHILD}/task-2`;
const backgrounded = [
{ type: "PLANNER_RESPONSE", status: "DONE", tool_calls: [{ name: "run_command" }] },
{
type: "GENERIC",
status: "RUNNING",
content: `Tool is running as a background task with task id: ${task}\nTask Description: sleep 120`,
},
{ type: "PLANNER_RESPONSE", status: "DONE", content: "Waiting for sleep 120." },
];
const finished = {
type: "SYSTEM_MESSAGE",
status: "DONE",
content: `[Message] sender=${task} content=Task id "${task}" finished with result:\nCommand exited with code 0.`,
};

for (const [label, steps, atWork] of [
["post_message DONE", parked("post_message", "DONE"), false],
["run_command ERROR", parked("run_command", "ERROR"), false],
["run_command RUNNING", parked("run_command", "RUNNING"), true],
["background task running", backgrounded, true],
[
"background task finished",
[...backgrounded, finished, ...parked("post_message", "DONE")],
false,
],
] as const) {
yield* writeSteps(steps);
expect(yield* antigravitySwarmAtWork(profile, ROOT), label).toBe(atWork);
}
}),
);

it.effect("shares one transcript budget across the batch", () =>
Effect.gen(function* () {
const filler = JSON.stringify({
Expand Down
130 changes: 110 additions & 20 deletions apps/server/src/provider/acp/AntigravityChildWork.ts
Original file line number Diff line number Diff line change
Expand Up @@ -367,32 +367,24 @@ function transcriptSteps(
);
}

/** Reads the tail of the transcript at the named child's own unlinked profile path. */
async function readChildTranscript(
async function readTranscriptTail(
profileRoot: string,
child: InvokeRecord["children"][number],
prompt: string,
conversationId: string,
logUri: string | undefined,
byteCap: number,
) {
const expected = (
await antigravityManagedPath(
profileRoot,
[
"antigravity-acp",
"brain",
child.conversationId,
".system_generated",
"logs",
"transcript.jsonl",
],
["antigravity-acp", "brain", conversationId, ".system_generated", "logs", "transcript.jsonl"],
"file",
)
)?.path;
if (expected === undefined) return undefined;
if (child.logUri !== undefined) {
if (logUri !== undefined) {
let named: string;
try {
named = NodeURL.fileURLToPath(child.logUri);
named = NodeURL.fileURLToPath(logUri);
} catch {
return undefined;
}
Expand All @@ -414,16 +406,75 @@ async function readChildTranscript(
let lineStart = 0;
if (tailStart > 0) {
const newline = bytes.indexOf(0x0a);
if (newline === -1) return { steps: [], truncated: true };
if (newline === -1) return { contents: "", truncated: true };
lineStart = newline + 1;
}
const contents = bytes.toString("utf8", lineStart);
return { steps: transcriptSteps(contents, prompt), truncated: tailStart > 0 };
return { contents, truncated: tailStart > 0 };
} finally {
await handle.close();
}
}

const decodeSwarmRoster = Schema.decodeUnknownOption(
Schema.fromJsonString(
Schema.Struct({
members: Schema.Record(
Schema.String,
Schema.Struct({
conversation_id: Schema.String,
killed: Schema.optional(Schema.Boolean),
wake_mode: Schema.optional(Schema.String),
}),
),
}),
),
);

const BACKGROUND_TASK = /running as a background task with task id: (\S+)/;

/** agy parks a worker whose command went to a background task until the task's finish message. */
function backgroundTaskRunning(lines: ReadonlyArray<string>): boolean {
const running = new Set<string>();
for (const line of lines) {
const step = Option.getOrUndefined(decodeTranscriptLine(line));
const content = step?.content ?? "";
const started = step?.type === "GENERIC" ? BACKGROUND_TASK.exec(content)?.[1] : undefined;
if (started !== undefined) running.add(started);
if (step?.type !== "SYSTEM_MESSAGE") continue;
for (const id of running) if (content.includes(`Task id "${id}"`)) running.delete(id);
}
return running.size > 0;
}

function swarmWorkerAtWork(transcript: string): boolean {
const lines = transcript.split("\n");
const results: Array<string | undefined> = [];
if (Option.getOrUndefined(decodeTranscriptLine(lines.at(-1)))?.type === "ERROR_MESSAGE") {
return false;
}
if (backgroundTaskRunning(lines)) return true;
for (let index = lines.length - 1; index >= 0; index -= 1) {
const step = Option.getOrUndefined(decodeTranscriptLine(lines[index]));
if (step?.type === "GENERIC") {
results.push(step.status);
continue;
}
if (step?.type !== "PLANNER_RESPONSE" || step.status !== "DONE") return true;
const calls = step.tool_calls ?? [];
if (calls.length === 0) return results.length > 0;
const wait = calls.findIndex((call) => call.name === "swarm_wait");
// A sibling call that failed has ended; one still running keeps the worker at work.
return (
wait < 0 ||
results.length < calls.length ||
results[results.length - 1 - wait] !== "DONE" ||
results.some((status) => status !== "DONE" && status !== "ERROR")
);
}
return true;
}

class AntigravityChildWorkReadError extends Schema.TaggedError<AntigravityChildWorkReadError>()(
"AntigravityChildWorkReadError",
{ cause: Schema.Defect() },
Expand All @@ -433,6 +484,42 @@ class AntigravityChildWorkReadError extends Schema.TaggedError<AntigravityChildW
}
}

/** Swarm launches complete immediately. The board and worker transcripts track the actual work. */
export const antigravitySwarmAtWork = Effect.fn("antigravitySwarmAtWork")(function* (
profileDirectory: string,
sessionId: string,
) {
if (!NATIVE_ID.test(sessionId)) return false;
const read = async () => {
const root = await antigravityProfileRoot(profileDirectory);
if (root === undefined) return false;
const file = await antigravityManagedPath(
root,
["antigravity-acp", "brain", sessionId, ".system_generated", "swarm", "members.json"],
"file",
);
if (file === undefined || file.info.size > MAX_STEP_BYTES) return false;
const roster = Option.getOrUndefined(
decodeSwarmRoster(await NodeFSP.readFile(file.path, "utf8")),
);
if (roster === undefined) return false;
const workers = Object.values(roster.members);
if (workers.length > MAX_DETACHED_CHILDREN) return false;
for (const worker of workers) {
const id = worker.conversation_id;
if (worker.killed || id === sessionId || !NATIVE_ID.test(id)) continue;
const tail = await readTranscriptTail(root, id, undefined, MAX_STEP_BYTES);
const contents = tail?.contents.trimEnd();
if (contents ? swarmWorkerAtWork(contents) : worker.wake_mode === "working") return true;
}
return false;
};
return yield* Effect.tryPromise({
try: read,
catch: (cause) => new AntigravityChildWorkReadError({ cause }),
}).pipe(Effect.orElseSucceed(() => false));
});

/** Children a subagent tool call launched, proven by the parent's own session record. */
export const readAntigravityChildWork = Effect.fn("readAntigravityChildWork")(function* (input: {
readonly profileDirectory: string;
Expand Down Expand Up @@ -477,17 +564,20 @@ export const readAntigravityChildWork = Effect.fn("readAntigravityChildWork")(fu
);
return Promise.all(
children.map(async (child, index) => {
const transcript = await readChildTranscript(
const transcript = await readTranscriptTail(
profileRoot,
child,
launches[index]?.prompt ?? "",
child.conversationId,
child.logUri,
byteCap,
).catch(() => undefined);
return {
conversationId: child.conversationId,
role: launches[index]?.role ?? "",
prompt: launches[index]?.prompt ?? "",
steps: transcript?.steps ?? null,
steps:
transcript === undefined
? null
: transcriptSteps(transcript.contents, launches[index]?.prompt ?? ""),
truncated: transcript?.truncated ?? false,
};
}),
Expand Down
Loading
Loading