Open History to see the last commit
1import {
2 type ChatAttachment,
3 isCompactionCommandMessage,
4 type OrchestrationV2ProjectedTurnItem,
5 type OrchestrationV2ProviderCapabilities,
6} from "@t3tools/contracts";
7import { copySorted } from "@t3tools/shared/Array";
8
9import type { ThreadStructure } from "./models.ts";
10
11type Projection = ThreadStructure;
12type Run = Projection["runs"][number];
13type Message = Projection["messages"][number];
14type ProviderSession = Projection["providerSessions"][number];
15
16const ACTIVE_RUN_STATUSES = new Set<Run["status"]>(["preparing", "starting", "running", "waiting"]);
17const MERGE_BACK_RUN_STATUSES = new Set<Run["status"]>(["waiting", "completed"]);
18const MERGE_BACK_BLOCKING_RUN_STATUSES = new Set<Run["status"]>([
19 "preparing",
20 "starting",
21 "running",
22]);
23
24export interface QueuedThreadRun {
25 readonly run: Run;
26 readonly text: string;
27 readonly attachments: ReadonlyArray<ChatAttachment>;
28 readonly messageId: Message["id"];
29 readonly context?: Message["context"];
30 /** Carries the attribution a sent message shows: automation, agent sender, or guest. */
31 readonly message?: Message;
32}
33
34export interface ThreadQueueWorkflowState {
35 readonly activeRun: Run | null;
36 readonly queuedRuns: ReadonlyArray<QueuedThreadRun>;
37 readonly isHeld: boolean;
38 readonly canPromoteToSteer: boolean;
39 /** The active run is a compaction, so promoting a queued message stops it instead of steering. */
40 readonly promoteSkipsCompaction: boolean;
41 readonly canSendNow: boolean;
42}
43
44export function resolveActiveThreadRun(projection: Pick<Projection, "runs">): Run | null {
45 return projection.runs.findLast((run) => ACTIVE_RUN_STATUSES.has(run.status)) ?? null;
46}
47
48/**
49 * A successfully finished provider turn remains in `waiting` while its
50 * checkpoint is captured. Keep that newest turn available for merge-back
51 * instead of falling through to an older fully checkpointed run.
52 */
53export function resolveLatestMergeBackRun(projection: Projection): Run | null {
54 const latestProviderFinishedRun = projection.runs.reduce<Run | null>(
55 (latest, run) =>
56 MERGE_BACK_RUN_STATUSES.has(run.status) && (latest === null || run.ordinal > latest.ordinal)
57 ? run
58 : latest,
59 null,
60 );
61 if (latestProviderFinishedRun === null) return null;
62
63 const hasNewerActiveRun = projection.runs.some(
64 (run) =>
65 run.ordinal > latestProviderFinishedRun.ordinal &&
66 MERGE_BACK_BLOCKING_RUN_STATUSES.has(run.status),
67 );
68 return hasNewerActiveRun ? null : latestProviderFinishedRun;
69}
70
71function resolveThreadProviderSession(projection: Projection): ProviderSession | null {
72 const activeRun = resolveActiveThreadRun(projection);
73 const providerThreadId = activeRun?.providerThreadId ?? projection.thread.activeProviderThreadId;
74 const activeProviderThread =
75 providerThreadId === null
76 ? null
77 : (projection.providerThreads.find((thread) => thread.id === providerThreadId) ?? null);
78 const attachedProviderThread =
79 activeProviderThread ??
80 projection.providerThreads.find(
81 (thread) => thread.appThreadId === projection.thread.id && thread.providerSessionId !== null,
82 ) ??
83 null;
84 const sessionId = attachedProviderThread?.providerSessionId ?? null;
85 if (sessionId !== null) {
86 return projection.providerSessions.find((session) => session.id === sessionId) ?? null;
87 }
88 return (
89 projection.providerSessions.findLast(
90 (session) => session.status !== "stopped" && session.status !== "error",
91 ) ?? null
92 );
93}
94
95export function threadSupportsProviderHandoff(projection: Projection | null | undefined): boolean {
96 if (projection == null) return false;
97 const session = resolveThreadProviderSession(projection);
98 if (session !== null) {
99 return session.capabilities.sessions.supportsProviderSwitchingViaHandoff;
100 }
101 if (resolveActiveThreadRun(projection) !== null) return false;
102 if (projection.thread.historyOrigin === "v1_import" || projection.runs.length === 0) return true;
103
104 // Detaching a stopped session removes it from the projection, but its native
105 // provider thread remains available for the next turn's portable handoff.
106 return projection.providerThreads.some(
107 (thread) =>
108 thread.id === projection.thread.activeProviderThreadId &&
109 thread.appThreadId === projection.thread.id &&
110 thread.providerInstanceId === projection.thread.modelSelection.instanceId &&
111 thread.nativeThreadRef !== null,
112 );
113}
114
115export function getUserQueuedThreadRuns(
116 projection: Pick<Projection, "runs" | "messages">,
117): ReadonlyArray<Run> {
118 const automaticCompletionMessageIds = new Set(
119 projection.messages
120 .filter(
121 (message) =>
122 message.delegatedCompletion !== undefined || message.notification !== undefined,
123 )
124 .map((message) => message.id),
125 );
126 return projection.runs.filter(
127 (run) => run.status === "queued" && !automaticCompletionMessageIds.has(run.userMessageId),
128 );
129}
130
131export function deriveThreadQueueWorkflowState(projection: Projection): ThreadQueueWorkflowState {
132 const activeRun = resolveActiveThreadRun(projection);
133 const session = resolveThreadProviderSession(projection);
134 const capabilities = session?.capabilities.turns;
135 const activeMessage = projection.messages.find(
136 (message) => message.id === activeRun?.userMessageId,
137 );
138 const promoteSkipsCompaction =
139 activeMessage !== undefined && isCompactionCommandMessage(activeMessage);
140 const hasSteerableProviderTurn =
141 activeRun?.status === "running" &&
142 activeRun.activeAttemptId !== null &&
143 projection.providerTurns.some(
144 (turn) => turn.runAttemptId === activeRun.activeAttemptId && turn.status === "running",
145 );
146 const queuedRuns = copySorted(
147 getUserQueuedThreadRuns(projection),
148 (left, right) =>
149 (left.queuePosition ?? left.ordinal) - (right.queuePosition ?? right.ordinal) ||
150 left.ordinal - right.ordinal,
151 ).map((run) => {
152 const message = projection.messages.find((candidate) => candidate.id === run.userMessageId);
153 return {
154 run,
155 // A queued guest message shows the guest's words; the agent still gets the attributed text.
156 text: message?.context?.guest?.text ?? message?.text ?? "Queued message",
157 attachments: message?.attachments ?? [],
158 messageId: run.userMessageId,
159 ...(message?.context ? { context: message.context } : {}),
160 ...(message ? { message } : {}),
161 };
162 });
163
164 return {
165 activeRun,
166 queuedRuns,
167 isHeld: projection.runs.some((run) => run.status === "queued" && run.queueHeld === true),
168 canSendNow:
169 activeRun === null &&
170 projection.thread.archivedAt == null &&
171 projection.thread.deletedAt == null,
172 canPromoteToSteer:
173 promoteSkipsCompaction ||
174 (hasSteerableProviderTurn &&
175 (capabilities?.supportsActiveSteering === true ||
176 capabilities?.supportsSteeringByInterruptRestart === true)),
177 promoteSkipsCompaction,
178 };
179}
180
181export function canForkProjectedAssistantItem(input: {
182 readonly projectedItem: OrchestrationV2ProjectedTurnItem;
183 readonly capabilities?: OrchestrationV2ProviderCapabilities | undefined;
184}): boolean {
185 const item = input.projectedItem.item;
186 if (item.type !== "assistant_message" || item.runId === null || item.status !== "completed") {
187 return false;
188 }
189 if (input.capabilities === undefined) {
190 // Historical and inherited rows may outlive their provider-session record.
191 // Keep the portable server-side fallback available when capability evidence
192 // is absent; a known incapable provider is rejected below.
193 return true;
194 }
195 const capabilities = input.capabilities;
196 const canForkNatively =
197 capabilities.threads.canForkThread &&
198 capabilities.threads.canForkFromTurn &&
199 capabilities.identity.nativeThreadIds === "strong";
200 return canForkNatively || capabilities.context.supportsFullThreadHandoff;
201}
202
203export function canDetachThreadProviderSession(projection: Projection): boolean {
204 const session = resolveThreadProviderSession(projection);
205 return session !== null && session.status !== "stopped" && session.status !== "error";
206}