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

threadWorkflows.ts

223 lines8.5 KB

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