Open History to see the last commit
1import type {
2 OrchestrationV2ProjectedTurnItem,
3 OrchestrationV2ProviderCapabilities,
4 OrchestrationV2ThreadProjection,
5} from "@t3tools/contracts";
6import { copySorted } from "@t3tools/shared/Array";
7
8type Projection = OrchestrationV2ThreadProjection;
9type Run = Projection["runs"][number];
10type ProviderSession = Projection["providerSessions"][number];
11
12const ACTIVE_RUN_STATUSES = new Set<Run["status"]>(["preparing", "starting", "running", "waiting"]);
13const MERGE_BACK_RUN_STATUSES = new Set<Run["status"]>(["waiting", "completed"]);
14const MERGE_BACK_BLOCKING_RUN_STATUSES = new Set<Run["status"]>([
15 "preparing",
16 "starting",
17 "running",
18]);
19
20export interface QueuedThreadRun {
21 readonly run: Run;
22 readonly text: string;
23}
24
25export interface ThreadQueueWorkflowState {
26 readonly activeRun: Run | null;
27 readonly queuedRuns: ReadonlyArray<QueuedThreadRun>;
28 readonly canReorder: boolean;
29 readonly canPromoteToSteer: boolean;
30}
31
32export function resolveActiveThreadRun(projection: Projection): Run | null {
33 return projection.runs.findLast((run) => ACTIVE_RUN_STATUSES.has(run.status)) ?? null;
34}
35
36/**
37 * A successfully finished provider turn remains in `waiting` while its
38 * checkpoint is captured. Keep that newest turn available for merge-back
39 * instead of falling through to an older fully checkpointed run.
40 */
41export function resolveLatestMergeBackRun(projection: Projection): Run | null {
42 const latestProviderFinishedRun = projection.runs.reduce<Run | null>(
43 (latest, run) =>
44 MERGE_BACK_RUN_STATUSES.has(run.status) && (latest === null || run.ordinal > latest.ordinal)
45 ? run
46 : latest,
47 null,
48 );
49 if (latestProviderFinishedRun === null) return null;
50
51 const hasNewerActiveRun = projection.runs.some(
52 (run) =>
53 run.ordinal > latestProviderFinishedRun.ordinal &&
54 MERGE_BACK_BLOCKING_RUN_STATUSES.has(run.status),
55 );
56 return hasNewerActiveRun ? null : latestProviderFinishedRun;
57}
58
59export function resolveThreadProviderSession(projection: Projection): ProviderSession | null {
60 const activeRun = resolveActiveThreadRun(projection);
61 const providerThreadId = activeRun?.providerThreadId ?? projection.thread.activeProviderThreadId;
62 const activeProviderThread =
63 providerThreadId === null
64 ? null
65 : (projection.providerThreads.find((thread) => thread.id === providerThreadId) ?? null);
66 const attachedProviderThread =
67 activeProviderThread ??
68 projection.providerThreads.find(
69 (thread) => thread.appThreadId === projection.thread.id && thread.providerSessionId !== null,
70 ) ??
71 null;
72 const sessionId = attachedProviderThread?.providerSessionId ?? null;
73 if (sessionId !== null) {
74 return projection.providerSessions.find((session) => session.id === sessionId) ?? null;
75 }
76 return (
77 projection.providerSessions.findLast(
78 (session) => session.status !== "stopped" && session.status !== "error",
79 ) ?? null
80 );
81}
82
83export function deriveThreadQueueWorkflowState(projection: Projection): ThreadQueueWorkflowState {
84 const activeRun = resolveActiveThreadRun(projection);
85 const session = resolveThreadProviderSession(projection);
86 const capabilities = session?.capabilities.turns;
87 const hasSteerableProviderTurn =
88 activeRun?.status === "running" &&
89 activeRun.activeAttemptId !== null &&
90 projection.providerTurns.some(
91 (turn) => turn.runAttemptId === activeRun.activeAttemptId && turn.status === "running",
92 );
93 const queuedRuns = copySorted(
94 projection.runs.filter((run) => run.status === "queued"),
95 (left, right) =>
96 (left.queuePosition ?? left.ordinal) - (right.queuePosition ?? right.ordinal) ||
97 left.ordinal - right.ordinal,
98 ).map((run) => ({
99 run,
100 text:
101 projection.messages.find((message) => message.id === run.userMessageId)?.text ??
102 "Queued message",
103 }));
104
105 return {
106 activeRun,
107 queuedRuns,
108 canReorder: capabilities?.supportsQueuedMessages === true,
109 canPromoteToSteer:
110 hasSteerableProviderTurn &&
111 (capabilities?.supportsActiveSteering === true ||
112 capabilities?.supportsSteeringByInterruptRestart === true),
113 };
114}
115
116export function canForkProjectedAssistantItem(input: {
117 readonly projectedItem: OrchestrationV2ProjectedTurnItem;
118 readonly capabilities?: OrchestrationV2ProviderCapabilities | undefined;
119}): boolean {
120 const item = input.projectedItem.item;
121 if (item.type !== "assistant_message" || item.runId === null || item.status !== "completed") {
122 return false;
123 }
124 if (input.capabilities === undefined) {
125 // Historical and inherited rows may outlive their provider-session record.
126 // Keep the portable server-side fallback available when capability evidence
127 // is absent; a known incapable provider is rejected below.
128 return true;
129 }
130 const capabilities = input.capabilities;
131 const canForkNatively =
132 capabilities.threads.canForkThread &&
133 capabilities.threads.canForkFromTurn &&
134 capabilities.identity.nativeThreadIds === "strong";
135 return canForkNatively || capabilities.context.supportsFullThreadHandoff;
136}
137
138export function canDetachThreadProviderSession(projection: Projection): boolean {
139 const session = resolveThreadProviderSession(projection);
140 return session !== null && session.status !== "stopped" && session.status !== "error";
141}