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