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