Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

threadWorkflows.ts

188 lines7.1 KB

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