Open History to see the last commit
1import {
2 type OrchestrationV2AppThread,
3 OrchestrationV2ContextHandoff,
4 type OrchestrationV2TurnItem,
5 type OrchestrationV2Run,
6 type OrchestrationV2ThreadProjection,
7 ProviderInstanceId,
8 ProviderThreadId,
9 RunId,
10 ThreadId,
11} from "@t3tools/contracts";
12import * as Context from "effect/Context";
13import * as DateTime from "effect/DateTime";
14import * as Effect from "effect/Effect";
15import * as Layer from "effect/Layer";
16import * as Schema from "effect/Schema";
17
18import {
19 DEFAULT_HANDOFF_TOKEN_CAP,
20 handoffTokenCapConfig,
21 handoffCoverage,
22 historicalMessage,
23 renderHistory,
24 selectHistory,
25} from "@t3tools/provider-core/server/handoffBudget";
26import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
27import { createOrchestrationV2TurnItemVisibility } from "@t3tools/shared/orchestrationV2Timeline";
28import type { ProjectionStoreV2Shape } from "./ProjectionStore.ts";
29
30export class ContextHandoffPrepareError extends Schema.TaggedError<ContextHandoffPrepareError>()(
31 "ContextHandoffPrepareError",
32 {
33 threadId: ThreadId,
34 targetRunId: RunId,
35 fromProviderThreadIds: Schema.Array(ProviderThreadId),
36 toProviderThreadId: ProviderThreadId,
37 cause: Schema.optional(Schema.Defect()),
38 },
39) {
40 override get message(): string {
41 return `Failed to prepare context handoff for run ${this.targetRunId} in thread ${this.threadId}.`;
42 }
43}
44
45export const ContextHandoffServiceV2Error = Schema.Union([ContextHandoffPrepareError]);
46export type ContextHandoffServiceV2Error = typeof ContextHandoffServiceV2Error.Type;
47
48export interface ContextHandoffServiceV2Shape {
49 readonly prepareLegacyImport: (input: {
50 readonly threadId: ThreadId;
51 readonly targetRunId: RunId;
52 readonly toProviderThreadId: ProviderThreadId;
53 readonly toProviderInstanceId: ProviderInstanceId;
54 readonly items: ReadonlyArray<OrchestrationV2TurnItem>;
55 readonly createdAt: DateTime.Utc;
56 }) => Effect.Effect<OrchestrationV2ContextHandoff, ContextHandoffServiceV2Error>;
57 readonly prepareForkDelta: (input: {
58 readonly sourceThreadId: ThreadId;
59 readonly targetThreadId: ThreadId;
60 readonly targetRunId: RunId;
61 readonly transferId: OrchestrationV2ContextHandoff["transferId"];
62 readonly fromProviderThreadIds: ReadonlyArray<ProviderThreadId>;
63 readonly toProviderThreadId: ProviderThreadId;
64 readonly fromProviderInstanceId: ProviderInstanceId;
65 readonly toProviderInstanceId: ProviderInstanceId;
66 readonly coveredRunOrdinals: OrchestrationV2ContextHandoff["coveredRunOrdinals"];
67 readonly deltaItems: ReadonlyArray<OrchestrationV2TurnItem>;
68 readonly createdAt: DateTime.Utc;
69 }) => Effect.Effect<OrchestrationV2ContextHandoff, ContextHandoffServiceV2Error>;
70 readonly prepareProviderHandoff: (input: {
71 readonly threadId: ThreadId;
72 readonly targetRunId: RunId;
73 readonly transferId: OrchestrationV2ContextHandoff["transferId"];
74 readonly fromProviderThreadIds: ReadonlyArray<ProviderThreadId>;
75 readonly toProviderThreadId: ProviderThreadId;
76 readonly fromProviderInstanceId: ProviderInstanceId;
77 readonly toProviderInstanceId: ProviderInstanceId;
78 readonly coveredRunOrdinals: OrchestrationV2ContextHandoff["coveredRunOrdinals"];
79 readonly runs?: ReadonlyArray<OrchestrationV2Run>;
80 readonly strategy: Extract<
81 OrchestrationV2ContextHandoff["strategy"],
82 "delta_since_target_last_seen" | "full_thread_summary"
83 >;
84 readonly items: ReadonlyArray<OrchestrationV2TurnItem>;
85 readonly createdAt: DateTime.Utc;
86 }) => Effect.Effect<OrchestrationV2ContextHandoff, ContextHandoffServiceV2Error>;
87 /** Parent activity after the fork point, prepended to a side chat's first provider turn. */
88 readonly prepareSideChatContext: (input: {
89 readonly threadId: ThreadId;
90 readonly parentThreadId: ThreadId;
91 readonly targetRunId: RunId;
92 readonly transferId: NonNullable<OrchestrationV2ContextHandoff["transferId"]>;
93 readonly toProviderThreadId: ProviderThreadId;
94 readonly fromProviderInstanceId: ProviderInstanceId;
95 readonly toProviderInstanceId: ProviderInstanceId;
96 readonly coveredRunOrdinals: OrchestrationV2ContextHandoff["coveredRunOrdinals"];
97 readonly parentItems: ReadonlyArray<OrchestrationV2TurnItem>;
98 readonly createdAt: DateTime.Utc;
99 }) => Effect.Effect<OrchestrationV2ContextHandoff, ContextHandoffServiceV2Error>;
100}
101
102export class ContextHandoffServiceV2 extends Context.Service<
103 ContextHandoffServiceV2,
104 ContextHandoffServiceV2Shape
105>()("t3/orchestration-v2/ContextHandoffService/ContextHandoffServiceV2") {}
106
107function compactText(text: string, maxLength = 240): string {
108 const compacted = text.replace(/\s+/g, " ").trim();
109 if (compacted.length <= maxLength) {
110 return compacted;
111 }
112 const end = maxLength - 3;
113 const last = compacted.charCodeAt(end - 1);
114 return `${compacted.slice(0, last >= 0xd800 && last <= 0xdbff ? end - 1 : end)}...`;
115}
116
117export function visibleDeltaRunOrdinals(
118 projection: { readonly runs: ReadonlyArray<Pick<OrchestrationV2Run, "id" | "ordinal">> },
119 items: ReadonlyArray<Pick<OrchestrationV2TurnItem, "runId">>,
120): OrchestrationV2ContextHandoff["coveredRunOrdinals"] {
121 const ordinalByRunId = new Map(projection.runs.map((run) => [run.id, run.ordinal]));
122 let from = Infinity;
123 let to = -Infinity;
124 for (const item of items) {
125 const ordinal = item.runId === null ? undefined : ordinalByRunId.get(item.runId);
126 if (ordinal === undefined) continue;
127 from = Math.min(from, ordinal);
128 to = Math.max(to, ordinal);
129 }
130 return from === Infinity ? { from: 1, to: 1 } : { from, to };
131}
132
133/** Drops rolled-back runs and cancelled queued messages, which are not part of the conversation. */
134export function visibleConversationItems(
135 projection: Pick<OrchestrationV2ThreadProjection, "runs" | "attempts">,
136 items: ReadonlyArray<OrchestrationV2TurnItem>,
137): ReadonlyArray<OrchestrationV2TurnItem> {
138 const visible = createOrchestrationV2TurnItemVisibility({
139 runs: projection.runs,
140 attempts: projection.attempts,
141 items,
142 });
143 return items.filter(visible);
144}
145
146type ForkHistorySource = Pick<OrchestrationV2ThreadProjection, "thread" | "runs" | "attempts">;
147
148/** Visible rows of `source`'s own runs through `throughRun`, plus its v1 imported rows. */
149const readOwnHistoryItems = Effect.fn("orchestrationV2.contextHandoff.readOwnHistoryItems")(
150 function* (
151 projectionStore: Pick<ProjectionStoreV2Shape, "getThreadRecords">,
152 source: ForkHistorySource,
153 throughRun: Pick<OrchestrationV2Run, "ordinal">,
154 ) {
155 const { turnItems } = yield* projectionStore.getThreadRecords(source.thread.id, ["turnItems"], {
156 turnItemRunIds: [
157 ...source.runs.filter((run) => run.ordinal <= throughRun.ordinal).map((run) => run.id),
158 ...(source.thread.historyOrigin === "v1_import" ? [null] : []),
159 ],
160 });
161 return visibleConversationItems(source, turnItems);
162 },
163);
164
165/** History `thread` shows from its fork ancestors, oldest first. Side chats inherit no rows. */
166export const readInheritedHandoffItems = Effect.fn(
167 "orchestrationV2.contextHandoff.readInheritedHandoffItems",
168)(function* (
169 projectionStore: Pick<ProjectionStoreV2Shape, "getThreadRecords">,
170 thread: OrchestrationV2AppThread,
171) {
172 const segments: Array<ReadonlyArray<OrchestrationV2TurnItem>> = [];
173 const seen = new Set([thread.id]);
174 let current = thread;
175 while (
176 current.forkedFrom?.type === "run" &&
177 current.lineage.sideChat !== true &&
178 !seen.has(current.forkedFrom.threadId)
179 ) {
180 const { threadId, runId } = current.forkedFrom;
181 seen.add(threadId);
182 const source = yield* projectionStore
183 .getThreadRecords(threadId, ["runs", "attempts"])
184 .pipe(Effect.catchTags({ ProjectionStoreThreadNotFoundError: () => Effect.succeed(null) }));
185 const forkRun = source?.runs.find((run) => run.id === runId);
186 if (source === null || forkRun === undefined) break;
187 segments.unshift(yield* readOwnHistoryItems(projectionStore, source, forkRun));
188 current = source.thread;
189 }
190 return segments.flat();
191});
192
193/** What a portable fork from `throughRun` of `source` carries: inherited rows, then its own. */
194export const readForkHistoryItems = Effect.fn(
195 "orchestrationV2.contextHandoff.readForkHistoryItems",
196)(function* (
197 projectionStore: Pick<ProjectionStoreV2Shape, "getThreadRecords">,
198 source: ForkHistorySource,
199 throughRun: Pick<OrchestrationV2Run, "ordinal">,
200) {
201 return [
202 ...(yield* readInheritedHandoffItems(projectionStore, source.thread)),
203 ...(yield* readOwnHistoryItems(projectionStore, source, throughRun)),
204 ];
205});
206
207function summarizeDeltaItem(item: OrchestrationV2TurnItem): string | null {
208 switch (item.type) {
209 case "user_message":
210 return `- User: ${compactText(item.text)}`;
211 case "assistant_message":
212 return `- Assistant: ${compactText(item.text)}`;
213 case "command_execution":
214 return `- Command: ${compactText(item.input)}`;
215 case "file_change":
216 return `- File change: ${compactText(item.changes?.map((change) => change.path).join(", ") ?? item.fileName)}`;
217 case "checkpoint":
218 return `- Checkpoint: ${item.files.length} files`;
219 case "handoff":
220 return `- Handoff: ${compactText(item.summary ?? item.strategy)}`;
221 default:
222 return null;
223 }
224}
225
226function makeForkDeltaSummary(input: {
227 readonly sourceThreadId: ThreadId;
228 readonly targetThreadId: ThreadId;
229 readonly coveredRunOrdinals: OrchestrationV2ContextHandoff["coveredRunOrdinals"];
230 readonly deltaItems: ReadonlyArray<OrchestrationV2TurnItem>;
231}): string {
232 const itemLines = input.deltaItems.flatMap((item) => {
233 const line = summarizeDeltaItem(item);
234 return line === null ? [] : [line];
235 });
236 return [
237 "Merge-back context from forked conversation.",
238 `Source thread: ${input.sourceThreadId}`,
239 `Target thread: ${input.targetThreadId}`,
240 `Covered fork runs: ${input.coveredRunOrdinals.from}-${input.coveredRunOrdinals.to}`,
241 "",
242 "Fork delta:",
243 ...(itemLines.length === 0 ? ["- No user-visible delta items."] : itemLines),
244 ].join("\n");
245}
246
247const SIDE_CHAT_CONTEXT_MAX_CHARS = 8_000;
248
249/** Oldest first; raw parent items are summarized only until the context cap is reached. */
250export function makeSideChatContext(input: {
251 readonly parentThreadId: ThreadId;
252 readonly digest: ReadonlyArray<string | OrchestrationV2TurnItem>;
253}): string {
254 const framing =
255 "You are in a side chat beside the main thread. The main thread may still be running in the same worktree. Answer the user's questions; do not continue or redo the main thread's task.";
256 const header = "Main thread activity since this side chat's starting point:";
257 const truncated = "- Earlier items truncated.";
258 const footer = `Use t3_thread_read on thread ${input.parentThreadId} to see the main thread's live state.`;
259 const kept: Array<string> = [];
260 let omitted = false;
261 // The cap covers the whole block, so the fixed lines are reserved before any digest line.
262 let remaining =
263 SIDE_CHAT_CONTEXT_MAX_CHARS - [framing, "", header, truncated, "", footer].join("\n").length;
264 for (let index = input.digest.length - 1; index >= 0; index--) {
265 const item = input.digest[index]!;
266 const line = typeof item === "string" ? item : summarizeDeltaItem(item);
267 if (line === null) continue;
268 if (line.length + 1 > remaining) {
269 omitted = true;
270 break;
271 }
272 kept.unshift(line);
273 remaining -= line.length + 1;
274 }
275 return [
276 framing,
277 ...(kept.length === 0 ? [] : ["", header, ...(omitted ? [truncated] : []), ...kept]),
278 "",
279 footer,
280 ].join("\n");
281}
282
283/** Side chat context is prepended to the provider prompt, never replayed as budgeted history. */
284export const isSideChatContextHandoff = (handoff: OrchestrationV2ContextHandoff): boolean =>
285 handoff.strategy === "manual_context" && handoff.transferId != null;
286
287function makeLegacyImportSummary(items: ReadonlyArray<OrchestrationV2TurnItem>): string {
288 const sections = items.flatMap((item) => {
289 switch (item.type) {
290 case "user_message":
291 return [{ label: "User", body: item.text }];
292 case "assistant_message":
293 return [{ label: "Assistant", body: item.text }];
294 default:
295 return [];
296 }
297 });
298 const header =
299 "Imported conversation history from the previous T3 Code orchestrator. Use it as context; do not repeat it unless the user asks.";
300 const maxChars = 32_000;
301 const selected: Array<string> = [];
302 let remaining = maxChars - header.length - 2;
303 for (const section of sections.toReversed()) {
304 if (remaining <= 0) break;
305 const fullSection = `${section.label}:\n${section.body}`;
306 if (fullSection.length <= remaining) {
307 selected.unshift(fullSection);
308 remaining -= fullSection.length + 2;
309 continue;
310 }
311
312 const prefix = `${section.label}:\n... `;
313 const bodyBudget = remaining - prefix.length;
314 if (bodyBudget <= 0) continue;
315
316 const initialStart = section.body.length - bodyBudget;
317 let bodyStart = Math.max(0, initialStart);
318 if (
319 bodyStart > 0 &&
320 !/\s/.test(section.body[bodyStart - 1] ?? "") &&
321 !/\s/.test(section.body[bodyStart] ?? "")
322 ) {
323 const nextWhitespace = section.body.slice(bodyStart).search(/\s/);
324 if (nextWhitespace !== -1) {
325 bodyStart += nextWhitespace;
326 }
327 }
328 const codeUnitAtStart = section.body.charCodeAt(bodyStart);
329 const codeUnitBeforeStart = section.body.charCodeAt(bodyStart - 1);
330 if (
331 codeUnitAtStart >= 0xdc00 &&
332 codeUnitAtStart <= 0xdfff &&
333 codeUnitBeforeStart >= 0xd800 &&
334 codeUnitBeforeStart <= 0xdbff
335 ) {
336 bodyStart += 1;
337 }
338 const bodySuffix = section.body.slice(bodyStart).trimStart();
339 if (bodySuffix.length === 0) continue;
340
341 const suffix = `${prefix}${bodySuffix}`;
342 selected.unshift(suffix);
343 remaining -= suffix.length + 2;
344 }
345 return [header, ...selected].join("\n\n");
346}
347
348const makeContextHandoffService = Effect.fn("orchestrationV2.ContextHandoffService.layer")(
349 function* () {
350 const idAllocator = yield* IdAllocator.IdAllocatorV2;
351 const tokenCap = yield* handoffTokenCapConfig.pipe(
352 Effect.orElseSucceed(() => DEFAULT_HANDOFF_TOKEN_CAP),
353 );
354
355 const prepareLegacyImport = Effect.fn("orchestrationV2.contextHandoff.prepareLegacyImport")(
356 function* (input: {
357 readonly threadId: ThreadId;
358 readonly targetRunId: RunId;
359 readonly toProviderThreadId: ProviderThreadId;
360 readonly toProviderInstanceId: ProviderInstanceId;
361 readonly items: ReadonlyArray<OrchestrationV2TurnItem>;
362 readonly createdAt: DateTime.Utc;
363 }) {
364 const handoffId = yield* idAllocator.allocate
365 .contextHandoff({
366 threadId: input.threadId,
367 fromProviderInstanceId: ProviderInstanceId.make("legacy"),
368 toProviderInstanceId: input.toProviderInstanceId,
369 })
370 .pipe(
371 Effect.mapError(
372 (cause) =>
373 new ContextHandoffPrepareError({
374 threadId: input.threadId,
375 targetRunId: input.targetRunId,
376 fromProviderThreadIds: [],
377 toProviderThreadId: input.toProviderThreadId,
378 cause,
379 }),
380 ),
381 );
382 const coverage = handoffCoverage({ ...input, coveredRunOrdinals: { from: 1, to: 1 } });
383 const selected = selectHistory({
384 messages: input.items.flatMap((item) => {
385 const message = historicalMessage(item);
386 return message === null ? [] : [message];
387 }),
388 coverage,
389 budget: tokenCap,
390 });
391 return {
392 id: handoffId,
393 transferId: null,
394 threadId: input.threadId,
395 targetRunId: input.targetRunId,
396 fromProviderThreadIds: [],
397 toProviderThreadId: input.toProviderThreadId,
398 coveredRunOrdinals: { from: 1, to: 1 },
399 strategy: "manual_context",
400 status: "ready",
401 summaryMessageId: null,
402 summaryText: makeLegacyImportSummary(input.items),
403 history: {
404 messages: selected.messages,
405 coverage,
406 omittedItems: selected.omittedItems,
407 omittedItemIds: selected.omittedItemIds,
408 },
409 createdByProviderInstanceId: null,
410 createdAt: input.createdAt,
411 updatedAt: input.createdAt,
412 } satisfies OrchestrationV2ContextHandoff;
413 },
414 );
415
416 const prepareForkDelta = Effect.fn("orchestrationV2.contextHandoff.prepareForkDelta")(
417 function* (input: {
418 readonly sourceThreadId: ThreadId;
419 readonly targetThreadId: ThreadId;
420 readonly targetRunId: RunId;
421 readonly transferId: OrchestrationV2ContextHandoff["transferId"];
422 readonly fromProviderThreadIds: ReadonlyArray<ProviderThreadId>;
423 readonly toProviderThreadId: ProviderThreadId;
424 readonly fromProviderInstanceId: ProviderInstanceId;
425 readonly toProviderInstanceId: ProviderInstanceId;
426 readonly coveredRunOrdinals: OrchestrationV2ContextHandoff["coveredRunOrdinals"];
427 readonly deltaItems: ReadonlyArray<OrchestrationV2TurnItem>;
428 readonly createdAt: DateTime.Utc;
429 }) {
430 const handoffId = yield* idAllocator.allocate
431 .contextHandoff({
432 threadId: input.targetThreadId,
433 fromProviderInstanceId: input.fromProviderInstanceId,
434 toProviderInstanceId: input.toProviderInstanceId,
435 })
436 .pipe(
437 Effect.mapError(
438 (cause) =>
439 new ContextHandoffPrepareError({
440 threadId: input.targetThreadId,
441 targetRunId: input.targetRunId,
442 fromProviderThreadIds: Array.from(input.fromProviderThreadIds),
443 toProviderThreadId: input.toProviderThreadId,
444 cause,
445 }),
446 ),
447 );
448 const coverage = handoffCoverage({
449 threadId: input.sourceThreadId,
450 coveredRunOrdinals: input.coveredRunOrdinals,
451 items: input.deltaItems,
452 });
453 const selected = selectHistory({
454 messages: input.deltaItems.flatMap((item) => {
455 const message = historicalMessage(item);
456 return message === null ? [] : [message];
457 }),
458 coverage,
459 budget: tokenCap,
460 });
461 return {
462 id: handoffId,
463 transferId: input.transferId,
464 threadId: input.targetThreadId,
465 targetRunId: input.targetRunId,
466 fromProviderThreadIds: Array.from(input.fromProviderThreadIds),
467 toProviderThreadId: input.toProviderThreadId,
468 coveredRunOrdinals: input.coveredRunOrdinals,
469 strategy: "fork_delta_summary",
470 status: "ready",
471 summaryMessageId: null,
472 summaryText: makeForkDeltaSummary(input),
473 history: {
474 messages: selected.messages,
475 coverage,
476 omittedItems: selected.omittedItems,
477 omittedItemIds: selected.omittedItemIds,
478 },
479 createdByProviderInstanceId: null,
480 createdAt: input.createdAt,
481 updatedAt: input.createdAt,
482 } satisfies OrchestrationV2ContextHandoff;
483 },
484 );
485
486 const prepareProviderHandoff = Effect.fn(
487 "orchestrationV2.contextHandoff.prepareProviderHandoff",
488 )(function* (input: {
489 readonly threadId: ThreadId;
490 readonly targetRunId: RunId;
491 readonly transferId: OrchestrationV2ContextHandoff["transferId"];
492 readonly fromProviderThreadIds: ReadonlyArray<ProviderThreadId>;
493 readonly toProviderThreadId: ProviderThreadId;
494 readonly fromProviderInstanceId: ProviderInstanceId;
495 readonly toProviderInstanceId: ProviderInstanceId;
496 readonly coveredRunOrdinals: OrchestrationV2ContextHandoff["coveredRunOrdinals"];
497 readonly runs?: ReadonlyArray<OrchestrationV2Run>;
498 readonly strategy: Extract<
499 OrchestrationV2ContextHandoff["strategy"],
500 "delta_since_target_last_seen" | "full_thread_summary"
501 >;
502 readonly items: ReadonlyArray<OrchestrationV2TurnItem>;
503 readonly createdAt: DateTime.Utc;
504 }) {
505 const handoffId = yield* idAllocator.allocate
506 .contextHandoff({
507 threadId: input.threadId,
508 fromProviderInstanceId: input.fromProviderInstanceId,
509 toProviderInstanceId: input.toProviderInstanceId,
510 })
511 .pipe(
512 Effect.mapError(
513 (cause) =>
514 new ContextHandoffPrepareError({
515 threadId: input.threadId,
516 targetRunId: input.targetRunId,
517 fromProviderThreadIds: Array.from(input.fromProviderThreadIds),
518 toProviderThreadId: input.toProviderThreadId,
519 cause,
520 }),
521 ),
522 );
523 const runStatuses = new Map(input.runs?.map((run) => [run.id, run.status]));
524 const coverage = handoffCoverage(input);
525 const selected = selectHistory({
526 messages: input.items.flatMap((item) => {
527 const message = historicalMessage(item);
528 return message === null
529 ? []
530 : [
531 {
532 ...message,
533 ...(item.runId === null ? {} : { runStatus: runStatuses.get(item.runId) }),
534 },
535 ];
536 }),
537 coverage,
538 budget: tokenCap,
539 });
540 return {
541 id: handoffId,
542 transferId: input.transferId,
543 threadId: input.threadId,
544 targetRunId: input.targetRunId,
545 fromProviderThreadIds: Array.from(input.fromProviderThreadIds),
546 toProviderThreadId: input.toProviderThreadId,
547 coveredRunOrdinals: input.coveredRunOrdinals,
548 strategy: input.strategy,
549 status: "ready",
550 summaryMessageId: null,
551 summaryText: renderHistory(selected.messages, selected.context),
552 history: {
553 messages: selected.messages,
554 coverage,
555 omittedItems: selected.omittedItems,
556 omittedItemIds: selected.omittedItemIds,
557 },
558 createdByProviderInstanceId: null,
559 createdAt: input.createdAt,
560 updatedAt: input.createdAt,
561 } satisfies OrchestrationV2ContextHandoff;
562 });
563
564 const prepareSideChatContext = Effect.fn(
565 "orchestrationV2.contextHandoff.prepareSideChatContext",
566 )(function* (input: Parameters<ContextHandoffServiceV2Shape["prepareSideChatContext"]>[0]) {
567 const handoffId = yield* idAllocator.allocate
568 .contextHandoff({
569 threadId: input.threadId,
570 fromProviderInstanceId: input.fromProviderInstanceId,
571 toProviderInstanceId: input.toProviderInstanceId,
572 })
573 .pipe(
574 Effect.mapError(
575 (cause) =>
576 new ContextHandoffPrepareError({
577 threadId: input.threadId,
578 targetRunId: input.targetRunId,
579 fromProviderThreadIds: [],
580 toProviderThreadId: input.toProviderThreadId,
581 cause,
582 }),
583 ),
584 );
585 return {
586 id: handoffId,
587 transferId: input.transferId,
588 threadId: input.threadId,
589 targetRunId: input.targetRunId,
590 fromProviderThreadIds: [],
591 toProviderThreadId: input.toProviderThreadId,
592 coveredRunOrdinals: input.coveredRunOrdinals,
593 strategy: "manual_context",
594 status: "ready",
595 summaryMessageId: null,
596 summaryText: makeSideChatContext({
597 parentThreadId: input.parentThreadId,
598 digest: input.parentItems,
599 }),
600 createdByProviderInstanceId: null,
601 createdAt: input.createdAt,
602 updatedAt: input.createdAt,
603 } satisfies OrchestrationV2ContextHandoff;
604 });
605
606 return ContextHandoffServiceV2.of({
607 prepareLegacyImport,
608 prepareForkDelta,
609 prepareProviderHandoff,
610 prepareSideChatContext,
611 });
612 },
613);
614
615export const layer: Layer.Layer<ContextHandoffServiceV2, never, IdAllocator.IdAllocatorV2> =
616 Layer.effect(ContextHandoffServiceV2, makeContextHandoffService());