Open History to see the last commit
1import type {
2 ModelSelection,
3 OrchestrationV2Run,
4 OrchestrationV2ThreadProjection,
5 OrchestrationV2TurnItem,
6 ProviderInstanceId,
7 ServerProvider,
8} from "@t3tools/contracts";
9
10/**
11 * The subset of a projection run that handoff rows read. Kept minimal so the
12 * timeline can hold a content-stable snapshot: run status/timestamps churn on
13 * every stream event, but these fields only change when a run is added.
14 */
15export type HandoffTimelineRun = Pick<
16 OrchestrationV2Run,
17 "id" | "ordinal" | "providerInstanceId" | "modelSelection"
18>;
19
20export type HandoffEndpoints = ReturnType<typeof resolveHandoffEndpoints>;
21
22/** Preview the next send's handoff without adding anything to durable history. */
23export function resolvePendingHandoff(
24 projection: OrchestrationV2ThreadProjection | null | undefined,
25 selection: ModelSelection | null | undefined,
26 providers: ReadonlyArray<ServerProvider>,
27): HandoffEndpoints | null {
28 // A thread with an empty timeline has nothing to hand off. Any loaded row
29 // counts: paging can leave a window of only tool rows.
30 if (!projection?.visibleTurnItems.length) return null;
31 const from = projection.runs.findLast(
32 (run) => run.startedAt !== null && run.status !== "rolled_back",
33 )?.modelSelection;
34 if (from === undefined || selection == null) return null;
35 const source = providers.find((provider) => provider.instanceId === from.instanceId);
36 const target = providers.find((provider) => provider.instanceId === selection.instanceId);
37 const needsHandoff =
38 from.instanceId === selection.instanceId
39 ? from.model !== selection.model && target?.requiresNewThreadForModelChange === true
40 : // Accounts sharing a continuation group resume the same native thread.
41 source?.continuation?.groupKey === undefined ||
42 source.driver !== target?.driver ||
43 source.continuation.groupKey !== target.continuation?.groupKey;
44 return needsHandoff ? { from: [from], to: selection } : null;
45}
46
47export function resolveHandoffEndpoints(
48 item: Pick<
49 Extract<OrchestrationV2TurnItem, { type: "handoff" }>,
50 "runId" | "fromModelSelections" | "fromProviderInstanceIds" | "toModel" | "toProviderInstanceId"
51 >,
52 runs: ReadonlyArray<HandoffTimelineRun>,
53) {
54 // Items persisted before models were stamped only carry instance ids;
55 // recover the models from the thread's runs (the handoff's own run is
56 // the target, the newest earlier run per source instance is the origin).
57 // Clients fall back to the provider display name when neither source has a model.
58 const handoffRun = item.runId === null ? undefined : runs.find((run) => run.id === item.runId);
59 const toModel =
60 item.toModel ??
61 (handoffRun !== undefined && handoffRun.providerInstanceId === item.toProviderInstanceId
62 ? handoffRun.modelSelection.model
63 : undefined);
64 const fromEndpoints: ReadonlyArray<{
65 readonly instanceId: ProviderInstanceId;
66 readonly model?: string | undefined;
67 }> =
68 item.fromModelSelections !== undefined && item.fromModelSelections.length > 0
69 ? item.fromModelSelections
70 : item.fromProviderInstanceIds.map((instanceId) => ({
71 instanceId,
72 model: latestRunModelBefore(runs, instanceId, handoffRun?.ordinal),
73 }));
74 return { from: fromEndpoints, to: { instanceId: item.toProviderInstanceId, model: toModel } };
75}
76
77/**
78 * Model of the newest run for `instanceId` that started before the handoff's
79 * own run. Legacy handoff items don't record their source models, but the
80 * covered runs are still in the projection.
81 */
82function latestRunModelBefore(
83 runs: ReadonlyArray<HandoffTimelineRun>,
84 instanceId: ProviderInstanceId,
85 beforeOrdinal: number | undefined,
86): string | undefined {
87 let latest: HandoffTimelineRun | undefined;
88 for (const run of runs) {
89 if (run.providerInstanceId !== instanceId) continue;
90 if (beforeOrdinal !== undefined && run.ordinal >= beforeOrdinal) continue;
91 if (latest === undefined || run.ordinal > latest.ordinal) latest = run;
92 }
93 return latest?.modelSelection.model;
94}