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

threadWorkflows.ts

268 lines10.4 KB

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