Open History to see the last commit
1import {
2 CommandId,
3 type EnvironmentId,
4 isMovedThreadId,
5 linkOriginIsFenced,
6 type OrchestratorMcpFailure,
7 ThreadHandoffError,
8 type OrchestrationV2AppThread,
9 type OrchestrationV2ThreadHandoff,
10 type OrchestratorMcpImportedMessage,
11 type ProjectId,
12 type RuntimeMode,
13 type ThreadHandoffOption,
14 type ThreadHandoffProjectChoice,
15 type ThreadId,
16 TurnItemId,
17} from "@t3tools/contracts";
18import * as Context from "effect/Context";
19import * as SecureRandom from "effect/crypto/SecureRandom";
20import * as DateTime from "effect/DateTime";
21import * as Effect from "effect/Effect";
22import * as Fiber from "effect/Fiber";
23import * as FileSystem from "effect/FileSystem";
24import * as Layer from "effect/Layer";
25import * as Option from "effect/Option";
26import * as Scope from "effect/Scope";
27import * as Stream from "effect/Stream";
28import * as HttpBody from "effect/http/HttpBody";
29import * as HttpClient from "effect/http/HttpClient";
30import * as HttpClientRequest from "effect/http/HttpClientRequest";
31
32import { runtimeModeRank } from "../../mcp/delegatedTaskModes.ts";
33import type * as McpInvocationContext from "../../mcp/McpInvocationContext.ts";
34import { AttachmentToolkit } from "../../mcp/toolkits/attachment/tools.ts";
35import { ProjectToolkit } from "../../mcp/toolkits/project/tools.ts";
36import * as ProjectionStore from "../../orchestration-v2/ProjectionStore.ts";
37import * as ThreadManagement from "../../orchestration-v2/ThreadManagementService.ts";
38import * as ServerEnvironment from "../../environment/ServerEnvironment.ts";
39import * as ProjectService from "../../project/ProjectService.ts";
40import * as RepositoryIdentityResolver from "../../project/RepositoryIdentityResolver.ts";
41import { forkParked } from "../../serverActivation.ts";
42import * as PeerForwarding from "../PeerForwarding.ts";
43import * as PeerLinks from "../PeerLinks.ts";
44import * as HandoffGit from "./HandoffGit.ts";
45
46/** What the thread there starts with, unless the move names its own. */
47const DEFAULT_CONTINUATION =
48 "This thread was just moved here from another machine, with its conversation and its uncommitted work. Continue where it left off.";
49
50type HandoffState = OrchestrationV2ThreadHandoff["state"];
51
52/**
53 * Moves a thread to a linked environment with its conversation and git work. One copy stays
54 * live: this one takes no turns while moving and only reads once moved; a failed move releases
55 * it. An agent can only ask, with a card in its thread: the user accepts it and picks the
56 * machine. Accepted mid-turn, it waits for the turn to end, and a message before then cancels.
57 */
58export class ThreadHandoff extends Context.Service<
59 ThreadHandoff,
60 {
61 /** Where the thread can go: linked environments with a project of its repository. */
62 readonly options: (
63 threadId: ThreadId,
64 ) => Effect.Effect<ReadonlyArray<ThreadHandoffOption>, ThreadHandoffError>;
65 /**
66 * Shows a card in the calling agent's thread asking its user to move it. Nothing moves
67 * until a client answers with `start`; `environmentId` is a suggestion the user may change.
68 */
69 readonly propose: (
70 scope: McpInvocationContext.McpInvocationScope,
71 input: {
72 readonly environmentId?: EnvironmentId | undefined;
73 readonly projectId?: ProjectId | undefined;
74 readonly continuationPrompt?: string | undefined;
75 },
76 ) => Effect.Effect<
77 { readonly environmentId?: EnvironmentId; readonly label?: string },
78 ThreadHandoffError
79 >;
80 /**
81 * Moves `threadId` to `environmentId`, for its user. With `turnItemId` it accepts that
82 * request, and while the asking turn still runs the thread moves once it ends. Returns the
83 * state the move is in.
84 */
85 readonly start: (input: {
86 readonly threadId: ThreadId;
87 readonly environmentId: EnvironmentId;
88 readonly projectId?: ProjectId | undefined;
89 readonly turnItemId?: TurnItemId | undefined;
90 }) => Effect.Effect<OrchestrationV2ThreadHandoff, ThreadHandoffError>;
91 /** Declines the request `turnItemId`, or cancels a move still waiting for its turn to end. */
92 readonly cancel: (input: {
93 readonly threadId: ThreadId;
94 readonly turnItemId?: TurnItemId | undefined;
95 }) => Effect.Effect<void, ThreadHandoffError>;
96 /**
97 * Makes a thread that was moved here an ordinary thread of this environment, for a user
98 * here: it arrived fenced when its link is below full access, since this environment
99 * cannot tell that a person accepted the move there.
100 */
101 readonly adopt: (threadId: ThreadId) => Effect.Effect<void, ThreadHandoffError>;
102 /** Runs moves whose turn ended, and settles any a restart cut short. */
103 readonly start_: () => Effect.Effect<void, never, Scope.Scope>;
104 /** Settles one thread's move now: what the follower does when its turn ends. */
105 readonly settle: (threadId: ThreadId) => Effect.Effect<void>;
106 }
107>()("t3/peer/handoff/ThreadHandoff") {}
108
109/** A failure the other environment reported, carried as the move's own. */
110const STILL_FENCED =
111 "This thread arrived over a limited link. Its user here makes it a normal thread before it can move on.";
112
113const SUBAGENTS_STILL_WORK =
114 "Background subagents are still working in this thread. Move it once they finish, or stop them.";
115
116const fromRemote = (cause: OrchestratorMcpFailure) =>
117 new ThreadHandoffError({ reason: "failed", message: cause.message, cause });
118
119const make = Effect.gen(function* () {
120 const handoffs = yield* Scope.Scope;
121 const threads = yield* ThreadManagement.ThreadManagementService;
122 const projections = yield* ProjectionStore.ProjectionStoreV2;
123 const projects = yield* ProjectService.ProjectService;
124 const repositoryIdentities = yield* RepositoryIdentityResolver.RepositoryIdentityResolver;
125 const forwarding = yield* PeerForwarding.PeerForwarding;
126 const links = yield* PeerLinks.PeerLinks;
127 const git = yield* HandoffGit.HandoffGit;
128 const httpClient = yield* HttpClient.HttpClient;
129 const fileSystem = yield* FileSystem.FileSystem;
130 const random = yield* SecureRandom.SecureRandom;
131 const hereId = yield* ServerEnvironment.ServerEnvironment.pipe(
132 Effect.flatMap((environment) => environment.getEnvironmentId),
133 );
134
135 /** The thread's agent, acting on its own behalf there through the link. */
136 const scopeFor = (thread: {
137 readonly id: ThreadId;
138 readonly providerInstanceId: string;
139 }): McpInvocationContext.McpThreadInvocationScope => ({
140 environmentId: hereId,
141 requestNamespace: `handoff:${thread.id}`,
142 thread: {
143 threadId: thread.id,
144 providerSessionId: `handoff:${thread.id}`,
145 providerInstanceId: thread.providerInstanceId as never,
146 },
147 client: undefined,
148 capabilities: new Set(["orchestration"]),
149 issuedAt: 0,
150 });
151
152 const setHandoff = (
153 threadId: ThreadId,
154 expected: HandoffState | null,
155 handoff: OrchestrationV2ThreadHandoff | null,
156 step: string,
157 /** The move a clear ends, so clearing a later one is its own command. */
158 clearing?: string,
159 acceptRequestId?: TurnItemId,
160 ) =>
161 threads
162 .dispatch({
163 type: "thread.handoff.update",
164 commandId: CommandId.make(
165 `command:handoff:${threadId}:${handoff?.handoffId ?? clearing ?? "clear"}:${step}`,
166 ),
167 threadId,
168 expected,
169 handoff,
170 ...(acceptRequestId === undefined ? {} : { acceptRequestId }),
171 })
172 .pipe(
173 Effect.asVoid,
174 Effect.mapError(
175 (error) => new ThreadHandoffError({ reason: "refused", message: error.message }),
176 ),
177 );
178
179 /**
180 * The thread's mode there: its own, lowered to the most its link allows. The other
181 * environment refuses a broader one outright, which would fail the whole move.
182 */
183 const modeWithinLink = (environmentId: EnvironmentId, mode: RuntimeMode) =>
184 links.get(environmentId).pipe(
185 Effect.map(Option.getOrUndefined),
186 Effect.orElseSucceed(() => undefined),
187 Effect.map((link) =>
188 link === undefined ||
189 link.access === "read-only" ||
190 runtimeModeRank(mode) <= runtimeModeRank(link.access)
191 ? mode
192 : link.access,
193 ),
194 );
195
196 const inspectRemoteProject = Effect.fn("ThreadHandoff.inspectRemoteProject")(function* (
197 scope: McpInvocationContext.McpThreadInvocationScope,
198 environmentId: EnvironmentId,
199 projectId: ProjectId,
200 ) {
201 const here = yield* projects.getById(projectId).pipe(
202 Effect.map(Option.getOrUndefined),
203 Effect.orElseSucceed(() => undefined),
204 );
205 // The project's own identity reads blank while its cache is cold.
206 const key =
207 here === undefined
208 ? undefined
209 : (yield* repositoryIdentities.resolve(here.workspaceRoot))?.canonicalKey;
210 if (key === undefined) {
211 return {
212 projectId: null,
213 projectSelectionRequired: true,
214 reason: "Choose the destination project for this thread.",
215 } as const;
216 }
217 const matchesById = new Map<ProjectId, ThreadHandoffProjectChoice>();
218 let cursor: number | null = 0;
219 while (cursor !== null) {
220 const page: {
221 readonly projects: ReadonlyArray<
222 ThreadHandoffProjectChoice & {
223 readonly repositoryIdentity?: { readonly canonicalKey: string } | null | undefined;
224 }
225 >;
226 readonly nextCursor: number | null;
227 } = yield* forwarding
228 .call(scope, ProjectToolkit.tools.t3_project_list, environmentId, { limit: 100, cursor })
229 .pipe(Effect.mapError(fromRemote));
230 for (const { id, title, workspaceRoot, repositoryIdentity } of page.projects) {
231 if (repositoryIdentity?.canonicalKey === key) {
232 matchesById.set(id, { id, title, workspaceRoot });
233 }
234 }
235 cursor = page.nextCursor;
236 }
237 const matches = [...matchesById.values()];
238 if (matches.length === 1) return { projectId: matches[0]!.id, reason: null } as const;
239 return {
240 projectId: null,
241 projectSelectionRequired: true,
242 reason:
243 matches.length === 0
244 ? `No project there has this repository (${key}). Add it there first.`
245 : `Several projects there have this repository; pick one: ${matches.map((p) => p.title).join(", ")}.`,
246 ...(matches.length > 1 ? { projectChoices: matches } : {}),
247 } as const;
248 });
249
250 /** The project there with this thread's repository, or the one named. */
251 const remoteProject = Effect.fn("ThreadHandoff.remoteProject")(function* (
252 scope: McpInvocationContext.McpThreadInvocationScope,
253 environmentId: EnvironmentId,
254 projectId: ProjectId,
255 requested: ProjectId | undefined,
256 ) {
257 if (requested !== undefined) return requested;
258 const match = yield* inspectRemoteProject(scope, environmentId, projectId);
259 if (match.projectId !== null) return match.projectId;
260 return yield* new ThreadHandoffError({ reason: "project_required", message: match.reason });
261 });
262
263 /** The conversation as the thread there will see it. */
264 const conversation = (threadId: ThreadId) =>
265 threads
266 .getThreadRecords(threadId, ["messages"], {
267 messageRoles: ["user", "assistant"],
268 recentMessageLimit: 2_000,
269 })
270 .pipe(
271 Effect.map((records) => {
272 const messages: Array<OrchestratorMcpImportedMessage> = [];
273 let bytes = 0;
274 for (const message of records.messages.toReversed()) {
275 if (
276 message.streaming ||
277 message.notification !== undefined ||
278 message.delegatedCompletion !== undefined ||
279 message.text.trim() === ""
280 )
281 continue;
282 const imported = {
283 role: message.role === "user" ? ("user" as const) : ("assistant" as const),
284 text: message.text.slice(0, 200_000),
285 createdAt: DateTime.formatIso(message.createdAt),
286 };
287 bytes += Buffer.byteLength(JSON.stringify(imported)) + 1;
288 if (bytes > 4 * 1024 * 1024) break;
289 messages.push(imported);
290 }
291 return messages.reverse();
292 }),
293 Effect.mapError(
294 () =>
295 new ThreadHandoffError({
296 reason: "failed",
297 message: "The conversation could not be read.",
298 }),
299 ),
300 );
301
302 /** Uploads the bundle there through its signed upload route. */
303 const upload = Effect.fn("ThreadHandoff.upload")(function* (
304 scope: McpInvocationContext.McpThreadInvocationScope,
305 environmentId: EnvironmentId,
306 packed: HandoffGit.HandoffPackage,
307 ) {
308 const prepared = yield* forwarding
309 .call(scope, AttachmentToolkit.tools.t3_attachment_prepare_upload, environmentId, {
310 upload: {
311 type: "file",
312 name: `${packed.snapshot.slice(0, 12)}.bundle`,
313 mimeType: "application/x-git-bundle",
314 sizeBytes: packed.bundleBytes,
315 },
316 })
317 .pipe(Effect.mapError(fromRemote));
318 const resolved = yield* links
319 .resolve(environmentId)
320 .pipe(
321 Effect.mapError(
322 (error) => new ThreadHandoffError({ reason: "failed", message: error.message }),
323 ),
324 );
325 const bytes = yield* fileSystem.readFile(packed.bundlePath).pipe(
326 Effect.mapError(
327 () =>
328 new ThreadHandoffError({
329 reason: "failed",
330 message: "The bundle could not be read.",
331 }),
332 ),
333 );
334 const response = yield* httpClient
335 .execute(
336 HttpClientRequest.post(`${resolved.url}${prepared.relativeUrl}`).pipe(
337 HttpClientRequest.setBody(HttpBody.uint8Array(bytes, "application/x-git-bundle")),
338 ),
339 )
340 .pipe(
341 Effect.mapError(
342 () =>
343 new ThreadHandoffError({
344 reason: "failed",
345 message: "The linked environment stopped answering mid-upload.",
346 }),
347 ),
348 );
349 if (response.status !== 204) {
350 // The route answers a refusal with its reason as text.
351 const detail = (yield* response.text.pipe(Effect.orElseSucceed(() => ""))).trim();
352 return yield* new ThreadHandoffError({
353 reason: "failed",
354 message: `The linked environment refused the upload (HTTP ${response.status})${
355 detail === "" ? "." : `: ${detail.slice(0, 300)}`
356 }`,
357 });
358 }
359 return prepared.attachmentId;
360 });
361
362 /** The move itself, from `departing`: package, send, import, then mark departed. */
363 const recovering = new Map<ThreadId, string>();
364 const departOnce = Effect.fn("ThreadHandoff.depart")(function* (
365 thread: OrchestrationV2AppThread,
366 handoff: Extract<OrchestrationV2ThreadHandoff, { state: "departing" }>,
367 ) {
368 const threadId = thread.id;
369 const stopRecovering = () => {
370 if (recovering.get(threadId) === handoff.handoffId) recovering.delete(threadId);
371 };
372 let uncertain = handoff.confirmingImport === true;
373 if (uncertain) recovering.set(threadId, handoff.handoffId);
374 const scope = scopeFor(thread);
375 const result = yield* Effect.gen(function* () {
376 const projectId = yield* remoteProject(
377 scope,
378 handoff.environmentId,
379 thread.projectId,
380 handoff.projectId,
381 );
382 const project = yield* projects.getById(thread.projectId).pipe(
383 Effect.map(Option.getOrUndefined),
384 Effect.orElseSucceed(() => undefined),
385 );
386 const cwd = thread.worktreePath ?? project?.workspaceRoot;
387 const tempDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-handoff-" }).pipe(
388 Effect.mapError(
389 () =>
390 new ThreadHandoffError({
391 reason: "failed",
392 message: "No temp space for the move.",
393 }),
394 ),
395 );
396 const packed =
397 cwd === undefined
398 ? undefined
399 : yield* git.pack({ cwd, handoffId: handoff.handoffId, outDir: tempDir }).pipe(
400 Effect.catchTags({
401 // A thread outside git moves with its conversation only.
402 HandoffNotARepositoryError: () => Effect.undefined,
403 }),
404 Effect.mapError(
405 (error) => new ThreadHandoffError({ reason: "refused", message: error.message }),
406 ),
407 );
408 const attachmentId =
409 packed === undefined ? undefined : yield* upload(scope, handoff.environmentId, packed);
410 const importThere = forwarding.call(
411 scope,
412 ProjectToolkit.tools.t3_thread_import,
413 handoff.environmentId,
414 {
415 source: {
416 environmentId: hereId,
417 threadId,
418 handoffId: handoff.handoffId,
419 },
420 projectId,
421 title: thread.title,
422 modelSelection: thread.modelSelection,
423 runtimeMode: yield* modeWithinLink(handoff.environmentId, thread.runtimeMode),
424 interactionMode: thread.interactionMode,
425 messages: yield* conversation(threadId),
426 continuationPrompt:
427 handoff.continuationPrompt ??
428 (packed === undefined
429 ? "This thread was moved here with its conversation. Continue where it left off."
430 : DEFAULT_CONTINUATION),
431 ...(packed === undefined || attachmentId === undefined
432 ? {}
433 : {
434 bundle: {
435 attachmentId,
436 branch: packed.branch,
437 tip: packed.tip,
438 snapshot: packed.snapshot,
439 },
440 }),
441 },
442 );
443 // Persist the fence before sending an import whose reply may be lost.
444 if (handoff.confirmingImport !== true) {
445 yield* setHandoff(
446 threadId,
447 "departing",
448 { ...handoff, confirmingImport: true },
449 "confirming-import",
450 ).pipe(
451 Effect.tap(() => Effect.sync(() => recovering.set(threadId, handoff.handoffId))),
452 Effect.uninterruptible,
453 );
454 }
455 const reply = yield* Effect.result(importThere);
456 if (reply._tag === "Success") return reply.success;
457 if (reply.failure.code !== "orchestration_error") return yield* fromRemote(reply.failure);
458 uncertain = true;
459 return yield* importThere.pipe(Effect.mapError(() => fromRemote(reply.failure)));
460 }).pipe(Effect.scoped, Effect.result);
461 if (result._tag === "Failure") {
462 if (uncertain) return yield* result.failure;
463 yield* setHandoff(
464 threadId,
465 "departing",
466 {
467 state: "failed",
468 handoffId: handoff.handoffId,
469 environmentId: handoff.environmentId,
470 label: handoff.label,
471 lastError: result.failure.message,
472 },
473 "failed",
474 );
475 stopRecovering();
476 return yield* result.failure;
477 }
478 const departed: OrchestrationV2ThreadHandoff = {
479 state: "departed",
480 handoffId: handoff.handoffId,
481 environmentId: handoff.environmentId,
482 label: handoff.label,
483 threadId: result.success.threadId,
484 };
485 yield* setHandoff(threadId, "departing", departed, "departed");
486 stopRecovering();
487 return departed;
488 });
489
490 // A turn ending mid-move, or the startup sweep, would otherwise pack and send a second time.
491 const departing = new Set<string>();
492 const depart = Effect.fn("ThreadHandoff.departCurrent")(function* (threadId: ThreadId) {
493 const { thread } = yield* threads
494 .getThreadRecords(threadId, [])
495 .pipe(
496 Effect.mapError(
497 () =>
498 new ThreadHandoffError({ reason: "not_found", message: "The thread was not found." }),
499 ),
500 );
501 const handoff = thread.handoff;
502 if (handoff?.state !== "departing") {
503 recovering.delete(threadId);
504 return handoff;
505 }
506 const { handoffId } = handoff;
507 if (departing.has(handoffId)) return undefined;
508 departing.add(handoffId);
509 return yield* departOnce(thread, handoff).pipe(
510 Effect.ensuring(Effect.sync(() => departing.delete(handoffId))),
511 );
512 });
513
514 /** Background subagents outlive their turn and still change the checkout a move would pack. */
515 const subagentsStillWork = (threadId: ThreadId) =>
516 threads.getThreadShell(threadId).pipe(
517 Effect.map(
518 (shell) => shell?.pendingBackgroundTasks?.some((task) => task.kind === "subagent") ?? false,
519 ),
520 Effect.orElseSucceed(() => false),
521 );
522
523 const options: ThreadHandoff["Service"]["options"] = Effect.fn("ThreadHandoff.options")(
524 function* (threadId) {
525 const records = yield* threads
526 .getThreadRecords(threadId, [])
527 .pipe(
528 Effect.mapError(
529 () =>
530 new ThreadHandoffError({ reason: "not_found", message: "The thread was not found." }),
531 ),
532 );
533 const listed = yield* links.list.pipe(
534 Effect.mapError(
535 (cause) => new ThreadHandoffError({ reason: "failed", message: cause.message, cause }),
536 ),
537 );
538 return yield* Effect.forEach(
539 listed,
540 (link) =>
541 Effect.gen(function* () {
542 const destination = { environmentId: link.environmentId, label: link.label };
543 if (link.status !== "reachable" || link.access === "read-only") {
544 return {
545 ...destination,
546 projectId: null,
547 reason:
548 link.status === "expired"
549 ? "The link expired."
550 : link.status !== "reachable"
551 ? "Not answering right now."
552 : "This link is read-only, so nothing can be moved over it.",
553 };
554 }
555 return yield* inspectRemoteProject(
556 scopeFor(records.thread),
557 link.environmentId,
558 records.thread.projectId,
559 ).pipe(
560 Effect.map((match) => ({ ...destination, ...match })),
561 Effect.catch((error) =>
562 Effect.succeed({ ...destination, projectId: null, reason: error.message }),
563 ),
564 );
565 }),
566 { concurrency: 4 },
567 );
568 },
569 );
570
571 const notFound = () =>
572 new ThreadHandoffError({ reason: "not_found", message: "The thread was not found." });
573
574 const requestCards = (threadId: ThreadId) =>
575 threads
576 .getThreadRecords(threadId, ["turnItems"], {
577 turnItemTypes: ["handoff_request"],
578 messageRoles: [],
579 })
580 .pipe(
581 Effect.map((records) =>
582 records.turnItems.flatMap((item) =>
583 item.type === "handoff_request" && item.runId !== null && item.nodeId !== null
584 ? [{ ...item, runId: item.runId, nodeId: item.nodeId }]
585 : [],
586 ),
587 ),
588 Effect.mapError(notFound),
589 );
590 type RequestCard = Effect.Success<ReturnType<typeof requestCards>>[number];
591
592 const recordRequest = (
593 card: Pick<
594 RequestCard,
595 "id" | "threadId" | "runId" | "nodeId" | "environmentId" | "label" | "projectId"
596 > & { readonly continuationPrompt?: string | undefined },
597 handoffStatus: RequestCard["handoffStatus"],
598 ) =>
599 threads
600 .dispatch({
601 type: "handoff_request.record",
602 commandId: CommandId.make(`handoff-request:${card.id}:${handoffStatus}`),
603 threadId: card.threadId,
604 runId: card.runId,
605 nodeId: card.nodeId,
606 turnItemId: card.id,
607 ...(card.environmentId === undefined ? {} : { environmentId: card.environmentId }),
608 ...(card.label === undefined ? {} : { label: card.label }),
609 ...(card.projectId === undefined ? {} : { projectId: card.projectId }),
610 ...(card.continuationPrompt === undefined
611 ? {}
612 : { continuationPrompt: card.continuationPrompt }),
613 handoffStatus,
614 })
615 .pipe(
616 Effect.asVoid,
617 Effect.mapError(
618 (error) => new ThreadHandoffError({ reason: "refused", message: error.message }),
619 ),
620 );
621
622 /** Ends requests still open, which a newer request or a move by other means replaces. */
623 const closeOpenRequests = (threadId: ThreadId) =>
624 requestCards(threadId).pipe(
625 Effect.flatMap((cards) =>
626 Effect.forEach(
627 cards.filter((card) => card.handoffStatus === "pending"),
628 (card) => recordRequest(card, "cancelled"),
629 { discard: true },
630 ),
631 ),
632 );
633
634 const propose: ThreadHandoff["Service"]["propose"] = Effect.fn("ThreadHandoff.propose")(
635 function* (scope, input) {
636 if (scope.thread === undefined) {
637 return yield* new ThreadHandoffError({
638 reason: "refused",
639 message: "Only an agent running in a T3 thread can ask to move it.",
640 });
641 }
642 const threadId = scope.thread.threadId;
643 const records = yield* threads
644 .getThreadRecords(threadId, ["runs"], { messageRoles: [] })
645 .pipe(Effect.mapError(notFound));
646 const thread = records.thread;
647 if (thread.archivedAt !== null) {
648 return yield* new ThreadHandoffError({
649 reason: "refused",
650 message: "Unarchive the thread to move it.",
651 });
652 }
653 // Moving on over a broader link would shed the limit this thread arrived with.
654 if (thread.linkOrigin !== undefined && linkOriginIsFenced(thread.linkOrigin)) {
655 return yield* new ThreadHandoffError({ reason: "refused", message: STILL_FENCED });
656 }
657 const current = thread.handoff?.state ?? null;
658 if (current === "pending" || current === "departing" || current === "departed") {
659 return yield* new ThreadHandoffError({
660 reason: "refused",
661 message: `This thread's move is already ${current}.`,
662 });
663 }
664 // The card belongs to the turn that asks, as a link or secret request does.
665 const run = ThreadManagement.latestActiveRun(records);
666 if (
667 run === undefined ||
668 run.rootNodeId === null ||
669 run.providerInstanceId !== scope.thread.providerInstanceId
670 ) {
671 return yield* new ThreadHandoffError({
672 reason: "refused",
673 message: "Asking to move a thread requires an active run of that thread's own agent.",
674 });
675 }
676 const suggested =
677 input.environmentId === undefined
678 ? undefined
679 : yield* links.get(input.environmentId).pipe(
680 Effect.map(Option.getOrUndefined),
681 Effect.orElseSucceed(() => undefined),
682 );
683 const suggestion =
684 input.environmentId === undefined
685 ? {}
686 : {
687 environmentId: input.environmentId,
688 ...(suggested === undefined ? {} : { label: suggested.label }),
689 ...(input.projectId === undefined ? {} : { projectId: input.projectId }),
690 };
691 yield* closeOpenRequests(threadId);
692 yield* recordRequest(
693 {
694 id: TurnItemId.make(
695 `turn-item:handoff-request:${(yield* random.uuidV4()).replaceAll("-", "")}`,
696 ),
697 threadId,
698 runId: run.id,
699 nodeId: run.rootNodeId,
700 ...suggestion,
701 continuationPrompt: input.continuationPrompt,
702 },
703 "pending",
704 );
705 return suggestion;
706 },
707 );
708
709 const start: ThreadHandoff["Service"]["start"] = Effect.fn("ThreadHandoff.start")(
710 function* (input) {
711 const records = yield* threads
712 .getThreadRecords(input.threadId, ["runs"])
713 .pipe(Effect.mapError(notFound));
714 const thread = records.thread;
715 if (thread.archivedAt !== null) {
716 return yield* new ThreadHandoffError({
717 reason: "refused",
718 message: "Unarchive the thread to move it.",
719 });
720 }
721 // Moving on over a broader link would shed the limit this thread arrived with.
722 if (thread.linkOrigin !== undefined && linkOriginIsFenced(thread.linkOrigin)) {
723 return yield* new ThreadHandoffError({ reason: "refused", message: STILL_FENCED });
724 }
725 const current = thread.handoff?.state ?? null;
726 if (current === "pending" || current === "departing" || current === "departed") {
727 return yield* new ThreadHandoffError({
728 reason: "refused",
729 message: `This thread's move is already ${current}.`,
730 });
731 }
732 const request =
733 input.turnItemId === undefined
734 ? undefined
735 : (yield* requestCards(input.threadId)).find((card) => card.id === input.turnItemId);
736 if (input.turnItemId !== undefined && request?.handoffStatus !== "pending") {
737 return yield* new ThreadHandoffError({
738 reason: "refused",
739 message: "This request to move the thread was already answered.",
740 });
741 }
742 const link = (yield* links.list.pipe(Effect.orElseSucceed(() => []))).find(
743 (candidate) => candidate.environmentId === input.environmentId,
744 );
745 if (link === undefined) {
746 return yield* new ThreadHandoffError({
747 reason: "refused",
748 message: "That environment is not linked.",
749 });
750 }
751 // The project the agent named holds only for the machine it suggested.
752 const projectHint =
753 input.projectId ??
754 (request?.environmentId === input.environmentId ? request.projectId : undefined);
755 // Resolved once and kept, so a restart mid-move lands in the same project.
756 const projectId = yield* remoteProject(
757 scopeFor(thread),
758 input.environmentId,
759 thread.projectId,
760 projectHint,
761 );
762 const handoffId = (yield* random.uuidV4()).replaceAll("-", "");
763 const busy = records.runs.some(
764 (run) =>
765 run.status === "running" ||
766 run.status === "starting" ||
767 run.status === "waiting" ||
768 run.status === "queued" ||
769 run.status === "preparing",
770 );
771 const base = {
772 handoffId,
773 environmentId: input.environmentId,
774 label: link.label,
775 projectId,
776 ...(request?.continuationPrompt === undefined
777 ? {}
778 : { continuationPrompt: request.continuationPrompt }),
779 };
780 // Once the move starts, the server owns it even if the client stops waiting.
781 return yield* Effect.gen(function* () {
782 if (busy) {
783 // The agent that asked is still in its turn; anything else the user stops first.
784 if (request === undefined) {
785 return yield* new ThreadHandoffError({
786 reason: "refused",
787 message: "The thread is running a turn. Stop it, then move it.",
788 });
789 }
790 const pending: OrchestrationV2ThreadHandoff = {
791 state: "pending",
792 ...base,
793 acceptedAt: DateTime.formatIso(yield* DateTime.now),
794 };
795 yield* setHandoff(input.threadId, current, pending, "pending", undefined, request.id);
796 // The turn may have ended while the other machine was asked about its projects.
797 yield* settle(input.threadId);
798 const settled = yield* threads
799 .getThreadRecords(input.threadId, [])
800 .pipe(Effect.mapError(notFound));
801 if (settled.thread.handoff === undefined) {
802 return yield* new ThreadHandoffError({
803 reason: "refused",
804 message: "A message sent in the meantime keeps this thread here.",
805 });
806 }
807 return settled.thread.handoff;
808 }
809 if (yield* subagentsStillWork(input.threadId)) {
810 return yield* new ThreadHandoffError({
811 reason: "refused",
812 message: SUBAGENTS_STILL_WORK,
813 });
814 }
815 const moving: OrchestrationV2ThreadHandoff = { state: "departing", ...base };
816 yield* setHandoff(input.threadId, current, moving, "departing", undefined, request?.id);
817 if (request === undefined) {
818 yield* closeOpenRequests(input.threadId).pipe(Effect.ignoreCause({ log: true }));
819 }
820 return (yield* depart(input.threadId)) ?? moving;
821 }).pipe(Effect.forkIn(handoffs), Effect.flatMap(Fiber.join));
822 },
823 );
824
825 const cancel: ThreadHandoff["Service"]["cancel"] = Effect.fn("ThreadHandoff.cancel")(
826 function* (input) {
827 if (input.turnItemId !== undefined) {
828 const request = (yield* requestCards(input.threadId)).find(
829 (card) => card.id === input.turnItemId,
830 );
831 if (request?.handoffStatus !== "pending") {
832 return yield* new ThreadHandoffError({
833 reason: "refused",
834 message: "This request to move the thread was already answered.",
835 });
836 }
837 return yield* recordRequest(request, "declined");
838 }
839 const { thread } = yield* threads
840 .getThreadRecords(input.threadId, [])
841 .pipe(Effect.mapError(notFound));
842 const handoff = thread.handoff;
843 if (handoff?.state !== "pending") {
844 return yield* new ThreadHandoffError({
845 reason: "refused",
846 message: "This thread has no move to cancel.",
847 });
848 }
849 yield* setHandoff(input.threadId, handoff.state, null, "cancel", handoff.handoffId);
850 },
851 );
852
853 const adopt: ThreadHandoff["Service"]["adopt"] = Effect.fn("ThreadHandoff.adopt")(
854 function* (threadId) {
855 const { thread } = yield* threads
856 .getThreadRecords(threadId, [])
857 .pipe(Effect.mapError(notFound));
858 if (!isMovedThreadId(thread.id) || thread.linkOrigin === undefined) {
859 return yield* new ThreadHandoffError({
860 reason: "refused",
861 message: "This thread was not moved here from a linked environment.",
862 });
863 }
864 yield* threads
865 .dispatch({
866 type: "thread.link-origin.adopt",
867 commandId: CommandId.make(`command:handoff:${threadId}:adopt`),
868 threadId,
869 })
870 .pipe(
871 Effect.asVoid,
872 Effect.mapError(
873 (error) => new ThreadHandoffError({ reason: "refused", message: error.message }),
874 ),
875 );
876 },
877 );
878
879 /** A pending move whose turn ended departs; one a restart cut short is settled. */
880 const settle = Effect.fn("ThreadHandoff.settle")(
881 function* (threadId: ThreadId) {
882 const records = yield* threads.getThreadRecords(threadId, ["runs", "messages"], {
883 messageRoles: ["user"],
884 });
885 const handoff = records.thread.handoff;
886 if (handoff === undefined) return;
887 if (handoff.state === "pending") {
888 const live = records.runs.some(
889 (run) =>
890 run.status === "running" ||
891 run.status === "starting" ||
892 run.status === "waiting" ||
893 run.status === "preparing",
894 );
895 if (live) return;
896 // Someone wrote after the user accepted, steered into the turn or queued
897 // after it: new instructions win. That is the user, or an agent the
898 // user works through, such as an orchestrator.
899 const asked =
900 (handoff.acceptedAt === undefined
901 ? undefined
902 : Option.getOrUndefined(DateTime.make(handoff.acceptedAt))) ??
903 records.runs.at(-1)?.requestedAt;
904 const writtenSince = records.messages.some(
905 (message) => asked !== undefined && DateTime.isGreaterThan(message.createdAt, asked),
906 );
907 if (writtenSince || records.runs.some((run) => run.status === "queued")) {
908 yield* setHandoff(threadId, "pending", null, "cancel-by-user", handoff.handoffId);
909 return;
910 }
911 if (yield* subagentsStillWork(threadId)) {
912 const { acceptedAt: _a, projectId: _p, continuationPrompt: _c, ...failed } = handoff;
913 yield* setHandoff(
914 threadId,
915 "pending",
916 { ...failed, state: "failed", lastError: SUBAGENTS_STILL_WORK },
917 "failed",
918 );
919 return;
920 }
921 const { acceptedAt: _accepted, ...moving } = handoff;
922 yield* setHandoff(threadId, "pending", { ...moving, state: "departing" }, "departing");
923 }
924 const now = yield* threads.getThreadRecords(threadId, []);
925 if (now.thread.handoff?.state === "departing") {
926 yield* depart(threadId).pipe(Effect.ignoreCause({ log: true }));
927 }
928 },
929 Effect.ignoreCause({ log: true }),
930 );
931
932 const start_: ThreadHandoff["Service"]["start_"] = () =>
933 forkParked(
934 Effect.gen(function* () {
935 // Moves a restart cut short, or that were waiting for a turn that ended meanwhile.
936 const shells = yield* projections.getShellSnapshot().pipe(
937 Effect.map((snapshot) => snapshot.threads),
938 Effect.orElseSucceed(() => []),
939 );
940 yield* Effect.forEach(
941 shells.filter(
942 (shell) => shell.handoff?.state === "pending" || shell.handoff?.state === "departing",
943 ),
944 (shell) => settle(shell.id),
945 { discard: true },
946 );
947 yield* threads.streamDomainEvents.pipe(
948 Stream.filter(
949 (event) =>
950 event.type === "run.updated" &&
951 ["completed", "failed", "cancelled", "interrupted", "rolled_back"].includes(
952 event.payload.status,
953 ),
954 ),
955 Stream.map((event) => event.threadId),
956 Stream.merge(
957 Stream.tick("30 seconds").pipe(
958 Stream.flatMap(() => Stream.fromIterable([...recovering.keys()])),
959 ),
960 ),
961 Stream.runForEach(settle),
962 );
963 }).pipe(Effect.ignoreCause({ log: true })),
964 );
965
966 return ThreadHandoff.of({ options, propose, start, cancel, adopt, start_, settle });
967});
968
969export const layer = Layer.effect(ThreadHandoff, make);