TypeScript
fix(server): delegates finish when their leftover work settles, and Grok commands stop holding runs open (#22709)
Theo Browne163bdeaa119f
diff --git a/apps/server/scripts/acp-mock-agent.ts b/apps/server/scripts/acp-mock-agent.tsindex 6dcfde2ee33..7a749b501bd 100644--- a/apps/server/scripts/acp-mock-agent.ts+++ b/apps/server/scripts/acp-mock-agent.ts@@ -46,9 +46,11 @@ const emitXAiAskUserQuestionThenHang =process.env.T3_ACP_EMIT_XAI_ASK_USER_QUESTION_THEN_HANG === "1";const emitContentThenHang = process.env.T3_ACP_EMIT_CONTENT_THEN_HANG === "1";const emitPlanThenHang = process.env.T3_ACP_EMIT_PLAN_THEN_HANG === "1";+const grokKillTaskShape = process.env.T3_ACP_GROK_KILL_TASK_SHAPE;const emitActiveToolThenHang = process.env.T3_ACP_EMIT_ACTIVE_TOOL_THEN_HANG === "1";const emitGrokMonitorPostTurnPoll = process.env.T3_ACP_EMIT_GROK_MONITOR_POST_TURN_POLL === "1";const emitGrokBackgroundTaskStarted = process.env.T3_ACP_EMIT_GROK_BACKGROUND_TASK_STARTED === "1";+const emitGrokBackgroundTaskPoll = process.env.T3_ACP_GROK_BACKGROUND_TASK_COMPLETION === "poll";const emitForeignSessionUpdates = process.env.T3_ACP_EMIT_FOREIGN_SESSION_UPDATES === "1";const waitForResumeRelease = process.env.T3_ACP_WAIT_FOR_RESUME_RELEASE === "1";const completeFirstPromptOnCancel = process.env.T3_ACP_COMPLETE_FIRST_PROMPT_ON_CANCEL === "1";@@ -461,6 +463,71 @@ function modelState(): AcpCompat.SessionModelState {};}+function emitGrokKillTaskScenario(+ sessionId: string,+ promptId: string | undefined,+ shape: string,+): void {+ const taskId = "call-fb9d0000-0000-0000-0000-000000000026-29";+ const outcome =+ shape === "already_exited" || shape === "known_failure" ? "already_exited" : "killed";+ writeJsonRpcNotification("session/update", {+ sessionId,+ update: {+ sessionUpdate: "tool_call_update",+ toolCallId: "kill-target-command",+ title: "run_terminal_command",+ kind: "execute",+ status: "in_progress",+ rawInput: { command: "sleep 40" },+ },+ });+ writeJsonRpcNotification("session/update", {+ sessionId,+ update: {+ sessionUpdate: "tool_call_update",+ toolCallId: "kill-target-command",+ status: "completed",+ rawOutput: {+ type: "BackgroundTaskStarted",+ task_id: taskId,+ task_type: "bash",+ command: "sleep 40",+ },+ },+ });+ if (shape === "known_failure") {+ writeJsonRpcNotification("_x.ai/task_completed", {+ sessionId,+ update: {+ sessionUpdate: "task_completed",+ task_snapshot: { task_id: taskId, kind: "bash", exit_code: 7, output: "known failure\n" },+ },+ });+ }+ writeJsonRpcNotification("session/update", {+ sessionId,+ update: {+ sessionUpdate: "tool_call_update",+ toolCallId: "kill-command",+ title: `kill ${taskId} (${outcome})`,+ kind: "other",+ status: "completed",+ rawInput: {+ task_id: taskId,+ ...(shape === "output_only" ? {} : { variant: "KillTask" }),+ },+ ...(shape === "variant_only" ? {} : { rawOutput: { type: "KillTask", outcome } }),+ },+ });+ writeJsonRpcNotification("_x.ai/session/prompt_complete", {+ sessionId,+ promptId,+ stopReason: "end_turn",+ agentResult: null,+ });+}+const program = Effect.gen(function* () {const agent = yield* EffectAcpAgent.AcpAgent;const resumeRelease = yield* Deferred.make<void>();@@ -1498,6 +1565,16 @@ const program = Effect.gen(function* () {return yield* Effect.never;}+ if (grokKillTaskShape !== undefined) {+ emitGrokKillTaskScenario(+ requestedSessionId,+ promptIdFromRequestMeta(request),+ grokKillTaskShape,+ );+ // Keep the prompt RPC and peer alive after the kill result.+ return yield* Effect.never;+ }+if (emitPlanThenHang) {yield* agent.client.sessionUpdate({sessionId: requestedSessionId,@@ -1685,13 +1762,15 @@ const program = Effect.gen(function* () {return yield* Effect.never;}- if (emitGrokBackgroundTaskStarted) {- const toolCallId = "call-fb9d0000-0000-0000-0000-000000000026";+ if (emitGrokBackgroundTaskStarted || emitGrokBackgroundTaskPoll) {+ const toolCallId = !emitGrokBackgroundTaskPoll+ ? "call-fb9d0000-0000-0000-0000-000000000026"+ : "call-fb9d0000-0000-0000-0000-000000000026-29";const command = "sleep 40; echo done-a";writeJsonRpcNotification("session/update", {sessionId: requestedSessionId,update: {- sessionUpdate: "tool_call",+ sessionUpdate: !emitGrokBackgroundTaskPoll ? "tool_call" : "tool_call_update",toolCallId,title: "run_terminal_command",kind: "execute",@@ -1714,6 +1793,46 @@ const program = Effect.gen(function* () {},},});+ if (emitGrokBackgroundTaskPoll) {+ writeJsonRpcNotification("session/update", {+ sessionId: requestedSessionId,+ update: {+ sessionUpdate: "tool_call_update",+ toolCallId: "call-background-poll",+ title: "get_command_or_subagent_output",+ kind: "other",+ status: "completed",+ rawOutput: {+ type: "TaskOutput",+ Result: {+ task_id: toolCallId,+ command,+ status: "completed",+ exit_code: 0,+ output: "done-a",+ },+ },+ },+ });++ yield* agent.client.sessionUpdate({+ sessionId: requestedSessionId,+ update: {+ sessionUpdate: "agent_message_chunk",+ content: { type: "text", text: "The background command finished." },+ },+ });+ writeJsonRpcNotification("_x.ai/session/update", {+ sessionId: requestedSessionId,+ update: {+ sessionUpdate: "turn_completed",+ prompt_id: promptIdFromRequestMeta(request),+ stop_reason: "end_turn",+ },+ });+ // Neither the prompt RPC nor the process ends, matching the Grok incident.+ return yield* Effect.never;+ }writeJsonRpcNotification("_x.ai/session/prompt_complete", {sessionId: requestedSessionId,promptId: promptIdFromRequestMeta(request) ?? "mock-xai-prompt-1",diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.tsindex fa4b0883c07..1a0c6caf1f9 100644--- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts+++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts@@ -63,6 +63,8 @@ import {} from "@t3tools/provider-acp/server/sessionConfig";import {extractXAiAcpSubagentUpdate,+ makeGrokAdapterV2,+ makeXAiPromptCompletionRuntime,normalizeXAiAcpToolCallState,registerXAiBackgroundTaskTracking,} from "@t3tools/provider-grok/testing";@@ -3079,6 +3081,193 @@ describe("AcpAdapterV2", () => {}).pipe(Effect.provide(layerTest), Effect.scoped),);+ // Oracle: Grok incident frames. Command completion must release the turn even+ // when the CLI keeps the prompt RPC and process alive. Command polls stay visible.+ it.live(+ "completes a structured Grok background command from poll with an unanswered prompt RPC",+ () =>+ Effect.gen(function* () {+ const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;+ const path = yield* Path.Path;+ const mockAgentPath = yield* path.fromFileUrl(+ new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),+ );+ const instanceId = ProviderInstanceId.make("grok-background-completion");+ const adapter = yield* makeGrokAdapterV2({+ instanceId,+ settings: DEFAULT_GROK_SETTINGS,+ environment: {},+ hostPlatform: yield* HostProcess.Platform,+ selfInvocation: yield* resolveSelfInvocation(),+ makeRuntime: (input) =>+ makeMockRuntime({+ childProcessSpawner,+ mockAgentPath,+ environment: { T3_ACP_GROK_BACKGROUND_TASK_COMPLETION: "poll" },+ })(input).pipe(Effect.flatMap(makeXAiPromptCompletionRuntime)),+ });+ const threadId = ThreadId.make("grok-background-completion");+ const modelSelection = { instanceId, model: "default" } as const;+ const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({+ runtimeMode: "full-access",+ interactionMode: "default",+ cwd: process.cwd(),+ });+ const runtime = yield* adapter.openSession({+ threadId,+ providerSessionId: ProviderSessionId.make("grok-background-completion"),+ modelSelection,+ runtimePolicy,+ });+ const providerThread = yield* runtime.ensureThread({+ threadId,+ modelSelection,+ runtimePolicy,+ });+ const events = yield* Queue.unbounded<ProviderAdapter.ProviderAdapterV2Event>();+ yield* runtime.events.pipe(+ Stream.runForEach((event) => Queue.offer(events, event)),+ Effect.forkScoped,+ );+ yield* runtime.startTurn(+ makeTurnInput({+ threadId,+ providerThread,+ instanceId,+ runtimePolicy,+ now: yield* DateTime.now,+ }),+ );+ const observed = yield* Stream.fromQueue(events).pipe(+ Stream.takeUntil((event) => event.type === "turn.terminal"),+ Stream.runCollect,+ );+ const allEvents = [...observed];+ let next = yield* Queue.poll(events);+ while (Option.isSome(next)) {+ allEvents.push(next.value);+ next = yield* Queue.poll(events);+ }+ const terminals = allEvents.filter((event) => event.type === "turn.terminal");+ assert.deepEqual(+ terminals.map((event) => event.status),+ ["completed"],+ );+ const items = allEvents.flatMap((event) =>+ event.type === "turn_item.updated" ? [event.turnItem] : [],+ );+ assert.isFalse(items.some((item) => item.type === "subagent"));+ const command = items.findLast(+ (item) => item.nativeItemRef?.nativeId === "call-fb9d0000-0000-0000-0000-000000000026-29",+ );+ assert.equal(command?.type, "command_execution");+ assert.equal(command?.status, "completed");+ assert.isTrue(+ items.some((item) => item.nativeItemRef?.nativeId === "call-background-poll"),+ "command TaskOutput must retain its normal tool frame",+ );+ }).pipe(Effect.provide(layerTest), Effect.scoped),+ );++ // Oracle: #15888 KillTask reports. Command completion must release the turn even+ // when the CLI keeps the prompt RPC and process alive. Kill calls stay visible.+ it.live.each([+ { shape: "output_only", expectedCommand: { type: "command_execution", status: "completed" } },+ { shape: "variant_only", expectedCommand: { type: "command_execution", status: "completed" } },+ { shape: "killed", expectedCommand: { type: "command_execution", status: "completed" } },+ {+ shape: "already_exited",+ expectedCommand: { type: "command_execution", status: "completed" },+ },+ {+ shape: "known_failure",+ expectedCommand: { type: "command_execution", status: "failed", output: "known failure\n" },+ },+ ] as const)(+ "completes a Grok KillTask command ($shape) and preserves any known result",+ ({ shape, expectedCommand }) =>+ Effect.gen(function* () {+ const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;+ const path = yield* Path.Path;+ const mockAgentPath = yield* path.fromFileUrl(+ new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),+ );+ const instanceId = ProviderInstanceId.make("grok-kill-completion");+ const adapter = yield* makeGrokAdapterV2({+ instanceId,+ settings: DEFAULT_GROK_SETTINGS,+ environment: {},+ hostPlatform: yield* HostProcess.Platform,+ selfInvocation: yield* resolveSelfInvocation(),+ makeRuntime: (input) =>+ makeMockRuntime({+ childProcessSpawner,+ mockAgentPath,+ environment: { T3_ACP_GROK_KILL_TASK_SHAPE: shape },+ })(input).pipe(Effect.flatMap(makeXAiPromptCompletionRuntime)),+ });+ const threadId = ThreadId.make("grok-kill-completion");+ const modelSelection = { instanceId, model: "default" } as const;+ const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({+ runtimeMode: "full-access",+ interactionMode: "default",+ cwd: process.cwd(),+ });+ const runtime = yield* adapter.openSession({+ threadId,+ providerSessionId: ProviderSessionId.make("grok-kill-completion"),+ modelSelection,+ runtimePolicy,+ });+ const providerThread = yield* runtime.ensureThread({+ threadId,+ modelSelection,+ runtimePolicy,+ });+ const events = yield* Queue.unbounded<ProviderAdapter.ProviderAdapterV2Event>();+ yield* runtime.events.pipe(+ Stream.runForEach((event) => Queue.offer(events, event)),+ Effect.forkScoped,+ );+ yield* runtime.startTurn(+ makeTurnInput({+ threadId,+ providerThread,+ instanceId,+ runtimePolicy,+ now: yield* DateTime.now,+ }),+ );+ const observed = yield* Stream.fromQueue(events).pipe(+ Stream.takeUntil((event) => event.type === "turn.terminal"),+ Stream.runCollect,+ );+ const allEvents = [...observed];+ let next = yield* Queue.poll(events);+ while (Option.isSome(next)) {+ allEvents.push(next.value);+ next = yield* Queue.poll(events);+ }+ const terminals = allEvents.filter((event) => event.type === "turn.terminal");+ assert.deepEqual(+ terminals.map((event) => event.status),+ ["completed"],+ );+ const items = allEvents.flatMap((event) =>+ event.type === "turn_item.updated" ? [event.turnItem] : [],+ );+ assert.isFalse(items.some((item) => item.type === "subagent"));+ const command = items.findLast(+ (item) => item.nativeItemRef?.nativeId === "kill-target-command",+ );+ assert.deepInclude(command, expectedCommand);+ assert.isTrue(+ items.some((item) => item.nativeItemRef?.nativeId === "kill-command"),+ "KillTask must retain its normal tool frame",+ );+ }).pipe(Effect.provide(layerTest), Effect.scoped),+ );+it.effect("keeps an agent's empty-valued default choice selectable", () =>Effect.gen(function* () {const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;diff --git a/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts b/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.tsindex 0bdca007458..e58c8a1e528 100644--- a/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts+++ b/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts@@ -2402,4 +2402,224 @@ it.layer(layerTest)("delegated tasks across a server restart", (it) => {);}),);++ it.effect.each(["a background command", "a nested subagent"] as const)(+ "finalizes a child whose run ended before %s settled",+ (blocker) =>+ Effect.gen(function* () {+ const orchestrator = yield* Orchestrator.OrchestratorV2;+ const sink = yield* EventSink.EventSinkV2;+ const now = yield* DateTime.now;+ const key = blocker === "a background command" ? "command" : "nested";+ const threadId = ThreadId.make(`late-settle-parent-${key}`);+ const runId = RunId.make(`late-settle-parent-run-${key}`);+ const rootNodeId = NodeId.make(`late-settle-parent-root-${key}`);+ yield* seedParentWithTerminalTask({+ threadId,+ projectId: ProjectId.make(`late-settle-project-${key}`),+ runId,+ rootNodeId,+ taskId: NodeId.make(`late-settle-seed-task-${key}`),+ deliveryState: "acknowledged",+ now,+ });+ // A delegated child with a running task on the parent and a running run of its own.+ const delegate = (name: string) =>+ Effect.gen(function* () {+ const taskId = NodeId.make(`node:late-settle-${key}-${name}`);+ const childThreadId = ThreadId.make(`thread:late-settle-${key}-${name}`);+ const run = runEvent({+ threadId: childThreadId,+ runId: RunId.make(`run:late-settle-${key}-${name}`),+ ordinal: 1,+ status: "running",+ now,+ });+ yield* sink.write({+ events: [+ {+ id: EventId.make(`event:late-settle-${key}-${name}:thread`),+ type: "thread.created",+ threadId: childThreadId,+ occurredAt: now,+ payload: {+ createdBy: "agent",+ creationSource: "server",+ id: childThreadId,+ projectId: ProjectId.make(`late-settle-project-${key}`),+ title: name,+ providerInstanceId: modelSelection.instanceId,+ modelSelection,+ runtimeMode: "full-access",+ interactionMode: "default",+ branch: null,+ worktreePath: null,+ activeProviderThreadId: null,+ lineage: {+ parentThreadId: threadId,+ relationshipToParent: "subagent",+ rootThreadId: threadId,+ },+ forkedFrom: { type: "node", nodeId: taskId },+ createdAt: now,+ updatedAt: now,+ archivedAt: null,+ settledOverride: null,+ settledAt: null,+ lastVisitedAt: null,+ deletedAt: null,+ },+ },+ {+ id: EventId.make(`event:late-settle-${key}-${name}:task`),+ type: "subagent.updated",+ threadId,+ runId,+ nodeId: taskId,+ driver,+ providerInstanceId: modelSelection.instanceId,+ occurredAt: now,+ payload: {+ id: taskId,+ threadId,+ runId,+ parentNodeId: rootNodeId,+ origin: "app_owned",+ createdBy: "agent",+ driver,+ providerInstanceId: modelSelection.instanceId,+ providerThreadId: null,+ childThreadId,+ nativeTaskRef: null,+ prompt: `Run ${name}.`,+ title: null,+ model: null,+ completionWake: "always",+ status: "running",+ result: null,+ startedAt: now,+ completedAt: null,+ updatedAt: now,+ },+ },+ run,+ ],+ });+ return { task: { id: taskId }, childThreadId, run: run.payload };+ });+ const settled = (taskId: NodeId, afterSequence: number) =>+ sink.stream({ afterSequence, eventType: "subagent.updated" }).pipe(+ Stream.filter(+ (stored) =>+ stored.event.type === "subagent.updated" &&+ stored.event.payload.id === taskId &&+ stored.event.payload.status === "completed",+ ),+ Stream.take(1),+ Stream.runDrain,+ );+ const blocked = yield* delegate("blocked");+ const barrier = yield* delegate("barrier");+ const providerThread = {+ id: ProviderThreadId.make(`provider-thread:late-settle-child-${key}`),+ driver,+ providerInstanceId: modelSelection.instanceId,+ providerSessionId: null,+ appThreadId: blocked.childThreadId,+ ownerNodeId: null,+ nativeThreadRef: null,+ nativeConversationHeadRef: null,+ status: "idle" as const,+ firstRunOrdinal: 1,+ lastRunOrdinal: 1,+ handoffIds: [],+ forkedFrom: null,+ createdAt: now,+ updatedAt: now,+ };+ const nested = {+ id: NodeId.make(`late-settle-nested-${key}`),+ threadId: blocked.childThreadId,+ runId: blocked.run.id,+ parentNodeId: NodeId.make(`late-settle-child-root-${key}`),+ origin: "provider_native" as const,+ createdBy: "agent" as const,+ driver,+ providerInstanceId: modelSelection.instanceId,+ providerThreadId: null,+ childThreadId: null,+ nativeTaskRef: null,+ prompt: "Nested work",+ title: null,+ model: null,+ status: "running" as const,+ result: null,+ startedAt: now,+ completedAt: null,+ updatedAt: now,+ };+ const blockerEvent = (open: boolean) =>+ blocker === "a background command"+ ? {+ id: EventId.make(`event:late-settle-roster-${key}-${open}`),+ type: "provider-thread.updated" as const,+ threadId: blocked.childThreadId,+ driver,+ providerInstanceId: modelSelection.instanceId,+ occurredAt: now,+ payload: {+ ...providerThread,+ pendingBackgroundTasks: open+ ? [{ taskId: "sleep-900", kind: "command" as const }]+ : [],+ },+ }+ : {+ id: EventId.make(`event:late-settle-nested-${key}-${open}`),+ type: "subagent.updated" as const,+ threadId: blocked.childThreadId,+ runId: blocked.run.id,+ nodeId: nested.id,+ driver,+ providerInstanceId: modelSelection.instanceId,+ occurredAt: now,+ payload: open+ ? nested+ : { ...nested, status: "completed" as const, result: "done", completedAt: now },+ };+ const ended = (child: typeof blocked) => ({+ ...runEvent({+ threadId: child.childThreadId,+ runId: child.run.id,+ ordinal: child.run.ordinal,+ status: "completed",+ now,+ }),+ payload: { ...child.run, status: "completed" as const, startedAt: now, completedAt: now },+ });++ const beforeEnd = yield* sink.latestSequence();+ yield* sink.write({ events: [blockerEvent(true)] });+ yield* sink.write({ events: [ended(blocked)] });+ yield* sink.write({ events: [ended(barrier)] });+ // Run updates are handled in order, so the barrier settling means the blocked child's+ // run end was handled too, while its work still ran.+ yield* settled(barrier.task.id, beforeEnd);+ assert.equal(+ (yield* orchestrator.getThreadProjection(threadId)).subagents.find(+ (task) => task.id === blocked.task.id,+ )?.status,+ "running",+ );++ const beforeSettle = yield* sink.latestSequence();+ yield* sink.write({ events: [blockerEvent(false)] });+ yield* settled(blocked.task.id, beforeSettle);+ const finished = (yield* orchestrator.getThreadProjection(threadId)).subagents.find(+ (task) => task.id === blocked.task.id,+ );+ assert.equal(finished?.status, "completed");+ assert.notEqual(finished?.completionDelivery?.state, "disposed");+ }),+ );});diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.tsindex 22d3de23a69..213a1a31ab7 100644--- a/apps/server/src/orchestration-v2/Orchestrator.ts+++ b/apps/server/src/orchestration-v2/Orchestrator.ts@@ -11826,6 +11826,48 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functioEffect.forkDetach,);+ // A child whose run ends while its background tasks or its own subagents still run has no+ // result yet. When that work settles there is no run update to finalize it, so these events+ // do it (#17512). A background roster counts once it empties after it was seen non-empty.+ const providerThreadsWithBackgroundWork = new Set<string>();+ const settlesChildWork = (stored: OrchestrationV2StoredEvent) => {+ const { event } = stored;+ if (event.type === "subagent.updated")+ return !isOrchestrationV2WorkActive(event.payload.status);+ if (event.type !== "provider-thread.updated") return false;+ if ((event.payload.pendingBackgroundTasks?.length ?? 0) > 0) {+ providerThreadsWithBackgroundWork.add(event.payload.id);+ return false;+ }+ return providerThreadsWithBackgroundWork.delete(event.payload.id);+ };+ yield* Stream.merge(+ eventSink.stream({+ afterSequence: terminalEventsAfterSequence,+ eventType: "provider-thread.updated",+ }),+ eventSink.stream({ afterSequence: terminalEventsAfterSequence, eventType: "subagent.updated" }),+ ).pipe(+ Stream.filter(settlesChildWork),+ Stream.runForEach((stored) =>+ Effect.gen(function* () {+ const childThreadId = stored.event.threadId;+ const parentThreadId = yield* appOwnedSubagentParentThreadId(childThreadId);+ if (parentThreadId === undefined) return;+ yield* threadDispatch.withLock(parentThreadId, finalizeAppOwnedSubagent(childThreadId));+ }).pipe(+ Effect.catchCause((cause) =>+ Effect.logWarning("Failed to finalize a delegated child after its work settled", {+ threadId: stored.event.threadId,+ sequence: stored.sequence,+ cause,+ }),+ ),+ ),+ ),+ Effect.forkDetach,+ );+const recoverDelegatedTasks = Effect.gen(function* () {yield* projectionStore.getRecoveryThreadIds("subagent-results").pipe(Effect.tap((threadIds) =>diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.tsindex 202f26c32e9..01a729cd7c9 100644--- a/packages/provider-acp/src/server/adapter.ts+++ b/packages/provider-acp/src/server/adapter.ts@@ -3555,6 +3555,17 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (backgroundCompletion.appendOutput,): { ...target, status: nextStatus };+ // BackgroundTaskStarted normalization can reopen this row, so keep the+ // completion for settlement when no task_completed recorded one.+ if (+ backgroundCompletion.status !== "running" &&+ context.backgroundCommands.get(backgroundCompletion.taskId) === null+ ) {+ context.backgroundCommands.set(backgroundCompletion.taskId, {+ status: backgroundCompletion.status,+ output: toolOutputText(hydrated),+ });+ }yield* emitTool(context, hydrated);}}diff --git a/packages/provider-grok/src/server/xaiAcpExtension.test.ts b/packages/provider-grok/src/server/xaiAcpExtension.test.tsindex 5de0a88c198..8245d5f16b8 100644--- a/packages/provider-grok/src/server/xaiAcpExtension.test.ts+++ b/packages/provider-grok/src/server/xaiAcpExtension.test.ts@@ -484,6 +484,73 @@ describe("XAiAcpExtension", () => {expect(normalized.status).toBe("inProgress");});+ it("completes structured command TaskOutput ids without treating them as subagents", () => {+ // Oracle: BackgroundTaskStarted and TaskOutput from the Grok hang incident.+ const toolCall: AcpToolCallState = {+ toolCallId: "call-poll",+ title: "get_command_or_subagent_output",+ status: "completed",+ data: {+ rawInput: {+ variant: "TaskOutput",+ task_ids: ["call-7c835a60-7bf5-4284-a5c7-cf42a4212ece-29"],+ },+ rawOutput: {+ type: "TaskOutput",+ Result: {+ task_id: "call-7c835a60-7bf5-4284-a5c7-cf42a4212ece-29",+ status: "completed",+ exit_code: 0,+ output: "done",+ },+ },+ },+ };+ expect(extractXAiBackgroundTaskCompletion(toolCall)).toEqual([+ {+ taskId: "call-7c835a60-7bf5-4284-a5c7-cf42a4212ece-29",+ status: "completed",+ appendOutput: "done",+ },+ ]);+ expect(extractXAiAcpSubagentUpdate(toolCall)).toBeUndefined();+ });++ it("keeps the normal tool frame for a command result from a mixed-ID poll", () => {+ // Oracle: review 4325739061 requires the result ID to override requested subagent IDs.+ const toolCall: AcpToolCallState = {+ toolCallId: "call-mixed-poll",+ title: "get_command_or_subagent_output",+ status: "completed",+ data: {+ rawInput: {+ variant: "TaskOutput",+ task_ids: [+ "019f44a6-4820-7402-925d-bc862ee711dd",+ "call-7c835a60-7bf5-4284-a5c7-cf42a4212ece-29",+ ],+ },+ rawOutput: {+ type: "TaskOutput",+ Result: {+ task_id: "call-7c835a60-7bf5-4284-a5c7-cf42a4212ece-29",+ status: "completed",+ exit_code: 0,+ output: "done",+ },+ },+ },+ };+ expect(extractXAiAcpSubagentUpdate(toolCall)).toBeUndefined();+ expect(extractXAiBackgroundTaskCompletion(toolCall)).toEqual([+ {+ taskId: "call-7c835a60-7bf5-4284-a5c7-cf42a4212ece-29",+ status: "completed",+ appendOutput: "done",+ },+ ]);+ });+it("hydrates monitor completion from a standalone TaskOutput frame without rawInput", () => {// Post-settle shape observed live (2026-07-12): the final// get_command_or_subagent_output update carries only rawOutput; the frame@@ -615,6 +682,87 @@ describe("XAiAcpExtension", () => {]);});+ // Oracle: #15888 reports KillTask replies with killed and already_exited outcomes.+ it.each([+ { rawInput: { task_id: "call-bg-1" }, rawOutput: { type: "KillTask" } },+ { rawInput: { task_id: "call-bg-1" }, rawOutput: { type: "KillTask", outcome: "killed" } },+ { rawInput: { variant: "KillTask", task_id: "call-bg-1" } },+ {+ rawInput: { variant: "KillTask", task_id: "call-bg-1" },+ rawOutput: { type: "KillTask", outcome: "already_exited" },+ },+ ])("closes a background command from structured KillTask fields: %j", (data) => {+ expect(+ extractXAiKilledBackgroundTasks({+ toolCallId: "call-kill",+ title: "kill call-bg-1 (killed)",+ status: "completed",+ data,+ }),+ ).toEqual([{ taskId: "call-bg-1", status: "completed", appendOutput: "" }]);+ expect(+ extractXAiAcpSubagentUpdate({+ toolCallId: "call-kill",+ title: "kill call-bg-1 (killed)",+ status: "completed",+ data,+ }),+ ).toBeUndefined();+ });++ // Native child status still comes from its lifecycle/result path, not the kill RPC.+ it.each(["Kill", "KillTask"])(+ "keeps %s aimed at a native child out of child result parsing",+ (variant) => {+ expect(+ extractXAiAcpSubagentUpdate({+ toolCallId: "call-kill-child",+ title: "kill 019f44b8-8e98-7c80-a40e-df1e26a5f9e3 (killed)",+ status: "completed",+ data: {+ rawInput: { variant, task_id: "019f44b8-8e98-7c80-a40e-df1e26a5f9e3" },+ rawOutput: { type: "KillTask", outcome: "killed" },+ },+ }),+ ).toBeUndefined();+ },+ );++ // A successful RPC is not proof of a successful kill when its outcome says otherwise.+ it.each([+ { type: "KillTask", outcome: "failed" },+ { type: "KillTask", Result: { task_id: "call-bg-1", outcome: "error" } },+ ])("ignores a KillTask whose outcome is not a kill: %j", (rawOutput) => {+ expect(+ extractXAiKilledBackgroundTasks({+ toolCallId: "call-kill",+ title: "kill call-bg-1 (failed)",+ status: "completed",+ data: {+ rawInput: { variant: "KillTask", task_id: "call-bg-1" },+ rawOutput,+ },+ }),+ ).toEqual([]);+ });++ it.each(["failed", "inProgress"] as const)(+ "does not close the target of a %s KillTask call",+ (status) => {+ expect(+ extractXAiKilledBackgroundTasks({+ toolCallId: "call-kill",+ title: "kill call-bg-1 (killed)",+ status,+ data: {+ rawInput: { variant: "KillTask", task_id: "call-bg-1" },+ rawOutput: { type: "KillTask", outcome: "killed" },+ },+ }),+ ).toEqual([]);+ },+ );+it("tombstones confirmed kills and ignores failed kill calls", () => {expect(extractXAiKilledBackgroundTasks({diff --git a/packages/provider-grok/src/server/xaiAcpExtension.ts b/packages/provider-grok/src/server/xaiAcpExtension.tsindex 92c0c14535d..4f04cf6b41f 100644--- a/packages/provider-grok/src/server/xaiAcpExtension.ts+++ b/packages/provider-grok/src/server/xaiAcpExtension.ts@@ -272,8 +272,8 @@ export function isXAiMonitorTool(toolCall: AcpToolCallState): boolean {* A shell command Grok runs in the background (asked for, or moved there after* its auto-background timeout) acknowledges with* `{ type: "BackgroundTaskStarted", task_id }` and completes its tool call- * while the process still runs. Like a monitor, it ends only with- * `x.ai/task_completed` for that task id.+ * while the process still runs. It ends with a task completion notification+ * or completed TaskOutput for that task id.*/export function xAiBackgroundShellTaskId(toolCall: AcpToolCallState): string | undefined {const rawOutput = unknownRecord(toolCall.data.rawOutput);@@ -333,7 +333,9 @@ export function extractXAiBackgroundTaskCompletion(toolCall: AcpToolCallState):const appendOutput = resultFromGetOutputTool(toolCall, text) ?? "";// Prefer the completed identity from the result/header over the request list// (one call can poll multiple task_ids).- const resultTaskId = resultTaskIdFromGetOutputTool(toolCall, text);+ // Command task ids can be `call-<uuid>-<index>`; subagent ids stay UUID-only.+ const resultTaskId =+ structuredTaskIdFromGetOutputTool(toolCall) ?? resultTaskIdFromGetOutputTool(toolCall, text);if (resultTaskId !== undefined) {return [{ taskId: resultTaskId, status, appendOutput }];}@@ -355,8 +357,8 @@ export function extractXAiBackgroundTaskCompletion(toolCall: AcpToolCallState):/*** A finished kill_command_or_subagent call is the genuine end signal for every- * task id it names: the Grok CLI emits no `x.ai/task_completed` for a killed- * task. A failed kill is not proof the target stopped, so leave the existing+ * task id it names, even without a separate `x.ai/task_completed` notification.+ * A failed kill is not proof the target stopped, so leave the existing* task state unchanged until a genuine terminal signal arrives.*/export function extractXAiKilledBackgroundTasks(toolCall: AcpToolCallState): ReadonlyArray<{@@ -366,9 +368,15 @@ export function extractXAiKilledBackgroundTasks(toolCall: AcpToolCallState): Rea}> {const title = titleKey(toolCall);const rawInput = unknownRecord(toolCall.data.rawInput);+ const rawOutput = unknownRecord(toolCall.data.rawOutput);const variant = nonEmptyString(rawInput?.variant)?.toLowerCase();- if (!title.includes("kill_command_or_subagent") && variant !== "kill") return [];+ const legacy = title.includes("kill_command_or_subagent") || variant === "kill";+ if (!legacy && variant !== "killtask" && rawOutput?.type !== "KillTask") return [];if (toolCall.status !== "completed") return [];+ // Grok nests the outcome under Result; only a missing, killed or already_exited one ends the task.+ const outcome = rawOutput?.outcome ?? unknownRecord(rawOutput?.Result)?.outcome;+ if (!legacy && outcome !== undefined && outcome !== "killed" && outcome !== "already_exited")+ return [];const taskIds: string[] = [];const push = (value: unknown) => {const id = nonEmptyString(value);@@ -742,17 +750,22 @@ function taskIdsFromGetOutputTool(return [...new Set(ids)];}-function resultTaskIdFromGetOutputTool(- toolCall: AcpToolCallState,- output: string | undefined,-): string | undefined {+function structuredTaskIdFromGetOutputTool(toolCall: AcpToolCallState): string | undefined {const rawOutput = unknownRecord(toolCall.data.rawOutput);const result = unknownRecord(rawOutput?.Result) ?? unknownRecord(rawOutput?.result);- const structured =+ return (nonEmptyString(result?.task_id) ??nonEmptyString(result?.taskId) ??nonEmptyString(rawOutput?.task_id) ??- nonEmptyString(rawOutput?.taskId);+ nonEmptyString(rawOutput?.taskId)+ );+}++function resultTaskIdFromGetOutputTool(+ toolCall: AcpToolCallState,+ output: string | undefined,+): string | undefined {+ const structured = structuredTaskIdFromGetOutputTool(toolCall);if (structured !== undefined && new RegExp(`^${XAI_UUID_RE}$`, "i").test(structured)) {return structured;}@@ -831,6 +844,13 @@ export function extractXAiAcpSubagentUpdate(const output = xAiToolOutputText(toolCall);if (isXAiGetSubagentOutputTool(toolCall, rawInput)) {+ const structuredTaskId = structuredTaskIdFromGetOutputTool(toolCall);+ if (+ structuredTaskId !== undefined &&+ !new RegExp(`^${XAI_UUID_RE}$`, "i").test(structuredTaskId)+ ) {+ return undefined;+ }const taskIds = taskIdsFromGetOutputTool(toolCall, rawInput);const childSessionId =resultTaskIdFromGetOutputTool(toolCall, output) ??