Open History to see the last commit
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 );
52}
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 };
76}
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 );
89}
90
91function presentedLatestRun(
92 projection: ThreadStructure,
93): OrchestrationV2ThreadProjection["runs"][number] | null {
94 return presentedUsageLimitRun(projection) ?? latestUnheldRun(projection.runs);
95}
96
97export function deriveLatestThreadRun(projection: ThreadStructure): ThreadRunSummary | null {
98 const run = presentedLatestRun(projection);
99 return run === null ? null : summarizeThreadRun(projection, run);
100}
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);
107}
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;
116}
117
118export interface ProviderSubagentStatus {
119 readonly status: OrchestrationV2ExecutionNode["status"];
120 readonly startedAt: string | null;
121 readonly completedAt: string | null;
122}
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 };
137}
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;
146}
147
148export const REASONING_EFFORT_OPTION_IDS: ReadonlyArray<string> = [
149 "reasoningEffort",
150 "effort",
151 "reasoning",
152 "variant",
153 "reasoning_effort",
154];
155
156export function formatModelSelectionEffort(
157 selection: ModelSelection,
158 models: ReadonlyArray<ServerProviderModel> = [],
159 reportedSelection?: ModelSelection | null,
160): string | null {
161 const caps = models.find((model) => model.slug === selection.model)?.capabilities;
162 if (!caps) return null;
163 for (const id of REASONING_EFFORT_OPTION_IDS) {
164 const descriptor = caps.optionDescriptors?.find((candidate) => candidate.id === id);
165 if (descriptor?.type !== "select") continue;
166 const value = getProviderOptionStatedValue(id, selection, reportedSelection);
167 if (value === undefined && id !== "variant") continue;
168 if (typeof value === "boolean") continue;
169 // Bypass picker normalization so an obsolete choice cannot become a catalog default.
170 const label = getProviderOptionCurrentLabel(
171 { ...descriptor, currentValue: value },
172 selection,
173 reportedSelection,
174 );
175 if (label) return label;
176 }
177 return null;
178}
179
180const SUBAGENT_STATUS_LABELS: Record<OrchestrationV2ExecutionNode["status"], string> = {
181 idle: "Idle",
182 pending: "Working",
183 running: "Working",
184 waiting: "Waiting",
185 completed: "Completed",
186 interrupted: "Interrupted",
187 failed: "Failed",
188 cancelled: "Cancelled",
189 rolled_back: "Cancelled",
190};
191
192export function formatProviderSubagentStatus(
193 status: ProviderSubagentStatus | null,
194 nowMs: number,
195): string {
196 if (status === null) return "Starting";
197 const label = SUBAGENT_STATUS_LABELS[status.status];
198 const live = isOrchestrationV2WorkActive(status.status);
199 if (!live && status.status !== "completed") return label;
200 const start = status.startedAt === null ? Number.NaN : Date.parse(status.startedAt);
201 const end = live
202 ? nowMs
203 : status.completedAt === null
204 ? Number.NaN
205 : Date.parse(status.completedAt);
206 if (!Number.isFinite(start) || !Number.isFinite(end)) return label;
207 const elapsed = formatDuration(Math.max(1_000, Math.floor((end - start) / 1_000) * 1_000));
208 return live ? `${label} ${elapsed}` : `${label} in ${elapsed}`;
209}
210
211export function deriveThreadRuntime(
212 projection: ThreadStructure & Pick<OrchestrationV2ThreadProjection, "updatedAt">,
213): ThreadRuntimeSummary | null {
214 const runtime = deriveThreadStructureRuntime(projection);
215 return runtime === null
216 ? null
217 : { ...runtime, updatedAt: DateTime.formatIso(projection.updatedAt) };
218}
219
220/** The runtime summary a thread's structure determines: all of it but `updatedAt`. */
221export function deriveThreadStructureRuntime(
222 projection: ThreadStructure,
223): ThreadStructureRuntime | null {
224 const latestRun = deriveLatestThreadRun(projection);
225 const providerSession = projection.providerSessions.findLast(
226 (session) => session.providerInstanceId === projection.thread.providerInstanceId,
227 );
228 const usageLimitedRun = presentedUsageLimitRun(projection);
229 const latestRunProjection = presentedLatestRun(projection);
230 const activityRun = deriveThreadActivityRun(projection);
231 const liveActivityRun = latestMatchingRun(projection, (run) =>
232 ACTIVITY_RUN_STATUSES.has(run.status),
233 );
234 const backgroundWorkHoldsRun = backgroundWorkHoldsCompletion(
235 derivePendingBackgroundWork({
236 latestRun: latestRunProjection,
237 providerThreads: projection.providerThreads,
238 turnItems: projection.turnItems,
239 activeProviderThreadId: projection.thread.activeProviderThreadId,
240 runs: projection.runs,
241 pullRequests: projection.thread.pullRequests,
242 }),
243 );
244 // A pull request watch can hold a thread that never ran.
245 if (
246 latestRun === null &&
247 projection.thread.activeProviderThreadId === null &&
248 !backgroundWorkHoldsRun
249 ) {
250 return null;
251 }
252 const activeRunId =
253 latestMatchingRun(projection, (run) => INTERRUPTIBLE_RUN_STATUSES.has(run.status))?.id ?? null;
254 return {
255 status: usageLimitedRun
256 ? "failed"
257 : backgroundWorkHoldsRun && latestRunProjection?.status !== "failed"
258 ? "idle"
259 : (activityRun?.status ?? "idle"),
260 activeRunId,
261 activityStartedAt:
262 liveActivityRun === null
263 ? null
264 : DateTime.formatIso(orchestrationV2RunWorkStartedAt(liveActivityRun)),
265 providerInstanceId: projection.thread.providerInstanceId,
266 providerName: providerSession?.driver ?? null,
267 ...threadErrorSummary(
268 latestRootProviderFailure(latestRunProjection, projection.turnItems),
269 providerSession?.lastError ?? null,
270 ),
271 };
272}
273
274export function threadRuntimeHasInterruptibleRun(
275 runtime: ThreadStructureRuntime | null | undefined,
276): boolean {
277 return (
278 threadRuntimeIsActive(runtime) &&
279 runtime?.activeRunId !== null &&
280 runtime?.activeRunId !== undefined
281 );
282}
283
284type BackgroundWorkKind = OrchestrationV2PendingBackgroundTask["kind"];
285
286const BACKGROUND_WORK_KINDS: Record<
287 BackgroundWorkKind,
288 { readonly order: number; readonly singular: string; readonly plural: string }
289> = {
290 subagent: { order: 0, singular: "subagent", plural: "subagents" },
291 command: { order: 1, singular: "command", plural: "commands" },
292 monitor: { order: 2, singular: "monitor", plural: "monitors" },
293 background_task: { order: 3, singular: "background task", plural: "background tasks" },
294};
295
296export interface PendingBackgroundWorkItem {
297 readonly taskId: string;
298 readonly kind: BackgroundWorkKind;
299 readonly label: string;
300 readonly childThreadId: ThreadId | undefined;
301}
302
303export interface PendingBackgroundWorkPresentation {
304 readonly title: string;
305 readonly items: ReadonlyArray<PendingBackgroundWorkItem>;
306 readonly waiting: boolean;
307}
308
309function joinWithAnd(parts: ReadonlyArray<string>): string {
310 if (parts.length <= 1) return parts.join("");
311 return `${parts.slice(0, -1).join(", ")} and ${parts.at(-1)}`;
312}
313
314export function presentPendingBackgroundWork(
315 tasks: ReadonlyArray<OrchestrationV2PendingBackgroundTask>,
316): PendingBackgroundWorkPresentation | null {
317 if (tasks.length === 0) return null;
318 const waiting = backgroundWorkHoldsCompletion(tasks);
319 const items = tasks
320 .map((task): PendingBackgroundWorkItem => {
321 const description = task.description?.trim();
322 const label =
323 task.kind === "subagent" && description !== undefined
324 ? formatSubagentDisplayTitle(description).trim()
325 : description;
326 return {
327 taskId: task.taskId,
328 kind: task.kind,
329 label:
330 label === undefined || label.length === 0
331 ? BACKGROUND_WORK_KINDS[task.kind].singular
332 : label,
333 childThreadId: task.kind === "subagent" ? task.childThreadId : undefined,
334 };
335 })
336 // `map` returned a new array; Hermes has no `toSorted`.
337 .sort(
338 (left, right) =>
339 BACKGROUND_WORK_KINDS[left.kind].order - BACKGROUND_WORK_KINDS[right.kind].order,
340 );
341 const [only] = items;
342 if (items.length === 1 && only !== undefined) {
343 const noun = BACKGROUND_WORK_KINDS[only.kind].singular;
344 const named = only.label !== noun;
345 const title = waiting
346 ? named
347 ? `${only.kind === "monitor" ? "" : `Waiting on ${noun} `}${only.label}`
348 : `Waiting on a ${noun}`
349 : named
350 ? `Running: ${only.label}`
351 : `Running a ${noun}`;
352 return { title, items, waiting };
353 }
354 const counts = new Map<BackgroundWorkKind, number>();
355 for (const item of items) counts.set(item.kind, (counts.get(item.kind) ?? 0) + 1);
356 const groups = Array.from(counts, ([kind, count]) => {
357 const { singular, plural } = BACKGROUND_WORK_KINDS[kind];
358 return `${count} ${count === 1 ? singular : plural}`;
359 });
360 return { title: `${waiting ? "Waiting on" : "Running"} ${joinWithAnd(groups)}`, items, waiting };
361}
362
363export interface ProviderGoalPresentation {
364 readonly title: string;
365 readonly objective: string;
366 readonly usage: string | null;
367 readonly canResume: boolean;
368}
369
370const PROVIDER_GOAL_TITLES: Record<OrchestrationV2ProviderGoal["status"], string> = {
371 active: "Pursuing goal",
372 paused: "Goal paused",
373 blocked: "Goal blocked",
374 usage_limited: "Goal hit a usage limit",
375 budget_limited: "Goal reached its token budget",
376 complete: "Goal complete",
377};
378
379function formatGoalTokens(tokens: number): string {
380 if (tokens < 1_000) return `${tokens}`;
381 if (tokens < 1_000_000) return `${Math.round(tokens / 1_000)}k`;
382 return `${(tokens / 1_000_000).toFixed(1).replace(/\.0$/, "")}m`;
383}
384
385export function presentProviderGoal(
386 goal: OrchestrationV2ProviderGoal,
387 working: boolean,
388): ProviderGoalPresentation {
389 const usage: Array<string> = [];
390 if (goal.tokensUsed !== undefined && goal.tokensUsed > 0) {
391 usage.push(
392 goal.tokenBudget == null
393 ? `${formatGoalTokens(goal.tokensUsed)} tokens`
394 : `${formatGoalTokens(goal.tokensUsed)} / ${formatGoalTokens(goal.tokenBudget)} tokens`,
395 );
396 }
397 if (goal.timeUsedSeconds !== undefined && goal.timeUsedSeconds >= 60) {
398 usage.push(formatDuration(goal.timeUsedSeconds * 1_000));
399 }
400 if (goal.checks !== undefined && goal.checks > 0) {
401 usage.push(`${goal.checks} ${goal.checks === 1 ? "check" : "checks"}`);
402 }
403 return {
404 title: goal.status === "active" && !working ? "Goal set" : PROVIDER_GOAL_TITLES[goal.status],
405 objective: goal.objective,
406 usage: usage.length === 0 ? null : usage.join(" · "),
407 canResume: goal.status !== "active" && goal.status !== "complete",
408 };
409}
410
411export function notificationChildThreadId(
412 source: OrchestrationV2NotificationSource,
413): ThreadId | undefined {
414 switch (source.kind) {
415 case "subagent":
416 case "delegated_task":
417 return source.childThreadId;
418 case "command":
419 case "monitor":
420 case "background_task":
421 case "system":
422 return undefined;
423 default:
424 source satisfies never;
425 return undefined;
426 }
427}