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

threadExecution.ts

477 lines16.9 KB

1import {
2 latestRootProviderFailure,
3 latestUnheldRun,
4 threadErrorSummary,
5 usageLimitRunPresentedAsLatest,
6} from "@t3tools/shared/orchestrationV2ThreadError";
7import {
8 isOrchestrationV2WorkActive,
9 isProviderNativeSubagentThread,
10 latestProviderTurnForAttempt,
11 type ModelSelection,
12 type OrchestrationV2NotificationSource,
13 type OrchestrationV2PendingBackgroundTask,
14 type OrchestrationV2ProviderGoal,
15 type ServerProviderModel,
16 type OrchestrationV2ExecutionNode,
17 type OrchestrationV2ThreadProjection,
18 orchestrationV2RunWorkStartedAt,
19 type ThreadId,
20} from "@t3tools/contracts";
21import {
22 backgroundWorkHoldsCompletion,
23 derivePendingBackgroundWork,
24} from "@t3tools/shared/orchestrationV2PendingBackgroundWork";
25import { getProviderOptionCurrentLabel, getProviderOptionStatedValue } from "@t3tools/shared/model";
26import { formatDuration } from "@t3tools/shared/orchestrationTiming";
27import * as DateTime from "effect/DateTime";
28​
29import {
30 threadRuntimeIsActive,
31 type ThreadRunSummary,
32 type ThreadRuntimeSummary,
33 type ThreadStructure,
34 type ThreadStructureRuntime,
35} from "./models.ts";
36import { formatSubagentDisplayTitle } from "./subagentDisplay.ts";
37​
38const ACTIVITY_RUN_STATUSES = new Set(["preparing", "starting", "running", "waiting"]);
39const INTERRUPTIBLE_RUN_STATUSES = new Set(["preparing", "starting", "running"]);
40​
41function latestMatchingRun(
42 projection: ThreadStructure,
43 predicate: (run: OrchestrationV2ThreadProjection["runs"][number]) => boolean,
44): OrchestrationV2ThreadProjection["runs"][number] | null {
45 return projection.runs.reduce<OrchestrationV2ThreadProjection["runs"][number] | null>(
46 (latest, candidate) =>
47 predicate(candidate) && (latest === null || candidate.ordinal > latest.ordinal)
48 ? candidate
49 : latest,
50 null,
51 );
53​
54function summarizeThreadRun(
55 projection: ThreadStructure,
56 run: OrchestrationV2ThreadProjection["runs"][number],
57): ThreadRunSummary {
58 const turnStatus = ACTIVITY_RUN_STATUSES.has(run.status)
59 ? latestProviderTurnForAttempt(projection.providerTurns, run.activeAttemptId)?.status
60 : undefined;
61 return {
62 runId: run.id,
63 status: run.status,
64 requestedAt: DateTime.formatIso(run.requestedAt),
65 startedAt: run.startedAt === null ? null : DateTime.formatIso(run.startedAt),
66 completedAt: run.completedAt === null ? null : DateTime.formatIso(run.completedAt),
67 assistantMessageId:
68 projection.messages.findLast(
69 (message) => message.runId === run.id && message.role === "assistant",
70 )?.id ?? null,
71 ...(turnStatus === undefined || turnStatus === "pending" || turnStatus === "running"
72 ? {}
73 : { turnEnded: true }),
74 ...(run.sourcePlanRef === undefined ? {} : { sourcePlanRef: run.sourcePlanRef }),
75 };
77​
78function presentedUsageLimitRun(
79 projection: ThreadStructure,
80): OrchestrationV2ThreadProjection["runs"][number] | null {
81 const providerSession = projection.providerSessions.findLast(
82 (session) => session.providerInstanceId === projection.thread.providerInstanceId,
83 );
84 return usageLimitRunPresentedAsLatest(
85 projection.runs,
86 projection.turnItems,
87 providerSession?.lastError ?? null,
88 );
90​
91function presentedLatestRun(
92 projection: ThreadStructure,
93): OrchestrationV2ThreadProjection["runs"][number] | null {
94 return presentedUsageLimitRun(projection) ?? latestUnheldRun(projection.runs);
96​
97export function deriveLatestThreadRun(projection: ThreadStructure): ThreadRunSummary | null {
98 const run = presentedLatestRun(projection);
99 return run === null ? null : summarizeThreadRun(projection, run);
101​
102export function deriveThreadActivityRun(projection: ThreadStructure): ThreadRunSummary | null {
103 const run =
104 latestMatchingRun(projection, (candidate) => ACTIVITY_RUN_STATUSES.has(candidate.status)) ??
105 presentedLatestRun(projection);
106 return run === null ? null : summarizeThreadRun(projection, run);
108​
109/**
110 * Provider-native subagent threads never get app runs: their work is a runless
111 * root turn whose status follows the subagent.
112 */
113export function deriveRunlessWorkStartedAt(projection: ThreadStructure): 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​
124export function deriveProviderSubagentStatus(
125 projection: ThreadStructure,
126): ProviderSubagentStatus | null {
127 if (!isProviderNativeSubagentThread(projection.thread)) return null;
128 const node = projection.nodes.findLast(
129 (candidate) => candidate.kind === "root_turn" && candidate.runId === null,
130 );
131 if (node === undefined) return null;
132 return {
133 status: node.status,
134 startedAt: node.startedAt === null ? null : DateTime.formatIso(node.startedAt),
135 completedAt: node.completedAt === null ? null : DateTime.formatIso(node.completedAt),
136 };
138​
139export function deriveReportedModelSelection(projection: ThreadStructure): ModelSelection | null {
140 const providerThread = projection.providerThreads.find(
141 (candidate) =>
142 candidate.id === projection.thread.activeProviderThreadId &&
143 candidate.providerInstanceId === projection.thread.modelSelection.instanceId,
144 );
145 return providerThread?.nativeMetadata?.modelSelection ?? null;
147​
148export const REASONING_EFFORT_OPTION_IDS: ReadonlyArray<string> = [
149 "reasoningEffort",
150 "effort",
151 "reasoning",
152 "variant",
153 "reasoning_effort",
154 "thinking_level",
155];
156​
157export function formatModelSelectionEffort(
158 selection: ModelSelection,
159 models: ReadonlyArray<ServerProviderModel> = [],
160 reportedSelection?: ModelSelection | null,
161): string | null {
162 const caps = models.find((model) => model.slug === selection.model)?.capabilities;
163 if (!caps) return null;
164 for (const id of REASONING_EFFORT_OPTION_IDS) {
165 const descriptor = caps.optionDescriptors?.find((candidate) => candidate.id === id);
166 if (descriptor?.type !== "select") continue;
167 const value = getProviderOptionStatedValue(id, selection, reportedSelection);
168 if (value === undefined && id !== "variant") continue;
169 if (typeof value === "boolean") continue;
170 // Bypass picker normalization so an obsolete choice cannot become a catalog default.
171 const label = getProviderOptionCurrentLabel(
172 { ...descriptor, currentValue: value },
173 selection,
174 reportedSelection,
175 );
176 if (label) return label;
177 }
178 return null;
180​
181const SUBAGENT_STATUS_LABELS: Record<OrchestrationV2ExecutionNode["status"], string> = {
182 idle: "Idle",
183 pending: "Working",
184 running: "Working",
185 waiting: "Waiting",
186 completed: "Completed",
187 interrupted: "Interrupted",
188 failed: "Failed",
189 cancelled: "Cancelled",
190 rolled_back: "Cancelled",
191};
192​
193export function formatProviderSubagentStatus(
194 status: ProviderSubagentStatus | null,
195 nowMs: number,
196): string {
197 if (status === null) return "Starting";
198 const label = SUBAGENT_STATUS_LABELS[status.status];
199 const live = isOrchestrationV2WorkActive(status.status);
200 if (!live && status.status !== "completed") return label;
201 const start = status.startedAt === null ? Number.NaN : Date.parse(status.startedAt);
202 const end = live
203 ? nowMs
204 : status.completedAt === null
205 ? Number.NaN
206 : Date.parse(status.completedAt);
207 if (!Number.isFinite(start) || !Number.isFinite(end)) return label;
208 const elapsed = formatDuration(Math.max(1_000, Math.floor((end - start) / 1_000) * 1_000));
209 return live ? `${label} ${elapsed}` : `${label} in ${elapsed}`;
211​
212export function deriveThreadRuntime(
213 projection: ThreadStructure & Pick<OrchestrationV2ThreadProjection, "updatedAt">,
214): ThreadRuntimeSummary | null {
215 const runtime = deriveThreadStructureRuntime(projection);
216 return runtime === null
217 ? null
218 : { ...runtime, updatedAt: DateTime.formatIso(projection.updatedAt) };
220​
221/** The runtime summary a thread's structure determines: all of it but `updatedAt`. */
222export function deriveThreadStructureRuntime(
223 projection: ThreadStructure,
224): ThreadStructureRuntime | null {
225 const latestRun = deriveLatestThreadRun(projection);
226 const providerSession = projection.providerSessions.findLast(
227 (session) => session.providerInstanceId === projection.thread.providerInstanceId,
228 );
229 const usageLimitedRun = presentedUsageLimitRun(projection);
230 const latestRunProjection = presentedLatestRun(projection);
231 const activityRun = deriveThreadActivityRun(projection);
232 const liveActivityRun = latestMatchingRun(projection, (run) =>
233 ACTIVITY_RUN_STATUSES.has(run.status),
234 );
235 const backgroundWorkHoldsRun = backgroundWorkHoldsCompletion(
236 derivePendingBackgroundWork({
237 latestRun: latestRunProjection,
238 providerThreads: projection.providerThreads,
239 turnItems: projection.turnItems,
240 activeProviderThreadId: projection.thread.activeProviderThreadId,
241 runs: projection.runs,
242 pullRequests: projection.thread.pullRequests,
243 }),
244 );
245 // A pull request watch can hold a thread that never ran.
246 if (
247 latestRun === null &&
248 projection.thread.activeProviderThreadId === null &&
249 !backgroundWorkHoldsRun
250 ) {
251 return null;
252 }
253 const activeRunId =
254 latestMatchingRun(projection, (run) => INTERRUPTIBLE_RUN_STATUSES.has(run.status))?.id ?? null;
255 return {
256 status: usageLimitedRun
257 ? "failed"
258 : backgroundWorkHoldsRun && latestRunProjection?.status !== "failed"
259 ? "idle"
260 : (activityRun?.status ?? "idle"),
261 activeRunId,
262 activityStartedAt:
263 liveActivityRun === null
264 ? null
265 : DateTime.formatIso(orchestrationV2RunWorkStartedAt(liveActivityRun)),
266 providerInstanceId: projection.thread.providerInstanceId,
267 providerName: providerSession?.driver ?? null,
268 ...threadErrorSummary(
269 latestRootProviderFailure(latestRunProjection, projection.turnItems),
270 providerSession?.lastError ?? null,
271 ),
272 };
274​
275export function threadRuntimeHasInterruptibleRun(
276 runtime: ThreadStructureRuntime | null | undefined,
277): boolean {
278 return (
279 threadRuntimeIsActive(runtime) &&
280 runtime?.activeRunId !== null &&
281 runtime?.activeRunId !== undefined
282 );
284​
285type BackgroundWorkKind = OrchestrationV2PendingBackgroundTask["kind"];
286​
287const BACKGROUND_WORK_KINDS: Record<
288 BackgroundWorkKind,
289 { readonly order: number; readonly singular: string; readonly plural: string }
290> = {
291 subagent: { order: 0, singular: "subagent", plural: "subagents" },
292 command: { order: 1, singular: "command", plural: "commands" },
293 monitor: { order: 2, singular: "monitor", plural: "monitors" },
294 background_task: { order: 3, singular: "background task", plural: "background tasks" },
295};
296​
297export interface RunStopPresentation {
298 /** `unresponsive`: the provider did not confirm the stop in time, so Force stop is offered. */
299 readonly state: "stopping" | "unresponsive";
300 readonly runId: ThreadStructure["runs"][number]["id"];
301 readonly requestedAt: string;
302 /** The run already ended; the Stop targeted its background work. */
303 readonly background: boolean;
305​
306/**
307 * A Stop the provider has not finished yet. It stays `stopping` while the agent winds down,
308 * since some providers confirm the request before the turn actually ends. On a run that
309 * already ended, only an unanswered Stop of its background work counts.
310 */
311export function presentRunStop(
312 projection: Pick<ThreadStructure, "runs" | "turnItems">,
313): RunStopPresentation | null {
314 let active: ThreadStructure["runs"][number] | null = null;
315 let latest: ThreadStructure["runs"][number] | null = null;
316 for (const candidate of projection.runs) {
317 // Queued follow-ups never ran, so they hold no Stop of their own.
318 if (candidate.status !== "queued" && candidate.ordinal > (latest?.ordinal ?? -1))
319 latest = candidate;
320 if (
321 INTERRUPTIBLE_RUN_STATUSES.has(candidate.status) &&
322 candidate.ordinal > (active?.ordinal ?? -1)
323 )
324 active = candidate;
325 }
326 const run = active ?? latest;
327 if (run === null) return null;
328 let request:
329 | Extract<ThreadStructure["turnItems"][number], { type: "run_interrupt_request" }>
330 | undefined;
331 for (const item of projection.turnItems) {
332 if (item.runId !== run.id) continue;
333 if (item.type === "run_interrupt_result") return null;
334 if (item.type === "run_interrupt_request") request = item;
335 }
336 if (request === undefined || (active === null && request.unresponsiveAt === undefined))
337 return null;
338 return {
339 state: request.unresponsiveAt === undefined ? "stopping" : "unresponsive",
340 runId: run.id,
341 requestedAt: DateTime.formatIso(request.startedAt ?? request.updatedAt),
342 background: active === null,
343 };
345​
346export interface PendingBackgroundWorkItem {
347 readonly taskId: string;
348 readonly kind: BackgroundWorkKind;
349 readonly label: string;
350 readonly childThreadId: ThreadId | undefined;
352​
353export interface PendingBackgroundWorkPresentation {
354 readonly title: string;
355 readonly items: ReadonlyArray<PendingBackgroundWorkItem>;
356 readonly waiting: boolean;
358​
359function joinWithAnd(parts: ReadonlyArray<string>): string {
360 if (parts.length <= 1) return parts.join("");
361 return `${parts.slice(0, -1).join(", ")} and ${parts.at(-1)}`;
363​
364export function presentPendingBackgroundWork(
365 tasks: ReadonlyArray<OrchestrationV2PendingBackgroundTask>,
366): PendingBackgroundWorkPresentation | null {
367 if (tasks.length === 0) return null;
368 const waiting = backgroundWorkHoldsCompletion(tasks);
369 const items = tasks
370 .map((task): PendingBackgroundWorkItem => {
371 const description = task.description?.trim();
372 const label =
373 task.kind === "subagent" && description !== undefined
374 ? formatSubagentDisplayTitle(description).trim()
375 : description;
376 return {
377 taskId: task.taskId,
378 kind: task.kind,
379 label:
380 label === undefined || label.length === 0
381 ? BACKGROUND_WORK_KINDS[task.kind].singular
382 : label,
383 childThreadId: task.kind === "subagent" ? task.childThreadId : undefined,
384 };
385 })
386 // `map` returned a new array; Hermes has no `toSorted`.
387 .sort(
388 (left, right) =>
389 BACKGROUND_WORK_KINDS[left.kind].order - BACKGROUND_WORK_KINDS[right.kind].order,
390 );
391 const [only] = items;
392 if (items.length === 1 && only !== undefined) {
393 const noun = BACKGROUND_WORK_KINDS[only.kind].singular;
394 const named = only.label !== noun;
395 const title = waiting
396 ? named
397 ? `${only.kind === "monitor" ? "" : `Waiting on ${noun} `}${only.label}`
398 : `Waiting on a ${noun}`
399 : named
400 ? `Running: ${only.label}`
401 : `Running a ${noun}`;
402 return { title, items, waiting };
403 }
404 const counts = new Map<BackgroundWorkKind, number>();
405 for (const item of items) counts.set(item.kind, (counts.get(item.kind) ?? 0) + 1);
406 const groups = Array.from(counts, ([kind, count]) => {
407 const { singular, plural } = BACKGROUND_WORK_KINDS[kind];
408 return `${count} ${count === 1 ? singular : plural}`;
409 });
410 return { title: `${waiting ? "Waiting on" : "Running"} ${joinWithAnd(groups)}`, items, waiting };
412​
413export interface ProviderGoalPresentation {
414 readonly title: string;
415 readonly objective: string;
416 readonly usage: string | null;
417 readonly canResume: boolean;
419​
420const PROVIDER_GOAL_TITLES: Record<OrchestrationV2ProviderGoal["status"], string> = {
421 active: "Pursuing goal",
422 paused: "Goal paused",
423 blocked: "Goal blocked",
424 usage_limited: "Goal hit a usage limit",
425 budget_limited: "Goal reached its token budget",
426 complete: "Goal complete",
427};
428​
429function formatGoalTokens(tokens: number): string {
430 if (tokens < 1_000) return `${tokens}`;
431 if (tokens < 1_000_000) return `${Math.round(tokens / 1_000)}k`;
432 return `${(tokens / 1_000_000).toFixed(1).replace(/\.0$/, "")}m`;
434​
435export function presentProviderGoal(
436 goal: OrchestrationV2ProviderGoal,
437 working: boolean,
438): ProviderGoalPresentation {
439 const usage: Array<string> = [];
440 if (goal.tokensUsed !== undefined && goal.tokensUsed > 0) {
441 usage.push(
442 goal.tokenBudget == null
443 ? `${formatGoalTokens(goal.tokensUsed)} tokens`
444 : `${formatGoalTokens(goal.tokensUsed)} / ${formatGoalTokens(goal.tokenBudget)} tokens`,
445 );
446 }
447 if (goal.timeUsedSeconds !== undefined && goal.timeUsedSeconds >= 60) {
448 usage.push(formatDuration(goal.timeUsedSeconds * 1_000));
449 }
450 if (goal.checks !== undefined && goal.checks > 0) {
451 usage.push(`${goal.checks} ${goal.checks === 1 ? "check" : "checks"}`);
452 }
453 return {
454 title: goal.status === "active" && !working ? "Goal set" : PROVIDER_GOAL_TITLES[goal.status],
455 objective: goal.objective,
456 usage: usage.length === 0 ? null : usage.join(" · "),
457 canResume: goal.status !== "active" && goal.status !== "complete",
458 };
460​
461export function notificationChildThreadId(
462 source: OrchestrationV2NotificationSource,
463): ThreadId | undefined {
464 switch (source.kind) {
465 case "subagent":
466 case "delegated_task":
467 return source.childThreadId;
468 case "command":
469 case "monitor":
470 case "background_task":
471 case "system":
472 return undefined;
473 default:
474 source satisfies never;
475 return undefined;
476 }