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 automaticCompletionMessageIds = new Set(
94 projection.messages
95 .filter((message) => message.delegatedCompletion !== undefined)
96 .map((message) => message.id),
97 );
98 const queuedRuns = copySorted(
99 projection.runs.filter(
100 (run) => run.status === "queued" && !automaticCompletionMessageIds.has(run.userMessageId),
101 ),
102 (left, right) =>
103 (left.queuePosition ?? left.ordinal) - (right.queuePosition ?? right.ordinal) ||
104 left.ordinal - right.ordinal,
105 ).map((run) => ({
106 run,
107 text:
108 projection.messages.find((message) => message.id === run.userMessageId)?.text ??
109 "Queued message",
110 }));
111
112 return {
113 activeRun,
114 queuedRuns,
115 canReorder: capabilities?.supportsQueuedMessages === true,
116 canPromoteToSteer:
117 hasSteerableProviderTurn &&
118 (capabilities?.supportsActiveSteering === true ||
119 capabilities?.supportsSteeringByInterruptRestart === true),
120 };
121}
122
123export function canForkProjectedAssistantItem(input: {
124 readonly projectedItem: OrchestrationV2ProjectedTurnItem;
125 readonly capabilities?: OrchestrationV2ProviderCapabilities | undefined;
126}): boolean {
127 const item = input.projectedItem.item;
128 if (item.type !== "assistant_message" || item.runId === null || item.status !== "completed") {
129 return false;
130 }
131 if (input.capabilities === undefined) {
132 // Historical and inherited rows may outlive their provider-session record.
133 // Keep the portable server-side fallback available when capability evidence
134 // is absent; a known incapable provider is rejected below.
135 return true;
136 }
137 const capabilities = input.capabilities;
138 const canForkNatively =
139 capabilities.threads.canForkThread &&
140 capabilities.threads.canForkFromTurn &&
141 capabilities.identity.nativeThreadIds === "strong";
142 return canForkNatively || capabilities.context.supportsFullThreadHandoff;
143}
144
145export function canDetachThreadProviderSession(projection: Projection): boolean {
146 const session = resolveThreadProviderSession(projection);
147 return session !== null && session.status !== "stopped" && session.status !== "error";
148}