Open History to see the last commit
1import {
2 CommandId,
3 type EnvironmentId,
4 NodeId,
5 OrchestratorMcpCapabilitiesInput,
6 OrchestratorMcpCapabilitiesResult,
7 OrchestratorMcpFailure,
8 type OrchestratorMcpDelegateTaskInput,
9 type OrchestratorMcpTaskCancelResult,
10 type OrchestratorMcpThreadRun,
11 type OrchestratorMcpThreadSendInput,
12 type OrchestratorMcpThreadSendResult,
13 type OrchestratorMcpThreadTimelineItem,
14 type OrchestrationV2RemoteTaskChild,
15 type OrchestrationV2Subagent,
16 type ProjectId,
17 type ProviderInstanceId,
18 ProviderDriverKind,
19 type RunId,
20 type ThreadId,
21} from "@t3tools/contracts";
22import * as Cause from "effect/Cause";
23import * as Context from "effect/Context";
24import * as SecureRandom from "effect/crypto/SecureRandom";
25import * as DateTime from "effect/DateTime";
26import * as Duration from "effect/Duration";
27import * as Effect from "effect/Effect";
28import * as Layer from "effect/Layer";
29import * as Option from "effect/Option";
30import * as Schedule from "effect/Schedule";
31import * as Scope from "effect/Scope";
32import * as Stream from "effect/Stream";
33import * as Tool from "effect/ai/Tool";
34import { withExecutedModelNote } from "@t3tools/provider-core/server/subagentProjection";
35
36import type * as McpInvocationContext from "../mcp/McpInvocationContext.ts";
37import { ProjectToolkit } from "../mcp/toolkits/project/tools.ts";
38import {
39 providerOptionDescriptors,
40 resolveInteractionMode,
41 resolveRuntimeMode,
42 taskPrompt,
43 withoutAgentModePicks,
44} from "../mcp/delegatedTaskModes.ts";
45import { followUpOwnerRun } from "../orchestration-v2/CommandPolicy.ts";
46import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts";
47import * as ThreadManagement from "../orchestration-v2/ThreadManagementService.ts";
48import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
49import * as ProjectService from "../project/ProjectService.ts";
50import * as ProviderRegistry from "../provider/ProviderRegistry.ts";
51import * as RepositoryIdentityResolver from "../project/RepositoryIdentityResolver.ts";
52import { forkParked } from "../serverActivation.ts";
53import * as PeerForwarding from "./PeerForwarding.ts";
54import * as PeerLinks from "./PeerLinks.ts";
55
56/** How long one follow of a remote task waits on its thread there before checking again. */
57const FOLLOW_WAIT_MS = 10 * 60 * 1_000;
58/** A linked environment that stops answering is retried, backing off to this. */
59const FOLLOW_MAX_BACKOFF = Duration.minutes(5);
60/** A follower that hits this many defects in a row fails its task instead of retrying. */
61const FOLLOW_MAX_DEFECTS = 3;
62/** How a follower retries; tests step it by hand. */
63export const FollowRetrySchedule = Context.Reference<Schedule.Schedule<unknown>>(
64 "t3/peer/RemoteDelegation/FollowRetrySchedule",
65 {
66 defaultValue: () =>
67 Schedule.exponential(Duration.seconds(2)).pipe(
68 Schedule.modifyDelay(({ duration }) =>
69 Effect.succeed(Duration.min(duration, FOLLOW_MAX_BACKOFF)),
70 ),
71 ),
72 },
73);
74
75type ThreadScope = McpInvocationContext.McpThreadInvocationScope;
76
77/** `orchestrator_capabilities` there. Its toolkit imports this module, so it is described here. */
78const RemoteCapabilitiesTool = Tool.make("orchestrator_capabilities", {
79 parameters: OrchestratorMcpCapabilitiesInput,
80 success: OrchestratorMcpCapabilitiesResult,
81 failure: OrchestratorMcpFailure,
82 failureMode: "return",
83});
84
85/**
86 * `delegate_task` to a linked environment. The task's child is an ordinary
87 * thread there, launched through the link; the parent here records the task
88 * like a local one, without a child thread, and a follower completes it when
89 * the thread there ends, so the parent wakes as it would for a local child.
90 */
91export class RemoteDelegation extends Context.Service<
92 RemoteDelegation,
93 {
94 readonly delegate: (
95 scope: ThreadScope,
96 input: OrchestratorMcpDelegateTaskInput & {
97 readonly target: NonNullable<OrchestratorMcpDelegateTaskInput["target"]> & {
98 readonly environmentId: EnvironmentId;
99 };
100 },
101 ) => Effect.Effect<{ readonly taskId: NodeId }, OrchestratorMcpFailure>;
102 /**
103 * A `t3_thread_send` there that started or queued a run on the thread of
104 * one of this thread's tasks that has its result: like a follow-up to a
105 * finished child here, that run is a new task, whose id the send returns.
106 * Any other send is returned as it came.
107 */
108 readonly followUp: (
109 scope: McpInvocationContext.McpInvocationScope,
110 environmentId: EnvironmentId,
111 request: Pick<OrchestratorMcpThreadSendInput, "message" | "clientRequestId">,
112 sent: OrchestratorMcpThreadSendResult,
113 ) => Effect.Effect<OrchestratorMcpThreadSendResult, OrchestratorMcpFailure>;
114 /**
115 * Stops the task's thread there, then completes it here as cancelled. A
116 * task that already has its result keeps it; its thread there is still
117 * stopped, as cancelling a local task stops follow-up work on its child.
118 */
119 readonly cancel: (
120 scope: ThreadScope,
121 task: OrchestrationV2Subagent,
122 input: {
123 readonly reason?: string | undefined;
124 readonly clientRequestId?: string | undefined;
125 },
126 ) => Effect.Effect<OrchestratorMcpTaskCancelResult, OrchestratorMcpFailure>;
127 /**
128 * The status of the task's run there, or null when it cannot be read: an
129 * unreachable machine reads as no news rather than failing the read here.
130 */
131 readonly runStatus: (
132 scope: ThreadScope,
133 task: OrchestrationV2Subagent,
134 ) => Effect.Effect<OrchestratorMcpThreadRun["status"] | null>;
135 /**
136 * Follows every open remote task until it ends, including after a
137 * restart, and a finished one again when a Stop here owes it a stop there.
138 */
139 readonly start: () => Effect.Effect<void, never, Scope.Scope>;
140 }
141>()("t3/peer/RemoteDelegation") {}
142
143/** The other side refused because the thread there runs above this caller's modes. */
144const isModeRefusal = (error: OrchestratorMcpFailure) =>
145 error.code === "runtime_mode_escalation_denied" ||
146 error.code === "interaction_mode_escalation_denied";
147
148/**
149 * Refusals that following again cannot change: the link was revoked, expired
150 * or forgotten, or the thread or run there is gone. Anything else (the other
151 * machine asleep, a dropped route) is worth retrying.
152 */
153const isFinal = (error: OrchestratorMcpFailure) =>
154 error.code === "capability_denied" ||
155 error.code === "thread_not_found" ||
156 error.code === "run_not_found";
157
158const make = Effect.gen(function* () {
159 const followRetry = yield* FollowRetrySchedule;
160 const forwarding = yield* PeerForwarding.PeerForwarding;
161 const links = yield* PeerLinks.PeerLinks;
162 const providerRegistry = yield* ProviderRegistry.ProviderRegistry;
163 const threads = yield* ThreadManagement.ThreadManagementService;
164 const projections = yield* ProjectionStore.ProjectionStoreV2;
165 const projects = yield* ProjectService.ProjectService;
166 const repositoryIdentities = yield* RepositoryIdentityResolver.RepositoryIdentityResolver;
167 const random = yield* SecureRandom.SecureRandom;
168 const hereId = yield* ServerEnvironment.ServerEnvironment.pipe(
169 Effect.flatMap((environment) => environment.getEnvironmentId),
170 );
171 // Followers live as long as this service, so shutting down stops them.
172 const followers = yield* Scope.Scope;
173
174 // One follower runs per open task and holds what it read across a wait of
175 // up to FOLLOW_WAIT_MS, so it reads its own task, never the parent's whole
176 // task list: a parent with thousands of tasks made every restart decode
177 // that list once per open task at the same time and ran out of heap.
178 const readTask = (parentThreadId: ThreadId, taskId: NodeId) =>
179 threads
180 .getThreadRecords(parentThreadId, ["subagents"], { subagentIds: [taskId] })
181 .pipe(Effect.map(({ thread, subagents }) => ({ thread, task: subagents[0] })));
182
183 /** The peer's project with this thread's repository, or the one the caller named. */
184 const resolveRemoteProject = Effect.fn("RemoteDelegation.resolveRemoteProject")(function* (
185 scope: ThreadScope,
186 environmentId: EnvironmentId,
187 parentProjectId: ProjectId,
188 requested: ProjectId | undefined,
189 ) {
190 if (requested !== undefined) return requested;
191 const here = yield* projects.getById(parentProjectId).pipe(
192 Effect.map(Option.getOrUndefined),
193 Effect.orElseSucceed(() => undefined),
194 );
195 // The project's own identity is a one-minute cache that reads blank when
196 // cold, so resolve it here, as the other side's t3_project_list does.
197 const key =
198 here === undefined
199 ? undefined
200 : (yield* repositoryIdentities.resolve(here.workspaceRoot))?.canonicalKey;
201 if (key === undefined) {
202 return yield* new OrchestratorMcpFailure({
203 code: "target_required",
204 message: "Pass target.projectId: this thread's project has no repository to match there.",
205 });
206 }
207 const matches: Array<{ readonly id: ProjectId; readonly title: string }> = [];
208 let cursor: number | null = 0;
209 while (cursor !== null) {
210 const listed: Tool.Success<typeof ProjectToolkit.tools.t3_project_list> =
211 yield* forwarding.call(scope, ProjectToolkit.tools.t3_project_list, environmentId, {
212 cursor,
213 limit: 100,
214 });
215 matches.push(
216 ...listed.projects.filter((project) => project.repositoryIdentity?.canonicalKey === key),
217 );
218 cursor = listed.nextCursor;
219 }
220 if (matches.length === 1) return matches[0]!.id;
221 return yield* new OrchestratorMcpFailure({
222 code: "invalid_request",
223 message:
224 matches.length === 0
225 ? `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.`
226 : `Several projects there have this repository: ${matches.map((project) => `${project.title} (${project.id})`).join(", ")}. Pass target.projectId.`,
227 });
228 });
229
230 /** The instance there of the driver the caller named, preferring the one this thread runs on, as a task here does. */
231 const resolveRemoteInstance = Effect.fn("RemoteDelegation.resolveRemoteInstance")(function* (
232 scope: ThreadScope,
233 environmentId: EnvironmentId,
234 requested: {
235 readonly driverKind: ProviderDriverKind;
236 readonly providerInstanceId: ProviderInstanceId | undefined;
237 readonly inheritedInstanceId: ProviderInstanceId;
238 },
239 ) {
240 const { providers } = yield* forwarding.call(scope, RemoteCapabilitiesTool, environmentId, {});
241 if (requested.providerInstanceId !== undefined) {
242 const named = providers.find(
243 (provider) => provider.providerInstanceId === requested.providerInstanceId,
244 );
245 if (named !== undefined && named.driverKind !== requested.driverKind) {
246 return yield* new OrchestratorMcpFailure({
247 code: "invalid_request",
248 message: `Provider instance ${named.providerInstanceId} there uses driver ${named.driverKind}, not ${requested.driverKind}.`,
249 });
250 }
251 return requested.providerInstanceId;
252 }
253 const candidates = providers.filter(
254 (provider) => provider.driverKind === requested.driverKind && provider.canRunChildTask,
255 );
256 const chosen =
257 candidates.find(
258 (provider) => provider.providerInstanceId === requested.inheritedInstanceId,
259 ) ?? candidates[0];
260 if (chosen === undefined) {
261 return yield* new OrchestratorMcpFailure({
262 code: "provider_unavailable",
263 message: `No instance of driver ${requested.driverKind} there can run a child task. orchestrator_capabilities with this environmentId lists its providers.`,
264 });
265 }
266 return chosen.providerInstanceId;
267 });
268
269 const delegate: RemoteDelegation["Service"]["delegate"] = Effect.fn("RemoteDelegation.delegate")(
270 function* (scope, input) {
271 const parent = yield* threads.getThreadRecords(scope.thread.threadId, ["runs"]).pipe(
272 Effect.mapError(
273 () =>
274 new OrchestratorMcpFailure({
275 code: "thread_not_found",
276 message: "The calling thread was not found.",
277 }),
278 ),
279 );
280 const parentRun = parent.runs
281 .filter(ThreadManagement.isActiveRun)
282 .toSorted((left, right) => right.ordinal - left.ordinal)[0];
283 if (
284 parentRun === undefined ||
285 parentRun.rootNodeId === null ||
286 parentRun.providerInstanceId !== scope.thread.providerInstanceId
287 ) {
288 return yield* new OrchestratorMcpFailure({
289 code: "parent_not_active",
290 message: "Delegated tasks require an active run owned by this MCP provider session.",
291 });
292 }
293 const parentNodeId = parentRun.rootNodeId;
294 const { target } = input;
295 // A worktree there would branch from a commit this checkout has and the
296 // other may not, so a remote task runs in that project's checkout.
297 if (input.isolation === "worktree") {
298 return yield* new OrchestratorMcpFailure({
299 code: "invalid_request",
300 message:
301 '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.',
302 });
303 }
304 // The provider and model inherit as they do for a task here. Another
305 // provider there has no model to inherit, so the caller names one.
306 const inherited = parent.thread.modelSelection;
307 const instanceId =
308 target.driverKind === undefined
309 ? (target.providerInstanceId ?? inherited.instanceId)
310 : yield* resolveRemoteInstance(scope, target.environmentId, {
311 driverKind: target.driverKind,
312 providerInstanceId: target.providerInstanceId,
313 inheritedInstanceId: inherited.instanceId,
314 });
315 const model =
316 target.model ?? (instanceId === inherited.instanceId ? inherited.model : undefined);
317 if (model === undefined) {
318 return yield* new OrchestratorMcpFailure({
319 code: "target_required",
320 message: "Pass target.model from orchestrator_capabilities with this environmentId.",
321 });
322 }
323 const inheritedOptions =
324 instanceId === inherited.instanceId && model === inherited.model
325 ? inherited.options
326 : undefined;
327 // Only full access may pick an agent's own mode there, and the other side cannot see
328 // that this thread already runs in one. Below that the task starts in the agent's default.
329 const options =
330 target.options ??
331 (inheritedOptions === undefined ||
332 (parent.thread.runtimeMode === "full-access" &&
333 (yield* links.get(target.environmentId).pipe(
334 Effect.map((link) => Option.getOrUndefined(link)?.access === "full-access"),
335 Effect.orElseSucceed(() => false),
336 )))
337 ? inheritedOptions
338 : withoutAgentModePicks(
339 inheritedOptions,
340 providerOptionDescriptors(
341 (yield* providerRegistry.getProviders).find(
342 (provider) => provider.instanceId === instanceId,
343 ),
344 ),
345 ));
346 // Modes asked for are checked against this thread. Omitted ones are left
347 // to the other side, which inherits this thread's modes capped by the
348 // link's access, so a narrower link still takes the task.
349 const runtimeMode =
350 input.runtimeMode === undefined || input.runtimeMode === "inherit"
351 ? undefined
352 : yield* resolveRuntimeMode(parent.thread.runtimeMode, input.runtimeMode);
353 const interactionMode =
354 input.interactionMode === undefined || input.interactionMode === "inherit"
355 ? undefined
356 : yield* resolveInteractionMode(parent.thread.interactionMode, input.interactionMode);
357 const projectId = yield* resolveRemoteProject(
358 scope,
359 target.environmentId,
360 parent.thread.projectId,
361 target.projectId,
362 );
363 // One key for the launch there and the record here, so a retry finds both.
364 // Both are scoped to the provider session, as every key a caller passes is:
365 // the forwarder scopes the launch's, and the record's names it.
366 const key = input.clientRequestId ?? (yield* random.uuidV4());
367 const task = taskPrompt(input);
368 const title = input.title ?? parent.thread.title;
369 const launched = yield* forwarding.call(
370 scope,
371 ProjectToolkit.tools.t3_thread_launch,
372 target.environmentId,
373 {
374 projectId,
375 title,
376 modelSelection: { instanceId, model, ...(options === undefined ? {} : { options }) },
377 ...(runtimeMode === undefined ? {} : { runtimeMode }),
378 ...(interactionMode === undefined ? {} : { interactionMode }),
379 message: task,
380 clientRequestId: `delegate:${scope.thread.threadId}:${key}`,
381 // The thread there shows it is this thread's subagent, with a way back.
382 delegatedFrom: {
383 environmentId: hereId,
384 threadId: parent.thread.id,
385 title: parent.thread.title,
386 },
387 },
388 );
389 const link = yield* links.get(target.environmentId).pipe(
390 Effect.map(Option.getOrUndefined),
391 Effect.orElseSucceed(() => undefined),
392 );
393 const commandId = CommandId.make(
394 `command:mcp:${encodeURIComponent(scope.requestNamespace)}:remote-delegate:${encodeURIComponent(key)}`,
395 );
396 const remoteChild: OrchestrationV2RemoteTaskChild = {
397 environmentId: target.environmentId,
398 threadId: launched.threadId,
399 label: link?.label ?? target.environmentId,
400 title,
401 ...(launched.runId === null ? {} : { runId: launched.runId }),
402 };
403 const recorded = yield* threads
404 .dispatch({
405 type: "delegated_task.remote.request",
406 commandId,
407 parentThreadId: scope.thread.threadId,
408 parentRunId: parentRun.id,
409 parentNodeId,
410 task,
411 ...(input.title === undefined ? {} : { title: input.title }),
412 // The driver runs there; this side only labels the task with it.
413 driver: ProviderDriverKind.make("remote"),
414 modelSelection: launched.modelSelection,
415 remoteChild,
416 completionWake: input.mode === "wait" ? "settled_only" : "always",
417 })
418 .pipe(
419 // The cause goes to the log; the caller learns only that recording failed.
420 Effect.tapError((cause) =>
421 Effect.logWarning("remote-delegation.record-failed", {
422 parentThreadId: scope.thread.threadId,
423 cause,
424 }),
425 ),
426 Effect.mapError(
427 () =>
428 new OrchestratorMcpFailure({
429 code: "orchestration_error",
430 message: "Unable to record the delegated task.",
431 }),
432 ),
433 // Nothing here follows a thread the task was never recorded for, so stop it there.
434 // A crash between the launch and this record still leaves it running there
435 // until a retry with the same clientRequestId records it.
436 Effect.tapError(() =>
437 stopThere(followScope(scope.thread, remoteChild), remoteChild, "stop").pipe(
438 Effect.ignoreCause({ log: true }),
439 ),
440 ),
441 );
442 const taskEvent = recorded.storedEvents.find(
443 (stored) => stored.event.type === "subagent.updated",
444 );
445 const taskId =
446 taskEvent?.event.type === "subagent.updated"
447 ? taskEvent.event.payload.id
448 : // A replayed request recorded the task the first time.
449 yield* threads.getThreadRecords(scope.thread.threadId, ["subagents"]).pipe(
450 Effect.map(
451 ({ subagents }) =>
452 subagents.find((task) => task.remoteChild?.threadId === launched.threadId)?.id,
453 ),
454 Effect.orElseSucceed(() => undefined),
455 );
456 if (taskId === undefined) {
457 return yield* new OrchestratorMcpFailure({
458 code: "orchestration_error",
459 message: "The delegated task was not recorded.",
460 });
461 }
462 yield* followOne(scope.thread.threadId, taskId).pipe(Effect.forkIn(followers));
463 return { taskId };
464 },
465 );
466
467 const followUp: RemoteDelegation["Service"]["followUp"] = Effect.fn("RemoteDelegation.followUp")(
468 function* (scope, environmentId, request, sent) {
469 // A steer joins a run that is already some task's, or no one's.
470 if (scope.thread === undefined || (sent.delivery !== "started" && sent.delivery !== "queued"))
471 return sent;
472 const parentThreadId = scope.thread.threadId;
473 const parent = yield* threads
474 .getThreadRecords(parentThreadId, ["runs", "subagents"])
475 .pipe(Effect.orElseSucceed(() => undefined));
476 const isThere = (task: OrchestrationV2Subagent) =>
477 task.remoteChild?.environmentId === environmentId &&
478 task.remoteChild.threadId === sent.threadId;
479 const finished = parent?.subagents.find((task) => isThere(task) && task.result !== null);
480 // Bound as a follow-up here is: a background caller's foreground run may have ended.
481 const parentRun = parent === undefined ? null : followUpOwnerRun(parent.runs);
482 if (
483 finished?.remoteChild === undefined ||
484 finished.model === null ||
485 parentRun === null ||
486 parentRun.rootNodeId === null
487 )
488 return sent;
489 // The message id there is the send's, so a retry that reached the same send records once.
490 const commandId = CommandId.make(
491 `command:remote-followup:${encodeURIComponent(parentThreadId)}:${encodeURIComponent(environmentId)}:${encodeURIComponent(sent.messageId)}`,
492 );
493 const recorded = yield* threads
494 .dispatch({
495 type: "delegated_task.remote.request",
496 commandId,
497 parentThreadId,
498 parentRunId: parentRun.id,
499 parentNodeId: parentRun.rootNodeId,
500 task: request.message,
501 ...(finished.title === null ? {} : { title: finished.title }),
502 driver: finished.driver,
503 modelSelection: { instanceId: finished.providerInstanceId, model: finished.model },
504 remoteChild: {
505 environmentId,
506 threadId: sent.threadId,
507 label: finished.remoteChild.label,
508 runId: sent.runId,
509 },
510 completionWake: "always",
511 })
512 .pipe(
513 Effect.tapError((cause) =>
514 Effect.logWarning("remote-delegation.followup-record-failed", {
515 parentThreadId,
516 cause,
517 }),
518 ),
519 Effect.mapError(
520 () =>
521 new OrchestratorMcpFailure({
522 code: "orchestration_error",
523 message:
524 request.clientRequestId === undefined
525 ? "The message was sent, but its task was not recorded; read the thread for its answer instead of sending it again."
526 : "The message was sent, but its task was not recorded; send it again with the same clientRequestId to record it.",
527 }),
528 ),
529 );
530 const taskEvent = recorded.storedEvents.find(
531 (stored) => stored.event.type === "subagent.updated",
532 );
533 const taskId =
534 taskEvent?.event.type === "subagent.updated"
535 ? taskEvent.event.payload.id
536 : // A replayed request recorded the task the first time.
537 yield* threads.getThreadRecords(parentThreadId, ["subagents"]).pipe(
538 Effect.map(
539 ({ subagents }) =>
540 subagents.find((task) => isThere(task) && task.remoteChild?.runId === sent.runId)
541 ?.id,
542 ),
543 Effect.orElseSucceed(() => undefined),
544 );
545 if (taskId === undefined) return sent;
546 yield* followOne(parentThreadId, taskId).pipe(Effect.forkIn(followers));
547 return { ...sent, taskId };
548 },
549 );
550
551 /**
552 * Completes `task` here with its thread there's final state. Each attempt is its own
553 * command, so a failed one never blocks the next; a report refused because the task already
554 * has its result (a cancel, a Stop or an earlier report) is done. `stoppedThere` records that
555 * nothing is left to stop there, even on a task that already has its result.
556 */
557 const complete = Effect.fn("RemoteDelegation.complete")(function* (
558 parentThreadId: ThreadId,
559 taskId: NodeId,
560 status: "completed" | "failed" | "cancelled" | "interrupted",
561 result: string,
562 stoppedThere: "ran-out" | "stopped" | undefined,
563 stopCount?: number,
564 executedModel?: string,
565 ) {
566 const attempt = yield* random.uuidV4();
567 yield* threads
568 .dispatch({
569 type: "delegated_task.remote.complete",
570 commandId: CommandId.make(`command:remote-task-complete:${taskId}:${attempt}`),
571 parentThreadId,
572 taskId,
573 status,
574 result,
575 ...(stoppedThere === undefined ? {} : { stoppedThere }),
576 ...(stopCount === undefined ? {} : { stopCount }),
577 ...(executedModel === undefined ? {} : { executedModel }),
578 })
579 .pipe(
580 Effect.catch((error) =>
581 readTask(parentThreadId, taskId).pipe(
582 Effect.flatMap(({ task }) => (task?.result != null ? Effect.void : Effect.fail(error))),
583 ),
584 ),
585 );
586 });
587
588 /**
589 * How this environment reaches a task's thread there: as the parent
590 * thread, under one namespace per parent, so a stop sent again after a
591 * restart or a dropped route is recorded there once.
592 */
593 const followScope = (
594 parent: { readonly threadId: ThreadId; readonly providerInstanceId: ProviderInstanceId },
595 remote: OrchestrationV2RemoteTaskChild,
596 ): ThreadScope => ({
597 environmentId: hereId,
598 requestNamespace: `remote-task:${parent.threadId}`,
599 thread: {
600 threadId: parent.threadId,
601 providerSessionId: `remote-task:${remote.threadId}`,
602 providerInstanceId: parent.providerInstanceId,
603 },
604 client: undefined,
605 capabilities: new Set(["orchestration"]),
606 issuedAt: 0,
607 });
608
609 /**
610 * Stops the task's own thread there as its Stop button does: its running turn, queued
611 * messages, pull request watches and delegated tasks. `key` names the stop (the follower
612 * sends one, each cancel its own), and each is recorded there once however often it is sent.
613 */
614 const stopThere = (
615 scope: ThreadScope,
616 remote: OrchestrationV2RemoteTaskChild,
617 key: string,
618 reason?: string,
619 ) =>
620 forwarding
621 .interruptThread(scope, remote.environmentId, {
622 threadId: remote.threadId,
623 stop: true,
624 ...(reason === undefined ? {} : { reason }),
625 clientRequestId: `${key}:${remote.threadId}`,
626 })
627 .pipe(Effect.asVoid);
628
629 /**
630 * The last reply `runId` gave on the task's thread there, which is its
631 * result, read whole however long it is. A failed run prefers its error
632 * from the activity view over an earlier reply, without taking another run's.
633 * Led by a note when its provider reported running another model than it asked for.
634 */
635 const lastReply = Effect.fn("RemoteDelegation.lastReply")(function* (
636 scope: ThreadScope,
637 remote: OrchestrationV2RemoteTaskChild,
638 runId: RunId | null,
639 failed = false,
640 probeSuccess = true,
641 ) {
642 let reply: OrchestratorMcpThreadTimelineItem | undefined;
643 let error: OrchestratorMcpThreadTimelineItem | undefined;
644 // Linked peers read newest first without a cursor, so this scan runs forward. It starts
645 // after position 0, the message that started the thread, which no run's reply can precede;
646 // older peers refuse -1.
647 let afterPosition = 0;
648 let run: OrchestratorMcpThreadRun | undefined;
649 let remainingItems = 0;
650 let tailProbed = false;
651 while (true) {
652 const read = yield* forwarding.readThread(scope, remote.environmentId, {
653 threadId: remote.threadId,
654 view: failed ? "activity" : "messages",
655 limit: 100,
656 runLimit: 50,
657 // Keep the first and expected final activity pages whole. A result on a
658 // middle page then needs an extra text read after the scan.
659 maxCharsPerItem: failed && remainingItems > 100 ? 1 : 20_000,
660 afterPosition,
661 });
662 run ??= read.recentRuns.find((candidate) => candidate.runId === runId);
663 reply =
664 read.items.findLast(
665 (item) => item.type === "assistant_message" && (runId === null || item.runId === runId),
666 ) ?? reply;
667 if (failed) {
668 error =
669 read.items.findLast(
670 (item) => item.type === "error" && (runId === null || item.runId === runId),
671 ) ?? error;
672 }
673 if (!read.hasMore || read.nextPosition === null) break;
674 if (!failed && probeSuccess && !tailProbed) {
675 tailProbed = true;
676 const tailPosition = Math.floor((read.thread.itemCount - 1) / 100) * 100 - 1;
677 if (tailPosition > read.nextPosition) {
678 const tail = yield* forwarding.readThread(scope, remote.environmentId, {
679 threadId: remote.threadId,
680 view: "messages",
681 limit: 100,
682 maxCharsPerItem: 20_000,
683 afterPosition: tailPosition,
684 });
685 const tailReply = tail.items.findLast(
686 (item) => item.type === "assistant_message" && (runId === null || item.runId === runId),
687 );
688 if (!tail.hasMore && tailReply !== undefined) {
689 reply = tailReply;
690 break;
691 }
692 }
693 }
694 afterPosition = read.nextPosition;
695 remainingItems = read.thread.itemCount - afterPosition - 1;
696 }
697 reply = error ?? reply;
698 const executedModel = run?.executedModel ?? undefined;
699 if (reply === undefined) return { text: undefined, executedModel };
700 let text = reply.text ?? "";
701 let textOffset = reply.textTruncated ? (reply.nextTextOffset ?? null) : null;
702 while (textOffset !== null) {
703 const rest = yield* forwarding.readThread(scope, remote.environmentId, {
704 threadId: remote.threadId,
705 itemId: reply.itemId,
706 textOffset,
707 maxCharsPerItem: 20_000,
708 });
709 const part = rest.items[0];
710 if (part === undefined) break;
711 text += part.text ?? "";
712 textOffset = part.textTruncated ? (part.nextTextOffset ?? null) : null;
713 }
714 return {
715 text: run === undefined ? text : withExecutedModelNote(text, run.model, run.executedModel),
716 executedModel,
717 };
718 });
719
720 /**
721 * Why following a task can never succeed, if that is what `error` means.
722 * The far side's message already says what was refused and what to do; a
723 * link forgotten here only reads as a bad request, so it is named.
724 */
725 const finalReason = Effect.fn("RemoteDelegation.finalReason")(
726 function* (parentThreadId: ThreadId, taskId: NodeId, error: OrchestratorMcpFailure) {
727 if (isFinal(error)) return error.message;
728 if (error.code !== "invalid_request") return undefined;
729 const { task } = yield* readTask(parentThreadId, taskId);
730 const environmentId = task?.remoteChild?.environmentId;
731 if (environmentId === undefined) return error.message;
732 const link = yield* links.get(environmentId);
733 return Option.isSome(link) ? undefined : error.message;
734 },
735 Effect.orElseSucceed(() => undefined),
736 );
737
738 /** A task's thread there that ended without a reply. */
739 const noReply = "(The thread in the linked environment ended without a reply.)";
740
741 /**
742 * Waits for the task's run there to end, completes the task here, and stops it there if it
743 * ended here first. A revoked, expired or forgotten link, or a thread or run gone there,
744 * fails the task with nothing left to stop; repeated defects here fail it too. Anything else
745 * (the other machine asleep, a dropped route) is retried with back-off, and so is completing.
746 */
747 const follow = (parentThreadId: ThreadId, taskId: NodeId): Effect.Effect<void> =>
748 Effect.suspend(() => {
749 let defects = 0;
750 const noDefect = Effect.sync(() => {
751 defects = 0;
752 });
753 return followOnce(parentThreadId, taskId).pipe(
754 Effect.tap(noDefect),
755 // `false` means it is still running there: follow again straight away.
756 Effect.repeat({ while: (done) => !done }),
757 Effect.catchTags({
758 OrchestratorMcpFailure: Effect.fn("RemoteDelegation.followFailed")(function* (error) {
759 const reason = yield* finalReason(parentThreadId, taskId, error);
760 if (reason === undefined) return yield* error;
761 // Gone there, or no link to reach it by: nothing left to stop there.
762 const { task } = yield* readTask(parentThreadId, taskId);
763 const stopCount = task?.remoteChild?.stopCount;
764 yield* complete(parentThreadId, taskId, "failed", reason, "stopped", stopCount);
765 }),
766 }),
767 Effect.tapError(() => noDefect),
768 Effect.tapDefect(() =>
769 Effect.sync(() => {
770 defects += 1;
771 }),
772 ),
773 failOnDefect,
774 Effect.retry({ schedule: followRetry, while: () => defects < FOLLOW_MAX_DEFECTS }),
775 Effect.catch(
776 Effect.fn("RemoteDelegation.followGaveUp")(
777 function* () {
778 const { task } = yield* readTask(parentThreadId, taskId);
779 const remote = task?.remoteChild;
780 // A task with its result keeps it; completing it again would owe another stop there.
781 if (remote === undefined || task?.result !== null) return;
782 const result = `Following the thread ${remote.threadId} in ${remote.label} failed repeatedly, so it may still run there (task_cancel stops it).`;
783 yield* complete(parentThreadId, taskId, "failed", result, undefined);
784 },
785 failOnDefect,
786 Effect.retry(followRetry),
787 ),
788 ),
789 Effect.ignoreCause({ log: true }),
790 );
791 });
792
793 /**
794 * One wait on the task's thread there; true once the task here is done.
795 * A task completed here first (cancelled, or its parent stopped) is
796 * stopped there, and done once that stop is recorded here.
797 */
798 const followOnce = Effect.fn("RemoteDelegation.followOnce")(function* (
799 parentThreadId: ThreadId,
800 taskId: NodeId,
801 ) {
802 const sequence = yield* threads.getThreadEventSequence(parentThreadId);
803 const { thread, task } = yield* readTask(parentThreadId, taskId);
804 if (task?.remoteChild === undefined) return true;
805 const remote = task.remoteChild;
806 const scope = followScope(
807 { threadId: parentThreadId, providerInstanceId: thread.providerInstanceId },
808 remote,
809 );
810 // Ended here, maybe while this follower backed off from an unreachable
811 // machine or before a restart: it still has to be stopped there. So
812 // does one its parent here was stopped after, for what followed there.
813 if (task.result !== null) {
814 if (
815 remote.stoppedThere === false ||
816 ((task.status === "cancelled" || task.status === "interrupted") &&
817 remote.stoppedThere !== true)
818 ) {
819 const count = remote.stopCount === undefined ? "stop" : `stop-${remote.stopCount}`;
820 // Named for its run too: a follow-up task shares the thread there and counts its own stops.
821 const key = remote.runId === undefined ? count : `${count}:${remote.runId}`;
822 yield* stopThere(scope, remote, key).pipe(
823 // Its thread there now runs above what this side may touch, say
824 // because the parent here was lowered since; no retry changes that.
825 Effect.catchIf(isModeRefusal, (error) =>
826 Effect.logWarning("A linked environment refused to stop a delegated task", {
827 taskId,
828 reason: error.message,
829 }),
830 ),
831 );
832 yield* complete(
833 parentThreadId,
834 taskId,
835 terminalStatus(task.status),
836 task.result,
837 "stopped",
838 remote.stopCount,
839 );
840 return yield* settled(parentThreadId, taskId);
841 }
842 return true;
843 }
844 const endedHere = threads
845 .streamStoredEventsFrom({
846 threadId: parentThreadId,
847 afterSequence: sequence,
848 eventType: "subagent.updated",
849 })
850 .pipe(
851 Stream.filter(
852 (stored) =>
853 stored.event.type === "subagent.updated" &&
854 stored.event.payload.id === taskId &&
855 stored.event.payload.result !== null,
856 ),
857 Stream.runHead,
858 Effect.flatMap((ended) =>
859 Option.isSome(ended) ? Effect.succeed({ endedHere: true } as const) : Effect.never,
860 ),
861 );
862 const waited = yield* forwarding
863 .waitForThread(scope, remote.environmentId, {
864 threadId: remote.threadId,
865 ...(remote.runId === undefined ? {} : { runId: remote.runId }),
866 timeoutMs: FOLLOW_WAIT_MS,
867 // A thread there whose run ended may still be waiting on its own
868 // tasks to wake it for the answer, which a task here waits for too.
869 // An older peer ignores this and reports the run alone.
870 untilDelegatedWorkSettled: true,
871 })
872 .pipe(Effect.raceFirst(endedHere));
873 // The next look reads the result and stops it there.
874 if ("endedHere" in waited) return false;
875 if (waited.timedOut) return false;
876 // A task recorded without its run waits on the thread's latest; a
877 // thread there with none has nothing left to wait for.
878 if (waited.runId === null) {
879 const reply = yield* lastReply(scope, remote, null);
880 yield* complete(
881 parentThreadId,
882 taskId,
883 reply.text === undefined ? "failed" : "completed",
884 reply.text ?? "The thread in the linked environment has no run to follow.",
885 "ran-out",
886 );
887 return yield* settled(parentThreadId, taskId);
888 }
889 if (!isTerminal(waited.status)) return false;
890 // A later run's answer there may be another open follow-up's, or its restart, which no run id
891 // here names; concurrent sends may record here out of their order there. Then this task's
892 // answer is its own run's latest restart, the one waited on.
893 const sharedThread =
894 waited.resultRun !== undefined &&
895 waited.resultRun.runId !== waited.runId &&
896 (yield* threads.getThreadRecords(parentThreadId, ["subagents"]).pipe(
897 Effect.map(({ subagents }) => {
898 const recordedAt = subagents.find((task) => task.id === taskId)?.startedAt ?? null;
899 return subagents.some(
900 (other) =>
901 other.id !== taskId &&
902 other.remoteChild?.environmentId === remote.environmentId &&
903 other.remoteChild.threadId === remote.threadId &&
904 // One that settled before this was recorded ran before it there.
905 (recordedAt === null ||
906 other.completedAt === null ||
907 DateTime.isGreaterThan(other.completedAt, recordedAt)),
908 );
909 }),
910 ));
911 const resultRun =
912 waited.resultRun !== undefined && !sharedThread
913 ? waited.resultRun
914 : { runId: waited.runId, status: waited.status };
915 const result = yield* lastReply(
916 scope,
917 remote,
918 resultRun.runId,
919 resultRun.status === "failed",
920 resultRun.status === "completed",
921 );
922 yield* complete(
923 parentThreadId,
924 taskId,
925 terminalStatus(resultRun.status),
926 result.text ?? noReply,
927 "ran-out",
928 undefined,
929 result.executedModel,
930 );
931 return yield* settled(parentThreadId, taskId);
932 });
933
934 /**
935 * Whether the task is done here after the follower reported its run ran
936 * out there. A cancel or Stop that landed while the reply was read keeps
937 * its result, and still owes a stop there for what may follow the run;
938 * the next look sends it.
939 */
940 const settled = (parentThreadId: ThreadId, taskId: NodeId) =>
941 readTask(parentThreadId, taskId).pipe(
942 Effect.map(({ task }) => task?.remoteChild?.stoppedThere === true),
943 );
944
945 const following = new Map<NodeId, { again: boolean }>();
946
947 /**
948 * `follow`, at most once per task. Asked again while it runs, say by a
949 * Stop here on a task that already has its result, it looks once more
950 * before it ends, so that stop is not missed.
951 */
952 const followOne = (parentThreadId: ThreadId, taskId: NodeId) =>
953 Effect.suspend(() => {
954 const running = following.get(taskId);
955 if (running !== undefined) {
956 running.again = true;
957 return Effect.void;
958 }
959 const state = { again: false };
960 following.set(taskId, state);
961 return follow(parentThreadId, taskId).pipe(
962 // Checked and released in one step, so a request between them is never lost.
963 Effect.repeat({
964 while: () => {
965 if (state.again) {
966 state.again = false;
967 return true;
968 }
969 following.delete(taskId);
970 return false;
971 },
972 }),
973 Effect.ensuring(
974 Effect.sync(() => {
975 if (following.get(taskId) === state) following.delete(taskId);
976 }),
977 ),
978 );
979 });
980
981 const cancel: RemoteDelegation["Service"]["cancel"] = Effect.fn("RemoteDelegation.cancel")(
982 function* (scope, task, input) {
983 const remote = task.remoteChild;
984 if (remote === undefined) {
985 return yield* new OrchestratorMcpFailure({
986 code: "task_not_found",
987 message: `Delegated task ${task.id} is not remote.`,
988 });
989 }
990 const { reason } = input;
991 const there = followScope(scope.thread, remote);
992 // A later cancel stops what started there since; a retry of this one, nothing new.
993 const key = `cancel:${encodeURIComponent(scope.requestNamespace)}:${
994 input.clientRequestId ?? (yield* random.uuidV4())
995 }`;
996 if (task.result !== null) {
997 // Best effort: the result stands whether or not the stop gets there.
998 yield* stopThere(there, remote, key, reason).pipe(
999 Effect.andThen(
1000 complete(
1001 task.threadId,
1002 task.id,
1003 terminalStatus(task.status),
1004 task.result,
1005 "stopped",
1006 remote.stopCount,
1007 ),
1008 ),
1009 Effect.ignoreCause({ log: true }),
1010 );
1011 return {
1012 taskId: task.id,
1013 status:
1014 task.status === "completed" || task.status === "failed" || task.status === "interrupted"
1015 ? task.status
1016 : "cancelled",
1017 } satisfies OrchestratorMcpTaskCancelResult;
1018 }
1019 // A link that is gone or a machine that is down still cancels the task
1020 // here; its follower keeps trying to stop it there, across restarts.
1021 const unstopped = yield* stopThere(there, remote, key, reason).pipe(
1022 Effect.as(undefined),
1023 Effect.catch((error) => Effect.succeed(error.message)),
1024 );
1025 const cancelled = reason === undefined ? "Cancelled." : `Cancelled: ${reason}`;
1026 yield* complete(
1027 task.threadId,
1028 task.id,
1029 "cancelled",
1030 unstopped === undefined
1031 ? cancelled
1032 : `${cancelled} It could not be stopped in ${remote.label} and may still run there: ${unstopped}`,
1033 unstopped === undefined ? "stopped" : undefined,
1034 remote.stopCount,
1035 ).pipe(
1036 Effect.tapError((cause) =>
1037 Effect.logWarning("remote-delegation.cancel-record-failed", { taskId: task.id, cause }),
1038 ),
1039 Effect.mapError(
1040 () =>
1041 new OrchestratorMcpFailure({
1042 code: "orchestration_error",
1043 message: "Unable to record the cancellation.",
1044 }),
1045 ),
1046 );
1047 return {
1048 taskId: task.id,
1049 status: "cancel_requested",
1050 } satisfies OrchestratorMcpTaskCancelResult;
1051 },
1052 );
1053
1054 const runStatus = Effect.fn("RemoteDelegation.runStatus")(
1055 function* (scope: ThreadScope, task: OrchestrationV2Subagent) {
1056 const remote = task.remoteChild;
1057 if (remote?.runId === undefined) return null;
1058 const read = yield* forwarding.readThread(
1059 followScope(scope.thread, remote),
1060 remote.environmentId,
1061 { threadId: remote.threadId, limit: 1, runLimit: 50 },
1062 );
1063 return read.recentRuns.find((run) => run.runId === remote.runId)?.status ?? null;
1064 },
1065 Effect.orElseSucceed(() => null),
1066 );
1067
1068 const start: RemoteDelegation["Service"]["start"] = () =>
1069 forkParked(
1070 Effect.gen(function* () {
1071 // A finished task's follower has ended, so a Stop here that owes its
1072 // thread there a stop starts it again. Started before the scan below;
1073 // a Stop that slips between the two stays owed for the next start.
1074 yield* Stream.runForEach(threads.streamDomainEvents, (event) =>
1075 event.type === "subagent.updated" && event.payload.remoteChild?.stoppedThere === false
1076 ? followOne(event.threadId, event.payload.id).pipe(Effect.forkIn(followers))
1077 : Effect.void,
1078 ).pipe(
1079 Effect.ignoreCause({ log: true }),
1080 Effect.forkIn(followers, { startImmediately: true }),
1081 );
1082 const open = yield* projections.getOpenRemoteDelegatedTasks;
1083 yield* Effect.forEach(
1084 open,
1085 ({ parentThreadId, taskId }) => followOne(parentThreadId, taskId),
1086 {
1087 concurrency: "unbounded",
1088 discard: true,
1089 },
1090 );
1091 }).pipe(Effect.ignoreCause({ log: true })),
1092 );
1093
1094 return RemoteDelegation.of({ delegate, followUp, cancel, runStatus, start });
1095});
1096
1097/** A defect, logged, as a failure, so a retry covers it. */
1098const failOnDefect = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
1099 Effect.catchDefect(effect, (defect) =>
1100 Effect.logWarning("A remote task's follower hit a defect", Cause.die(defect)).pipe(
1101 Effect.andThen(Effect.fail(new Cause.UnknownError(defect, "A follower hit a defect."))),
1102 ),
1103 );
1104
1105const isTerminal = (status: string) =>
1106 status === "completed" ||
1107 status === "failed" ||
1108 status === "cancelled" ||
1109 status === "interrupted" ||
1110 status === "rolled_back";
1111
1112const terminalStatus = (status: string): "completed" | "failed" | "cancelled" | "interrupted" =>
1113 status === "completed" || status === "failed" || status === "interrupted" ? status : "cancelled";
1114
1115export const layer = Layer.effect(RemoteDelegation, make);