@devries-cameron20 / t3code Mirror · read-only / commits / 6f891541fd
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 22, 23:15 UTC

fix(server): return delegated waits on pending approvals (#20037)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Julius Marminge <julius0216@outlook.com>

Gustav committed Oct 20, 2026 at 07:06 UTC 6f891541fd160fe76c25ff80104296d7081a22ac
6 files changed +449 -11
apps/server/src/mcp/OrchestratorMcpService.ts
+64 -4
@@ -54,6 +54,7 @@ import {
54 type ProviderInstanceId,
55 type ProviderOptionDescriptor,
56 type ProviderOptionSelection,
57 + ProviderRequestKind,
58 type RuntimeMode,
59 type ScheduledTask,
60 type ScheduledTaskUpsertInput,
@@ -416,6 +417,53 @@ function isTerminalTaskStatus(
417 );
418 }
419
420 +function endsTaskWait(result: OrchestratorMcpDelegateTaskResult): boolean {
421 + return (
422 + result.hasPendingQuestion ||
423 + result.pendingApproval !== null ||
424 + isTerminalTaskStatus(result.status)
425 + );
426 +}
427 +
428 +const isApprovalRequestKind = Schema.is(ProviderRequestKind);
429 +
430 +function pendingTaskApproval(
431 + child: Pick<OrchestrationV2ThreadProjection, "runs" | "nodes" | "runtimeRequests">,
432 + taskId: NodeId,
433 + originalRun: OrchestrationV2Run | undefined,
434 +) {
435 + const taskRunIds = new Set(
436 + child.runs
437 + .filter(
438 + (run) =>
439 + !ThreadManagementService.isTerminalRunStatus(run.status) &&
440 + (run.delegatedTaskId === taskId ||
441 + // Legacy tasks own only their original run, not later turns in the child thread.
442 + (run.delegatedTaskId === undefined && run.id === originalRun?.id)),
443 + )
444 + .map((run) => run.id),
445 + );
446 + let approval: OrchestratorMcpDelegateTaskResult["pendingApproval"] = null;
447 + let oldestCreatedAt = Infinity;
448 + for (const request of child.runtimeRequests) {
449 + if (
450 + request.status !== "pending" ||
451 + request.responseCapability.type !== "live" ||
452 + !isApprovalRequestKind(request.kind)
453 + ) {
454 + continue;
455 + }
456 + const runId = child.nodes.find((node) => node.id === request.nodeId)?.runId;
457 + if (runId === undefined || runId === null || !taskRunIds.has(runId)) continue;
458 + const createdAt = DateTime.toEpochMillis(request.createdAt);
459 + if (createdAt < oldestCreatedAt) {
460 + oldestCreatedAt = createdAt;
461 + approval = { requestId: request.id, kind: request.kind, runId };
462 + }
463 + }
464 + return approval;
465 +}
466 +
467 function directAppOwnedChildTasks(
468 parent: Pick<OrchestrationV2ThreadProjection, "thread" | "subagents">,
469 target: Pick<OrchestrationV2ThreadProjection, "thread" | "runs">,
@@ -1379,8 +1427,16 @@ const make = Effect.gen(function* () {
1427 const childControls = yield* threadManagement
1428 .getThreadRecords(
1429 task.childThreadId,
1382 - ["runs", "messages", "contextTransfers", "subagents", "providerThreads", "runtimeRequests"],
1383 - { messageRoles: ["user"] },
1430 + [
1431 + "runs",
1432 + "messages",
1433 + "contextTransfers",
1434 + "subagents",
1435 + "providerThreads",
1436 + "runtimeRequests",
1437 + "nodes",
1438 + ],
1439 + { messageRoles: ["user"], omitSettledLeafNodes: true },
1440 )
1441 .pipe(Effect.mapError(threadManagementFailure));
1442 const childRun = delegatedTaskRun(childControls, task);
@@ -1502,6 +1558,10 @@ const make = Effect.gen(function* () {
1558 request.status === "pending" &&
1559 request.responseCapability.type === "live",
1560 ),
1561 + pendingApproval:
1562 + isTerminalTaskStatus(status) || task.completionDelivery?.state === "disposed"
1563 + ? null
1564 + : pendingTaskApproval(childControls, task.id, childRun),
1565 waitTimedOut,
1566 } satisfies OrchestratorMcpDelegateTaskResult;
1567 if (
@@ -1552,7 +1612,7 @@ const make = Effect.gen(function* () {
1612 .getThreadEventSequence(scope.thread.threadId)
1613 .pipe(Effect.mapError(streamError));
1614 const initial = yield* readTask(scope, taskId, false, true);
1555 - if (initial.hasPendingQuestion || isTerminalTaskStatus(initial.status)) {
1615 + if (endsTaskWait(initial)) {
1616 return Option.some(initial);
1617 }
1618 // One stream per event type, so transcript events never fill a buffer.
@@ -1568,7 +1628,7 @@ const make = Effect.gen(function* () {
1628 ).pipe(
1629 Stream.mapError(streamError),
1630 Stream.mapEffect(() => readTask(scope, taskId, false, true)),
1571 - Stream.filter((result) => result.hasPendingQuestion || isTerminalTaskStatus(result.status)),
1631 + Stream.filter(endsTaskWait),
1632 Stream.runHead,
1633 );
1634 },
apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts
+346 -2
@@ -9,11 +9,15 @@ import {
9 IsoDateTime,
10 isProviderNativeSubagentThread,
11 MessageId,
12 + NodeId,
13 + RunId,
14 type ModelSelection,
15 type OrchestrationV2DelegatedCompletionDelivery,
16 + type OrchestrationV2DomainEvent,
17 type OrchestrationV2ProviderCapabilities,
18 type OrchestrationV2ProviderSession,
19 type OrchestrationV2ProviderThread,
20 + type OrchestrationV2RuntimeRequest,
21 type OrchestrationV2ThreadProjection,
22 OrchestratorMcpCreateThreadsResult,
23 OrchestratorMcpDelegateTaskResult,
@@ -56,6 +60,7 @@ import { CodexProviderCapabilitiesV2 } from "../orchestration-v2/Adapters/CodexA
60 import { CodexOrchestratorReplayHarness } from "../orchestration-v2/Adapters/CodexAdapterV2.testkit.ts";
61 import { threadShellFromProjection } from "../orchestration-v2/ProjectionStore.ts";
62 import * as CommandReceiptStore from "../orchestration-v2/CommandReceiptStore.ts";
63 +import * as EffectWorker from "../orchestration-v2/EffectWorker.ts";
64 import * as EventSink from "../orchestration-v2/EventSink.ts";
65 import * as Orchestrator from "../orchestration-v2/Orchestrator.ts";
66 import * as ThreadLaunchService from "../orchestration-v2/ThreadLaunchService.ts";
@@ -108,6 +113,7 @@ const cancellationPrompt = "Remain active until the parent cancels this delegate
113 const createdThreadPrompt = "Complete the newly created ordinary thread.";
114 const queuedFollowupPrompt = "Complete the queued follow-up and return the final result.";
115 const queuedFollowupResult = "Queued delegated follow-up completed.";
116 +const approvalCompletionPrompt = "Finish the delegated work once its approval is decided.";
117
118 const decodeCreateThreadsResult = Schema.decodeUnknownEffect(OrchestratorMcpCreateThreadsResult);
119 const decodeDelegateTaskResult = Schema.decodeUnknownEffect(OrchestratorMcpDelegateTaskResult);
@@ -542,6 +548,8 @@ describe("orchestrator MCP toolkit", () => {
548 const steerReceivedGates = new Map<string, Deferred.Deferred<void>>();
549 const parentTerminalGates = new Map<ThreadId, Deferred.Deferred<void>>();
550 const deliveryTerminalGates = new Map<ThreadId, Deferred.Deferred<void>>();
551 + // Holds a delegated child whose thread id is not known until it starts.
552 + const promptTerminalGates = new Map<string, Deferred.Deferred<void>>();
553 const layerRegistry = ProviderAdapterRegistry.layerFromAdapters([
554 makeDeterministicAdapter({
555 instanceId: codexInstanceId,
@@ -557,7 +565,8 @@ describe("orchestrator MCP toolkit", () => {
565 turn.message.text.startsWith("Delegated task") ||
566 turn.message.text.startsWith("Delegated tasks")
567 ? deliveryTerminalGates.get(turn.threadId)
560 - : parentTerminalGates.get(turn.threadId),
568 + : (parentTerminalGates.get(turn.threadId) ??
569 + promptTerminalGates.get(turn.message.text)),
570 response: (turn) => `Codex completed: ${turn.message.text}`,
571 }),
572 makeDeterministicAdapter({
@@ -578,6 +587,8 @@ describe("orchestrator MCP toolkit", () => {
587 steerReceived: (steer) => steerReceivedGates.get(steer.message.text),
588 }),
589 ]);
590 + const approvalParentId = ThreadId.make("thread:mcp-approval-parent");
591 + const approvalOffered = yield* Deferred.make<void>();
592 const continuationOffers = yield* Ref.make<
593 ReadonlyArray<ProviderContinuationRequests.ProviderContinuationRequest>
594 >([]);
@@ -585,7 +596,13 @@ describe("orchestrator MCP toolkit", () => {
596 ProviderContinuationRequests.ProviderContinuationRequests,
597 {
598 offer: (request) =>
588 - Ref.update(continuationOffers, (existing) => [...existing, request]),
599 + Ref.update(continuationOffers, (existing) => [...existing, request]).pipe(
600 + Effect.andThen(
601 + request.threadId === approvalParentId
602 + ? Deferred.succeed(approvalOffered, undefined)
603 + : Effect.void,
604 + ),
605 + ),
606 take: Effect.never,
607 },
608 );
@@ -2964,6 +2981,43 @@ describe("orchestrator MCP toolkit", () => {
2981 p.subagents.some((task) => task.id === question.id && task.status === "interrupted"),
2982 );
2983
2984 + // Stop disposes delivery even if a live approval record survives it.
2985 + yield* (yield* EventSink.EventSinkV2).write({
2986 + events: [
2987 + {
2988 + id: EventId.make("event:approval-after-stop"),
2989 + type: "runtime-request.updated",
2990 + threadId: question.childThreadId!,
2991 + occurredAt: askedAt,
2992 + payload: {
2993 + id: RuntimeRequestId.make("request:approval-after-stop"),
2994 + nodeId: asking.nodes.find((node) => node.runId === asking.runs[0]!.id)!.id,
2995 + providerTurnId: null,
2996 + nativeRequestRef: null,
2997 + kind: "command",
2998 + status: "pending",
2999 + responseCapability: {
3000 + type: "live",
3001 + providerSessionId: asking.providerSessions[0]!.id,
3002 + },
3003 + createdAt: askedAt,
3004 + resolvedAt: null,
3005 + },
3006 + },
3007 + ],
3008 + });
3009 + expect(
3010 + (yield* invoke("task_status", { taskId: question.id })).structuredContent,
3011 + ).toMatchObject({
3012 + status: "interrupted",
3013 + pendingApproval: null,
3014 + });
3015 + expect(
3016 + (yield* orchestrator.getThreadProjection(parentThreadId)).subagents.find(
3017 + (task) => task.id === question.id,
3018 + )?.completionDelivery,
3019 + ).toMatchObject({ state: "disposed" });
3020 +
3021 const terminalUpgrade = yield* orchestrator.dispatch({
3022 type: "delegated_task.wake-policy",
3023 commandId: CommandId.make("command:mcp-parent:wake-policy-terminal"),
@@ -4010,6 +4064,296 @@ describe("orchestrator MCP toolkit", () => {
4064 thirdFanoutDelivery.messageId,
4065 ]),
4066 );
4067 +
4068 + // Keep completion delivery separate from the earlier fan-out cohorts.
4069 + const approvalParentGate = yield* Deferred.make<void>();
4070 + const approvalChildGate = yield* Deferred.make<void>();
4071 + parentTerminalGates.set(approvalParentId, approvalParentGate);
4072 + promptTerminalGates.set(approvalCompletionPrompt, approvalChildGate);
4073 + yield* Ref.set(continuationOffers, []);
4074 + const approvalStart = (yield* orchestrator.dispatch({
4075 + type: "thread.create",
4076 + createdBy: "user",
4077 + creationSource: "web",
4078 + commandId: CommandId.make("command:approval-parent:create"),
4079 + threadId: approvalParentId,
4080 + projectId,
4081 + title: "Approval parent",
4082 + modelSelection: codexSelection,
4083 + runtimeMode: "full-access",
4084 + interactionMode: "default",
4085 + branch: null,
4086 + worktreePath: cwd,
4087 + })).sequence;
4088 + const awaitApprovalEvent = (
4089 + threadId: ThreadId,
4090 + matches: (event: OrchestrationV2DomainEvent) => boolean,
4091 + ) =>
4092 + orchestrator.streamStoredEventsFrom({ threadId, afterSequence: approvalStart }).pipe(
4093 + Stream.filter((stored) => matches(stored.event)),
4094 + Stream.runHead,
4095 + Effect.flatMap(
4096 + Option.match({
4097 + onNone: () => Effect.die("Approval scenario event stream ended."),
4098 + onSome: () => Effect.void,
4099 + }),
4100 + ),
4101 + );
4102 + yield* orchestrator.dispatch({
4103 + type: "message.dispatch",
4104 + createdBy: "user",
4105 + creationSource: "web",
4106 + commandId: CommandId.make("command:approval-parent:start"),
4107 + threadId: approvalParentId,
4108 + messageId: MessageId.make("message:approval-parent:start"),
4109 + text: "Hold this parent while its child asks for approval.",
4110 + attachments: [],
4111 + modelSelection: codexSelection,
4112 + dispatchMode: { type: "start_immediately" },
4113 + });
4114 + yield* awaitApprovalEvent(
4115 + approvalParentId,
4116 + (event) =>
4117 + event.type === "provider-turn.updated" && event.payload.status === "running",
4118 + );
4119 + const approvalScope = {
4120 + ...invocation,
4121 + requestNamespace: "mcp-approval-parent",
4122 + thread: { ...invocation.thread!, threadId: approvalParentId },
4123 + };
4124 + const delegateApproval = invokeAs(approvalScope, "delegate_task", {
4125 + task: approvalCompletionPrompt,
4126 + title: "Approval completion",
4127 + target: { providerInstanceId: codexInstanceId, model: codexModel },
4128 + mode: "wait",
4129 + timeoutMs: 30_000,
4130 + clientRequestId: "delegate-approval-completion",
4131 + });
4132 + const approvalWait = yield* delegateApproval.pipe(Effect.forkChild);
4133 + yield* awaitApprovalEvent(
4134 + approvalParentId,
4135 + (event) => event.type === "subagent.updated" && event.payload.childThreadId !== null,
4136 + );
4137 + const approvalTask = (yield* orchestrator.getThreadProjection(approvalParentId))
4138 + .subagents[0]!;
4139 + const approvalChildId = approvalTask.childThreadId!;
4140 + yield* awaitApprovalEvent(
4141 + approvalChildId,
4142 + (event) =>
4143 + event.type === "provider-turn.updated" && event.payload.status === "running",
4144 + );
4145 + const approvalChild = yield* orchestrator.getThreadProjection(approvalChildId);
4146 + const approvalRun = approvalChild.runs[0]!;
4147 + const approvalNode = approvalChild.nodes.find((node) => node.runId === approvalRun.id)!;
4148 + const approvalAskedAt = yield* DateTime.now;
4149 + const approvalRequest = (
4150 + id: string,
4151 + overrides: Partial<OrchestrationV2RuntimeRequest> = {},
4152 + ): OrchestrationV2RuntimeRequest => ({
4153 + id: RuntimeRequestId.make(`request:approval:${id}`),
4154 + nodeId: approvalNode.id,
4155 + providerTurnId: null,
4156 + nativeRequestRef: null,
4157 + kind: "command",
4158 + status: "pending",
4159 + responseCapability: {
4160 + type: "live",
4161 + providerSessionId: approvalChild.providerSessions[0]!.id,
4162 + },
4163 + createdAt: approvalAskedAt,
4164 + resolvedAt: null,
4165 + ...overrides,
4166 + });
4167 + const eventSink = yield* EventSink.EventSinkV2;
4168 + let approvalEventId = 0;
4169 + const persistApprovalEvent = (event: OrchestrationV2DomainEvent) =>
4170 + eventSink.write({ events: [event] });
4171 + const persistRequest = (
4172 + request: OrchestrationV2RuntimeRequest,
4173 + threadId = approvalChildId,
4174 + ) =>
4175 + persistApprovalEvent({
4176 + id: EventId.make(`event:approval:${++approvalEventId}`),
4177 + type: "runtime-request.updated",
4178 + threadId,
4179 + occurredAt: approvalAskedAt,
4180 + payload: request,
4181 + });
4182 + const readApprovalStatus = () =>
4183 + invokeAs(approvalScope, "task_status", { taskId: approvalTask.id }).pipe(
4184 + Effect.flatMap((result) => decodeDelegateTaskResult(result.structuredContent)),
4185 + Effect.orDie,
4186 + );
4187 +
4188 + // These durable records must not make the parent's wait return an approval.
4189 + for (const request of [
4190 + approvalRequest("resolved", { status: "resolved", resolvedAt: approvalAskedAt }),
4191 + approvalRequest("expired", { status: "expired", resolvedAt: approvalAskedAt }),
4192 + approvalRequest("cancelled", { status: "cancelled", resolvedAt: approvalAskedAt }),
4193 + approvalRequest("message", { responseCapability: { type: "message" } }),
4194 + approvalRequest("not-live", {
4195 + responseCapability: { type: "not_resumable", reason: "Session ended." },
4196 + }),
4197 + approvalRequest("question", {
4198 + kind: "user_input",
4199 + responseCapability: { type: "message" },
4200 + }),
4201 + approvalRequest("auth", { kind: "auth_refresh" }),
4202 + approvalRequest("tool", { kind: "dynamic_tool_call" }),
4203 + approvalRequest("missing-node", { nodeId: NodeId.make("node:missing-approval") }),
4204 + ]) {
4205 + yield* persistRequest(request);
4206 + }
4207 + expect((yield* readApprovalStatus()).pendingApproval).toBeNull();
4208 +
4209 + // An unrelated untagged turn must not inherit the task's approval ownership.
4210 + const { delegatedTaskId: _, ...legacyRun } = approvalRun;
4211 + const foreignRun = {
4212 + ...legacyRun,
4213 + id: RunId.make("run:foreign-approval"),
4214 + ordinal: 2,
4215 + };
4216 + const foreignNode = {
4217 + ...approvalNode,
4218 + id: NodeId.make("node:foreign-approval"),
4219 + runId: foreignRun.id,
4220 + };
4221 + yield* eventSink.write({
4222 + events: [
4223 + {
4224 + id: EventId.make("event:foreign-approval-run"),
4225 + type: "run.updated",
4226 + threadId: approvalChildId,
4227 + occurredAt: approvalAskedAt,
4228 + payload: foreignRun,
4229 + },
4230 + {
4231 + id: EventId.make("event:foreign-approval-node"),
4232 + type: "node.updated",
4233 + threadId: approvalChildId,
4234 + occurredAt: approvalAskedAt,
4235 + payload: foreignNode,
4236 + },
4237 + ],
4238 + });
4239 + yield* persistRequest(approvalRequest("foreign", { nodeId: foreignNode.id }));
4240 + expect((yield* readApprovalStatus()).pendingApproval).toBeNull();
4241 +
4242 + const liveApproval = approvalRequest("live");
4243 + yield* persistRequest(liveApproval);
4244 + const approvalResult = yield* decodeDelegateTaskResult(
4245 + (yield* Fiber.join(approvalWait)).structuredContent,
4246 + ).pipe(Effect.orDie);
4247 + const expectedApproval = {
4248 + requestId: liveApproval.id,
4249 + kind: "command",
4250 + runId: approvalRun.id,
4251 + };
4252 + expect(approvalResult).toMatchObject({
4253 + taskId: approvalTask.id,
4254 + status: "running",
4255 + hasPendingQuestion: false,
4256 + pendingApproval: expectedApproval,
4257 + waitTimedOut: false,
4258 + });
4259 + expect(approvalResult.pendingApproval).toEqual(expectedApproval);
4260 + // A retry sees the persisted approval in its initial snapshot.
4261 + expect((yield* delegateApproval).structuredContent).toMatchObject({
4262 + taskId: approvalTask.id,
4263 + status: "running",
4264 + pendingApproval: expectedApproval,
4265 + waitTimedOut: false,
4266 + });
4267 + const earlierApproval = approvalRequest("earlier", {
4268 + createdAt: DateTime.subtract(approvalAskedAt, { seconds: 1 }),
4269 + });
4270 + yield* persistRequest(earlierApproval);
4271 + expect((yield* readApprovalStatus()).pendingApproval?.requestId).toBe(
4272 + earlierApproval.id,
4273 + );
4274 + yield* persistRequest({
4275 + ...earlierApproval,
4276 + status: "resolved",
4277 + resolvedAt: approvalAskedAt,
4278 + });
4279 +
4280 + // Legacy ownership falls back to the original run, never the other run.
4281 + yield* persistApprovalEvent({
4282 + id: EventId.make("event:approval-legacy"),
4283 + type: "run.updated",
4284 + threadId: approvalChildId,
4285 + occurredAt: approvalAskedAt,
4286 + payload: legacyRun,
4287 + });
4288 + expect((yield* readApprovalStatus()).pendingApproval).toEqual(expectedApproval);
4289 + yield* persistRequest({
4290 + ...liveApproval,
4291 + status: "resolved",
4292 + resolvedAt: approvalAskedAt,
4293 + });
4294 + expect((yield* readApprovalStatus()).pendingApproval).toBeNull();
4295 + // Finish the synthetic foreign run before releasing the real child.
4296 + yield* eventSink.write({
4297 + events: [
4298 + {
4299 + id: EventId.make("event:approval-modern"),
4300 + type: "run.updated",
4301 + threadId: approvalChildId,
4302 + occurredAt: approvalAskedAt,
4303 + payload: approvalRun,
4304 + },
4305 + {
4306 + id: EventId.make("event:foreign-approval-done"),
4307 + type: "run.updated",
4308 + threadId: approvalChildId,
4309 + occurredAt: approvalAskedAt,
4310 + payload: { ...foreignRun, status: "completed", completedAt: approvalAskedAt },
4311 + },
4312 + ],
4313 + });
4314 + yield* Deferred.succeed(approvalChildGate, undefined);
4315 + yield* awaitApprovalEvent(
4316 + approvalParentId,
4317 + (event) =>
4318 + event.type === "subagent.updated" &&
4319 + event.payload.id === approvalTask.id &&
4320 + event.payload.status === "completed",
4321 + );
4322 + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
4323 + yield* Deferred.await(approvalOffered);
4324 + yield* worker.drain();
4325 + const approvalCompletedTask = (yield* orchestrator.getThreadProjection(
4326 + approvalParentId,
4327 + )).subagents[0]!;
4328 + expect(approvalCompletedTask).toMatchObject({
4329 + status: "completed",
4330 + completionWake: "always",
4331 + result: `Codex completed: ${approvalCompletionPrompt}`,
4332 + });
4333 + const offers = (yield* Ref.get(continuationOffers)).filter(
4334 + (offer) => offer.threadId === approvalParentId,
4335 + );
4336 + expect(offers).toHaveLength(1);
4337 + const approvalParent = yield* orchestrator.getThreadProjection(approvalParentId);
4338 + const approvalDelivery = approvalParent.runs[0]!.delegatedCompletion?.delivery;
4339 + expect(approvalDelivery?.taskIds).toEqual([approvalTask.id]);
4340 + expect(offers[0]?.delegatedCompletion?.messageId).toBe(approvalDelivery?.messageId);
4341 + expect(yield* readApprovalStatus()).toMatchObject({
4342 + status: "completed",
4343 + summary: `Codex completed: ${approvalCompletionPrompt}`,
4344 + pendingApproval: null,
4345 + waitTimedOut: false,
4346 + });
4347 + // Durable live records may outlast a terminal run or a stopped/disposed task.
4348 + yield* persistRequest(approvalRequest("after-completion"));
4349 + expect((yield* readApprovalStatus()).pendingApproval).toBeNull();
4350 + yield* worker.drain();
4351 + expect(
4352 + (yield* Ref.get(continuationOffers)).filter(
4353 + (offer) => offer.threadId === approvalParentId,
4354 + ),
4355 + ).toHaveLength(1);
4356 + yield* Deferred.succeed(approvalParentGate, undefined);
4357 }).pipe(Effect.provide(layerTest));
4358 }),
4359 ),
apps/server/src/mcp/toolkits/orchestrator/tools.ts
+2 -2
@@ -65,7 +65,7 @@ const OrchestratorCapabilitiesTool = Tool.make("orchestrator_capabilities", {
65
66 export const DelegateTaskTool = Tool.make("delegate_task", {
67 description:
68 - "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.",
68 + "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.",
69 parameters: OrchestratorMcpDelegateTaskInput,
70 success: OrchestratorMcpDelegateTaskResult,
71 failure: OrchestratorMcpFailure,
@@ -78,7 +78,7 @@ export const DelegateTaskTool = Tool.make("delegate_task", {
78
79 const TaskStatusTool = Tool.make("task_status", {
80 description:
81 - "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.",
81 + "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.",
82 parameters: OrchestratorMcpTaskStatusInput,
83 success: OrchestratorMcpDelegateTaskResult,
84 failure: OrchestratorMcpFailure,
docs/orchestration-v2/orchestrator-mcp-server.md
+9 -1
@@ -263,7 +263,10 @@ the timeout expires. A wait timeout does not cancel the child; the result sets
263 question also ends the wait with `hasPendingQuestion: true` and `waitTimedOut: false`.
264 If `hasPendingQuestion`, pass `threadId=childThreadId` to `t3_pending_request_list`,
265 `t3_pending_request_read` (with `requestId`) and `t3_pending_request_respond`, or ask
266 -the user; the task's completion still wakes this thread. Async questions and approvals
266 +the user; the task's completion still wakes this thread. A pending live approval for the
267 +task's own unfinished work also ends the wait. Its identity appears in `pendingApproval`;
268 +it grants no approval authority. Read the fresh full request in the child thread before
269 +responding, since the durable record can outlive its provider callback. Async questions
270 do not end the wait.
271
272 ```ts
@@ -284,6 +287,11 @@ type DelegateTaskResult = {
287 latestTerminalSummary: string | null;
288 latestTerminalResultContextTransferId: string | null;
289 hasPendingQuestion: boolean;
290 + pendingApproval: {
291 + requestId: string;
292 + kind: "command" | "file-read" | "file-change" | "mcp-elicitation" | "permission";
293 + runId: string;
294 + } | null;
295 waitTimedOut: boolean;
296 };
297 ```
packages/contracts/src/orchestratorMcp.test.ts
+19
@@ -59,12 +59,31 @@ describe("orchestrator MCP contracts", () => {
59 latestTerminalSummary: "Workspace inspected.",
60 latestTerminalResultContextTransferId: "context-transfer-result-1",
61 hasPendingQuestion: false,
62 + pendingApproval: null,
63 waitTimedOut: false,
64 });
65
66 expect(request.target?.providerInstanceId).toBe("claudeAgent");
67 expect(result.status).toBe("completed");
68 expect(result.summary).toBe("Workspace inspected.");
69 + expect(result.pendingApproval).toBeNull();
70 + const pendingApproval = {
71 + requestId: "request-approval-1",
72 + kind: "command",
73 + runId: "run-child-1",
74 + };
75 + expect(
76 + decodeDelegateTaskResult({
77 + ...result,
78 + pendingApproval: { ...pendingApproval, input: { command: "private command" } },
79 + }).pendingApproval,
80 + ).toEqual(pendingApproval);
81 + expect(() =>
82 + decodeDelegateTaskResult({
83 + ...result,
84 + pendingApproval: { ...pendingApproval, kind: "user_input" },
85 + }),
86 + ).toThrow();
87 });
88
89 it("decodes target model options in canonical and shorthand shapes", () => {
packages/contracts/src/orchestratorMcp.ts
+9 -2
@@ -11,6 +11,7 @@ import {
11 PositiveInt,
12 ProjectId,
13 RunId,
14 + RuntimeRequestId,
15 ScheduledTaskId,
16 SecretRef,
17 ThreadId,
@@ -22,7 +23,7 @@ import {
23 ScheduledTaskSchedule,
24 ScheduledTaskUpsertSchedule,
25 } from "./scheduledTask.ts";
25 -import { ProviderInteractionMode, RuntimeMode } from "./providerPolicy.ts";
26 +import { ProviderInteractionMode, ProviderRequestKind, RuntimeMode } from "./providerPolicy.ts";
27 import { PullRequestState } from "./pullRequest.ts";
28 import {
29 ThreadLinkedPullRequest,
@@ -176,7 +177,7 @@ export const OrchestratorMcpDelegateTaskInput = Schema.Struct({
177 mode: Schema.optional(
178 Schema.Literals(["async", "wait"]).annotate({
179 description:
179 - "Defaults to async. Use wait only when this turn needs the child's result before you can continue.",
180 + "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.",
181 }),
182 ),
183 timeoutMs: Schema.optional(Schema.Finite).annotate({
@@ -220,6 +221,12 @@ export const OrchestratorMcpDelegateTaskResult = Schema.Struct({
221 description:
222 "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.",
223 }),
224 + pendingApproval: Schema.NullOr(
225 + Schema.Struct({ requestId: RuntimeRequestId, kind: ProviderRequestKind, runId: RunId }),
226 + ).annotate({
227 + description:
228 + "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.",
229 + }),
230 waitTimedOut: Schema.Boolean.annotate({
231 description:
232 "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.",