Skip to content
Merged
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 @@ -98,6 +98,20 @@ describe("AntigravityAdapterV2 flavor", () => {
});
assert.equal(launch?.title, "Readme Reader");
assert.equal(launch?.prompt, "Read README.md");

// agy 1.5.x auto-approves one subagent per call with a flat input.
const single = flavor.extractSubagentUpdate?.({
toolCallId: "call_16976942396429577770",
title: "Run invoke_subagent",
kind: "other",
status: "completed",
data: {
rawInput: { TypeName: "research", Role: "Codebase Researcher", Prompt: "Read README.md" },
},
});
assert.equal(single?.status, "running");
assert.equal(single?.title, "Codebase Researcher");
assert.equal(single?.prompt, "Read README.md");
});

it("routes interaction_* permission requests to the question card", () => {
Expand Down Expand Up @@ -901,6 +915,8 @@ describe("AntigravityAdapterV2 html_render pages", () => {
*/
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,
) {
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const path = yield* Path.Path;
Expand Down Expand Up @@ -959,7 +975,18 @@ const openSessionWithRunningCommand = Effect.fn("openSessionWithRunningCommand")
}).pipe(Effect.andThen(runtime.handleRequestPermission(handler))),
prompt: () =>
Effect.gen(function* () {
yield* send({ sessionUpdate: "tool_call", ...command, status: "in_progress" });
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" },
},
);
yield* send({
sessionUpdate: "agent_message_chunk",
content: { type: "text", text: "I'll render once the fetch finishes." },
Expand All @@ -972,6 +999,7 @@ const openSessionWithRunningCommand = Effect.fn("openSessionWithRunningCommand")
},
withProcess: (_stop, task) => task,
defaultModel: Effect.undefined,
...(detachedChildProfile === undefined ? {} : { profileDirectory: detachedChildProfile }),
});
const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
runtimeMode: "full-access",
Expand Down Expand Up @@ -1182,6 +1210,99 @@ describe("AntigravityAdapterV2 work after the prompt ends", () => {
}).pipe(Effect.provide(layerSession)),
);

// 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 }) =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const profile = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-antigravity-kids-" });
const records = (conversationId: string, kind: string) =>
path.join(profile, "antigravity-acp", "brain", conversationId, ".system_generated", kind);
const write = (directory: string, name: string, value: unknown) =>
fileSystem
.makeDirectory(directory, { recursive: true })
.pipe(
Effect.andThen(
fileSystem.writeFileString(path.join(directory, name), JSON.stringify(value)),
),
);
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",
});
if (duringPrompt) yield* report;

const { usage, offers, send, startTurn, until, throughPromptSettled } =
yield* openSessionWithRunningCommand({}, profile);
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");
if (!duringPrompt) {
yield* TestClock.adjust("10 minutes");
yield* report;
yield* send({
sessionUpdate: "agent_message_chunk",
content: { type: "text", text: "The researcher found it." },
});
yield* send(usage);
yield* TestClock.adjust("3 seconds");
}
const run = yield* until((event) => event.type === "turn.terminal");
const terminal = run.at(-1);
assert.equal(terminal?.type === "turn.terminal" && terminal.status, "completed");
assert.equal(statuses([...prompt, ...run]).at(-1), "idle");
assert.equal(
JSON.stringify(run).includes("The researcher found it."),
!duringPrompt,
"the reply about the report is part of the run",
);
assert.lengthOf(offers, 0, "the open run needs no continuation");
}).pipe(Effect.provide(layerSession)),
);

it.effect("ends a continuation run whose replayed reply launched a subagent", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
// No records: nothing proves a child is at work, so none may hold a run open.
const profile = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-antigravity-kids-" });
const { usage, offers, send, startTurn, throughTerminal } =
yield* openSessionWithRunningCommand({}, profile);
yield* startTurn(1, false);
yield* throughTerminal;
yield* send({
sessionUpdate: "tool_call",
toolCallId: "call_follow_up",
kind: "other",
title: "Run invoke_subagent",
status: "completed",
rawInput: { TypeName: "research", Role: "Checker", Prompt: "Check it" },
});
yield* send({
sessionUpdate: "agent_message_chunk",
content: { type: "text", text: "Started a checker." },
});
yield* send(usage);
assert.lengthOf(offers, 1, "the agent's own reply must wake the thread");
yield* offers[0]!.dispatchIfCurrent!(Effect.void);
yield* startTurn(2, true);
yield* TestClock.adjust("3 seconds");
const terminal = (yield* throughTerminal).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" },
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import {
ANTIGRAVITY_SUBAGENT_BATCH_TITLE,
antigravitySubagentLaunches,
describeAntigravitySubagentLaunches,
readAntigravityChildrenAtWork,
} from "../../provider/acp/AntigravityChildWork.ts";
import { readAntigravityClientTextFile } from "../../provider/acp/AntigravityClientFiles.ts";
import { watchAntigravityPromptOutcome } from "../../provider/acp/AntigravityTurnOutcome.ts";
Expand Down Expand Up @@ -303,6 +304,12 @@ export function makeAntigravityAcpAdapterFlavor(
: {
watchPromptOutcome: (sessionId: string) =>
watchAntigravityPromptOutcome(profileDirectory, sessionId),
subagentsOutlivingPrompt: ({ sessionId, nativeTaskIds }) =>
readAntigravityChildrenAtWork({
profileDirectory,
rootSessionId: sessionId,
toolCallIds: nativeTaskIds,
}),
}),
};
}
Expand Down
102 changes: 98 additions & 4 deletions apps/server/src/provider/acp/AntigravityChildWork.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@ const TRANSCRIPT_BYTE_CAP = 256 * 1024;
const BATCH_TRANSCRIPT_BYTES = 512 * 1024;
const STEP_TEXT_CAP = 4_000;
const TOOL_INPUT_CAP = 1_000;
const MAX_MESSAGE_FILES = 256;
const MAX_DETACHED_CHILDREN = 64;

