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

ContextHandoffService.ts

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