Open History to see the last commit
1import type {
2 OrchestrationV2Run,
3 OrchestrationV2TurnItem,
4 ProviderInstanceId,
5} from "@t3tools/contracts";
6
7/**
8 * The subset of a projection run that handoff rows read. Kept minimal so the
9 * timeline can hold a content-stable snapshot: run status/timestamps churn on
10 * every stream event, but these fields only change when a run is added.
11 */
12export type HandoffTimelineRun = Pick<
13 OrchestrationV2Run,
14 "id" | "ordinal" | "providerInstanceId" | "modelSelection"
15>;
16
17export function resolveHandoffEndpoints(
18 item: Pick<
19 Extract<OrchestrationV2TurnItem, { type: "handoff" }>,
20 "runId" | "fromModelSelections" | "fromProviderInstanceIds" | "toModel" | "toProviderInstanceId"
21 >,
22 runs: ReadonlyArray<HandoffTimelineRun>,
23) {
24 // Items persisted before models were stamped only carry instance ids;
25 // recover the models from the thread's runs (the handoff's own run is
26 // the target, the newest earlier run per source instance is the origin).
27 // Clients fall back to the provider display name when neither source has a model.
28 const handoffRun = item.runId === null ? undefined : runs.find((run) => run.id === item.runId);
29 const toModel =
30 item.toModel ??
31 (handoffRun !== undefined && handoffRun.providerInstanceId === item.toProviderInstanceId
32 ? handoffRun.modelSelection.model
33 : undefined);
34 const fromEndpoints: ReadonlyArray<{
35 readonly instanceId: ProviderInstanceId;
36 readonly model?: string | undefined;
37 }> =
38 item.fromModelSelections !== undefined && item.fromModelSelections.length > 0
39 ? item.fromModelSelections
40 : item.fromProviderInstanceIds.map((instanceId) => ({
41 instanceId,
42 model: latestRunModelBefore(runs, instanceId, handoffRun?.ordinal),
43 }));
44 return { from: fromEndpoints, to: { instanceId: item.toProviderInstanceId, model: toModel } };
45}
46
47/**
48 * Model of the newest run for `instanceId` that started before the handoff's
49 * own run. Legacy handoff items don't record their source models, but the
50 * covered runs are still in the projection.
51 */
52function latestRunModelBefore(
53 runs: ReadonlyArray<HandoffTimelineRun>,
54 instanceId: ProviderInstanceId,
55 beforeOrdinal: number | undefined,
56): string | undefined {
57 let latest: HandoffTimelineRun | undefined;
58 for (const run of runs) {
59 if (run.providerInstanceId !== instanceId) continue;
60 if (beforeOrdinal !== undefined && run.ordinal >= beforeOrdinal) continue;
61 if (latest === undefined || run.ordinal > latest.ordinal) latest = run;
62 }
63 return latest?.modelSelection.model;
64}