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

ContextHandoffService.ts

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