Open History to see the last commit
1import {
2 CommandId,
3 type EnvironmentId,
4 NodeId,
5 OrchestratorMcpFailure,
6 type OrchestratorMcpDelegateTaskInput,
7 type OrchestratorMcpTaskCancelResult,
8 type OrchestratorMcpThreadTimelineItem,
9 type OrchestrationV2RemoteTaskChild,
10 type OrchestrationV2Subagent,
11 type ProjectId,
12 type ProviderInstanceId,
13 ProviderDriverKind,
14 type RunId,
15 type ThreadId,
16} from "@t3tools/contracts";
17import * as Context from "effect/Context";
18import * as SecureRandom from "effect/crypto/SecureRandom";
19import * as Duration from "effect/Duration";
20import * as Effect from "effect/Effect";
21import * as Layer from "effect/Layer";
22import * as Option from "effect/Option";
23import * as Schedule from "effect/Schedule";
24import * as Scope from "effect/Scope";
25import * as Stream from "effect/Stream";
26import type * as Tool from "effect/ai/Tool";
27
28import type * as McpInvocationContext from "../mcp/McpInvocationContext.ts";
29import { ProjectToolkit } from "../mcp/toolkits/project/tools.ts";
30import {
31 resolveInteractionMode,
32 resolveRuntimeMode,
33 taskPrompt,
34} from "../mcp/delegatedTaskModes.ts";
35import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts";
36import * as ThreadManagement from "../orchestration-v2/ThreadManagementService.ts";
37import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
38import * as ProjectService from "../project/ProjectService.ts";
39import * as RepositoryIdentityResolver from "../project/RepositoryIdentityResolver.ts";
40import { forkParked } from "../serverActivation.ts";
41import * as PeerForwarding from "./PeerForwarding.ts";
42import * as PeerLinks from "./PeerLinks.ts";
43
44/** How long one follow of a remote task waits on its thread there before checking again. */
45const FOLLOW_WAIT_MS = 10 * 60 * 1_000;
46/** A linked environment that stops answering is retried, backing off to this. */
47const FOLLOW_MAX_BACKOFF = Duration.minutes(5);
48/** How a follower retries; tests step it by hand. */
49export const FollowRetrySchedule = Context.Reference<Schedule.Schedule<unknown>>(
50 "t3/peer/RemoteDelegation/FollowRetrySchedule",
51 {
52 defaultValue: () =>
53 Schedule.exponential(Duration.seconds(2)).pipe(
54 Schedule.modifyDelay(({ duration }) =>
55 Effect.succeed(Duration.min(duration, FOLLOW_MAX_BACKOFF)),
56 ),
57 ),
58 },
59);
60
61type ThreadScope = McpInvocationContext.McpThreadInvocationScope;
62
63/**
64 * `delegate_task` to a linked environment. The task's child is an ordinary
65 * thread there, launched through the link; the parent here records the task
66 * like a local one, without a child thread, and a follower completes it when
67 * the thread there ends, so the parent wakes as it would for a local child.
68 */
69export class RemoteDelegation extends Context.Service<
70 RemoteDelegation,
71 {
72 readonly delegate: (
73 scope: ThreadScope,
74 input: OrchestratorMcpDelegateTaskInput & {
75 readonly target: NonNullable<OrchestratorMcpDelegateTaskInput["target"]> & {
76 readonly environmentId: EnvironmentId;
77 };
78 },
79 ) => Effect.Effect<{ readonly taskId: NodeId }, OrchestratorMcpFailure>;
80 /**
81 * Stops the task's thread there, then completes it here as cancelled. A
82 * task that already has its result keeps it; its thread there is still
83 * stopped, as cancelling a local task stops follow-up work on its child.
84 */
85 readonly cancel: (
86 scope: ThreadScope,
87 task: OrchestrationV2Subagent,
88 input: {
89 readonly reason?: string | undefined;
90 readonly clientRequestId?: string | undefined;
91 },
92 ) => Effect.Effect<OrchestratorMcpTaskCancelResult, OrchestratorMcpFailure>;
93 /**
94 * Follows every open remote task until it ends, including after a
95 * restart, and a finished one again when a Stop here owes it a stop there.
96 */
97 readonly start: () => Effect.Effect<void, never, Scope.Scope>;
98 }
99>()("t3/peer/RemoteDelegation") {}
100
101/** The other side refused because the thread there runs above this caller's modes. */
102const isModeRefusal = (error: OrchestratorMcpFailure) =>
103 error.code === "runtime_mode_escalation_denied" ||
104 error.code === "interaction_mode_escalation_denied";
105
106/**
107 * Refusals that following again cannot change: the link was revoked, expired
108 * or forgotten, or the thread or run there is gone. Anything else (the other
109 * machine asleep, a dropped route) is worth retrying.
110 */
111const isFinal = (error: OrchestratorMcpFailure) =>
112 error.code === "capability_denied" ||
113 error.code === "thread_not_found" ||
114 error.code === "run_not_found";
115
116const make = Effect.gen(function* () {
117 const followRetry = yield* FollowRetrySchedule;
118 const forwarding = yield* PeerForwarding.PeerForwarding;
119 const links = yield* PeerLinks.PeerLinks;
120 const threads = yield* ThreadManagement.ThreadManagementService;
121 const projections = yield* ProjectionStore.ProjectionStoreV2;
122 const projects = yield* ProjectService.ProjectService;
123 const repositoryIdentities = yield* RepositoryIdentityResolver.RepositoryIdentityResolver;
124 const random = yield* SecureRandom.SecureRandom;
125 const hereId = yield* ServerEnvironment.ServerEnvironment.pipe(
126 Effect.flatMap((environment) => environment.getEnvironmentId),
127 );
128 // Followers live as long as this service, so shutting down stops them.
129 const followers = yield* Scope.Scope;
130
131 // One follower runs per open task and holds what it read across a wait of
132 // up to FOLLOW_WAIT_MS, so it reads its own task, never the parent's whole
133 // task list: a parent with thousands of tasks made every restart decode
134 // that list once per open task at the same time and ran out of heap.
135 const readTask = (parentThreadId: ThreadId, taskId: NodeId) =>
136 threads
137 .getThreadRecords(parentThreadId, ["subagents"], { subagentIds: [taskId] })
138 .pipe(Effect.map(({ thread, subagents }) => ({ thread, task: subagents[0] })));
139
140 /** The peer's project with this thread's repository, or the one the caller named. */
141 const resolveRemoteProject = Effect.fn("RemoteDelegation.resolveRemoteProject")(function* (
142 scope: ThreadScope,
143 environmentId: EnvironmentId,
144 parentProjectId: ProjectId,
145 requested: ProjectId | undefined,
146 ) {
147 if (requested !== undefined) return requested;
148 const here = yield* projects.getById(parentProjectId).pipe(
149 Effect.map(Option.getOrUndefined),
150 Effect.orElseSucceed(() => undefined),
151 );
152 // The project's own identity is a one-minute cache that reads blank when
153 // cold, so resolve it here, as the other side's t3_project_list does.
154 const key =
155 here === undefined
156 ? undefined
157 : (yield* repositoryIdentities.resolve(here.workspaceRoot))?.canonicalKey;
158 if (key === undefined) {
159 return yield* new OrchestratorMcpFailure({
160 code: "target_required",
161 message: "Pass target.projectId: this thread's project has no repository to match there.",
162 });
163 }
164 const matches: Array<{ readonly id: ProjectId; readonly title: string }> = [];
165 let cursor: number | null = 0;
166 while (cursor !== null) {
167 const listed: Tool.Success<typeof ProjectToolkit.tools.t3_project_list> =
168 yield* forwarding.call(scope, ProjectToolkit.tools.t3_project_list, environmentId, {
169 cursor,
170 limit: 100,
171 });
172 matches.push(
173 ...listed.projects.filter((project) => project.repositoryIdentity?.canonicalKey === key),
174 );
175 cursor = listed.nextCursor;
176 }
177 if (matches.length === 1) return matches[0]!.id;
178 return yield* new OrchestratorMcpFailure({
179 code: "invalid_request",
180 message:
181 matches.length === 0
182 ? `No project there has this repository (${key}). Pass target.projectId; t3_project_list with this environmentId lists them. To bring the repository there, use t3_project_clone and then t3_project_create with this environmentId.`
183 : `Several projects there have this repository: ${matches.map((project) => `${project.title} (${project.id})`).join(", ")}. Pass target.projectId.`,
184 });
185 });
186
187 const delegate: RemoteDelegation["Service"]["delegate"] = Effect.fn("RemoteDelegation.delegate")(
188 function* (scope, input) {
189 const parent = yield* threads.getThreadRecords(scope.thread.threadId, ["runs"]).pipe(
190 Effect.mapError(
191 () =>
192 new OrchestratorMcpFailure({
193 code: "thread_not_found",
194 message: "The calling thread was not found.",
195 }),
196 ),
197 );
198 const parentRun = parent.runs
199 .filter(ThreadManagement.isActiveRun)
200 .toSorted((left, right) => right.ordinal - left.ordinal)[0];
201 if (
202 parentRun === undefined ||
203 parentRun.rootNodeId === null ||
204 parentRun.providerInstanceId !== scope.thread.providerInstanceId
205 ) {
206 return yield* new OrchestratorMcpFailure({
207 code: "parent_not_active",
208 message: "Delegated tasks require an active run owned by this MCP provider session.",
209 });
210 }
211 const parentNodeId = parentRun.rootNodeId;
212 const { target } = input;
213 // A worktree there would branch from a commit this checkout has and the
214 // other may not, so a remote task runs in that project's checkout.
215 if (input.isolation === "worktree") {
216 return yield* new OrchestratorMcpFailure({
217 code: "invalid_request",
218 message:
219 'A task in a linked environment runs in that project\'s checkout; isolation "worktree" is not supported there. Omit isolation, or use t3_thread_launch with environmentId and a worktree workspaceStrategy.',
220 });
221 }
222 // The provider and model inherit as they do for a task here. Another
223 // provider there has no model to inherit, so the caller names one.
224 const inherited = parent.thread.modelSelection;
225 const instanceId = target.providerInstanceId ?? inherited.instanceId;
226 const model =
227 target.model ?? (instanceId === inherited.instanceId ? inherited.model : undefined);
228 if (model === undefined) {
229 return yield* new OrchestratorMcpFailure({
230 code: "target_required",
231 message: "Pass target.model from orchestrator_capabilities with this environmentId.",
232 });
233 }
234 const options =
235 target.options ??
236 (instanceId === inherited.instanceId && model === inherited.model
237 ? inherited.options
238 : undefined);
239 // Modes asked for are checked against this thread. Omitted ones are left
240 // to the other side, which inherits this thread's modes capped by the
241 // link's access, so a narrower link still takes the task.
242 const runtimeMode =
243 input.runtimeMode === undefined || input.runtimeMode === "inherit"
244 ? undefined
245 : yield* resolveRuntimeMode(parent.thread.runtimeMode, input.runtimeMode);
246 const interactionMode =
247 input.interactionMode === undefined || input.interactionMode === "inherit"
248 ? undefined
249 : yield* resolveInteractionMode(parent.thread.interactionMode, input.interactionMode);
250 const projectId = yield* resolveRemoteProject(
251 scope,
252 target.environmentId,
253 parent.thread.projectId,
254 target.projectId,
255 );
256 // One key for the launch there and the record here, so a retry finds both.
257 // Both are scoped to the provider session, as every key a caller passes is:
258 // the forwarder scopes the launch's, and the record's names it.
259 const key = input.clientRequestId ?? (yield* random.uuidV4());
260 const task = taskPrompt(input);
261 const launched = yield* forwarding.call(
262 scope,
263 ProjectToolkit.tools.t3_thread_launch,
264 target.environmentId,
265 {
266 projectId,
267 title: input.title ?? parent.thread.title,
268 modelSelection: { instanceId, model, ...(options === undefined ? {} : { options }) },
269 ...(runtimeMode === undefined ? {} : { runtimeMode }),
270 ...(interactionMode === undefined ? {} : { interactionMode }),
271 message: task,
272 clientRequestId: `delegate:${scope.thread.threadId}:${key}`,
273 // The thread there shows it is this thread's subagent, with a way back.
274 delegatedFrom: {
275 environmentId: hereId,
276 threadId: parent.thread.id,
277 title: parent.thread.title,
278 },
279 },
280 );
281 const link = yield* links.get(target.environmentId).pipe(
282 Effect.map(Option.getOrUndefined),
283 Effect.orElseSucceed(() => undefined),
284 );
285 const commandId = CommandId.make(
286 `command:mcp:${encodeURIComponent(scope.requestNamespace)}:remote-delegate:${encodeURIComponent(key)}`,
287 );
288 const remoteChild: OrchestrationV2RemoteTaskChild = {
289 environmentId: target.environmentId,
290 threadId: launched.threadId,
291 label: link?.label ?? target.environmentId,
292 ...(launched.runId === null ? {} : { runId: launched.runId }),
293 };
294 const recorded = yield* threads
295 .dispatch({
296 type: "delegated_task.remote.request",
297 commandId,
298 parentThreadId: scope.thread.threadId,
299 parentRunId: parentRun.id,
300 parentNodeId,
301 task,
302 ...(input.title === undefined ? {} : { title: input.title }),
303 // The driver runs there; this side only labels the task with it.
304 driver: ProviderDriverKind.make("remote"),
305 modelSelection: launched.modelSelection,
306 remoteChild,
307 completionWake: input.mode === "wait" ? "settled_only" : "always",
308 })
309 .pipe(
310 // The cause goes to the log; the caller learns only that recording failed.
311 Effect.tapError((cause) =>
312 Effect.logWarning("remote-delegation.record-failed", {
313 parentThreadId: scope.thread.threadId,
314 cause,
315 }),
316 ),
317 Effect.mapError(
318 () =>
319 new OrchestratorMcpFailure({
320 code: "orchestration_error",
321 message: "Unable to record the delegated task.",
322 }),
323 ),
324 // Nothing here follows a thread the task was never recorded for, so stop it there.
325 // A crash between the launch and this record still leaves it running there
326 // until a retry with the same clientRequestId records it.
327 Effect.tapError(() =>
328 stopThere(followScope(scope.thread, remoteChild), remoteChild, "stop").pipe(
329 Effect.ignoreCause({ log: true }),
330 ),
331 ),
332 );
333 const taskEvent = recorded.storedEvents.find(
334 (stored) => stored.event.type === "subagent.updated",
335 );
336 const taskId =
337 taskEvent?.event.type === "subagent.updated"
338 ? taskEvent.event.payload.id
339 : // A replayed request recorded the task the first time.
340 yield* threads.getThreadRecords(scope.thread.threadId, ["subagents"]).pipe(
341 Effect.map(
342 ({ subagents }) =>
343 subagents.find((task) => task.remoteChild?.threadId === launched.threadId)?.id,
344 ),
345 Effect.orElseSucceed(() => undefined),
346 );
347 if (taskId === undefined) {
348 return yield* new OrchestratorMcpFailure({
349 code: "orchestration_error",
350 message: "The delegated task was not recorded.",
351 });
352 }
353 yield* followOne(scope.thread.threadId, taskId).pipe(Effect.forkIn(followers));
354 return { taskId };
355 },
356 );
357
358 /**
359 * Completes `task` here with its thread there's final state. Each attempt is its own
360 * command, so a failed one never blocks the next; a report refused because the task already
361 * has its result (a cancel, a Stop or an earlier report) is done. `stoppedThere` records that
362 * nothing is left to stop there, even on a task that already has its result.
363 */
364 const complete = Effect.fn("RemoteDelegation.complete")(function* (
365 parentThreadId: ThreadId,
366 taskId: NodeId,
367 status: "completed" | "failed" | "cancelled" | "interrupted",
368 result: string,
369 stoppedThere: "ran-out" | "stopped" | undefined,
370 stopCount?: number,
371 ) {
372 const attempt = yield* random.uuidV4();
373 yield* threads
374 .dispatch({
375 type: "delegated_task.remote.complete",
376 commandId: CommandId.make(`command:remote-task-complete:${taskId}:${attempt}`),
377 parentThreadId,
378 taskId,
379 status,
380 result,
381 ...(stoppedThere === undefined ? {} : { stoppedThere }),
382 ...(stopCount === undefined ? {} : { stopCount }),
383 })
384 .pipe(
385 Effect.catch((error) =>
386 readTask(parentThreadId, taskId).pipe(
387 Effect.flatMap(({ task }) => (task?.result != null ? Effect.void : Effect.fail(error))),
388 ),
389 ),
390 );
391 });
392
393 /**
394 * How this environment reaches a task's thread there: as the parent
395 * thread, under one namespace per parent, so a stop sent again after a
396 * restart or a dropped route is recorded there once.
397 */
398 const followScope = (
399 parent: { readonly threadId: ThreadId; readonly providerInstanceId: ProviderInstanceId },
400 remote: OrchestrationV2RemoteTaskChild,
401 ): ThreadScope => ({
402 environmentId: hereId,
403 requestNamespace: `remote-task:${parent.threadId}`,
404 thread: {
405 threadId: parent.threadId,
406 providerSessionId: `remote-task:${remote.threadId}`,
407 providerInstanceId: parent.providerInstanceId,
408 },
409 client: undefined,
410 capabilities: new Set(["orchestration"]),
411 issuedAt: 0,
412 });
413
414 /**
415 * Stops the task's own thread there as its Stop button does: its running turn, queued
416 * messages, pull request watches and delegated tasks. `key` names the stop (the follower
417 * sends one, each cancel its own), and each is recorded there once however often it is sent.
418 */
419 const stopThere = (
420 scope: ThreadScope,
421 remote: OrchestrationV2RemoteTaskChild,
422 key: string,
423 reason?: string,
424 ) =>
425 forwarding
426 .interruptThread(scope, remote.environmentId, {
427 threadId: remote.threadId,
428 stop: true,
429 ...(reason === undefined ? {} : { reason }),
430 clientRequestId: `${key}:${remote.threadId}`,
431 })
432 .pipe(Effect.asVoid);
433
434 /**
435 * The last reply `runId` gave on the task's thread there, which is its
436 * result, read whole however long it is. A failed run prefers its error
437 * from the activity view over an earlier reply, without taking another run's.
438 */
439 const lastReply = Effect.fn("RemoteDelegation.lastReply")(function* (
440 scope: ThreadScope,
441 remote: OrchestrationV2RemoteTaskChild,
442 runId: RunId | null,
443 failed = false,
444 ) {
445 let reply: OrchestratorMcpThreadTimelineItem | undefined;
446 let error: OrchestratorMcpThreadTimelineItem | undefined;
447 let afterPosition: number | undefined;
448 while (true) {
449 const read = yield* forwarding.readThread(scope, remote.environmentId, {
450 threadId: remote.threadId,
451 view: failed ? "activity" : "messages",
452 limit: 100,
453 ...(afterPosition === undefined ? {} : { afterPosition }),
454 });
455 reply =
456 read.items.findLast(
457 (item) => item.type === "assistant_message" && (runId === null || item.runId === runId),
458 ) ?? reply;
459 if (failed) {
460 error =
461 read.items.findLast(
462 (item) => item.type === "error" && (runId === null || item.runId === runId),
463 ) ?? error;
464 }
465 if (!read.hasMore || read.nextPosition === null) break;
466 afterPosition = read.nextPosition;
467 }
468 reply = error ?? reply;
469 if (reply === undefined) return undefined;
470 let text = reply.text ?? "";
471 let textOffset = reply.textTruncated ? (reply.nextTextOffset ?? null) : null;
472 while (textOffset !== null) {
473 const rest = yield* forwarding.readThread(scope, remote.environmentId, {
474 threadId: remote.threadId,
475 itemId: reply.itemId,
476 textOffset,
477 maxCharsPerItem: 50_000,
478 });
479 const part = rest.items[0];
480 if (part === undefined) break;
481 text += part.text ?? "";
482 textOffset = part.textTruncated ? (part.nextTextOffset ?? null) : null;
483 }
484 return text;
485 });
486
487 /**
488 * Why following a task can never succeed, if that is what `error` means.
489 * The far side's message already says what was refused and what to do; a
490 * link forgotten here only reads as a bad request, so it is named.
491 */
492 const finalReason = Effect.fn("RemoteDelegation.finalReason")(
493 function* (parentThreadId: ThreadId, taskId: NodeId, error: OrchestratorMcpFailure) {
494 if (isFinal(error)) return error.message;
495 if (error.code !== "invalid_request") return undefined;
496 const { task } = yield* readTask(parentThreadId, taskId);
497 const environmentId = task?.remoteChild?.environmentId;
498 if (environmentId === undefined) return error.message;
499 const link = yield* links.get(environmentId);
500 return Option.isSome(link) ? undefined : error.message;
501 },
502 Effect.orElseSucceed(() => undefined),
503 );
504
505 /** A task's thread there that ended without a reply. */
506 const noReply = "(The thread in the linked environment ended without a reply.)";
507
508 /**
509 * Waits for the task's run there to end, completes the task here, and stops it there if it
510 * ended here first. A revoked, expired or forgotten link, or a thread or run gone there,
511 * fails the task with nothing left to stop; anything else (the other machine asleep, a
512 * dropped route) is retried with back-off, and so is completing.
513 */
514 const follow = (parentThreadId: ThreadId, taskId: NodeId): Effect.Effect<void> =>
515 followOnce(parentThreadId, taskId).pipe(
516 // `false` means it is still running there: follow again straight away.
517 Effect.repeat({ while: (done) => !done }),
518 Effect.catchTags({
519 OrchestratorMcpFailure: Effect.fn("RemoteDelegation.followFailed")(function* (error) {
520 const reason = yield* finalReason(parentThreadId, taskId, error);
521 if (reason === undefined) return yield* error;
522 // Gone there, or no link to reach it by: nothing left to stop there.
523 const { task } = yield* readTask(parentThreadId, taskId);
524 const stopCount = task?.remoteChild?.stopCount;
525 yield* complete(parentThreadId, taskId, "failed", reason, "stopped", stopCount);
526 }),
527 }),
528 Effect.retry(followRetry),
529 Effect.ignoreCause({ log: true }),
530 );
531
532 /**
533 * One wait on the task's thread there; true once the task here is done.
534 * A task completed here first (cancelled, or its parent stopped) is
535 * stopped there, and done once that stop is recorded here.
536 */
537 const followOnce = Effect.fn("RemoteDelegation.followOnce")(function* (
538 parentThreadId: ThreadId,
539 taskId: NodeId,
540 ) {
541 const sequence = yield* threads.getThreadEventSequence(parentThreadId);
542 const { thread, task } = yield* readTask(parentThreadId, taskId);
543 if (task?.remoteChild === undefined) return true;
544 const remote = task.remoteChild;
545 const scope = followScope(
546 { threadId: parentThreadId, providerInstanceId: thread.providerInstanceId },
547 remote,
548 );
549 // Ended here, maybe while this follower backed off from an unreachable
550 // machine or before a restart: it still has to be stopped there. So
551 // does one its parent here was stopped after, for what followed there.
552 if (task.result !== null) {
553 if (
554 remote.stoppedThere === false ||
555 ((task.status === "cancelled" || task.status === "interrupted") &&
556 remote.stoppedThere !== true)
557 ) {
558 const key = remote.stopCount === undefined ? "stop" : `stop-${remote.stopCount}`;
559 yield* stopThere(scope, remote, key).pipe(
560 // Its thread there now runs above what this side may touch, say
561 // because the parent here was lowered since; no retry changes that.
562 Effect.catchIf(isModeRefusal, (error) =>
563 Effect.logWarning("A linked environment refused to stop a delegated task", {
564 taskId,
565 reason: error.message,
566 }),
567 ),
568 );
569 yield* complete(
570 parentThreadId,
571 taskId,
572 terminalStatus(task.status),
573 task.result,
574 "stopped",
575 remote.stopCount,
576 );
577 return yield* settled(parentThreadId, taskId);
578 }
579 return true;
580 }
581 const endedHere = threads
582 .streamStoredEventsFrom({
583 threadId: parentThreadId,
584 afterSequence: sequence,
585 eventType: "subagent.updated",
586 })
587 .pipe(
588 Stream.filter(
589 (stored) =>
590 stored.event.type === "subagent.updated" &&
591 stored.event.payload.id === taskId &&
592 stored.event.payload.result !== null,
593 ),
594 Stream.runHead,
595 Effect.flatMap((ended) =>
596 Option.isSome(ended) ? Effect.succeed({ endedHere: true } as const) : Effect.never,
597 ),
598 );
599 const waited = yield* forwarding
600 .waitForThread(scope, remote.environmentId, {
601 threadId: remote.threadId,
602 ...(remote.runId === undefined ? {} : { runId: remote.runId }),
603 timeoutMs: FOLLOW_WAIT_MS,
604 // A thread there whose run ended may still be waiting on its own
605 // tasks to wake it for the answer, which a task here waits for too.
606 // An older peer ignores this and reports the run alone.
607 untilDelegatedWorkSettled: true,
608 })
609 .pipe(Effect.raceFirst(endedHere));
610 // The next look reads the result and stops it there.
611 if ("endedHere" in waited) return false;
612 if (waited.timedOut) return false;
613 // A task recorded without its run waits on the thread's latest; a
614 // thread there with none has nothing left to wait for.
615 if (waited.runId === null) {
616 const reply = yield* lastReply(scope, remote, null);
617 yield* complete(
618 parentThreadId,
619 taskId,
620 reply === undefined ? "failed" : "completed",
621 reply ?? "The thread in the linked environment has no run to follow.",
622 "ran-out",
623 );
624 return yield* settled(parentThreadId, taskId);
625 }
626 if (!isTerminal(waited.status)) return false;
627 const resultRun = waited.resultRun ?? {
628 runId: remote.runId ?? waited.runId,
629 status: waited.status,
630 };
631 const result = yield* lastReply(scope, remote, resultRun.runId, resultRun.status === "failed");
632 yield* complete(
633 parentThreadId,
634 taskId,
635 terminalStatus(resultRun.status),
636 result ?? noReply,
637 "ran-out",
638 );
639 return yield* settled(parentThreadId, taskId);
640 });
641
642 /**
643 * Whether the task is done here after the follower reported its run ran
644 * out there. A cancel or Stop that landed while the reply was read keeps
645 * its result, and still owes a stop there for what may follow the run;
646 * the next look sends it.
647 */
648 const settled = (parentThreadId: ThreadId, taskId: NodeId) =>
649 readTask(parentThreadId, taskId).pipe(
650 Effect.map(({ task }) => task?.remoteChild?.stoppedThere === true),
651 );
652
653 const following = new Map<NodeId, { again: boolean }>();
654
655 /**
656 * `follow`, at most once per task. Asked again while it runs, say by a
657 * Stop here on a task that already has its result, it looks once more
658 * before it ends, so that stop is not missed.
659 */
660 const followOne = (parentThreadId: ThreadId, taskId: NodeId) =>
661 Effect.suspend(() => {
662 const running = following.get(taskId);
663 if (running !== undefined) {
664 running.again = true;
665 return Effect.void;
666 }
667 const state = { again: false };
668 following.set(taskId, state);
669 return follow(parentThreadId, taskId).pipe(
670 // Checked and released in one step, so a request between them is never lost.
671 Effect.repeat({
672 while: () => {
673 if (state.again) {
674 state.again = false;
675 return true;
676 }
677 following.delete(taskId);
678 return false;
679 },
680 }),
681 Effect.ensuring(
682 Effect.sync(() => {
683 if (following.get(taskId) === state) following.delete(taskId);
684 }),
685 ),
686 );
687 });
688
689 const cancel: RemoteDelegation["Service"]["cancel"] = Effect.fn("RemoteDelegation.cancel")(
690 function* (scope, task, input) {
691 const remote = task.remoteChild;
692 if (remote === undefined) {
693 return yield* new OrchestratorMcpFailure({
694 code: "task_not_found",
695 message: `Delegated task ${task.id} is not remote.`,
696 });
697 }
698 const { reason } = input;
699 const there = followScope(scope.thread, remote);
700 // A later cancel stops what started there since; a retry of this one, nothing new.
701 const key = `cancel:${encodeURIComponent(scope.requestNamespace)}:${
702 input.clientRequestId ?? (yield* random.uuidV4())
703 }`;
704 if (task.result !== null) {
705 // Best effort: the result stands whether or not the stop gets there.
706 yield* stopThere(there, remote, key, reason).pipe(
707 Effect.andThen(
708 complete(
709 task.threadId,
710 task.id,
711 terminalStatus(task.status),
712 task.result,
713 "stopped",
714 remote.stopCount,
715 ),
716 ),
717 Effect.ignoreCause({ log: true }),
718 );
719 return {
720 taskId: task.id,
721 status:
722 task.status === "completed" || task.status === "failed" || task.status === "interrupted"
723 ? task.status
724 : "cancelled",
725 } satisfies OrchestratorMcpTaskCancelResult;
726 }
727 // A link that is gone or a machine that is down still cancels the task
728 // here; its follower keeps trying to stop it there, across restarts.
729 const unstopped = yield* stopThere(there, remote, key, reason).pipe(
730 Effect.as(undefined),
731 Effect.catch((error) => Effect.succeed(error.message)),
732 );
733 const cancelled = reason === undefined ? "Cancelled." : `Cancelled: ${reason}`;
734 yield* complete(
735 task.threadId,
736 task.id,
737 "cancelled",
738 unstopped === undefined
739 ? cancelled
740 : `${cancelled} It could not be stopped in ${remote.label} and may still run there: ${unstopped}`,
741 unstopped === undefined ? "stopped" : undefined,
742 remote.stopCount,
743 ).pipe(
744 Effect.tapError((cause) =>
745 Effect.logWarning("remote-delegation.cancel-record-failed", { taskId: task.id, cause }),
746 ),
747 Effect.mapError(
748 () =>
749 new OrchestratorMcpFailure({
750 code: "orchestration_error",
751 message: "Unable to record the cancellation.",
752 }),
753 ),
754 );
755 return {
756 taskId: task.id,
757 status: "cancel_requested",
758 } satisfies OrchestratorMcpTaskCancelResult;
759 },
760 );
761
762 const start: RemoteDelegation["Service"]["start"] = () =>
763 forkParked(
764 Effect.gen(function* () {
765 // A finished task's follower has ended, so a Stop here that owes its
766 // thread there a stop starts it again. Started before the scan below;
767 // a Stop that slips between the two stays owed for the next start.
768 yield* Stream.runForEach(threads.streamDomainEvents, (event) =>
769 event.type === "subagent.updated" && event.payload.remoteChild?.stoppedThere === false
770 ? followOne(event.threadId, event.payload.id).pipe(Effect.forkIn(followers))
771 : Effect.void,
772 ).pipe(
773 Effect.ignoreCause({ log: true }),
774 Effect.forkIn(followers, { startImmediately: true }),
775 );
776 const open = yield* projections.getOpenRemoteDelegatedTasks;
777 yield* Effect.forEach(
778 open,
779 ({ parentThreadId, taskId }) => followOne(parentThreadId, taskId),
780 {
781 concurrency: "unbounded",
782 discard: true,
783 },
784 );
785 }).pipe(Effect.ignoreCause({ log: true })),
786 );
787
788 return RemoteDelegation.of({ delegate, cancel, start });
789});
790
791const isTerminal = (status: string) =>
792 status === "completed" ||
793 status === "failed" ||
794 status === "cancelled" ||
795 status === "interrupted" ||
796 status === "rolled_back";
797
798const terminalStatus = (status: string): "completed" | "failed" | "cancelled" | "interrupted" =>
799 status === "completed" || status === "failed" || status === "interrupted" ? status : "cancelled";
800
801export const layer = Layer.effect(RemoteDelegation, make);