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

threadExecution.ts

339 lines12.7 KB

1import {
2 latestRootProviderFailure,
3 threadErrorSummary,
4 usageLimitRunPresentedAsLatest,
5} from "@t3tools/shared/orchestrationV2ThreadError";
6import {
7 isOrchestrationV2WorkActive,
8 isProviderNativeSubagentThread,
9 type ModelSelection,
10 type OrchestrationV2NotificationSource,
11 type OrchestrationV2PendingBackgroundTask,
12 type ServerProviderModel,
13 type OrchestrationV2ExecutionNode,
14 type OrchestrationV2ThreadProjection,
15 type ThreadId,
16} from "@t3tools/contracts";
17import { derivePendingBackgroundWork } from "@t3tools/shared/orchestrationV2PendingBackgroundWork";
18import { getProviderOptionCurrentLabel, getProviderOptionDescriptors } from "@t3tools/shared/model";
19import { formatDuration } from "@t3tools/shared/orchestrationTiming";
20import * as DateTime from "effect/DateTime";
21​
22import {
23 threadRuntimeIsActive,
24 type ThreadRunSummary,
25 type ThreadRuntimeSummary,
26} from "./models.ts";
27​
28const ACTIVITY_RUN_STATUSES = new Set(["preparing", "starting", "running", "waiting"]);
29const INTERRUPTIBLE_RUN_STATUSES = new Set(["preparing", "starting", "running"]);
30​
31function latestMatchingRun(
32 projection: OrchestrationV2ThreadProjection,
33 predicate: (run: OrchestrationV2ThreadProjection["runs"][number]) => boolean,
34): OrchestrationV2ThreadProjection["runs"][number] | null {
35 return projection.runs.reduce<OrchestrationV2ThreadProjection["runs"][number] | null>(
36 (latest, candidate) =>
37 predicate(candidate) && (latest === null || candidate.ordinal > latest.ordinal)
38 ? candidate
39 : latest,
40 null,
41 );
43​
44function summarizeThreadRun(
45 projection: OrchestrationV2ThreadProjection,
46 run: OrchestrationV2ThreadProjection["runs"][number],
47): ThreadRunSummary {
48 return {
49 runId: run.id,
50 status: run.status,
51 requestedAt: DateTime.formatIso(run.requestedAt),
52 startedAt: run.startedAt === null ? null : DateTime.formatIso(run.startedAt),
53 completedAt: run.completedAt === null ? null : DateTime.formatIso(run.completedAt),
54 assistantMessageId:
55 projection.messages.findLast(
56 (message) => message.runId === run.id && message.role === "assistant",
57 )?.id ?? null,
58 ...(run.sourcePlanRef === undefined ? {} : { sourcePlanRef: run.sourcePlanRef }),
59 };
61​
62function presentedUsageLimitRun(
63 projection: OrchestrationV2ThreadProjection,
64): OrchestrationV2ThreadProjection["runs"][number] | null {
65 const providerSession = projection.providerSessions.findLast(
66 (session) => session.providerInstanceId === projection.thread.providerInstanceId,
67 );
68 return usageLimitRunPresentedAsLatest(
69 projection.runs,
70 projection.turnItems,
71 providerSession?.lastError ?? null,
72 );
74​
75export function deriveLatestThreadRun(
76 projection: OrchestrationV2ThreadProjection,
77): ThreadRunSummary | null {
78 const run = presentedUsageLimitRun(projection) ?? latestMatchingRun(projection, () => true);
79 return run === null ? null : summarizeThreadRun(projection, run);
81​
82/**
83 * Returns the run that owns live provider work, falling back to the newest run
84 * once the thread is idle. A newer queued run must not make an older executing
85 * run look settled in clients that render per-run activity.
86 */
87export function deriveThreadActivityRun(
88 projection: OrchestrationV2ThreadProjection,
89): ThreadRunSummary | null {
90 const run =
91 latestMatchingRun(projection, (candidate) => ACTIVITY_RUN_STATUSES.has(candidate.status)) ??
92 presentedUsageLimitRun(projection) ??
93 latestMatchingRun(projection, () => true);
94 return run === null ? null : summarizeThreadRun(projection, run);
96​
97/**
98 * Provider-native subagent threads never get app runs: their work is a runless
99 * root turn whose status follows the subagent. Returns when that work started
100 * while it is still active, so clients can show the same working state (and
101 * timer) as a run. Stop, queue, and steer stay run-only.
102 */
103export function deriveRunlessWorkStartedAt(
104 projection: OrchestrationV2ThreadProjection,
105): string | null {
106 const status = deriveProviderSubagentStatus(projection);
107 return status !== null && isOrchestrationV2WorkActive(status.status) ? status.startedAt : null;
109​
110export interface ProviderSubagentStatus {
111 readonly status: OrchestrationV2ExecutionNode["status"];
112 readonly startedAt: string | null;
113 readonly completedAt: string | null;
115​
116/**
117 * Status of a provider-native subagent thread (see
118 * isProviderNativeSubagentThread), read from its runless root turn. Null
119 * until that root turn arrives, and for every other thread.
120 */
121export function deriveProviderSubagentStatus(
122 projection: OrchestrationV2ThreadProjection,
123): ProviderSubagentStatus | null {
124 if (!isProviderNativeSubagentThread(projection.thread)) return null;
125 const node = projection.nodes.findLast(
126 (candidate) => candidate.kind === "root_turn" && candidate.runId === null,
127 );
128 if (node === undefined) return null;
129 return {
130 status: node.status,
131 startedAt: node.startedAt === null ? null : DateTime.formatIso(node.startedAt),
132 completedAt: node.completedAt === null ? null : DateTime.formatIso(node.completedAt),
133 };
135​
136// Option ids providers use for reasoning effort (Codex, Claude, Grok/ACP, OpenCode).
137const REASONING_EFFORT_OPTION_IDS = ["reasoningEffort", "effort", "reasoning", "variant"] as const;
138​
139/**
140 * The reasoning effort a thread's model runs at, resolved and named the way
141 * the composer's effort picker does: the stored choice when valid, else the
142 * descriptor's current value, else the model's default. Null when the
143 * provider catalog has no effort option for this model (a subagent on a
144 * model the catalog does not describe), rather than guessing.
145 */
146export function formatModelSelectionEffort(
147 selection: ModelSelection,
148 models: ReadonlyArray<ServerProviderModel> = [],
149): string | null {
150 const caps = models.find((model) => model.slug === selection.model)?.capabilities;
151 if (!caps) return null;
152 const descriptors = getProviderOptionDescriptors({ caps, selections: selection.options });
153 for (const id of REASONING_EFFORT_OPTION_IDS) {
154 const descriptor = descriptors.find((candidate) => candidate.id === id);
155 if (descriptor?.type !== "select") continue;
156 const label = getProviderOptionCurrentLabel(descriptor);
157 if (label) return label;
158 }
159 return null;
161​
162const SUBAGENT_STATUS_LABELS: Record<OrchestrationV2ExecutionNode["status"], string> = {
163 idle: "Idle",
164 pending: "Working",
165 running: "Working",
166 waiting: "Waiting",
167 completed: "Completed",
168 interrupted: "Interrupted",
169 failed: "Failed",
170 cancelled: "Cancelled",
171 rolled_back: "Cancelled",
172};
173​
174/**
175 * One line for the read-only subagent bar: "Working 12s", "Completed in 34s",
176 * or just the status when no duration is known.
177 */
178export function formatProviderSubagentStatus(
179 status: ProviderSubagentStatus | null,
180 nowMs: number,
181): string {
182 if (status === null) return "Starting";
183 const label = SUBAGENT_STATUS_LABELS[status.status];
184 const live = isOrchestrationV2WorkActive(status.status);
185 if (!live && status.status !== "completed") return label;
186 const start = status.startedAt === null ? Number.NaN : Date.parse(status.startedAt);
187 const end = live
188 ? nowMs
189 : status.completedAt === null
190 ? Number.NaN
191 : Date.parse(status.completedAt);
192 if (!Number.isFinite(start) || !Number.isFinite(end)) return label;
193 // Whole seconds: a ticking label must not flicker through tenths.
194 const elapsed = formatDuration(Math.max(1_000, Math.floor((end - start) / 1_000) * 1_000));
195 return live ? `${label} ${elapsed}` : `${label} in ${elapsed}`;
197​
198export function deriveThreadRuntime(
199 projection: OrchestrationV2ThreadProjection,
200): ThreadRuntimeSummary | null {
201 const latestRun = deriveLatestThreadRun(projection);
202 const providerSession = projection.providerSessions.findLast(
203 (session) => session.providerInstanceId === projection.thread.providerInstanceId,
204 );
205 const usageLimitedRun = presentedUsageLimitRun(projection);
206 const latestRunProjection = usageLimitedRun ?? latestMatchingRun(projection, () => true);
207 const activityRun = deriveThreadActivityRun(projection);
208 if (latestRun === null && projection.thread.activeProviderThreadId === null) return null;
209 const activeRunId =
210 latestMatchingRun(projection, (run) => INTERRUPTIBLE_RUN_STATUSES.has(run.status))?.id ?? null;
211 const hasPendingBackgroundTasks =
212 derivePendingBackgroundWork({
213 latestRun: latestRunProjection,
214 providerThreads: projection.providerThreads,
215 turnItems: projection.turnItems,
216 activeProviderThreadId: projection.thread.activeProviderThreadId,
217 runs: projection.runs,
218 }).length > 0;
219 return {
220 status: usageLimitedRun
221 ? "failed"
222 : hasPendingBackgroundTasks && latestRunProjection?.status !== "failed"
223 ? "idle"
224 : (activityRun?.status ?? "idle"),
225 activeRunId,
226 activityStartedAt:
227 activityRun !== null && ACTIVITY_RUN_STATUSES.has(activityRun.status)
228 ? (activityRun.startedAt ?? activityRun.requestedAt)
229 : null,
230 providerInstanceId: projection.thread.providerInstanceId,
231 providerName: providerSession?.driver ?? null,
232 ...threadErrorSummary(
233 latestRootProviderFailure(latestRunProjection, projection.turnItems),
234 providerSession?.lastError ?? null,
235 ),
236 updatedAt: DateTime.formatIso(projection.updatedAt),
237 };
239​
240export function threadRuntimeHasInterruptibleRun(
241 runtime: ThreadRuntimeSummary | null | undefined,
242): boolean {
243 return (
244 threadRuntimeIsActive(runtime) &&
245 runtime?.activeRunId !== null &&
246 runtime?.activeRunId !== undefined
247 );
249​
250type BackgroundWorkKind = OrchestrationV2PendingBackgroundTask["kind"];
251​
252// `order` groups work the way a reader thinks about it: agents first, loose tasks last.
253const BACKGROUND_WORK_KINDS: Record<
254 BackgroundWorkKind,
255 { readonly order: number; readonly singular: string; readonly plural: string }
256> = {
257 subagent: { order: 0, singular: "subagent", plural: "subagents" },
258 command: { order: 1, singular: "command", plural: "commands" },
259 monitor: { order: 2, singular: "monitor", plural: "monitors" },
260 background_task: { order: 3, singular: "background task", plural: "background tasks" },
261};
262​
263export interface PendingBackgroundWorkItem {
264 readonly taskId: string;
265 readonly kind: BackgroundWorkKind;
266 /** The work's name, or its noun when the provider gave none. */
267 readonly label: string;
268 /** A subagent's own thread, when it has one. */
269 readonly childThreadId: ThreadId | undefined;
271​
272export interface PendingBackgroundWorkPresentation {
273 /** "Waiting on subagent Review src/math.ts", "Waiting on 2 subagents and 1 command". */
274 readonly title: string;
275 readonly items: ReadonlyArray<PendingBackgroundWorkItem>;
277​
278function joinWithAnd(parts: ReadonlyArray<string>): string {
279 if (parts.length <= 1) return parts.join("");
280 return `${parts.slice(0, -1).join(", ")} and ${parts.at(-1)}`;
282​
283/** Names what a settled thread is still waiting on, grouped by kind, for the composer strip. */
284export function presentPendingBackgroundWork(
285 tasks: ReadonlyArray<OrchestrationV2PendingBackgroundTask>,
286): PendingBackgroundWorkPresentation | null {
287 if (tasks.length === 0) return null;
288 const items = tasks
289 .map((task): PendingBackgroundWorkItem => {
290 const description = task.description?.trim();
291 return {
292 taskId: task.taskId,
293 kind: task.kind,
294 label:
295 description === undefined || description.length === 0
296 ? BACKGROUND_WORK_KINDS[task.kind].singular
297 : description,
298 childThreadId: task.kind === "subagent" ? task.childThreadId : undefined,
299 };
300 })
301 // `map` returned a new array; Hermes has no `toSorted`.
302 .sort(
303 (left, right) =>
304 BACKGROUND_WORK_KINDS[left.kind].order - BACKGROUND_WORK_KINDS[right.kind].order,
305 );
306 const [only] = items;
307 if (items.length === 1 && only !== undefined) {
308 const noun = BACKGROUND_WORK_KINDS[only.kind].singular;
309 return {
310 title: only.label === noun ? `Waiting on a ${noun}` : `Waiting on ${noun} ${only.label}`,
311 items,
312 };
313 }
314 const counts = new Map<BackgroundWorkKind, number>();
315 for (const item of items) counts.set(item.kind, (counts.get(item.kind) ?? 0) + 1);
316 const groups = Array.from(counts, ([kind, count]) => {
317 const { singular, plural } = BACKGROUND_WORK_KINDS[kind];
318 return `${count} ${count === 1 ? singular : plural}`;
319 });
320 return { title: `Waiting on ${joinWithAnd(groups)}`, items };
322​
323/** The thread a notification row opens: that of the one subagent or delegated task it reports. */
324export function notificationChildThreadId(
325 source: OrchestrationV2NotificationSource,
326): ThreadId | undefined {
327 switch (source.kind) {
328 case "subagent":
329 case "delegated_task":
330 return source.childThreadId;
331 case "command":
332 case "monitor":
333 case "background_task":
334 return undefined;
335 default:
336 source satisfies never;
337 return undefined;
338 }