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

threadExecution.ts

351 lines13.1 KB

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