Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

RemoteDelegation.ts

809 lines32.4 KB

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