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