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

RemoteDelegation.ts

1,028 lines42.3 KB

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