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

ContextHandoffService.ts

629 lines24.3 KB

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