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

threadWorkflows.ts

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