diff --git a/apps/server/src/mcp/toolkits/orchestrator/tools.ts b/apps/server/src/mcp/toolkits/orchestrator/tools.ts index 629a5352587f0..0d71844bde63b 100644 --- a/apps/server/src/mcp/toolkits/orchestrator/tools.ts +++ b/apps/server/src/mcp/toolkits/orchestrator/tools.ts @@ -145,7 +145,7 @@ const WorkflowStopTool = Tool.make("t3_workflow_stop", { const BackgroundWaitTool = Tool.make("t3_background_wait", { description: - "Keep this thread in Working while background work runs. Pass its task ID once started. Not for work left running (dev server, watcher). `waiting=false` clears. Doesn't stop tasks. Claude/OpenCode only.", + "Keep this thread in Working while background work runs. Pass its task ID once started. Not for work left running (dev server, watcher). `waiting=false` clears. Doesn't stop tasks. Claude/OpenCode/Antigravity.", parameters: Schema.Struct({ taskIds: Schema.Array(TrimmedNonEmptyString).check( Schema.isMinLength(1), diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts index b281ecc16ab84..ba8982fbe4fe6 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts @@ -19,8 +19,8 @@ import * as DateTime from "effect/DateTime"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; -import * as FileSystem from "effect/FileSystem"; import * as Fiber from "effect/Fiber"; +import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Path from "effect/Path"; import * as Ref from "effect/Ref"; @@ -67,7 +67,7 @@ function permissionRequest( } describe("AntigravityAdapterV2 flavor", () => { - it("keeps a successful subagent launch running until the parent turn becomes idle", () => { + it("treats a successful subagent launch as running, not as a child result", () => { const batch = flavor.extractSubagentUpdate?.({ toolCallId: "trajectory:4", title: "Running start_subagent", @@ -1274,3 +1274,344 @@ describe("AntigravityAdapterV2 session system prompt", () => { }).pipe(Effect.provide(layerSession)), ); }); + +describe("AntigravityAdapterV2 foreground command waits", () => { + it.effect( + "holds awaitBackgroundTasks until a backgrounded foreground command settles and ignores IsDaemon", + () => + Effect.gen(function* () { + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const crypto = yield* SecureRandom.SecureRandom; + const mockAgentPath = yield* path.fromFileUrl( + new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), + ); + const workspace = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-ag-bg-wait-" }); + type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"]; + type SessionUpdateHandler = Parameters[0]; + let sessionUpdate: SessionUpdateHandler | undefined; + let promptCalls = 0; + const foregroundStarted = yield* Deferred.make(); + const finishForeground = yield* Deferred.make(); + const finishPrompt = yield* Deferred.make(); + + const instanceId = ProviderInstanceId.make("antigravity-bg-wait-test"); + const adapter = yield* makeAntigravityAdapterV2({ + instanceId, + selfInvocation: yield* resolveSelfInvocation(), + makeRuntime: (input) => + makeAntigravityAcpRuntime({ + ...input, + childProcessSpawner, + spawn: { + command: process.execPath, + args: [mockAgentPath], + cwd: input.cwd, + env: { T3_ACP_ANTIGRAVITY: "1" }, + }, + }).pipe( + Effect.provideService(SecureRandom.SecureRandom, crypto), + Effect.map((runtime): RuntimeService => ({ + ...runtime, + handleSessionUpdate: (handler) => + Effect.sync(() => { + sessionUpdate = handler; + }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))), + prompt: (_payload, promptOptions) => + Effect.gen(function* () { + promptCalls += 1; + if (promptOptions?.dispatched !== undefined) { + yield* Deferred.succeed(promptOptions.dispatched, undefined); + } + const send = sessionUpdate!; + const emit = (update: EffectAcpSchema.SessionUpdate) => + send( + normalizeAntigravitySessionUpdate({ sessionId: "mock-session-1", update }), + ); + yield* emit({ + sessionUpdate: "tool_call", + toolCallId: "call_daemon", + title: "Dev server", + kind: "execute", + status: "in_progress", + rawInput: { CommandLine: "npm run dev", IsDaemon: true }, + }); + yield* emit({ + sessionUpdate: "tool_call", + toolCallId: "call_fg", + title: "Unit tests", + kind: "execute", + status: "in_progress", + rawInput: { CommandLine: "npm test", IsDaemon: false }, + }); + yield* Deferred.succeed(foregroundStarted, undefined); + yield* Deferred.await(finishForeground); + yield* emit({ + sessionUpdate: "tool_call_update", + toolCallId: "call_fg", + status: "completed", + rawOutput: "Command output:\nALL_TESTS_OK\n", + }); + yield* Deferred.await(finishPrompt); + return { stopReason: "end_turn" as const }; + }), + })), + ), + withProcess: (_stop, task) => task, + defaultModel: Effect.undefined, + }); + + const threadId = ThreadId.make("thread-antigravity-bg-wait"); + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: workspace, + }); + const modelSelection = { instanceId, model: "gemini-test-low" } as const; + const session = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make("provider-session-antigravity-bg-wait"), + modelSelection, + runtimePolicy, + }); + const providerThread = yield* session.ensureThread({ + threadId, + modelSelection, + runtimePolicy, + }); + const eventsFiber = yield* session.events.pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runCollect, + Effect.forkScoped, + ); + const now = yield* DateTime.now; + yield* session.startTurn({ + appThread: { + createdBy: "user", + creationSource: "web", + id: threadId, + projectId: ProjectId.make("project-antigravity-bg-wait"), + title: "Antigravity foreground wait", + providerInstanceId: instanceId, + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: workspace, + activeProviderThreadId: providerThread.id, + lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId }, + forkedFrom: null, + createdAt: now, + updatedAt: now, + archivedAt: null, + settledOverride: null, + settledAt: null, + lastVisitedAt: null, + deletedAt: null, + }, + threadId, + runId: RunId.make("run-antigravity-bg-wait"), + runOrdinal: 1, + providerTurnOrdinal: 1, + attemptId: RunAttemptId.make("attempt-antigravity-bg-wait"), + rootNodeId: NodeId.make("node-antigravity-bg-wait"), + providerThread, + message: { + createdBy: "user", + creationSource: "web", + messageId: MessageId.make("message-antigravity-bg-wait"), + text: "start dev server and run tests", + attachments: [], + }, + modelSelection, + runtimePolicy, + }); + + yield* Deferred.await(foregroundStarted); + assert.isDefined(session.awaitBackgroundTasks); + const waitFiber = yield* session + .awaitBackgroundTasks({ + providerThread, + taskIds: ["call_fg"], + awaited: true, + }) + .pipe(Effect.forkScoped({ startImmediately: true })); + assert.isUndefined(waitFiber.pollUnsafe()); + yield* Deferred.succeed(finishForeground, undefined); + const waited = yield* Fiber.join(waitFiber); + assert.deepEqual(waited, { matched: ["call_fg"] }); + + yield* Deferred.succeed(finishPrompt, undefined); + const events = Array.from(yield* Fiber.join(eventsFiber)); + assert.equal(promptCalls, 1); + const terminal = events.filter((event) => event.type === "turn.terminal"); + assert.equal(terminal.length, 1); + assert.equal(terminal[0]?.status, "completed"); + }).pipe(Effect.provide(layerSession), Effect.scoped), + ); + + it.effect( + "re-attaches a continuation prompt when end_turn arrives while an unreleased foreground command is open", + () => + Effect.gen(function* () { + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const crypto = yield* SecureRandom.SecureRandom; + const mockAgentPath = yield* path.fromFileUrl( + new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), + ); + const workspace = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-ag-bg-cont-" }); + type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"]; + type SessionUpdateHandler = Parameters[0]; + let sessionUpdate: SessionUpdateHandler | undefined; + const receivedPrompts: Array = []; + + const instanceId = ProviderInstanceId.make("antigravity-bg-continuation-test"); + const adapter = yield* makeAntigravityAdapterV2({ + instanceId, + selfInvocation: yield* resolveSelfInvocation(), + makeRuntime: (input) => + makeAntigravityAcpRuntime({ + ...input, + childProcessSpawner, + spawn: { + command: process.execPath, + args: [mockAgentPath], + cwd: input.cwd, + env: { T3_ACP_ANTIGRAVITY: "1" }, + }, + }).pipe( + Effect.provideService(SecureRandom.SecureRandom, crypto), + Effect.map((runtime): RuntimeService => ({ + ...runtime, + handleSessionUpdate: (handler) => + Effect.sync(() => { + sessionUpdate = handler; + }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))), + prompt: (payload, promptOptions) => + Effect.gen(function* () { + receivedPrompts.push(JSON.stringify(payload.prompt)); + if (promptOptions?.dispatched !== undefined) { + yield* Deferred.succeed(promptOptions.dispatched, undefined); + } + const send = sessionUpdate!; + const emit = (update: EffectAcpSchema.SessionUpdate) => + send( + normalizeAntigravitySessionUpdate({ sessionId: "mock-session-1", update }), + ); + if (receivedPrompts.length === 1) { + yield* emit({ + sessionUpdate: "tool_call", + toolCallId: "call_build", + title: "Build package", + kind: "execute", + status: "in_progress", + rawInput: { CommandLine: "npm run build", IsDaemon: false }, + }); + return { stopReason: "end_turn" as const }; + } + yield* emit({ + sessionUpdate: "tool_call_update", + toolCallId: "call_build", + status: "completed", + rawOutput: "Command output:\nBUILD_OK\n", + }); + yield* emit({ + sessionUpdate: "agent_message_chunk", + content: { type: "text", text: "Build finished." }, + }); + return { stopReason: "end_turn" as const }; + }), + })), + ), + withProcess: (_stop, task) => task, + defaultModel: Effect.undefined, + }); + + const threadId = ThreadId.make("thread-antigravity-bg-continuation"); + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: workspace, + }); + const modelSelection = { instanceId, model: "gemini-test-low" } as const; + const session = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make("provider-session-antigravity-bg-continuation"), + modelSelection, + runtimePolicy, + }); + const providerThread = yield* session.ensureThread({ + threadId, + modelSelection, + runtimePolicy, + }); + const eventsFiber = yield* session.events.pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runCollect, + Effect.forkScoped, + ); + const now = yield* DateTime.now; + yield* session.startTurn({ + appThread: { + createdBy: "user", + creationSource: "web", + id: threadId, + projectId: ProjectId.make("project-antigravity-bg-continuation"), + title: "Antigravity continuation fallback", + providerInstanceId: instanceId, + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: workspace, + activeProviderThreadId: providerThread.id, + lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId }, + forkedFrom: null, + createdAt: now, + updatedAt: now, + archivedAt: null, + settledOverride: null, + settledAt: null, + lastVisitedAt: null, + deletedAt: null, + }, + threadId, + runId: RunId.make("run-antigravity-bg-continuation"), + runOrdinal: 1, + providerTurnOrdinal: 1, + attemptId: RunAttemptId.make("attempt-antigravity-bg-continuation"), + rootNodeId: NodeId.make("node-antigravity-bg-continuation"), + providerThread, + message: { + createdBy: "user", + creationSource: "web", + messageId: MessageId.make("message-antigravity-bg-continuation"), + text: "build the project", + attachments: [], + }, + modelSelection, + runtimePolicy, + }); + + const events = Array.from(yield* Fiber.join(eventsFiber)); + assert.equal(receivedPrompts.length, 2); + assert.include(receivedPrompts[1] ?? "", ""); + assert.include(receivedPrompts[1] ?? "", "npm run build"); + const completedCommand = events.findLast( + (event) => + event.type === "turn_item.updated" && + event.turnItem.nativeItemRef?.nativeId === "call_build", + ); + assert.equal( + completedCommand?.type === "turn_item.updated" ? completedCommand.turnItem.status : null, + "completed", + ); + const terminals = events.filter((event) => event.type === "turn.terminal"); + assert.equal(terminals.length, 1); + assert.equal(terminals[0]?.status, "completed"); + }).pipe(Effect.provide(layerSession), Effect.scoped), + ); +}); diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts index 8566cbb83f9e9..f9b8749c6f430 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts @@ -30,7 +30,9 @@ import { import { ANTIGRAVITY_SUBAGENT_BATCH_TITLE, antigravitySubagentLaunches, + makeAntigravitySubagentStatusReader, describeAntigravitySubagentLaunches, + readAntigravityTaskIds, } from "../../provider/acp/AntigravityChildWork.ts"; import { readAntigravityClientTextFile } from "../../provider/acp/AntigravityClientFiles.ts"; import { watchAntigravityPromptOutcome } from "../../provider/acp/AntigravityTurnOutcome.ts"; @@ -39,6 +41,8 @@ import { antigravitySubagentOutput, classifyAntigravitySubagentToolCall, extractAntigravityUserInputQuestion, + isAntigravityForegroundCommand, + isAntigravityForegroundCommandOpen, makeAntigravityReadRepair, makeAntigravityUserInputResponse, normalizeAntigravityToolCall, @@ -53,6 +57,12 @@ import { const ANTIGRAVITY_PROVIDER = ProviderDriverKind.make("antigravity"); +// Over ACP, ending `session/prompt` detaches Antigravity's update and permission streams +// before a backgrounded `run_command` finishes, stranding its wakeup without a listener. +const ANTIGRAVITY_BACKGROUND_WAIT_INSTRUCTIONS = `### Background work you wait on + +Over ACP, ending your turn closes T3 Code's active stream before background work can report back. When a foreground \`run_command\` (\`IsDaemon\` false) moves to the background, call \`t3_background_wait\` with its task ID instead of ending your turn. After native subagent launches, pass their conversation IDs to the same tool. A completed launch means the worker was created, not that it finished. Repeat the wait when it returns before the results arrive. After all awaited subagent results or failures arrive, call the tool with those IDs and \`waiting: false\` before giving your final answer. Also use \`waiting: false\` for processes deliberately left running, such as dev servers and watchers.`; + const AntigravityProviderCapabilitiesV2 = { ...AcpProviderCapabilitiesV2, sessions: { @@ -102,7 +112,7 @@ export interface AntigravityAdapterV2Options { /** * Native subagent tools report no child session ids, so children stay read-only. - * Only permission prompts carry the launch; NativeChildWorkQuery matches their ids by this text. + * NativeChildWorkQuery matches launches against persisted records by this text. */ const extractAntigravitySubagentUpdate: NonNullable = ( toolCall, @@ -186,7 +196,10 @@ export function makeAntigravityAcpAdapterFlavor( ), ), prompt: (payload, promptOptions) => - Effect.sync(reads.reset).pipe(Effect.andThen(runtime.prompt(payload, promptOptions))), + Effect.sync(reads.reset).pipe( + Effect.andThen(runtime.prompt(payload, promptOptions)), + Effect.tap(() => updates.withPermit(Effect.void)), + ), handleSessionUpdate: (handler) => { projectUpdate = handler; return runtime.handleSessionUpdate((notification) => @@ -218,6 +231,48 @@ export function makeAntigravityAcpAdapterFlavor( supportsNativeGoals: options.supportsNativeGoals ?? Effect.succeed(false), // Agents that advertise HTTP MCP skip the stdio bridge process; others keep stdio. mcpOverHttp: true, + mcpInstructions: ANTIGRAVITY_BACKGROUND_WAIT_INSTRUCTIONS, + foregroundCommandWait: { + ...(profileDirectory === undefined + ? {} + : { + resolveTaskIds: (sessionId, tools, requestedIds) => + readAntigravityTaskIds( + profileDirectory, + sessionId, + tools.map((tool) => ({ + id: tool.toolCallId, + input: tool.data.rawInput, + command: tool.kind === "execute", + })), + requestedIds, + ), + }), + isOpenForegroundCommand: isAntigravityForegroundCommandOpen, + isForegroundCommand: isAntigravityForegroundCommand, + buildContinuationPrompt: (openTools, { hasT3Mcp }) => { + const commands = openTools + .map((tool) => tool.command ?? tool.title) + .filter((value): value is string => Boolean(value?.trim())) + .slice(0, 3); + const summary = commands.length > 0 ? ` (${commands.join("; ")})` : ""; + const hasSubagents = openTools.some( + (tool) => classifyAntigravitySubagentToolCall(tool) === "subagent", + ); + const waitInstruction = + hasT3Mcp && hasSubagents + ? "Call `t3_background_wait` with the native subagents' conversation IDs while their results are pending. After all awaited work finishes, release the wait with `waiting: false` and finish the user's request." + : hasT3Mcp + ? "If it is still running, call `t3_background_wait` with its task ID until its `` completion arrives, or pass `waiting: false` only if it is meant to stay running in the background." + : "If it is still running, wait for its `` completion in this turn before ending your turn."; + return [ + { + type: "text", + text: `\nBackground work started in this turn${summary} was still pending when your turn ended. ${waitInstruction} Once its output arrives, continue and finish the user's request.\n`, + }, + ]; + }, + }, sessionCarriesPullRequestLinking: antigravityAppendsSystemPrompt, makeRuntime, buildAttachmentPrompt: ({ @@ -242,6 +297,12 @@ export function makeAntigravityAcpAdapterFlavor( ), // Loading history replays tool calls; resume avoids replay. subagentsIdleOnTurnCompletion: true, + ...(profileDirectory === undefined + ? {} + : { + makeSubagentStatusReader: (sessionId: string) => + makeAntigravitySubagentStatusReader(profileDirectory, sessionId), + }), ...(options.onSessionEvent === undefined ? {} : { onSessionEvent: options.onSessionEvent }), applyModelSelection: Effect.fn("AntigravityAdapterV2.applyModelSelection")(function* ({ runtime, diff --git a/apps/server/src/orchestration-v2/ThreadManagementService.ts b/apps/server/src/orchestration-v2/ThreadManagementService.ts index bfd676d7a3a22..a36e5149bd536 100644 --- a/apps/server/src/orchestration-v2/ThreadManagementService.ts +++ b/apps/server/src/orchestration-v2/ThreadManagementService.ts @@ -1589,7 +1589,7 @@ const make = Effect.gen(function* () { const { matched } = yield* runtime.value .awaitBackgroundTasks({ providerThread, taskIds: input.taskIds, awaited: input.awaited }) .pipe( - Effect.timeout("15 seconds"), + Effect.timeout("5 minutes"), Effect.mapError( (cause) => new ThreadManagementBackgroundWaitError({ diff --git a/apps/server/src/provider/acp/AntigravityChildWork.ts b/apps/server/src/provider/acp/AntigravityChildWork.ts index ea12e0e2b20de..faeda951db666 100644 --- a/apps/server/src/provider/acp/AntigravityChildWork.ts +++ b/apps/server/src/provider/acp/AntigravityChildWork.ts @@ -3,6 +3,8 @@ import * as NodeFS from "node:fs"; import * as NodeFSP from "node:fs/promises"; import * as NodeSqlite from "node:sqlite"; import * as NodeURL from "node:url"; +import * as NodeUtil from "node:util"; +import type { AcpToolCallState } from "@t3tools/provider-acp/server/runtimeModel"; import type { OrchestrationV2NativeChildStep, @@ -14,7 +16,11 @@ import * as Predicate from "effect/Predicate"; import * as Schema from "effect/Schema"; import { antigravityManagedPath, antigravityProfileRoot } from "./AntigravityProfilePaths.ts"; -import { boundAntigravityToolText, isCutAntigravityToolText } from "./AntigravityProtocol.ts"; +import { + boundAntigravityToolText, + isCutAntigravityToolText, + sanitizeAntigravityToolPayload, +} from "./AntigravityProtocol.ts"; // Field numbers from the runtime's trajectory protos (exa.cortex_pb). const STEP_METADATA = 5; @@ -22,6 +28,10 @@ const METADATA_TOOL_CALL = 4; const STEP_PLANNER_RESPONSE = 20; const PLANNER_TOOL_CALLS = 7; const STEP_INVOKE_SUBAGENT = 143; +const STEP_RUN_COMMAND = 28; +const RUN_COMMAND_ID = 13; +const STEP_GENERIC = 140; +const STEP_TASK_DETAILS = 148; const INVOKE_SPECS = 9; const INVOKE_RESULTS = 10; const INVOKE_SUBAGENT_STEP_TYPE = 127; @@ -44,10 +54,12 @@ interface AntigravityChildLaunch { readonly prompt: string; } +const SubagentLaunch = Schema.Struct({ Role: Schema.String, Prompt: Schema.String }); const decodeLaunchInput = Schema.decodeUnknownOption( - Schema.Struct({ - Subagents: Schema.NonEmptyArray(Schema.Struct({ Role: Schema.String, Prompt: Schema.String })), - }), + Schema.Union([ + Schema.Struct({ Subagents: Schema.NonEmptyArray(SubagentLaunch) }), + SubagentLaunch, + ]), ); /** `invoke_subagent` arguments, from the permission prompt or the persisted record. */ @@ -56,7 +68,10 @@ export function antigravitySubagentLaunches( ): ReadonlyArray | 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, + })), ), ); } @@ -187,6 +202,160 @@ const plannerCallIdsAt = (database: NodeSqlite.DatabaseSync, plannerIdx: number) return planner === undefined ? undefined : plannerInvokeCallIds(planner); }; +/** ACP omits native command/child IDs; the parent's persisted tool record owns that mapping. */ +export const readAntigravityTaskIds = Effect.fn("readAntigravityTaskIds")(function* ( + profileDirectory: string, + rootSessionId: string, + tools: ReadonlyArray<{ readonly id: string; readonly input: unknown; readonly command: boolean }>, + requestedIds: ReadonlyArray, +) { + if (!NATIVE_ID.test(rootSessionId)) return new Map>(); + return yield* Effect.tryPromise({ + try: async () => { + const result = new Map>(); + const root = await antigravityProfileRoot(profileDirectory); + if (root === undefined) return result; + // The CLI's app-data-directory option selects either native session store. + const file = + (await antigravityManagedPath( + root, + ["antigravity-cli", "conversations", `${rootSessionId}.db`], + "file", + )) ?? + (await antigravityManagedPath( + root, + ["antigravity-acp", "conversations", `${rootSessionId}.db`], + "file", + )); + if (file === undefined) return result; + const database = new NodeSqlite.DatabaseSync(file.path, { readOnly: true }); + try { + const owners = new Map(tools.map(({ id }) => [id, id])); + for (const { id, input, command } of tools) { + const step = /^(.*):(\d+)$/.exec(id); + if (step?.[1] !== rootSessionId) continue; + const payload = payloadOf( + database + .prepare( + "SELECT step_payload FROM steps WHERE idx = ? AND step_format = 0 AND length(step_payload) <= ?", + ) + .get(Number(step[2]), MAX_STEP_BYTES), + ); + const calls = + payload === undefined + ? [] + : safely((bytes) => + messages( + message(bytes, STEP_PLANNER_RESPONSE) ?? new Uint8Array(), + PLANNER_TOOL_CALLS, + ).map((call) => ({ + id: text(call, 1), + name: text(call, 2), + args: text(call, 3), + })), + )(payload); + const candidates = calls?.filter((call) => + command + ? call.name === "run_command" + : call.name === "invoke_subagent" || call.name === "start_subagent", + ); + const matches = + candidates?.length === 1 + ? candidates + : candidates?.filter( + (call) => + call.args !== undefined && + input !== undefined && + Option.exists(decodeArgument(call.args), (args) => + NodeUtil.isDeepStrictEqual(sanitizeAntigravityToolPayload(args), input), + ), + ); + const match = matches?.length === 1 ? matches[0]?.id : undefined; + owners.delete(id); + if (match !== undefined && !owners.has(match)) owners.set(match, id); + } + if (owners.size === 0) return result; + const byIndex = database.prepare( + "SELECT idx, metadata FROM steps WHERE idx = ? AND step_format = 0 AND length(metadata) <= ?", + ); + // Native command IDs encode their trajectory row; the payload still has to prove ownership. + const indexed = requestedIds.flatMap((id) => { + const step = /^(.+)\/task-(\d+)$/.exec(id); + if (step?.[1] !== rootSessionId) return []; + const idx = Number(step[2]); + if (!Number.isSafeInteger(idx)) return []; + const row = byIndex.get(idx, MAX_STEP_BYTES); + return row === undefined ? [] : [row]; + }); + let metadataBytes = 0; + let bytes = 0; + let rows = 0; + // Cortex step types: RUN_COMMAND=21, INVOKE_SUBAGENT=127, GENERIC=132 (exa.cortex_pb). + const recent = database + .prepare( + "SELECT idx, CASE WHEN step_type IN (21, 127, 132) AND step_format = 0 AND length(metadata) <= ? THEN metadata END AS metadata FROM steps ORDER BY idx DESC LIMIT 2048", + ) + .iterate(MAX_STEP_BYTES); + function* candidates() { + yield* indexed; + yield* recent; + } + for (const row of candidates()) { + const metadata = row.metadata; + if (!(metadata instanceof Uint8Array)) continue; + metadataBytes += metadata.length; + if (metadataBytes > MAX_SCAN_BYTES) break; + const callId = safely((data) => text(message(data, METADATA_TOOL_CALL), 1))(metadata); + const owner = callId === undefined ? undefined : owners.get(callId); + if (owner === undefined || result.has(owner)) continue; + const payload = payloadOf( + database + .prepare("SELECT step_payload FROM steps WHERE idx = ? AND length(step_payload) <= ?") + .get(row.idx!, MAX_STEP_BYTES), + ); + if (payload === undefined) continue; + bytes += payload.length; + if (++rows > MAX_INVOKE_ROWS || bytes > MAX_SCAN_BYTES) break; + const record = safely((data) => { + const callId = text(message(message(data, STEP_METADATA), METADATA_TOOL_CALL), 1); + const taskId = text(message(data, STEP_TASK_DETAILS), 1); + const commandId = text(message(data, STEP_RUN_COMMAND), RUN_COMMAND_ID); + const genericPayload = message(message(message(data, STEP_GENERIC), 2), 6); + const genericChildren = + text(genericPayload, 1) === "type.googleapis.com/exa.cortex.core.tools.InvokeSubagent" + ? messages(message(genericPayload, 2) ?? new Uint8Array(), 2) + : []; + const children = messages( + message(data, STEP_INVOKE_SUBAGENT) ?? new Uint8Array(), + INVOKE_RESULTS, + ) + .concat(genericChildren) + .flatMap((child) => { + const id = text(child, 1); + return id === undefined ? [] : [id]; + }); + const id = taskId || commandId; + return { callId, ids: children.length > 0 ? children : id ? [id] : [] }; + })(payload); + if ( + record !== undefined && + record.callId === callId && + record.ids.length > 0 && + !result.has(owner) + ) { + result.set(owner, record.ids); + if (result.size === owners.size) break; + } + } + return result; + } finally { + database.close(); + } + }, + catch: (cause) => new AntigravityChildWorkReadError({ cause }), + }); +}); + /** * Auto-approved calls carry `:`; the record with that planner call's id * is the proof. Permission prompts carry a random id, so the launch text must match one record @@ -408,6 +577,68 @@ async function readChildTranscript( } } +export function makeAntigravitySubagentStatusReader(profileDirectory: string, sessionId: string) { + const children = new Map>(); + return Effect.fn("readAntigravitySubagentStatuses")(function* ( + tools: ReadonlyArray, + ) { + const missing = tools.filter((tool) => !children.has(tool.toolCallId)); + if (missing.length > 0) { + const resolved = yield* readAntigravityTaskIds( + profileDirectory, + sessionId, + missing.map((tool) => ({ + id: tool.toolCallId, + input: tool.data.rawInput, + command: false, + })), + [], + ); + for (const tool of missing) { + const ids = resolved.get(tool.toolCallId); + if (ids && ids.length === antigravitySubagentLaunches(tool.data.rawInput)?.length) { + children.set(tool.toolCallId, ids); + } + } + } + const result = new Map(); + if (children.size === 0) return result; + return yield* Effect.tryPromise({ + try: async () => { + const root = await antigravityProfileRoot(profileDirectory); + if (root === undefined) return result; + for (const store of ["antigravity-cli", "antigravity-acp"]) { + const file = await antigravityManagedPath( + root, + [store, "conversation_summaries.db"], + "file", + ); + if (file === undefined) continue; + const db = new NodeSqlite.DatabaseSync(file.path, { readOnly: true }); + try { + const query = db.prepare( + "SELECT status FROM conversation_summaries WHERE conversation_id = ? AND parent_conversation_id = ?", + ); + for (const tool of tools) { + const ids = children.get(tool.toolCallId); + if (!ids || result.has(tool.toolCallId)) continue; + const states = ids.map((id) => query.get(id, sessionId)?.status); + if (states.includes("CASCADE_RUN_STATUS_RUNNING")) + result.set(tool.toolCallId, "running"); + else if (states.every((state) => state === "CASCADE_RUN_STATUS_IDLE")) + result.set(tool.toolCallId, "idle"); + } + } finally { + db.close(); + } + } + return result; + }, + catch: (cause) => new AntigravityChildWorkReadError({ cause }), + }); + }); +} + class AntigravityChildWorkReadError extends Schema.TaggedError()( "AntigravityChildWorkReadError", { cause: Schema.Defect() }, diff --git a/apps/server/src/provider/acp/AntigravityProtocol.ts b/apps/server/src/provider/acp/AntigravityProtocol.ts index 5b74756a1de11..f2ffcb0f9326f 100644 --- a/apps/server/src/provider/acp/AntigravityProtocol.ts +++ b/apps/server/src/provider/acp/AntigravityProtocol.ts @@ -28,6 +28,9 @@ const NativeToolFields = Schema.Struct({ CommandLine: Schema.optional(Schema.String), command_line: Schema.optional(Schema.String), commandLine: Schema.optional(Schema.String), + IsDaemon: Schema.optional(Schema.Boolean), + isDaemon: Schema.optional(Schema.Boolean), + is_daemon: Schema.optional(Schema.Boolean), cwd: Schema.optional(Schema.String), Cwd: Schema.optional(Schema.String), WorkingDirectory: Schema.optional(Schema.String), @@ -439,12 +442,18 @@ export function normalizeAntigravityToolCall( const aggregatedOutput = nativeOutput === undefined ? undefined : boundText(nativeOutput); const exitCode = output?.exitCode ?? output?.exit_code; const imagePath = localImagePath(output?.imagePath); + const isDaemon = + input?.IsDaemon ?? + input?.isDaemon ?? + input?.is_daemon ?? + (toolCall.data.isDaemon === true ? true : undefined); const sanitizedData = sanitizeAntigravityToolPayload(toolCall.data); const data: Record = Predicate.isObject(sanitizedData) ? sanitizedData : {}; const kind = toolCall.kind ?? (command !== undefined ? "execute" : undefined); if (kind !== undefined) data.kind = kind; if (command !== undefined) data.command = command; if (cwd !== undefined) data.cwd = cwd; + if (isDaemon === true) data.isDaemon = true; if (imagePath !== undefined) data.imagePath = imagePath; if (kind === "edit") { const content = Array.isArray(data.content) ? data.content : []; @@ -481,8 +490,10 @@ export function normalizeAntigravityToolCall( } const ANTIGRAVITY_SUBAGENT_TITLES = new Set([ + "Run start_subagent", "Running start_subagent", "Run start_subagent?", + "Run invoke_subagent", "Running invoke_subagent", "Run invoke_subagent?", ]); @@ -507,3 +518,20 @@ export function antigravitySubagentOutput(toolCall: AcpToolCallState): string | const output = toolCall.data.rawOutput; return typeof output === "string" && output.trim() ? boundText(output.trim()) : undefined; } + +export function isAntigravityForegroundCommand(toolCall: AcpToolCallState): boolean { + return ( + (toolCall.kind === "execute" && toolCall.data.isDaemon !== true) || + classifyAntigravitySubagentToolCall(toolCall) === "subagent" + ); +} + +export function isAntigravityForegroundCommandOpen(toolCall: AcpToolCallState): boolean { + return ( + isAntigravityForegroundCommand(toolCall) && + (toolCall.status === "pending" || + toolCall.status === "inProgress" || + (toolCall.status === "completed" && + classifyAntigravitySubagentToolCall(toolCall) === "subagent")) + ); +} diff --git a/apps/server/src/provider/agentContextBudget.json b/apps/server/src/provider/agentContextBudget.json index 6658b3beaea3b..0b2c6312eeb8d 100644 --- a/apps/server/src/provider/agentContextBudget.json +++ b/apps/server/src/provider/agentContextBudget.json @@ -1,5 +1,5 @@ { "claudeSystemAppendBytes": 6037, "codexAdditionalContextBytes": 7431, - "mcpToolListJsonBytes": 52145 + "mcpToolListJsonBytes": 52152 } diff --git a/docs/user/providers-antigravity.md b/docs/user/providers-antigravity.md index c62cc56b310d6..170049d7f41db 100644 --- a/docs/user/providers-antigravity.md +++ b/docs/user/providers-antigravity.md @@ -98,6 +98,8 @@ without the turns you removed. Manual context compaction is unavailable through Antigravity's ACP runtime, even though its CLI has `/compact`. Send `/clear` when you need a fresh context. +Antigravity’s native `schedule` tool does not wake a completed T3 thread. For one-shot timers and recurring jobs, use T3 Code’s [scheduled tasks](./project-settings.md#scheduled-tasks-on-mobile). + ### Skills and attachments Put project skills in `.agents/skills`. T3 Code also reads `.gemini/skills` and the diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index 8ededca9258c0..49fa3f1341fa7 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -339,6 +339,27 @@ export function acpPerTurnPromptUsage( }; } +function mergeAcpPromptUsage( + previous: EffectAcpSchema.Usage | undefined, + incoming: EffectAcpSchema.Usage | null | undefined, +): EffectAcpSchema.Usage | undefined { + if (incoming == null) return previous; + if (previous === undefined) return incoming; + const sumOptional = (left: number | null | undefined, right: number | null | undefined) => + left == null && right == null ? undefined : (left ?? 0) + (right ?? 0); + const cachedReadTokens = sumOptional(previous.cachedReadTokens, incoming.cachedReadTokens); + const cachedWriteTokens = sumOptional(previous.cachedWriteTokens, incoming.cachedWriteTokens); + const thoughtTokens = sumOptional(previous.thoughtTokens, incoming.thoughtTokens); + return { + inputTokens: previous.inputTokens + incoming.inputTokens, + outputTokens: previous.outputTokens + incoming.outputTokens, + totalTokens: previous.totalTokens + incoming.totalTokens, + ...(cachedReadTokens === undefined ? {} : { cachedReadTokens }), + ...(cachedWriteTokens === undefined ? {} : { cachedWriteTokens }), + ...(thoughtTokens === undefined ? {} : { thoughtTokens }), + }; +} + interface AcpPromptOutcomeFailure { readonly failure: OrchestrationV2ProviderFailure; readonly threadDisposition: "reusable" | "broken"; @@ -500,6 +521,11 @@ export interface AcpAdapterV2Flavor { event: AcpSessionRuntime.AcpSessionRuntimeEvent, ) => Effect.Effect; readonly subagentsIdleOnTurnCompletion?: boolean; + readonly makeSubagentStatusReader?: ( + sessionId: string, + ) => ( + tools: ReadonlyArray, + ) => Effect.Effect, Error>; readonly supportsCompaction?: boolean; /** Sends `/compact` as a prompt, only to sessions whose advertised commands include `compact`. */ readonly compactViaAdvertisedCommand?: boolean; @@ -633,6 +659,24 @@ export interface AcpAdapterV2Flavor { readonly sessionCarriesPullRequestLinking?: ( initializeResult: EffectAcpSchema.InitializeResponse, ) => boolean; + /** Extra MCP guidance appended inside `` when T3 MCP is active. */ + readonly mcpInstructions?: string; + /** Keeps the ACP prompt stream attached when `end_turn` arrives before foreground commands settle. */ + readonly foregroundCommandWait?: { + readonly isOpenForegroundCommand: (toolCall: AcpToolCallState) => boolean; + readonly isForegroundCommand?: (toolCall: AcpToolCallState) => boolean; + readonly resolveTaskIds?: ( + sessionId: string, + tools: ReadonlyArray, + requestedIds: ReadonlyArray, + ) => Effect.Effect>, Error>; + readonly buildContinuationPrompt: ( + openTools: ReadonlyArray, + context: { readonly hasT3Mcp: boolean }, + ) => ReadonlyArray; + readonly waitSlice?: Duration.Input; + readonly maxContinuations?: number; + }; } function acpSupportsImagePrompts(input: { @@ -1502,6 +1546,9 @@ interface ActiveAcpTurn { { readonly status: "completed" | "failed"; readonly output?: string } | null >; readonly persistentBackgroundTaskIds: Set; + readonly releasedForegroundTaskIds: Set; + readonly foregroundTaskIds: Map>; + readonly foregroundToolWaiters: Set>; /** Monitor end notices lack output; wait for hydration or the safety timeout. */ readonly awaitingBackgroundHydration: Set; readonly pendingInjectedReport: Set; @@ -4113,6 +4160,69 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( return next ?? current; }); + // Runs on every tool-call emission and turn transition inside untraced hot paths. + const notifyForegroundToolWaiters = Effect.fnUntraced(function* (context: ActiveAcpTurn) { + if (context.foregroundToolWaiters.size === 0) return; + const waiters = [...context.foregroundToolWaiters]; + context.foregroundToolWaiters.clear(); + for (const waiter of waiters) { + yield* Deferred.succeed(waiter, undefined).pipe(Effect.ignore); + } + }); + + const unreleasedOpenForegroundTools = ( + context: ActiveAcpTurn, + requestedTaskIds?: ReadonlySet, + ): ReadonlyArray => + flavor.foregroundCommandWait === undefined + ? [] + : [...context.tools.values()].filter( + (tool) => + !context.releasedForegroundTaskIds.has(tool.toolCallId) && + (context.foregroundTaskIds.get(tool.toolCallId) ?? [tool.toolCallId]).some( + (id) => + !context.releasedForegroundTaskIds.has(id) && + (requestedTaskIds === undefined || + requestedTaskIds.has(tool.toolCallId) || + requestedTaskIds.has(id)), + ) && + flavor.foregroundCommandWait!.isOpenForegroundCommand(tool), + ); + + const waitUntilForegroundToolsSettle = Effect.fn( + "AcpAdapterV2.waitUntilForegroundToolsSettle", + )(function* ( + context: ActiveAcpTurn, + bound: Duration.Input, + requestedTaskIds?: ReadonlySet, + ) { + yield* Effect.gen(function* () { + while ( + !context.finalized && + !context.interrupted && + unreleasedOpenForegroundTools(context, requestedTaskIds).length > 0 + ) { + const signal = yield* Deferred.make(); + context.foregroundToolWaiters.add(signal); + if ( + context.finalized || + context.interrupted || + unreleasedOpenForegroundTools(context, requestedTaskIds).length === 0 + ) { + context.foregroundToolWaiters.delete(signal); + break; + } + yield* Deferred.await(signal).pipe( + Effect.ensuring( + Effect.sync(() => { + context.foregroundToolWaiters.delete(signal); + }), + ), + ); + } + }).pipe(Effect.timeoutOption(bound), Effect.asVoid); + }); + emitTool = Effect.fnUntraced(function* ( context: ActiveAcpTurn, incoming: AcpToolCallState, @@ -4158,6 +4268,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( ? toolCall : { ...toolCall, backgroundCommandTaskId }, ); + yield* notifyForegroundToolWaiters(context); // A failure racing Stop needs the provider's cancellation signal before relabeling it. const previousStatus = previous === undefined ? undefined : toolStatus(previous.status); if ( @@ -5281,6 +5392,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( // Native close sends cancelled idle before acknowledging the user's Stop. if (work.stopReason === "cancelled" && pendingStopCloseTurn === context) { context.interrupted = true; + yield* notifyForegroundToolWaiters(context); } const failure = context.interrupted ? undefined @@ -8098,6 +8210,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const threadDisposition = options?.threadDisposition ?? "reusable"; context.finalizedStatus = settledStatus; context.finalized = true; + yield* notifyForegroundToolWaiters(context); const watchdog = context.inactivityWatchdog; context.inactivityWatchdog = undefined; if (watchdog !== undefined) { @@ -8520,6 +8633,9 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( ...(previousInstructionState === undefined || compactionMarker !== undefined ? {} : { previousState: previousInstructionState }), + ...(flavor.mcpInstructions === undefined + ? {} + : { mcpInstructions: flavor.mcpInstructions }), }); const sessionSetup = yield* Ref.get(activeSessionSetup); const runtimeInstructions = buildRuntimeInstructions({ @@ -8549,6 +8665,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( } return { prompt, + hasT3Mcp: instructionState.hasT3Mcp, instructionState: text === messageText ? undefined : instructionState, runtimeInstructions: sendRuntimeInstructions ? runtimeInstructions : undefined, compactionMarker, @@ -8732,6 +8849,9 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( toolCallIdsByBackgroundTaskId: new Map(), backgroundCommands: new Map(), persistentBackgroundTaskIds: new Set(), + releasedForegroundTaskIds: new Set(), + foregroundTaskIds: new Map(), + foregroundToolWaiters: new Set(), awaitingBackgroundHydration: new Set(), pendingInjectedReport: new Set(), earlyInjectedReportObserved: false, @@ -8897,10 +9017,6 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( } return; } - const checkPromptOutcome = - flavor.watchPromptOutcome === undefined - ? undefined - : yield* flavor.watchPromptOutcome(requestedSessionId); const promptGeneration = yield* Ref.get(runtimeCallbackGeneration); const promptOptions = { dispatched: context.promptDispatched, @@ -8917,32 +9033,151 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const compactSession = isCompactionMessage(turnInput.message) ? flavor.compactSession : undefined; - yield* ( - compactSession === undefined - ? sendPromptWhenIdle(context, () => - runtime.prompt({ prompt: promptParts!.prompt }, promptOptions), - ) - : Deferred.succeed(context.promptDispatched, undefined).pipe( - Effect.andThen(compactSession.compact(runtime, requestedSessionId)), - Effect.as({ stopReason: "end_turn" } satisfies EffectAcpSchema.PromptResponse), - ) - ).pipe( - // Settle the wire before the completion callback's permit so a settled-soft - // Stop sees the native return. Capture usage only before finalize: a late - // response must not flip a settled turn. - Effect.tap((result) => - Effect.sync(() => { - if (flavor.reportsPerTurnPromptUsage === true && !context.finalized) { - context.promptUsage = result.usage ?? undefined; - } - }).pipe( - Effect.andThen( - Deferred.succeed(context.promptWireSettled, undefined).pipe(Effect.asVoid), + const runPromptLoop = Effect.gen(function* () { + if (compactSession !== undefined) { + yield* Deferred.succeed(context.promptDispatched, undefined); + yield* compactSession.compact(runtime, requestedSessionId); + return { + result: { stopReason: "end_turn" } satisfies EffectAcpSchema.PromptResponse, + hiddenFailure: undefined, + }; + } + let currentPrompt: ReadonlyArray = promptParts!.prompt; + let isInitialPrompt = true; + let continuations = 0; + const maxContinuations = flavor.foregroundCommandWait?.maxContinuations ?? 24; + + while (true) { + const checkPromptOutcome = + flavor.watchPromptOutcome === undefined + ? undefined + : yield* flavor.watchPromptOutcome(requestedSessionId); + context.promptSentAt = yield* Clock.currentTimeMillis; + const result = yield* sendPromptWhenIdle(context, () => + Effect.suspend(() => + context.interrupted || context.finalized + ? Effect.succeed({ + stopReason: "cancelled", + }) + : runtime.prompt( + { prompt: currentPrompt }, + isInitialPrompt ? promptOptions : undefined, + ), ), - ), + ); + isInitialPrompt = false; + if (flavor.reportsPerTurnPromptUsage === true && !context.finalized) { + context.promptUsage = mergeAcpPromptUsage(context.promptUsage, result.usage); + } + const hiddenFailure = + checkPromptOutcome === undefined || + context.interrupted || + result.stopReason === "error" || + result.stopReason === "cancelled" + ? undefined + : yield* checkPromptOutcome(result); + + if ( + flavor.foregroundCommandWait === undefined || + context.interrupted || + context.finalized || + hiddenFailure !== undefined || + result.stopReason !== "end_turn" || + continuations >= maxContinuations + ) { + return { result, hiddenFailure }; + } + + yield* runtime.drainEvents; + if (context.interrupted || context.finalized) return { result, hiddenFailure }; + const openTools = yield* runtimeCallbackPermit.withPermit( + Effect.sync(() => + unreleasedOpenForegroundTools(context).filter( + (tool) => + promptParts?.hasT3Mcp === true || extractSubagentUpdate(tool) === undefined, + ), + ), + ); + if (openTools.length === 0) { + return { result, hiddenFailure }; + } + + if (continuations >= 1) { + yield* waitUntilForegroundToolsSettle(context, "10 seconds"); + if (context.interrupted || context.finalized) { + return { result, hiddenFailure }; + } + } + + const toolsForPrompt = yield* runtimeCallbackPermit.withPermit( + Effect.gen(function* () { + yield* closeTextStreams(context); + return unreleasedOpenForegroundTools(context).filter( + (tool) => + promptParts?.hasT3Mcp === true || extractSubagentUpdate(tool) === undefined, + ); + }), + ); + if (toolsForPrompt.length === 0) return { result, hiddenFailure }; + currentPrompt = flavor.foregroundCommandWait.buildContinuationPrompt( + toolsForPrompt, + { hasT3Mcp: promptParts?.hasT3Mcp === true }, + ); + continuations += 1; + } + }); + const readStatuses = flavor.makeSubagentStatusReader?.(requestedSessionId); + const observedPrompt = + readStatuses === undefined + ? runPromptLoop + : Effect.scoped( + Effect.gen(function* () { + yield* Effect.gen(function* () { + yield* Effect.sleep("3 seconds"); + if (context.finalized || context.interrupted) return; + const tools = [...context.subagents.keys()].flatMap((id) => { + const tool = context.tools.get(id); + return tool ? [tool] : []; + }); + if (tools.length === 0) return; + const statuses = yield* readStatuses(tools).pipe(Effect.option); + if (Option.isNone(statuses)) return; + yield* runRuntimeCallbackAtGeneration( + promptGeneration, + Effect.gen(function* () { + if (context.finalized || context.interrupted) return; + for (const [id, status] of statuses.value) { + const child = context.subagents.get(id); + if (!child || child.task.status === status) continue; + if (child.task.status === "idle" && status === "running") { + child.task = { ...child.task, status, completedAt: null }; + child.terminalStatusProjected = false; + } else if (!acpSubagentStatusBlocksTurnSettlement(child.task.status)) + continue; + yield* emitSubagent(context, { + nativeTaskId: id, + status, + childSessionId: child.childSessionId, + prompt: child.task.prompt, + model: child.task.model, + title: child.task.title, + result: null, + }); + } + }).pipe(Effect.uninterruptible), + ); + }).pipe(Effect.forever, Effect.forkScoped); + return yield* runPromptLoop; + }), + ); + yield* observedPrompt.pipe( + // Settle the wire before the completion callback's permit so a settled-soft + // Stop sees the native return. + Effect.tap(() => + Deferred.succeed(context.promptWireSettled, undefined).pipe(Effect.asVoid), ), Effect.tap(() => options.testHooks?.afterPromptWireSettled?.() ?? Effect.void), - Effect.flatMap((result) => + Effect.flatMap(({ result, hiddenFailure }) => runRuntimeCallbackAtGeneration( promptGeneration, Effect.gen(function* () { @@ -8982,14 +9217,6 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( }); } if (context.finalized || followsAgentWorkState) return; - // ACP v2 reports a failed prompt through its idle stop reason, not an RPC error. - const hiddenFailure = - checkPromptOutcome === undefined || - context.interrupted || - result.stopReason === "error" || - result.stopReason === "cancelled" - ? undefined - : yield* checkPromptOutcome(result); if (hiddenFailure !== undefined) { yield* Ref.set(runtimeRestartRequired, true); } @@ -9503,7 +9730,10 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( agentRequests.clear(); nativeChildren.clear(); yield* quarantineStoppedRun(); - if (context !== null) context.interrupted = true; + if (context !== null) { + context.interrupted = true; + yield* notifyForegroundToolWaiters(context); + } yield* cancelPendingRuntimeRequests(); yield* terminalizeCarryoverSubagents(carryover); if (context !== null) { @@ -9680,6 +9910,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( }); const runTransition = Effect.gen(function* () { context.interrupted = true; + yield* notifyForegroundToolWaiters(context); if (hardRestart || turnInput.requestRuntimeRestart === true) { yield* quarantineStoppedRun(); } @@ -9776,6 +10007,78 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( ), ), ), + ...(flavor.foregroundCommandWait === undefined + ? {} + : { + awaitBackgroundTasks: Effect.fn("AcpAdapterV2.awaitBackgroundTasks")(function* ({ + providerThread, + taskIds, + awaited, + }) { + const sessionId = yield* nativeThreadId(driver, providerThread); + const context = yield* Ref.get(activeTurn); + const uniqueTaskIds = [...new Set(taskIds)]; + if ( + context === null || + context.nativeThreadId !== sessionId || + context.finalized || + context.interrupted + ) { + return { matched: [] }; + } + const wait = flavor.foregroundCommandWait!; + const tools = [...context.tools.values()].filter( + wait.isForegroundCommand ?? ((tool) => tool.kind === "execute"), + ); + const matchesTaskId = (id: string) => + tools.some( + (tool) => + id === tool.toolCallId || + context.foregroundTaskIds.get(tool.toolCallId)?.includes(id), + ); + if ( + wait.resolveTaskIds !== undefined && + tools.length > 0 && + uniqueTaskIds.some((id) => !matchesTaskId(id)) + ) { + const resolved = yield* wait + .resolveTaskIds(sessionId, tools, uniqueTaskIds) + .pipe( + Effect.mapError( + (cause) => + new ProviderAdapter.ProviderAdapterProtocolError({ + driver, + detail: "Failed to read native background task identities", + payload: cause, + }), + ), + ); + for (const [id, nativeIds] of resolved) + context.foregroundTaskIds.set(id, nativeIds); + } + if (context.finalized || context.interrupted) return { matched: [] }; + const matched = uniqueTaskIds.filter(matchesTaskId); + if (!awaited) { + for (const id of matched) { + context.releasedForegroundTaskIds.add(id); + } + yield* notifyForegroundToolWaiters(context); + return { matched }; + } + const requested = new Set(matched); + const openTools = unreleasedOpenForegroundTools(context, requested); + if (openTools.length === 0) return { matched }; + yield* waitUntilForegroundToolsSettle( + context, + // Native launch ACKs never report worker completion; let the parent read queued results. + openTools.some((tool) => extractSubagentUpdate(tool) !== undefined) + ? "10 seconds" + : (flavor.foregroundCommandWait?.waitSlice ?? "4 minutes"), + requested, + ); + return { matched }; + }), + }), respondToRuntimeRequest: (requestInput) => Effect.uninterruptibleMask((restore) => Effect.gen(function* () { diff --git a/packages/provider-core/src/server/orchestrationInstructions.ts b/packages/provider-core/src/server/orchestrationInstructions.ts index 4ce08d71119fe..061572a9787d3 100644 --- a/packages/provider-core/src/server/orchestrationInstructions.ts +++ b/packages/provider-core/src/server/orchestrationInstructions.ts @@ -78,6 +78,7 @@ export function t3AcpPromptWithInstructions(input: { readonly prompt: string; readonly state: T3AcpInstructionState; readonly previousState?: T3AcpInstructionState; + readonly mcpInstructions?: string | undefined; }): string { // Native slash commands must remain at the start of the prompt. if (input.prompt.trimStart().startsWith("/")) return input.prompt; @@ -88,6 +89,7 @@ export function t3AcpPromptWithInstructions(input: { ) { return input.prompt; } + const mcpExtra = input.mcpInstructions?.trim(); const instructions = [ input.state.interactionMode === "plan" ? T3_CODE_ACP_PLAN_MODE_INSTRUCTIONS @@ -97,6 +99,7 @@ export function t3AcpPromptWithInstructions(input: { T3_CODE_BROWSER_TOOL_INSTRUCTIONS.trim(), ...(input.state.hasDeviceTools ? [T3_CODE_DEVICE_TOOL_INSTRUCTIONS] : []), T3_CODE_ORCHESTRATION_INSTRUCTIONS.trim(), + ...(mcpExtra ? [mcpExtra] : []), T3_CODE_ACP_MCP_FALLBACK_INSTRUCTIONS, ] : []),