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 * Stops the task there. A follow-up whose run there is still queued shares the thread with
631 * other runs, so only that run is cancelled; anything else is stopped as `stopThere` does.
632 */
633 const stopTaskThere = (
634 scope: ThreadScope,
635 remote: OrchestrationV2RemoteTaskChild,
636 key: string,
637 reason?: string,
638 ) => {
639 const runId = remote.runId;
640 if (runId === undefined) return stopThere(scope, remote, key, reason);
641 return forwarding
642 .readThread(scope, remote.environmentId, {
643 threadId: remote.threadId,
644 limit: 1,
645 runLimit: 50,
646 })
647 .pipe(
648 Effect.map((read) =>
649 read.recentRuns.some((run) => run.runId === runId && run.status === "queued"),
650 ),
651 Effect.orElseSucceed(() => false),
652 Effect.flatMap((queued) =>
653 queued
654 ? forwarding
655 .interruptThread(scope, remote.environmentId, {
656 threadId: remote.threadId,
657 runId,
658 ...(reason === undefined ? {} : { reason }),
659 clientRequestId: `${key}:${remote.threadId}`,
660 })
661 .pipe(Effect.asVoid)
662 : stopThere(scope, remote, key, reason),
663 ),
664 );
665 };
666
667 /**
668 * The last reply `runId` gave on the task's thread there, which is its
669 * result, read whole however long it is. A failed run prefers its error
670 * from the activity view over an earlier reply, without taking another run's.
671 * Led by a note when its provider reported running another model than it asked for.
672 */
673 const lastReply = Effect.fn("RemoteDelegation.lastReply")(function* (
674 scope: ThreadScope,
675 remote: OrchestrationV2RemoteTaskChild,
676 runId: RunId | null,
677 failed = false,
678 probeSuccess = true,
679 ) {
680 let reply: OrchestratorMcpThreadTimelineItem | undefined;
681 let error: OrchestratorMcpThreadTimelineItem | undefined;
682 // Linked peers read newest first without a cursor, so this scan runs forward. It starts
683 // after position 0, the message that started the thread, which no run's reply can precede;
684 // older peers refuse -1.
685 let afterPosition = 0;
686 let run: OrchestratorMcpThreadRun | undefined;
687 let remainingItems = 0;
688 let tailProbed = false;
689 while (true) {
690 const read = yield* forwarding.readThread(scope, remote.environmentId, {
691 threadId: remote.threadId,
692 view: failed ? "activity" : "messages",
693 limit: 100,
694 runLimit: 50,
695 // Keep the first and expected final activity pages whole. A result on a
696 // middle page then needs an extra text read after the scan.
697 maxCharsPerItem: failed && remainingItems > 100 ? 1 : 20_000,
698 afterPosition,
699 });
700 run ??= read.recentRuns.find((candidate) => candidate.runId === runId);
701 reply =
702 read.items.findLast(
703 (item) => item.type === "assistant_message" && (runId === null || item.runId === runId),
704 ) ?? reply;
705 if (failed) {
706 error =
707 read.items.findLast(
708 (item) => item.type === "error" && (runId === null || item.runId === runId),
709 ) ?? error;
710 }
711 if (!read.hasMore || read.nextPosition === null) break;
712 if (!failed && probeSuccess && !tailProbed) {
713 tailProbed = true;
714 const tailPosition = Math.floor((read.thread.itemCount - 1) / 100) * 100 - 1;
715 if (tailPosition > read.nextPosition) {
716 const tail = yield* forwarding.readThread(scope, remote.environmentId, {
717 threadId: remote.threadId,
718 view: "messages",
719 limit: 100,
720 maxCharsPerItem: 20_000,
721 afterPosition: tailPosition,
722 });
723 const tailReply = tail.items.findLast(
724 (item) => item.type === "assistant_message" && (runId === null || item.runId === runId),
725 );
726 if (!tail.hasMore && tailReply !== undefined) {
727 reply = tailReply;
728 break;
729 }
730 }
731 }
732 afterPosition = read.nextPosition;
733 remainingItems = read.thread.itemCount - afterPosition - 1;
734 }
735 reply = error ?? reply;
736 const executedModel = run?.executedModel ?? undefined;
737 if (reply === undefined) return { text: undefined, executedModel };
738 let text = reply.text ?? "";
739 let textOffset = reply.textTruncated ? (reply.nextTextOffset ?? null) : null;
740 while (textOffset !== null) {
741 const rest = yield* forwarding.readThread(scope, remote.environmentId, {
742 threadId: remote.threadId,
743 itemId: reply.itemId,
744 textOffset,
745 maxCharsPerItem: 20_000,
746 });
747 const part = rest.items[0];
748 if (part === undefined) break;
749 text += part.text ?? "";
750 textOffset = part.textTruncated ? (part.nextTextOffset ?? null) : null;
751 }
752 return {
753 text: run === undefined ? text : withExecutedModelNote(text, run.model, run.executedModel),
754 executedModel,
755 };
756 });
757
758 /**
759 * Why following a task can never succeed, if that is what `error` means.
760 * The far side's message already says what was refused and what to do; a
761 * link forgotten here only reads as a bad request, so it is named.
762 */
763 const finalReason = Effect.fn("RemoteDelegation.finalReason")(
764 function* (parentThreadId: ThreadId, taskId: NodeId, error: OrchestratorMcpFailure) {
765 if (isFinal(error)) return error.message;
766 if (error.code !== "invalid_request") return undefined;
767 const { task } = yield* readTask(parentThreadId, taskId);
768 const environmentId = task?.remoteChild?.environmentId;
769 if (environmentId === undefined) return error.message;
770 const link = yield* links.get(environmentId);
771 return Option.isSome(link) ? undefined : error.message;
772 },
773 Effect.orElseSucceed(() => undefined),
774 );
775
776 /** A task's thread there that ended without a reply. */
777 const noReply = "(The thread in the linked environment ended without a reply.)";
778
779 /**
780 * Waits for the task's run there to end, completes the task here, and stops it there if it
781 * ended here first. A revoked, expired or forgotten link, or a thread or run gone there,
782 * fails the task with nothing left to stop; repeated defects here fail it too. Anything else
783 * (the other machine asleep, a dropped route) is retried with back-off, and so is completing.
784 */
785 const follow = (parentThreadId: ThreadId, taskId: NodeId): Effect.Effect<void> =>
786 Effect.suspend(() => {
787 let defects = 0;
788 const noDefect = Effect.sync(() => {
789 defects = 0;
790 });
791 return followOnce(parentThreadId, taskId).pipe(
792 Effect.tap(noDefect),
793 // `false` means it is still running there: follow again straight away.
794 Effect.repeat({ while: (done) => !done }),
795 Effect.catchTags({
796 OrchestratorMcpFailure: Effect.fn("RemoteDelegation.followFailed")(function* (error) {
797 const reason = yield* finalReason(parentThreadId, taskId, error);
798 if (reason === undefined) return yield* error;
799 // Gone there, or no link to reach it by: nothing left to stop there.
800 const { task } = yield* readTask(parentThreadId, taskId);
801 const stopCount = task?.remoteChild?.stopCount;
802 yield* complete(parentThreadId, taskId, "failed", reason, "stopped", stopCount);
803 }),
804 }),
805 Effect.tapError(() => noDefect),
806 Effect.tapDefect(() =>
807 Effect.sync(() => {
808 defects += 1;
809 }),
810 ),
811 failOnDefect,
812 Effect.retry({ schedule: followRetry, while: () => defects < FOLLOW_MAX_DEFECTS }),
813 Effect.catch(
814 Effect.fn("RemoteDelegation.followGaveUp")(
815 function* () {
816 const { task } = yield* readTask(parentThreadId, taskId);
817 const remote = task?.remoteChild;
818 // A task with its result keeps it; completing it again would owe another stop there.
819 if (remote === undefined || task?.result !== null) return;
820 const result = `Following the thread ${remote.threadId} in ${remote.label} failed repeatedly, so it may still run there (task_cancel stops it).`;
821 yield* complete(parentThreadId, taskId, "failed", result, undefined);
822 },
823 failOnDefect,
824 Effect.retry(followRetry),
825 ),
826 ),
827 Effect.ignoreCause({ log: true }),
828 );
829 });
830
831 /**
832 * One wait on the task's thread there; true once the task here is done.
833 * A task completed here first (cancelled, or its parent stopped) is
834 * stopped there, and done once that stop is recorded here.
835 */
836 const followOnce = Effect.fn("RemoteDelegation.followOnce")(function* (
837 parentThreadId: ThreadId,
838 taskId: NodeId,
839 ) {
840 const sequence = yield* threads.getThreadEventSequence(parentThreadId);
841 const { thread, task } = yield* readTask(parentThreadId, taskId);
842 if (task?.remoteChild === undefined) return true;
843 const remote = task.remoteChild;
844 const scope = followScope(
845 { threadId: parentThreadId, providerInstanceId: thread.providerInstanceId },
846 remote,
847 );
848 // Ended here, maybe while this follower backed off from an unreachable
849 // machine or before a restart: it still has to be stopped there. So
850 // does one its parent here was stopped after, for what followed there.
851 if (task.result !== null) {
852 if (
853 remote.stoppedThere === false ||
854 ((task.status === "cancelled" || task.status === "interrupted") &&
855 remote.stoppedThere !== true)
856 ) {
857 const count = remote.stopCount === undefined ? "stop" : `stop-${remote.stopCount}`;
858 // Named for its run too: a follow-up task shares the thread there and counts its own stops.
859 const key = remote.runId === undefined ? count : `${count}:${remote.runId}`;
860 yield* stopTaskThere(scope, remote, key).pipe(
861 // Its thread there now runs above what this side may touch, say
862 // because the parent here was lowered since; no retry changes that.
863 Effect.catchIf(isModeRefusal, (error) =>
864 Effect.logWarning("A linked environment refused to stop a delegated task", {
865 taskId,
866 reason: error.message,
867 }),
868 ),
869 );
870 yield* complete(
871 parentThreadId,
872 taskId,
873 terminalStatus(task.status),
874 task.result,
875 "stopped",
876 remote.stopCount,
877 );
878 return yield* settled(parentThreadId, taskId);
879 }
880 return true;
881 }
882 const endedHere = threads
883 .streamStoredEventsFrom({
884 threadId: parentThreadId,
885 afterSequence: sequence,
886 eventType: "subagent.updated",
887 })
888 .pipe(
889 Stream.filter(
890 (stored) =>
891 stored.event.type === "subagent.updated" &&
892 stored.event.payload.id === taskId &&
893 stored.event.payload.result !== null,
894 ),
895 Stream.runHead,
896 Effect.flatMap((ended) =>
897 Option.isSome(ended) ? Effect.succeed({ endedHere: true } as const) : Effect.never,
898 ),
899 );
900 const waited = yield* forwarding
901 .waitForThread(scope, remote.environmentId, {
902 threadId: remote.threadId,
903 ...(remote.runId === undefined ? {} : { runId: remote.runId }),
904 timeoutMs: FOLLOW_WAIT_MS,
905 // A thread there whose run ended may still be waiting on its own
906 // tasks to wake it for the answer, which a task here waits for too.
907 // An older peer ignores this and reports the run alone.
908 untilDelegatedWorkSettled: true,
909 })
910 .pipe(Effect.raceFirst(endedHere));
911 // The next look reads the result and stops it there.
912 if ("endedHere" in waited) return false;
913 if (waited.timedOut) return false;
914 // A task recorded without its run waits on the thread's latest; a
915 // thread there with none has nothing left to wait for.
916 if (waited.runId === null) {
917 const reply = yield* lastReply(scope, remote, null);
918 yield* complete(
919 parentThreadId,
920 taskId,
921 reply.text === undefined ? "failed" : "completed",
922 reply.text ?? "The thread in the linked environment has no run to follow.",
923 "ran-out",
924 );
925 return yield* settled(parentThreadId, taskId);
926 }
927 if (!isTerminal(waited.status)) return false;
928 // A later run's answer there may be another open follow-up's, or its restart, which no run id
929 // here names; concurrent sends may record here out of their order there. Then this task's
930 // answer is its own run's latest restart, the one waited on.
931 const sharedThread =
932 waited.resultRun !== undefined &&
933 waited.resultRun.runId !== waited.runId &&
934 (yield* threads.getThreadRecords(parentThreadId, ["subagents"]).pipe(
935 Effect.map(({ subagents }) => {
936 const recordedAt = subagents.find((task) => task.id === taskId)?.startedAt ?? null;
937 return subagents.some(
938 (other) =>
939 other.id !== taskId &&
940 other.remoteChild?.environmentId === remote.environmentId &&
941 other.remoteChild.threadId === remote.threadId &&
942 // One that settled before this was recorded ran before it there.
943 (recordedAt === null ||
944 other.completedAt === null ||
945 DateTime.isGreaterThan(other.completedAt, recordedAt)),
946 );
947 }),
948 ));
949 const resultRun =
950 waited.resultRun !== undefined && !sharedThread
951 ? waited.resultRun
952 : { runId: waited.runId, status: waited.status };
953 const result = yield* lastReply(
954 scope,
955 remote,
956 resultRun.runId,
957 resultRun.status === "failed",
958 resultRun.status === "completed",
959 );
960 yield* complete(
961 parentThreadId,
962 taskId,
963 terminalStatus(resultRun.status),
964 result.text ?? noReply,
965 "ran-out",
966 undefined,
967 result.executedModel,
968 );
969 return yield* settled(parentThreadId, taskId);
970 });
971
972 /**
973 * Whether the task is done here after the follower reported its run ran
974 * out there. A cancel or Stop that landed while the reply was read keeps
975 * its result, and still owes a stop there for what may follow the run;
976 * the next look sends it.
977 */
978 const settled = (parentThreadId: ThreadId, taskId: NodeId) =>
979 readTask(parentThreadId, taskId).pipe(
980 Effect.map(({ task }) => task?.remoteChild?.stoppedThere === true),
981 );
982
983 const following = new Map<NodeId, { again: boolean }>();
984
985 /**
986 * `follow`, at most once per task. Asked again while it runs, say by a
987 * Stop here on a task that already has its result, it looks once more
988 * before it ends, so that stop is not missed.
989 */
990 const followOne = (parentThreadId: ThreadId, taskId: NodeId) =>
991 Effect.suspend(() => {
992 const running = following.get(taskId);
993 if (running !== undefined) {
994 running.again = true;
995 return Effect.void;
996 }
997 const state = { again: false };
998 following.set(taskId, state);
999 return follow(parentThreadId, taskId).pipe(
1000 // Checked and released in one step, so a request between them is never lost.
1001 Effect.repeat({
1002 while: () => {
1003 if (state.again) {
1004 state.again = false;
1005 return true;
1006 }
1007 following.delete(taskId);
1008 return false;
1009 },
1010 }),
1011 Effect.ensuring(
1012 Effect.sync(() => {
1013 if (following.get(taskId) === state) following.delete(taskId);
1014 }),
1015 ),
1016 );
1017 });
1018
1019 const cancel: RemoteDelegation["Service"]["cancel"] = Effect.fn("RemoteDelegation.cancel")(
1020 function* (scope, task, input) {
1021 const remote = task.remoteChild;
1022 if (remote === undefined) {
1023 return yield* new OrchestratorMcpFailure({
1024 code: "task_not_found",
1025 message: `Delegated task ${task.id} is not remote.`,
1026 });
1027 }
1028 const { reason } = input;
1029 const there = followScope(scope.thread, remote);
1030 // A later cancel stops what started there since; a retry of this one, nothing new.
1031 const key = `cancel:${encodeURIComponent(scope.requestNamespace)}:${
1032 input.clientRequestId ?? (yield* random.uuidV4())
1033 }`;
1034 if (task.result !== null) {
1035 // Best effort: the result stands whether or not the stop gets there.
1036 yield* stopThere(there, remote, key, reason).pipe(
1037 Effect.andThen(
1038 complete(
1039 task.threadId,
1040 task.id,
1041 terminalStatus(task.status),
1042 task.result,
1043 "stopped",
1044 remote.stopCount,
1045 ),
1046 ),
1047 Effect.ignoreCause({ log: true }),
1048 );
1049 return {
1050 taskId: task.id,
1051 status:
1052 task.status === "completed" || task.status === "failed" || task.status === "interrupted"
1053 ? task.status
1054 : "cancelled",
1055 } satisfies OrchestratorMcpTaskCancelResult;
1056 }
1057 // A link that is gone or a machine that is down still cancels the task
1058 // here; its follower keeps trying to stop it there, across restarts.
1059 const unstopped = yield* stopTaskThere(there, remote, key, reason).pipe(
1060 Effect.as(undefined),
1061 Effect.catch((error) => Effect.succeed(error.message)),
1062 );
1063 const cancelled = reason === undefined ? "Cancelled." : `Cancelled: ${reason}`;
1064 yield* complete(
1065 task.threadId,
1066 task.id,
1067 "cancelled",
1068 unstopped === undefined
1069 ? cancelled
1070 : `${cancelled} It could not be stopped in ${remote.label} and may still run there: ${unstopped}`,
1071 unstopped === undefined ? "stopped" : undefined,
1072 remote.stopCount,
1073 ).pipe(
1074 Effect.tapError((cause) =>
1075 Effect.logWarning("remote-delegation.cancel-record-failed", { taskId: task.id, cause }),
1076 ),
1077 Effect.mapError(
1078 () =>
1079 new OrchestratorMcpFailure({
1080 code: "orchestration_error",
1081 message: "Unable to record the cancellation.",
1082 }),
1083 ),
1084 );
1085 return {
1086 taskId: task.id,
1087 status: "cancel_requested",
1088 } satisfies OrchestratorMcpTaskCancelResult;
1089 },
1090 );
1091
1092 const runStatus = Effect.fn("RemoteDelegation.runStatus")(
1093 function* (scope: ThreadScope, task: OrchestrationV2Subagent) {
1094 const remote = task.remoteChild;
1095 if (remote?.runId === undefined) return null;
1096 const read = yield* forwarding.readThread(
1097 followScope(scope.thread, remote),
1098 remote.environmentId,
1099 { threadId: remote.threadId, limit: 1, runLimit: 50 },
1100 );
1101 return read.recentRuns.find((run) => run.runId === remote.runId)?.status ?? null;
1102 },
1103 Effect.orElseSucceed(() => null),
1104 );
1105
1106 const start: RemoteDelegation["Service"]["start"] = () =>
1107 forkParked(
1108 Effect.gen(function* () {
1109 // A finished task's follower has ended, so a Stop here that owes its
1110 // thread there a stop starts it again. Started before the scan below;
1111 // a Stop that slips between the two stays owed for the next start.
1112 yield* Stream.runForEach(threads.streamDomainEvents, (event) =>
1113 event.type === "subagent.updated" && event.payload.remoteChild?.stoppedThere === false
1114 ? followOne(event.threadId, event.payload.id).pipe(Effect.forkIn(followers))
1115 : Effect.void,
1116 ).pipe(
1117 Effect.ignoreCause({ log: true }),
1118 Effect.forkIn(followers, { startImmediately: true }),
1119 );
1120 const open = yield* projections.getOpenRemoteDelegatedTasks;
1121 yield* Effect.forEach(
1122 open,
1123 ({ parentThreadId, taskId }) => followOne(parentThreadId, taskId),
1124 {
1125 concurrency: "unbounded",
1126 discard: true,
1127 },
1128 );
1129 }).pipe(Effect.ignoreCause({ log: true })),
1130 );
1131
1132 return RemoteDelegation.of({ delegate, followUp, cancel, runStatus, start });
1133});
1134
1135/** A defect, logged, as a failure, so a retry covers it. */
1136const failOnDefect = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
1137 Effect.catchDefect(effect, (defect) =>
1138 Effect.logWarning("A remote task's follower hit a defect", Cause.die(defect)).pipe(
1139 Effect.andThen(Effect.fail(new Cause.UnknownError(defect, "A follower hit a defect."))),
1140 ),
1141 );
1142
1143const isTerminal = (status: string) =>
1144 status === "completed" ||
1145 status === "failed" ||
1146 status === "cancelled" ||
1147 status === "interrupted" ||
1148 status === "rolled_back";
1149
1150const terminalStatus = (status: string): "completed" | "failed" | "cancelled" | "interrupted" =>
1151 status === "completed" || status === "failed" || status === "interrupted" ? status : "cancelled";
1152
1153export const layer = Layer.effect(RemoteDelegation, make);