TypeScript
fix(server): return delegated waits on pending approvals (#20037)
Gustav6f891541fd16
diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.tsindex c06a476cac9..5e028855c7f 100644--- a/apps/server/src/mcp/OrchestratorMcpService.ts+++ b/apps/server/src/mcp/OrchestratorMcpService.ts@@ -54,6 +54,7 @@ import {type ProviderInstanceId,type ProviderOptionDescriptor,type ProviderOptionSelection,+ ProviderRequestKind,type RuntimeMode,type ScheduledTask,type ScheduledTaskUpsertInput,@@ -416,6 +417,53 @@ function isTerminalTaskStatus();}+function endsTaskWait(result: OrchestratorMcpDelegateTaskResult): boolean {+ return (+ result.hasPendingQuestion ||+ result.pendingApproval !== null ||+ isTerminalTaskStatus(result.status)+ );+}++const isApprovalRequestKind = Schema.is(ProviderRequestKind);++function pendingTaskApproval(+ child: Pick<OrchestrationV2ThreadProjection, "runs" | "nodes" | "runtimeRequests">,+ taskId: NodeId,+ originalRun: OrchestrationV2Run | undefined,+) {+ const taskRunIds = new Set(+ child.runs+ .filter(+ (run) =>+ !ThreadManagementService.isTerminalRunStatus(run.status) &&+ (run.delegatedTaskId === taskId ||+ // Legacy tasks own only their original run, not later turns in the child thread.+ (run.delegatedTaskId === undefined && run.id === originalRun?.id)),+ )+ .map((run) => run.id),+ );+ let approval: OrchestratorMcpDelegateTaskResult["pendingApproval"] = null;+ let oldestCreatedAt = Infinity;+ for (const request of child.runtimeRequests) {+ if (+ request.status !== "pending" ||+ request.responseCapability.type !== "live" ||+ !isApprovalRequestKind(request.kind)+ ) {+ continue;+ }+ const runId = child.nodes.find((node) => node.id === request.nodeId)?.runId;+ if (runId === undefined || runId === null || !taskRunIds.has(runId)) continue;+ const createdAt = DateTime.toEpochMillis(request.createdAt);+ if (createdAt < oldestCreatedAt) {+ oldestCreatedAt = createdAt;+ approval = { requestId: request.id, kind: request.kind, runId };+ }+ }+ return approval;+}+function directAppOwnedChildTasks(parent: Pick<OrchestrationV2ThreadProjection, "thread" | "subagents">,target: Pick<OrchestrationV2ThreadProjection, "thread" | "runs">,@@ -1379,8 +1427,16 @@ const make = Effect.gen(function* () {const childControls = yield* threadManagement.getThreadRecords(task.childThreadId,- ["runs", "messages", "contextTransfers", "subagents", "providerThreads", "runtimeRequests"],- { messageRoles: ["user"] },+ [+ "runs",+ "messages",+ "contextTransfers",+ "subagents",+ "providerThreads",+ "runtimeRequests",+ "nodes",+ ],+ { messageRoles: ["user"], omitSettledLeafNodes: true },).pipe(Effect.mapError(threadManagementFailure));const childRun = delegatedTaskRun(childControls, task);@@ -1502,6 +1558,10 @@ const make = Effect.gen(function* () {request.status === "pending" &&request.responseCapability.type === "live",),+ pendingApproval:+ isTerminalTaskStatus(status) || task.completionDelivery?.state === "disposed"+ ? null+ : pendingTaskApproval(childControls, task.id, childRun),waitTimedOut,} satisfies OrchestratorMcpDelegateTaskResult;if (@@ -1552,7 +1612,7 @@ const make = Effect.gen(function* () {.getThreadEventSequence(scope.thread.threadId).pipe(Effect.mapError(streamError));const initial = yield* readTask(scope, taskId, false, true);- if (initial.hasPendingQuestion || isTerminalTaskStatus(initial.status)) {+ if (endsTaskWait(initial)) {return Option.some(initial);}// One stream per event type, so transcript events never fill a buffer.@@ -1568,7 +1628,7 @@ const make = Effect.gen(function* () {).pipe(Stream.mapError(streamError),Stream.mapEffect(() => readTask(scope, taskId, false, true)),- Stream.filter((result) => result.hasPendingQuestion || isTerminalTaskStatus(result.status)),+ Stream.filter(endsTaskWait),Stream.runHead,);},diff --git a/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts b/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.tsindex 325b3548296..b125361cd94 100644--- a/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts+++ b/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts@@ -9,11 +9,15 @@ import {IsoDateTime,isProviderNativeSubagentThread,MessageId,+ NodeId,+ RunId,type ModelSelection,type OrchestrationV2DelegatedCompletionDelivery,+ type OrchestrationV2DomainEvent,type OrchestrationV2ProviderCapabilities,type OrchestrationV2ProviderSession,type OrchestrationV2ProviderThread,+ type OrchestrationV2RuntimeRequest,type OrchestrationV2ThreadProjection,OrchestratorMcpCreateThreadsResult,OrchestratorMcpDelegateTaskResult,@@ -56,6 +60,7 @@ import { CodexProviderCapabilitiesV2 } from "../orchestration-v2/Adapters/CodexAimport { CodexOrchestratorReplayHarness } from "../orchestration-v2/Adapters/CodexAdapterV2.testkit.ts";import { threadShellFromProjection } from "../orchestration-v2/ProjectionStore.ts";import * as CommandReceiptStore from "../orchestration-v2/CommandReceiptStore.ts";+import * as EffectWorker from "../orchestration-v2/EffectWorker.ts";import * as EventSink from "../orchestration-v2/EventSink.ts";import * as Orchestrator from "../orchestration-v2/Orchestrator.ts";import * as ThreadLaunchService from "../orchestration-v2/ThreadLaunchService.ts";@@ -108,6 +113,7 @@ const cancellationPrompt = "Remain active until the parent cancels this delegateconst createdThreadPrompt = "Complete the newly created ordinary thread.";const queuedFollowupPrompt = "Complete the queued follow-up and return the final result.";const queuedFollowupResult = "Queued delegated follow-up completed.";+const approvalCompletionPrompt = "Finish the delegated work once its approval is decided.";const decodeCreateThreadsResult = Schema.decodeUnknownEffect(OrchestratorMcpCreateThreadsResult);const decodeDelegateTaskResult = Schema.decodeUnknownEffect(OrchestratorMcpDelegateTaskResult);@@ -542,6 +548,8 @@ describe("orchestrator MCP toolkit", () => {const steerReceivedGates = new Map<string, Deferred.Deferred<void>>();const parentTerminalGates = new Map<ThreadId, Deferred.Deferred<void>>();const deliveryTerminalGates = new Map<ThreadId, Deferred.Deferred<void>>();+ // Holds a delegated child whose thread id is not known until it starts.+ const promptTerminalGates = new Map<string, Deferred.Deferred<void>>();const layerRegistry = ProviderAdapterRegistry.layerFromAdapters([makeDeterministicAdapter({instanceId: codexInstanceId,@@ -557,7 +565,8 @@ describe("orchestrator MCP toolkit", () => {turn.message.text.startsWith("Delegated task") ||turn.message.text.startsWith("Delegated tasks")? deliveryTerminalGates.get(turn.threadId)- : parentTerminalGates.get(turn.threadId),+ : (parentTerminalGates.get(turn.threadId) ??+ promptTerminalGates.get(turn.message.text)),response: (turn) => `Codex completed: ${turn.message.text}`,}),makeDeterministicAdapter({@@ -578,6 +587,8 @@ describe("orchestrator MCP toolkit", () => {steerReceived: (steer) => steerReceivedGates.get(steer.message.text),}),]);+ const approvalParentId = ThreadId.make("thread:mcp-approval-parent");+ const approvalOffered = yield* Deferred.make<void>();const continuationOffers = yield* Ref.make<ReadonlyArray<ProviderContinuationRequests.ProviderContinuationRequest>>([]);@@ -585,7 +596,13 @@ describe("orchestrator MCP toolkit", () => {ProviderContinuationRequests.ProviderContinuationRequests,{offer: (request) =>- Ref.update(continuationOffers, (existing) => [...existing, request]),+ Ref.update(continuationOffers, (existing) => [...existing, request]).pipe(+ Effect.andThen(+ request.threadId === approvalParentId+ ? Deferred.succeed(approvalOffered, undefined)+ : Effect.void,+ ),+ ),take: Effect.never,},);@@ -2964,6 +2981,43 @@ describe("orchestrator MCP toolkit", () => {p.subagents.some((task) => task.id === question.id && task.status === "interrupted"),);+ // Stop disposes delivery even if a live approval record survives it.+ yield* (yield* EventSink.EventSinkV2).write({+ events: [+ {+ id: EventId.make("event:approval-after-stop"),+ type: "runtime-request.updated",+ threadId: question.childThreadId!,+ occurredAt: askedAt,+ payload: {+ id: RuntimeRequestId.make("request:approval-after-stop"),+ nodeId: asking.nodes.find((node) => node.runId === asking.runs[0]!.id)!.id,+ providerTurnId: null,+ nativeRequestRef: null,+ kind: "command",+ status: "pending",+ responseCapability: {+ type: "live",+ providerSessionId: asking.providerSessions[0]!.id,+ },+ createdAt: askedAt,+ resolvedAt: null,+ },+ },+ ],+ });+ expect(+ (yield* invoke("task_status", { taskId: question.id })).structuredContent,+ ).toMatchObject({+ status: "interrupted",+ pendingApproval: null,+ });+ expect(+ (yield* orchestrator.getThreadProjection(parentThreadId)).subagents.find(+ (task) => task.id === question.id,+ )?.completionDelivery,+ ).toMatchObject({ state: "disposed" });+const terminalUpgrade = yield* orchestrator.dispatch({type: "delegated_task.wake-policy",commandId: CommandId.make("command:mcp-parent:wake-policy-terminal"),@@ -4010,6 +4064,296 @@ describe("orchestrator MCP toolkit", () => {thirdFanoutDelivery.messageId,]),);++ // Keep completion delivery separate from the earlier fan-out cohorts.+ const approvalParentGate = yield* Deferred.make<void>();+ const approvalChildGate = yield* Deferred.make<void>();+ parentTerminalGates.set(approvalParentId, approvalParentGate);+ promptTerminalGates.set(approvalCompletionPrompt, approvalChildGate);+ yield* Ref.set(continuationOffers, []);+ const approvalStart = (yield* orchestrator.dispatch({+ type: "thread.create",+ createdBy: "user",+ creationSource: "web",+ commandId: CommandId.make("command:approval-parent:create"),+ threadId: approvalParentId,+ projectId,+ title: "Approval parent",+ modelSelection: codexSelection,+ runtimeMode: "full-access",+ interactionMode: "default",+ branch: null,+ worktreePath: cwd,+ })).sequence;+ const awaitApprovalEvent = (+ threadId: ThreadId,+ matches: (event: OrchestrationV2DomainEvent) => boolean,+ ) =>+ orchestrator.streamStoredEventsFrom({ threadId, afterSequence: approvalStart }).pipe(+ Stream.filter((stored) => matches(stored.event)),+ Stream.runHead,+ Effect.flatMap(+ Option.match({+ onNone: () => Effect.die("Approval scenario event stream ended."),+ onSome: () => Effect.void,+ }),+ ),+ );+ yield* orchestrator.dispatch({+ type: "message.dispatch",+ createdBy: "user",+ creationSource: "web",+ commandId: CommandId.make("command:approval-parent:start"),+ threadId: approvalParentId,+ messageId: MessageId.make("message:approval-parent:start"),+ text: "Hold this parent while its child asks for approval.",+ attachments: [],+ modelSelection: codexSelection,+ dispatchMode: { type: "start_immediately" },+ });+ yield* awaitApprovalEvent(+ approvalParentId,+ (event) =>+ event.type === "provider-turn.updated" && event.payload.status === "running",+ );+ const approvalScope = {+ ...invocation,+ requestNamespace: "mcp-approval-parent",+ thread: { ...invocation.thread!, threadId: approvalParentId },+ };+ const delegateApproval = invokeAs(approvalScope, "delegate_task", {+ task: approvalCompletionPrompt,+ title: "Approval completion",+ target: { providerInstanceId: codexInstanceId, model: codexModel },+ mode: "wait",+ timeoutMs: 30_000,+ clientRequestId: "delegate-approval-completion",+ });+ const approvalWait = yield* delegateApproval.pipe(Effect.forkChild);+ yield* awaitApprovalEvent(+ approvalParentId,+ (event) => event.type === "subagent.updated" && event.payload.childThreadId !== null,+ );+ const approvalTask = (yield* orchestrator.getThreadProjection(approvalParentId))+ .subagents[0]!;+ const approvalChildId = approvalTask.childThreadId!;+ yield* awaitApprovalEvent(+ approvalChildId,+ (event) =>+ event.type === "provider-turn.updated" && event.payload.status === "running",+ );+ const approvalChild = yield* orchestrator.getThreadProjection(approvalChildId);+ const approvalRun = approvalChild.runs[0]!;+ const approvalNode = approvalChild.nodes.find((node) => node.runId === approvalRun.id)!;+ const approvalAskedAt = yield* DateTime.now;+ const approvalRequest = (+ id: string,+ overrides: Partial<OrchestrationV2RuntimeRequest> = {},+ ): OrchestrationV2RuntimeRequest => ({+ id: RuntimeRequestId.make(`request:approval:${id}`),+ nodeId: approvalNode.id,+ providerTurnId: null,+ nativeRequestRef: null,+ kind: "command",+ status: "pending",+ responseCapability: {+ type: "live",+ providerSessionId: approvalChild.providerSessions[0]!.id,+ },+ createdAt: approvalAskedAt,+ resolvedAt: null,+ ...overrides,+ });+ const eventSink = yield* EventSink.EventSinkV2;+ let approvalEventId = 0;+ const persistApprovalEvent = (event: OrchestrationV2DomainEvent) =>+ eventSink.write({ events: [event] });+ const persistRequest = (+ request: OrchestrationV2RuntimeRequest,+ threadId = approvalChildId,+ ) =>+ persistApprovalEvent({+ id: EventId.make(`event:approval:${++approvalEventId}`),+ type: "runtime-request.updated",+ threadId,+ occurredAt: approvalAskedAt,+ payload: request,+ });+ const readApprovalStatus = () =>+ invokeAs(approvalScope, "task_status", { taskId: approvalTask.id }).pipe(+ Effect.flatMap((result) => decodeDelegateTaskResult(result.structuredContent)),+ Effect.orDie,+ );++ // These durable records must not make the parent's wait return an approval.+ for (const request of [+ approvalRequest("resolved", { status: "resolved", resolvedAt: approvalAskedAt }),+ approvalRequest("expired", { status: "expired", resolvedAt: approvalAskedAt }),+ approvalRequest("cancelled", { status: "cancelled", resolvedAt: approvalAskedAt }),+ approvalRequest("message", { responseCapability: { type: "message" } }),+ approvalRequest("not-live", {+ responseCapability: { type: "not_resumable", reason: "Session ended." },+ }),+ approvalRequest("question", {+ kind: "user_input",+ responseCapability: { type: "message" },+ }),+ approvalRequest("auth", { kind: "auth_refresh" }),+ approvalRequest("tool", { kind: "dynamic_tool_call" }),+ approvalRequest("missing-node", { nodeId: NodeId.make("node:missing-approval") }),+ ]) {+ yield* persistRequest(request);+ }+ expect((yield* readApprovalStatus()).pendingApproval).toBeNull();++ // An unrelated untagged turn must not inherit the task's approval ownership.+ const { delegatedTaskId: _, ...legacyRun } = approvalRun;+ const foreignRun = {+ ...legacyRun,+ id: RunId.make("run:foreign-approval"),+ ordinal: 2,+ };+ const foreignNode = {+ ...approvalNode,+ id: NodeId.make("node:foreign-approval"),+ runId: foreignRun.id,+ };+ yield* eventSink.write({+ events: [+ {+ id: EventId.make("event:foreign-approval-run"),+ type: "run.updated",+ threadId: approvalChildId,+ occurredAt: approvalAskedAt,+ payload: foreignRun,+ },+ {+ id: EventId.make("event:foreign-approval-node"),+ type: "node.updated",+ threadId: approvalChildId,+ occurredAt: approvalAskedAt,+ payload: foreignNode,+ },+ ],+ });+ yield* persistRequest(approvalRequest("foreign", { nodeId: foreignNode.id }));+ expect((yield* readApprovalStatus()).pendingApproval).toBeNull();++ const liveApproval = approvalRequest("live");+ yield* persistRequest(liveApproval);+ const approvalResult = yield* decodeDelegateTaskResult(+ (yield* Fiber.join(approvalWait)).structuredContent,+ ).pipe(Effect.orDie);+ const expectedApproval = {+ requestId: liveApproval.id,+ kind: "command",+ runId: approvalRun.id,+ };+ expect(approvalResult).toMatchObject({+ taskId: approvalTask.id,+ status: "running",+ hasPendingQuestion: false,+ pendingApproval: expectedApproval,+ waitTimedOut: false,+ });+ expect(approvalResult.pendingApproval).toEqual(expectedApproval);+ // A retry sees the persisted approval in its initial snapshot.+ expect((yield* delegateApproval).structuredContent).toMatchObject({+ taskId: approvalTask.id,+ status: "running",+ pendingApproval: expectedApproval,+ waitTimedOut: false,+ });+ const earlierApproval = approvalRequest("earlier", {+ createdAt: DateTime.subtract(approvalAskedAt, { seconds: 1 }),+ });+ yield* persistRequest(earlierApproval);+ expect((yield* readApprovalStatus()).pendingApproval?.requestId).toBe(+ earlierApproval.id,+ );+ yield* persistRequest({+ ...earlierApproval,+ status: "resolved",+ resolvedAt: approvalAskedAt,+ });++ // Legacy ownership falls back to the original run, never the other run.+ yield* persistApprovalEvent({+ id: EventId.make("event:approval-legacy"),+ type: "run.updated",+ threadId: approvalChildId,+ occurredAt: approvalAskedAt,+ payload: legacyRun,+ });+ expect((yield* readApprovalStatus()).pendingApproval).toEqual(expectedApproval);+ yield* persistRequest({+ ...liveApproval,+ status: "resolved",+ resolvedAt: approvalAskedAt,+ });+ expect((yield* readApprovalStatus()).pendingApproval).toBeNull();+ // Finish the synthetic foreign run before releasing the real child.+ yield* eventSink.write({+ events: [+ {+ id: EventId.make("event:approval-modern"),+ type: "run.updated",+ threadId: approvalChildId,+ occurredAt: approvalAskedAt,+ payload: approvalRun,+ },+ {+ id: EventId.make("event:foreign-approval-done"),+ type: "run.updated",+ threadId: approvalChildId,+ occurredAt: approvalAskedAt,+ payload: { ...foreignRun, status: "completed", completedAt: approvalAskedAt },+ },+ ],+ });+ yield* Deferred.succeed(approvalChildGate, undefined);+ yield* awaitApprovalEvent(+ approvalParentId,+ (event) =>+ event.type === "subagent.updated" &&+ event.payload.id === approvalTask.id &&+ event.payload.status === "completed",+ );+ const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;+ yield* Deferred.await(approvalOffered);+ yield* worker.drain();+ const approvalCompletedTask = (yield* orchestrator.getThreadProjection(+ approvalParentId,+ )).subagents[0]!;+ expect(approvalCompletedTask).toMatchObject({+ status: "completed",+ completionWake: "always",+ result: `Codex completed: ${approvalCompletionPrompt}`,+ });+ const offers = (yield* Ref.get(continuationOffers)).filter(+ (offer) => offer.threadId === approvalParentId,+ );+ expect(offers).toHaveLength(1);+ const approvalParent = yield* orchestrator.getThreadProjection(approvalParentId);+ const approvalDelivery = approvalParent.runs[0]!.delegatedCompletion?.delivery;+ expect(approvalDelivery?.taskIds).toEqual([approvalTask.id]);+ expect(offers[0]?.delegatedCompletion?.messageId).toBe(approvalDelivery?.messageId);+ expect(yield* readApprovalStatus()).toMatchObject({+ status: "completed",+ summary: `Codex completed: ${approvalCompletionPrompt}`,+ pendingApproval: null,+ waitTimedOut: false,+ });+ // Durable live records may outlast a terminal run or a stopped/disposed task.+ yield* persistRequest(approvalRequest("after-completion"));+ expect((yield* readApprovalStatus()).pendingApproval).toBeNull();+ yield* worker.drain();+ expect(+ (yield* Ref.get(continuationOffers)).filter(+ (offer) => offer.threadId === approvalParentId,+ ),+ ).toHaveLength(1);+ yield* Deferred.succeed(approvalParentGate, undefined);}).pipe(Effect.provide(layerTest));}),),diff --git a/apps/server/src/mcp/toolkits/orchestrator/tools.ts b/apps/server/src/mcp/toolkits/orchestrator/tools.tsindex 6ffdfcc6871..867555244fa 100644--- a/apps/server/src/mcp/toolkits/orchestrator/tools.ts+++ b/apps/server/src/mcp/toolkits/orchestrator/tools.ts@@ -65,7 +65,7 @@ const OrchestratorCapabilitiesTool = Tool.make("orchestrator_capabilities", {export const DelegateTaskTool = Tool.make("delegate_task", {description:- "Needs an agent running inside a T3 thread. Delegate one task to a T3-owned child agent/subagent of THIS thread and run it with only the supplied task prompt, without copying parent conversation history. Choose providers and models from orchestrator_capabilities, which uses the same live catalog as the composer. Prefer native subagent tools for same-provider work only when they support the chosen model and no model options are requested or inherited. Use this for any model missing from the native tool, including same-provider work, for cross-provider work, or for explicitly T3-owned child tasks. For every T3 delegated review round, call delegate_task again with the original brief, prior findings, responses, and unresolved objections in the task prompt. Track each round by its own taskId and use a distinct clientRequestId per round, stable across retries of that round. The childThreadId is backing storage, not the target for starting another delegated review round through t3_thread_send. Set isolation to worktree for a separate checkout based on the parent local commit, with project setup completed before the child starts. Uncommitted edits are not copied; omitted isolation shares the parent checkout. Use delegate_task when model options are requested or the child keeps the parent's provider instance and model with nonempty inheritedOptions from orchestrator_capabilities, even for native-supported models. Native subagents cannot reliably apply T3 model options. Set target.options using advertised IDs: Claude {effort: 'max', fastMode: true}; Codex {reasoningEffort: 'max', serviceTier: 'priority'}. Check providerInstanceId, model, and options in the result. Provider/model and modes inherit unless overridden. Options inherit only for the same instance and model; explicit entries override individual values and [] or {} clears them. A requested runtimeMode must be one the target provider lists in orchestrator_capabilities runtimeModes; an inherited one steps down to the broadest mode it offers. Leave runtimeMode unset unless the user asks for a supervised child: approval-required and auto-accept-edits usually make the child wait for a person at each action that needs approval. Prefer mode='async' for long work; mode='wait' blocks until completion, a blocking question, or timeout. If hasPendingQuestion, pass threadId=childThreadId to t3_pending_request_list, t3_pending_request_read (with requestId) and t3_pending_request_respond, or ask the user; the task's completion still wakes this thread. timeoutMs on mode=wait is only the parent's wait budget and does not cancel the child. waitTimedOut on that wait call means the timeout fired; keep that taskId and read status on later task_status. An async child's completion wakes this thread through a notification, steered into active turns where supported or queued otherwise, so end the turn instead of polling or spawning watchers; use task_status only when the result is needed mid-turn.",+ "Needs an agent running inside a T3 thread. Delegate one task to a T3-owned child agent/subagent of THIS thread and run it with only the supplied task prompt, without copying parent conversation history. Choose providers and models from orchestrator_capabilities, which uses the same live catalog as the composer. Prefer native subagent tools for same-provider work only when they support the chosen model and no model options are requested or inherited. Use this for any model missing from the native tool, including same-provider work, for cross-provider work, or for explicitly T3-owned child tasks. For every T3 delegated review round, call delegate_task again with the original brief, prior findings, responses, and unresolved objections in the task prompt. Track each round by its own taskId and use a distinct clientRequestId per round, stable across retries of that round. The childThreadId is backing storage, not the target for starting another delegated review round through t3_thread_send. Set isolation to worktree for a separate checkout based on the parent local commit, with project setup completed before the child starts. Uncommitted edits are not copied; omitted isolation shares the parent checkout. Use delegate_task when model options are requested or the child keeps the parent's provider instance and model with nonempty inheritedOptions from orchestrator_capabilities, even for native-supported models. Native subagents cannot reliably apply T3 model options. Set target.options using advertised IDs: Claude {effort: 'max', fastMode: true}; Codex {reasoningEffort: 'max', serviceTier: 'priority'}. Check providerInstanceId, model, and options in the result. Provider/model and modes inherit unless overridden. Options inherit only for the same instance and model; explicit entries override individual values and [] or {} clears them. A requested runtimeMode must be one the target provider lists in orchestrator_capabilities runtimeModes; an inherited one steps down to the broadest mode it offers. Leave runtimeMode unset unless the user asks for a supervised child: approval-required and auto-accept-edits usually make the child wait for a person at each action that needs approval. Prefer mode='async' for long work; mode='wait' blocks until completion, a blocking question, a pending approval, or timeout. If hasPendingQuestion, pass threadId=childThreadId to t3_pending_request_list, t3_pending_request_read (with requestId) and t3_pending_request_respond, or ask the user; the task's completion still wakes this thread. If pendingApproval is set, read the fresh full request in childThreadId before responding: the record can outlive its provider callback. It grants no approval authority; decisions remain with the child's existing approval holder, and pending request tools answer questions only. The child keeps running and its completion still wakes this thread. timeoutMs on mode=wait is only the parent's wait budget and does not cancel the child. waitTimedOut on that wait call means the timeout fired; keep that taskId and read status on later task_status. An async child's completion wakes this thread through a notification, steered into active turns where supported or queued otherwise, so end the turn instead of polling or spawning watchers; use task_status only when the result is needed mid-turn.",parameters: OrchestratorMcpDelegateTaskInput,success: OrchestratorMcpDelegateTaskResult,failure: OrchestratorMcpFailure,@@ -78,7 +78,7 @@ export const DelegateTaskTool = Tool.make("delegate_task", {const TaskStatusTool = Tool.make("task_status", {description:- "Needs an agent running inside a T3 thread. Read a T3-owned delegated task created by this parent thread. childRunId identifies the original delegated run. workState distinguishes working, waiting_for_children, and result_available; a completed turn with live nested work is not a completed task. summary is the final task result, including provider errors on failure, and remains stable after publication. hasPendingChildRuns reports later queued or executing turns in the backing child thread, even after the task is terminal; it does not reopen the task, and task_cancel stops those turns too. Turns held in a stopped queue wait for the user and do not count. latestTerminal* provides later non-monitor turn results; latestTerminalSummary and latestTerminalResultContextTransferId are independently null when they exactly repeat summary and resultContextTransferId, respectively. Reading a terminal result acknowledges its automatic parent delivery.",+ "Needs an agent running inside a T3 thread. Read a T3-owned delegated task created by this parent thread. childRunId identifies the original delegated run. workState distinguishes working, waiting_for_children, and result_available; a completed turn with live nested work is not a completed task. summary is the final task result, including provider errors on failure, and remains stable after publication. hasPendingChildRuns reports later queued or executing turns in the backing child thread, even after the task is terminal; it does not reopen the task, and task_cancel stops those turns too. Turns held in a stopped queue wait for the user and do not count. latestTerminal* provides later non-monitor turn results; latestTerminalSummary and latestTerminalResultContextTransferId are independently null when they exactly repeat summary and resultContextTransferId, respectively. pendingApproval identifies the oldest pending live approval for this task's own unfinished work. Read the fresh full request in childThreadId before responding: the record can outlive its provider callback and grants no approval authority. Decisions remain with the child's existing approval holder. Reading a terminal result acknowledges its automatic parent delivery.",parameters: OrchestratorMcpTaskStatusInput,success: OrchestratorMcpDelegateTaskResult,failure: OrchestratorMcpFailure,diff --git a/docs/orchestration-v2/orchestrator-mcp-server.md b/docs/orchestration-v2/orchestrator-mcp-server.mdindex 93f2f81d6bd..0672baf891d 100644--- a/docs/orchestration-v2/orchestrator-mcp-server.md+++ b/docs/orchestration-v2/orchestrator-mcp-server.md@@ -263,7 +263,10 @@ the timeout expires. A wait timeout does not cancel the child; the result setsquestion also ends the wait with `hasPendingQuestion: true` and `waitTimedOut: false`.If `hasPendingQuestion`, pass `threadId=childThreadId` to `t3_pending_request_list`,`t3_pending_request_read` (with `requestId`) and `t3_pending_request_respond`, or ask-the user; the task's completion still wakes this thread. Async questions and approvals+the user; the task's completion still wakes this thread. A pending live approval for the+task's own unfinished work also ends the wait. Its identity appears in `pendingApproval`;+it grants no approval authority. Read the fresh full request in the child thread before+responding, since the durable record can outlive its provider callback. Async questionsdo not end the wait.```ts@@ -284,6 +287,11 @@ type DelegateTaskResult = {latestTerminalSummary: string | null;latestTerminalResultContextTransferId: string | null;hasPendingQuestion: boolean;+ pendingApproval: {+ requestId: string;+ kind: "command" | "file-read" | "file-change" | "mcp-elicitation" | "permission";+ runId: string;+ } | null;waitTimedOut: boolean;};```diff --git a/packages/contracts/src/orchestratorMcp.test.ts b/packages/contracts/src/orchestratorMcp.test.tsindex e6e46a2346c..8b10fa9d325 100644--- a/packages/contracts/src/orchestratorMcp.test.ts+++ b/packages/contracts/src/orchestratorMcp.test.ts@@ -59,12 +59,31 @@ describe("orchestrator MCP contracts", () => {latestTerminalSummary: "Workspace inspected.",latestTerminalResultContextTransferId: "context-transfer-result-1",hasPendingQuestion: false,+ pendingApproval: null,waitTimedOut: false,});expect(request.target?.providerInstanceId).toBe("claudeAgent");expect(result.status).toBe("completed");expect(result.summary).toBe("Workspace inspected.");+ expect(result.pendingApproval).toBeNull();+ const pendingApproval = {+ requestId: "request-approval-1",+ kind: "command",+ runId: "run-child-1",+ };+ expect(+ decodeDelegateTaskResult({+ ...result,+ pendingApproval: { ...pendingApproval, input: { command: "private command" } },+ }).pendingApproval,+ ).toEqual(pendingApproval);+ expect(() =>+ decodeDelegateTaskResult({+ ...result,+ pendingApproval: { ...pendingApproval, kind: "user_input" },+ }),+ ).toThrow();});it("decodes target model options in canonical and shorthand shapes", () => {diff --git a/packages/contracts/src/orchestratorMcp.ts b/packages/contracts/src/orchestratorMcp.tsindex 9e0348b0120..7d643be9107 100644--- a/packages/contracts/src/orchestratorMcp.ts+++ b/packages/contracts/src/orchestratorMcp.ts@@ -11,6 +11,7 @@ import {PositiveInt,ProjectId,RunId,+ RuntimeRequestId,ScheduledTaskId,SecretRef,ThreadId,@@ -22,7 +23,7 @@ import {ScheduledTaskSchedule,ScheduledTaskUpsertSchedule,} from "./scheduledTask.ts";-import { ProviderInteractionMode, RuntimeMode } from "./providerPolicy.ts";+import { ProviderInteractionMode, ProviderRequestKind, RuntimeMode } from "./providerPolicy.ts";import { PullRequestState } from "./pullRequest.ts";import {ThreadLinkedPullRequest,@@ -176,7 +177,7 @@ export const OrchestratorMcpDelegateTaskInput = Schema.Struct({mode: Schema.optional(Schema.Literals(["async", "wait"]).annotate({description:- "Defaults to async. Use wait only when this turn needs the child's result before you can continue.",+ "Defaults to async. Use wait only when this turn needs the child's result before you can continue. A blocking question or a pending approval in the child ends the wait early with the task still running.",}),),timeoutMs: Schema.optional(Schema.Finite).annotate({@@ -220,6 +221,12 @@ export const OrchestratorMcpDelegateTaskResult = Schema.Struct({description:"Blocking question ends mode=wait. Pass threadId=childThreadId to t3_pending_request_list, t3_pending_request_read (with requestId) and t3_pending_request_respond, or ask the user; the task's completion still wakes this thread.",}),+ pendingApproval: Schema.NullOr(+ Schema.Struct({ requestId: RuntimeRequestId, kind: ProviderRequestKind, runId: RunId }),+ ).annotate({+ description:+ "Identity of the oldest pending live approval for this task's own unfinished work, or null. Ends mode=wait without cancelling the child; completion still wakes this thread. This grants no approval authority. Read the fresh full request in childThreadId before responding: the record can outlive its provider callback. Decisions remain with the child's existing approval holder; pending request tools answer questions only.",+ }),waitTimedOut: Schema.Boolean.annotate({description:"True only on that mode=wait call when timeoutMs elapsed. The timeout does not cancel the child. Later task_status reads return false and use status for liveness.",