/** T3's title for a batch whose launch text it never saw. */
export const ANTIGRAVITY_SUBAGENT_BATCH_TITLE = "Antigravity subagent batch";
Expand All @@ -44,10 +46,10 @@ interface AntigravityChildLaunch {
readonly prompt: string;
}

const LaunchInput = Schema.Struct({ Role: Schema.String, Prompt: Schema.String });
// agy 1.5 launches one child per call with a flat input; earlier releases send a batch.
const decodeLaunchInput = Schema.decodeUnknownOption(
Schema.Struct({
Subagents: Schema.NonEmptyArray(Schema.Struct({ Role: Schema.String, Prompt: Schema.String })),
}),
Schema.Union([Schema.Struct({ Subagents: Schema.NonEmptyArray(LaunchInput) }), LaunchInput]),
);

/** `invoke_subagent` arguments, from the permission prompt or the persisted record. */
Expand All @@ -56,7 +58,10 @@ export function antigravitySubagentLaunches(
): ReadonlyArray<AntigravityChildLaunch> | undefined {
return Option.getOrUndefined(
Option.map(decodeLaunchInput(input), (decoded) =>
decoded.Subagents.map((entry) => ({ role: entry.Role, prompt: entry.Prompt })),
("Subagents" in decoded ? decoded.Subagents : [decoded]).map((entry) => ({
role: entry.Role,
prompt: entry.Prompt,
})),
),
);
}
Expand Down Expand Up @@ -476,3 +481,92 @@ export const readAntigravityChildWork = Effect.fn("readAntigravityChildWork")(fu
catch: (cause) => new AntigravityChildWorkReadError({ cause }),
});
});

const decodeChildMessage = Schema.decodeUnknownOption(
Schema.fromJsonString(
Schema.Struct({
sender: Schema.String,
sourceMetadata: Schema.optional(
Schema.Struct({
tool: Schema.optional(
Schema.Struct({
toolCall: Schema.optional(Schema.Struct({ id: Schema.String, name: Schema.String })),
}),
),
}),
),
}),
),
);

/** A conversation's inbox. Throws past a bound or on a file it cannot read, so nothing is proven. */
async function readInbox(profileRoot: string, conversationId: string) {
const directory = ["antigravity-acp", "brain", conversationId, ".system_generated", "messages"];
const inbox = await antigravityManagedPath(profileRoot, directory, "directory");
if (inbox === undefined) return [];
// `read.json` is the runtime's read receipts, not a message.
const names = (await NodeFSP.readdir(inbox.path)).filter(
(name) => name.endsWith(".json") && name !== "read.json",
);
if (names.length > MAX_MESSAGE_FILES) throw new Error("Too many messages");
return Promise.all(
names.map(async (name) => {
const file = await antigravityManagedPath(profileRoot, [...directory, name], "file");
if (file === undefined || file.info.size > MAX_STEP_BYTES) throw new Error("Unreadable");
return Option.getOrThrow(decodeChildMessage(await NodeFSP.readFile(file.path, "utf8")));
}),
);
}

/**
* 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. Returns the
* launching tool call ids of children with no message yet; none when the records prove nothing.
*/
export const readAntigravityChildrenAtWork = Effect.fn("readAntigravityChildrenAtWork")(
function* (input: {
readonly profileDirectory: string;
readonly rootSessionId: string;
readonly toolCallIds: ReadonlyArray<string>;
}) {
if (!NATIVE_ID.test(input.rootSessionId)) return [];
const read = async (): Promise<ReadonlyArray<string>> => {
const profileRoot = await antigravityProfileRoot(input.profileDirectory);
const children =
profileRoot === undefined
? undefined
: await antigravityManagedPath(
profileRoot,
["antigravity-acp", "brain", input.rootSessionId, ".system_generated", "subagents"],
"directory",
);
if (profileRoot === undefined || children === undefined) return [];
const childIds = (await NodeFSP.readdir(children.path)).flatMap((name) =>
name.endsWith(".json") && NATIVE_ID.test(name.slice(0, -5)) ? [name.slice(0, -5)] : [],
);
if (childIds.length > MAX_DETACHED_CHILDREN) return [];
const reported = new Set(
(await readInbox(profileRoot, input.rootSessionId)).map((message) => message.sender),
);
const atWork: Array<string> = [];
for (const childId of childIds) {
if (reported.has(childId)) continue;
for (const message of await readInbox(profileRoot, childId)) {
const launch = message.sourceMetadata?.tool?.toolCall;
if (
message.sender === input.rootSessionId &&
launch?.name === "invoke_subagent" &&
input.toolCallIds.includes(launch.id)
) {
atWork.push(launch.id);
}
}
}
return atWork;
};
return yield* Effect.tryPromise({
try: read,
catch: (cause) => new AntigravityChildWorkReadError({ cause }),
}).pipe(Effect.orElseSucceed((): ReadonlyArray<string> => []));
},
);
2 changes: 2 additions & 0 deletions apps/server/src/provider/acp/AntigravityProtocol.ts
Original file line number Diff line number Diff line change
Expand Up @@ -494,6 +494,8 @@ const ANTIGRAVITY_SUBAGENT_TITLES = new Set([
"Run start_subagent?",
"Running invoke_subagent",
"Run invoke_subagent?",
// agy 1.5 auto-approved calls.
"Run invoke_subagent",
]);

/** The ACP agent reports subagent calls as ordinary tools without child IDs or models. */
Expand Down
Loading
Loading