Skip to content

Commit d1f9fbd

Browse files
feat(server): delegate_task to a linked environment
delegate_task takes target.environmentId (and optionally target.projectId). The child then runs as an ordinary thread in the linked environment, launched through the link with a key derived from the caller's clientRequestId, in the project there with this thread's repository unless one is named. The parent here records the task with delegated_task.remote.request: its node, subagent row and turn item, with remoteChild instead of a local child thread. RemoteDelegation follows the thread there and completes the task with delegated_task.remote.complete, which reuses the parent half of a local finalize, so the parent wakes as it would for a local child. Open remote tasks are followed again at startup. A revoked or expired link fails the task with that reason; any other error backs off, up to five minutes. task_status and mode=wait answer from the row, task_cancel interrupts the thread there and completes the task as cancelled, and restart recovery no longer treats a remote task as abandoned provider work. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
1 parent f9da197 commit d1f9fbd

19 files changed

Lines changed: 2016 additions & 49 deletions

‎apps/server/src/mcp/OrchestratorMcpService.ts‎

Lines changed: 144 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -138,6 +138,17 @@ export interface OrchestratorMcpServiceShape {
138138
scope: McpInvocationScope,
139139
input: OrchestratorMcpTaskCancelInput,
140140
) => Effect.Effect<OrchestratorMcpTaskCancelResult, OrchestratorMcpFailure>;
141+
/** `mode=wait` on a task already recorded, as `delegateTask` does for its own. */
142+
readonly awaitTask: (
143+
scope: McpThreadInvocationScope,
144+
taskId: NodeId,
145+
timeoutMs: number | undefined,
146+
) => Effect.Effect<OrchestratorMcpDelegateTaskResult, OrchestratorMcpFailure>;
147+
/** The caller's task `taskId` when it runs in a linked environment. */
148+
readonly remoteTask: (
149+
scope: McpInvocationScope,
150+
taskId: NodeId,
151+
) => Effect.Effect<OrchestrationV2Subagent | undefined, OrchestratorMcpFailure>;
141152
readonly createThreads: (
142153
scope: McpInvocationScope,
143154
input: OrchestratorMcpCreateThreadsInput,
@@ -1238,12 +1249,15 @@ const make = Effect.gen(function* () {
12381249
candidate.origin === "app_owned" &&
12391250
candidate.threadId === scope.thread.threadId,
12401251
);
1241-
if (task === undefined || task.childThreadId === null) {
1252+
if (task === undefined || (task.childThreadId === null && task.remoteChild === undefined)) {
12421253
return yield* failure(
12431254
"task_not_found",
12441255
`Delegated task ${taskId} does not belong to thread ${scope.thread.threadId}.`,
12451256
);
12461257
}
1258+
if (task.childThreadId === null) {
1259+
return yield* readRemoteTask(scope, task, waitTimedOut, acknowledgeTerminal);
1260+
}
12471261
const childControls = yield* threadManagement
12481262
.getThreadRecords(
12491263
task.childThreadId,
@@ -1377,6 +1391,82 @@ const make = Effect.gen(function* () {
13771391
return response;
13781392
});
13791393

1394+
/**
1395+
* A task that runs in a linked environment, answered from its row here:
1396+
* the follower records its result once its thread there ends.
1397+
*/
1398+
const readRemoteTask = (
1399+
scope: McpThreadInvocationScope,
1400+
task: OrchestrationV2Subagent,
1401+
waitTimedOut: boolean,
1402+
acknowledgeTerminal: boolean,
1403+
): Effect.Effect<OrchestratorMcpDelegateTaskResult, OrchestratorMcpFailure> =>
1404+
Effect.gen(function* () {
1405+
const status: OrchestratorMcpDelegateTaskResult["status"] =
1406+
task.result === null
1407+
? "running"
1408+
: task.status === "completed" ||
1409+
task.status === "failed" ||
1410+
task.status === "cancelled" ||
1411+
task.status === "interrupted"
1412+
? task.status
1413+
: "completed";
1414+
const terminal = isTerminalTaskStatus(status);
1415+
if (
1416+
acknowledgeTerminal &&
1417+
terminal &&
1418+
task.completionDelivery?.state !== "acknowledged" &&
1419+
task.completionDelivery?.state !== "disposed"
1420+
) {
1421+
const parentProjection = yield* loadProjection(scope.thread.threadId);
1422+
const observingRun = ThreadManagementService.latestActiveRun(parentProjection);
1423+
yield* threadManagement
1424+
.dispatch({
1425+
type: "delegated_task.completion-delivery.acknowledge",
1426+
commandId: stableCommandId({
1427+
scope,
1428+
requestKey: yield* requestKey(undefined),
1429+
operation: "task-status-acknowledge",
1430+
}),
1431+
parentThreadId: scope.thread.threadId,
1432+
taskId: task.id,
1433+
observedByRunId:
1434+
observingRun?.providerInstanceId === scope.thread.providerInstanceId
1435+
? observingRun.id
1436+
: null,
1437+
})
1438+
.pipe(
1439+
Effect.mapError((error) =>
1440+
failure(
1441+
"orchestration_error",
1442+
`Unable to acknowledge delegated task ${task.id}: ${errorMessage(error)}`,
1443+
),
1444+
),
1445+
);
1446+
}
1447+
return {
1448+
taskId: task.id,
1449+
childThreadId: null,
1450+
...(task.remoteChild === undefined ? {} : { remoteChild: task.remoteChild }),
1451+
childRunId: null,
1452+
childNodeId: task.id,
1453+
status,
1454+
workState: terminal ? "result_available" : "working",
1455+
hasPendingChildRuns: false,
1456+
providerInstanceId: task.providerInstanceId,
1457+
model: task.model,
1458+
summary: task.result,
1459+
resultContextTransferId: null,
1460+
latestTerminalRunId: null,
1461+
latestTerminalStatus: terminal
1462+
? (status as OrchestratorMcpDelegateTaskResult["latestTerminalStatus"])
1463+
: null,
1464+
latestTerminalSummary: terminal ? task.result : null,
1465+
latestTerminalResultContextTransferId: null,
1466+
waitTimedOut,
1467+
} satisfies OrchestratorMcpDelegateTaskResult;
1468+
});
1469+
13801470
// Re-read the task only when an event on the parent or child thread can
13811471
// change its status, instead of polling the projections every 50 ms.
13821472
const waitForTask = (scope: McpThreadInvocationScope, taskId: NodeId, timeoutMs: number) =>
@@ -1394,10 +1484,17 @@ const make = Effect.gen(function* () {
13941484
const initial = yield* readTask(scope, taskId, false, true);
13951485
if (isTerminalTaskStatus(initial.status)) return Option.some(initial);
13961486
// One stream per event type, so transcript events never fill a buffer.
1487+
// A remote task has no child here; its completion lands on the parent.
1488+
const childThreadId = initial.childThreadId;
1489+
const wakeEvents =
1490+
childThreadId === null
1491+
? TASK_WAKE_EVENTS.filter(({ thread }) => thread === "parent")
1492+
: TASK_WAKE_EVENTS;
13971493
return yield* Stream.mergeAll(
1398-
TASK_WAKE_EVENTS.map(({ thread, eventType }) =>
1494+
wakeEvents.map(({ thread, eventType }) =>
13991495
threadManagement.streamStoredEventsFrom({
1400-
threadId: thread === "parent" ? scope.thread.threadId : initial.childThreadId,
1496+
threadId:
1497+
thread === "parent" || childThreadId === null ? scope.thread.threadId : childThreadId,
14011498
afterSequence,
14021499
eventType,
14031500
}),
@@ -1949,6 +2046,39 @@ const make = Effect.gen(function* () {
19492046
);
19502047
return yield* readTask(scope, taskId, true, true);
19512048
}),
2049+
awaitTask: (scope, taskId, requestedTimeoutMs) =>
2050+
Effect.gen(function* () {
2051+
const timeoutMs = Math.min(
2052+
MAX_WAIT_TIMEOUT_MS,
2053+
Math.max(1, requestedTimeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS),
2054+
);
2055+
const waited = yield* waitForTask(scope, taskId, timeoutMs);
2056+
if (Option.isSome(waited)) return waited.value;
2057+
// As for a local task: once the blocking wait ends, a later result wakes the parent.
2058+
yield* threadManagement
2059+
.dispatch({
2060+
type: "delegated_task.wake-policy",
2061+
commandId: stableCommandId({
2062+
scope,
2063+
requestKey: taskId,
2064+
operation: "delegate-task-wake-policy",
2065+
}),
2066+
parentThreadId: scope.thread.threadId,
2067+
taskId,
2068+
completionWake: "always",
2069+
})
2070+
.pipe(Effect.ignoreCause({ log: true }));
2071+
return yield* readTask(scope, taskId, true, true);
2072+
}),
2073+
remoteTask: (callerScope, taskId) =>
2074+
Effect.gen(function* () {
2075+
const scope = yield* requireThreadScope(callerScope, "task_cancel");
2076+
const { subagents } = yield* loadProjection(scope.thread.threadId);
2077+
return subagents.find(
2078+
(task) =>
2079+
task.id === taskId && task.origin === "app_owned" && task.remoteChild !== undefined,
2080+
);
2081+
}),
19522082
taskStatus: (callerScope, taskId) =>
19532083
Effect.gen(function* () {
19542084
const scope = yield* requireThreadScope(callerScope, "task_status");
@@ -1958,6 +2088,13 @@ const make = Effect.gen(function* () {
19582088
Effect.gen(function* () {
19592089
const scope = yield* requireThreadScope(callerScope, "task_cancel");
19602090
const current = yield* readTask(scope, input.taskId);
2091+
const childThreadId = current.childThreadId;
2092+
if (childThreadId === null) {
2093+
return yield* failure(
2094+
"task_not_cancellable",
2095+
`Delegated task ${input.taskId} runs in a linked environment; cancel it through that link.`,
2096+
);
2097+
}
19612098
const key = yield* requestKey(input.clientRequestId);
19622099
const parentProjection = yield* loadProjection(scope.thread.threadId);
19632100
// Cancelling stops the child and every task under it, each a write to a
@@ -1985,7 +2122,7 @@ const make = Effect.gen(function* () {
19852122
}
19862123
}
19872124
});
1988-
yield* assertStoppable(current.childThreadId);
2125+
yield* assertStoppable(childThreadId);
19892126
const parentTask = parentProjection.subagents.find(
19902127
(task) => task.id === input.taskId && task.origin === "app_owned",
19912128
);
@@ -2022,7 +2159,7 @@ const make = Effect.gen(function* () {
20222159
.dispatch({
20232160
type: "thread.stop",
20242161
commandId,
2025-
threadId: current.childThreadId,
2162+
threadId: childThreadId,
20262163
...(reason === undefined ? {} : { reason }),
20272164
})
20282165
.pipe(
@@ -2035,7 +2172,7 @@ const make = Effect.gen(function* () {
20352172
);
20362173
// A retry with the same clientRequestId repeats only the stops that failed.
20372174
yield* threadManagement
2038-
.stopDelegatedTasks({ threadId: current.childThreadId, commandId, reason })
2175+
.stopDelegatedTasks({ threadId: childThreadId, commandId, reason })
20392176
.pipe(
20402177
Effect.mapError((error) =>
20412178
failure(
@@ -2079,7 +2216,7 @@ const make = Effect.gen(function* () {
20792216
}
20802217
// A task waiting on its own delegates has work to stop below it. One with neither
20812218
// a running turn nor delegates (such as one awaiting a restart) keeps its delivery.
2082-
const child = yield* loadProjection(current.childThreadId);
2219+
const child = yield* loadProjection(childThreadId);
20832220
if (
20842221
current.workState !== "waiting_for_children" &&
20852222
ThreadManagementService.latestActiveRun(child) === undefined

0 commit comments

Comments
 (0)