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} from "./models.ts";
34import { formatSubagentDisplayTitle } from "./subagentDisplay.ts";
35
36const ACTIVITY_RUN_STATUSES = new Set(["preparing", "starting", "running", "waiting"]);
37const INTERRUPTIBLE_RUN_STATUSES = new Set(["preparing", "starting", "running"]);
38
39function latestMatchingRun(
40 projection: OrchestrationV2ThreadProjection,
41 predicate: (run: OrchestrationV2ThreadProjection["runs"][number]) => boolean,
42): OrchestrationV2ThreadProjection["runs"][number] | null {
43 return projection.runs.reduce<OrchestrationV2ThreadProjection["runs"][number] | null>(
44 (latest, candidate) =>
45 predicate(candidate) && (latest === null || candidate.ordinal > latest.ordinal)
46 ? candidate
47 : latest,
48 null,
49 );
50}
51
52function summarizeThreadRun(
53 projection: OrchestrationV2ThreadProjection,
54 run: OrchestrationV2ThreadProjection["runs"][number],
55): ThreadRunSummary {
56 const turnStatus = ACTIVITY_RUN_STATUSES.has(run.status)
57 ? latestProviderTurnForAttempt(projection.providerTurns, run.activeAttemptId)?.status
58 : undefined;
59 return {
60 runId: run.id,
61 status: run.status,
62 requestedAt: DateTime.formatIso(run.requestedAt),
63 startedAt: run.startedAt === null ? null : DateTime.formatIso(run.startedAt),
64 completedAt: run.completedAt === null ? null : DateTime.formatIso(run.completedAt),
65 assistantMessageId:
66 projection.messages.findLast(
67 (message) => message.runId === run.id && message.role === "assistant",
68 )?.id ?? null,
69 ...(turnStatus === undefined || turnStatus === "pending" || turnStatus === "running"
70 ? {}
71 : { turnEnded: true }),
72 ...(run.sourcePlanRef === undefined ? {} : { sourcePlanRef: run.sourcePlanRef }),
73 };
74}
75
76function presentedUsageLimitRun(
77 projection: OrchestrationV2ThreadProjection,
78): OrchestrationV2ThreadProjection["runs"][number] | null {
79 const providerSession = projection.providerSessions.findLast(
80 (session) => session.providerInstanceId === projection.thread.providerInstanceId,
81 );
82 return usageLimitRunPresentedAsLatest(
83 projection.runs,
84 projection.turnItems,
85 providerSession?.lastError ?? null,
86 );
87}
88
89function presentedLatestRun(
90 projection: OrchestrationV2ThreadProjection,
91): OrchestrationV2ThreadProjection["runs"][number] | null {
92 return presentedUsageLimitRun(projection) ?? latestUnheldRun(projection.runs);
93}
94
95export function deriveLatestThreadRun(
96 projection: OrchestrationV2ThreadProjection,
97): ThreadRunSummary | null {
98 const run = presentedLatestRun(projection);
99 return run === null ? null : summarizeThreadRun(projection, run);
100}
101
102export function deriveThreadActivityRun(
103 projection: OrchestrationV2ThreadProjection,
104): ThreadRunSummary | null {
105 const run =
106 latestMatchingRun(projection, (candidate) => ACTIVITY_RUN_STATUSES.has(candidate.status)) ??
107 presentedLatestRun(projection);
108 return run === null ? null : summarizeThreadRun(projection, run);
109}
110
111/**
112 * Provider-native subagent threads never get app runs: their work is a runless
113 * root turn whose status follows the subagent.
114 */
115export function deriveRunlessWorkStartedAt(
116 projection: OrchestrationV2ThreadProjection,
117): string | null {
118 const status = deriveProviderSubagentStatus(projection);
119 return status !== null && isOrchestrationV2WorkActive(status.status) ? status.startedAt : null;
120}
121
122export interface ProviderSubagentStatus {
123 readonly status: OrchestrationV2ExecutionNode["status"];
124 readonly startedAt: string | null;
125 readonly completedAt: string | null;
126}
127
128export function deriveProviderSubagentStatus(
129 projection: OrchestrationV2ThreadProjection,
130): ProviderSubagentStatus | null {
131 if (!isProviderNativeSubagentThread(projection.thread)) return null;
132 const node = projection.nodes.findLast(
133 (candidate) => candidate.kind === "root_turn" && candidate.runId === null,
134 );
135 if (node === undefined) return null;
136 return {
137 status: node.status,
138 startedAt: node.startedAt === null ? null : DateTime.formatIso(node.startedAt),
139 completedAt: node.completedAt === null ? null : DateTime.formatIso(node.completedAt),
140 };
141}
142
143export function deriveReportedModelSelection(
144 projection: OrchestrationV2ThreadProjection,
145): ModelSelection | null {
146 const providerThread = projection.providerThreads.find(
147 (candidate) =>
148 candidate.id === projection.thread.activeProviderThreadId &&
149 candidate.providerInstanceId === projection.thread.modelSelection.instanceId,
150 );
151 return providerThread?.nativeMetadata?.modelSelection ?? null;
152}
153
154const REASONING_EFFORT_OPTION_IDS = ["reasoningEffort", "effort", "reasoning", "variant"] as const;
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: OrchestrationV2ThreadProjection,
213): ThreadRuntimeSummary | null {
214 const latestRun = deriveLatestThreadRun(projection);
215 const providerSession = projection.providerSessions.findLast(
216 (session) => session.providerInstanceId === projection.thread.providerInstanceId,
217 );
218 const usageLimitedRun = presentedUsageLimitRun(projection);
219 const latestRunProjection = presentedLatestRun(projection);
220 const activityRun = deriveThreadActivityRun(projection);
221 const liveActivityRun = latestMatchingRun(projection, (run) =>
222 ACTIVITY_RUN_STATUSES.has(run.status),
223 );
224 const backgroundWorkHoldsRun = backgroundWorkHoldsCompletion(
225 derivePendingBackgroundWork({
226 latestRun: latestRunProjection,
227 providerThreads: projection.providerThreads,
228 turnItems: projection.turnItems,
229 activeProviderThreadId: projection.thread.activeProviderThreadId,
230 runs: projection.runs,
231 pullRequests: projection.thread.pullRequests,
232 }),
233 );
234 // A pull request watch can hold a thread that never ran.
235 if (
236 latestRun === null &&
237 projection.thread.activeProviderThreadId === null &&
238 !backgroundWorkHoldsRun
239 ) {
240 return null;
241 }
242 const activeRunId =
243 latestMatchingRun(projection, (run) => INTERRUPTIBLE_RUN_STATUSES.has(run.status))?.id ?? null;
244 return {
245 status: usageLimitedRun
246 ? "failed"
247 : backgroundWorkHoldsRun && latestRunProjection?.status !== "failed"
248 ? "idle"
249 : (activityRun?.status ?? "idle"),
250 activeRunId,
251 activityStartedAt:
252 liveActivityRun === null
253 ? null
254 : DateTime.formatIso(orchestrationV2RunWorkStartedAt(liveActivityRun)),
255 providerInstanceId: projection.thread.providerInstanceId,
256 providerName: providerSession?.driver ?? null,
257 ...threadErrorSummary(
258 latestRootProviderFailure(latestRunProjection, projection.turnItems),
259 providerSession?.lastError ?? null,
260 ),
261 updatedAt: DateTime.formatIso(projection.updatedAt),
262 };
263}
264
265export function threadRuntimeHasInterruptibleRun(
266 runtime: ThreadRuntimeSummary | null | undefined,
267): boolean {
268 return (
269 threadRuntimeIsActive(runtime) &&
270 runtime?.activeRunId !== null &&
271 runtime?.activeRunId !== undefined
272 );
273}
274
275type BackgroundWorkKind = OrchestrationV2PendingBackgroundTask["kind"];
276
277const BACKGROUND_WORK_KINDS: Record<
278 BackgroundWorkKind,
279 { readonly order: number; readonly singular: string; readonly plural: string }
280> = {
281 subagent: { order: 0, singular: "subagent", plural: "subagents" },
282 command: { order: 1, singular: "command", plural: "commands" },
283 monitor: { order: 2, singular: "monitor", plural: "monitors" },
284 background_task: { order: 3, singular: "background task", plural: "background tasks" },
285};
286
287export interface PendingBackgroundWorkItem {
288 readonly taskId: string;
289 readonly kind: BackgroundWorkKind;
290 readonly label: string;
291 readonly childThreadId: ThreadId | undefined;
292}
293
294export interface PendingBackgroundWorkPresentation {
295 readonly title: string;
296 readonly items: ReadonlyArray<PendingBackgroundWorkItem>;
297 readonly waiting: boolean;
298}
299
300function joinWithAnd(parts: ReadonlyArray<string>): string {
301 if (parts.length <= 1) return parts.join("");
302 return `${parts.slice(0, -1).join(", ")} and ${parts.at(-1)}`;
303}
304
305export function presentPendingBackgroundWork(
306 tasks: ReadonlyArray<OrchestrationV2PendingBackgroundTask>,
307): PendingBackgroundWorkPresentation | null {
308 if (tasks.length === 0) return null;
309 const waiting = backgroundWorkHoldsCompletion(tasks);
310 const items = tasks
311 .map((task): PendingBackgroundWorkItem => {
312 const description = task.description?.trim();
313 const label =
314 task.kind === "subagent" && description !== undefined
315 ? formatSubagentDisplayTitle(description).trim()
316 : description;
317 return {
318 taskId: task.taskId,
319 kind: task.kind,
320 label:
321 label === undefined || label.length === 0
322 ? BACKGROUND_WORK_KINDS[task.kind].singular
323 : label,
324 childThreadId: task.kind === "subagent" ? task.childThreadId : undefined,
325 };
326 })
327 // `map` returned a new array; Hermes has no `toSorted`.
328 .sort(
329 (left, right) =>
330 BACKGROUND_WORK_KINDS[left.kind].order - BACKGROUND_WORK_KINDS[right.kind].order,
331 );
332 const [only] = items;
333 if (items.length === 1 && only !== undefined) {
334 const noun = BACKGROUND_WORK_KINDS[only.kind].singular;
335 const named = only.label !== noun;
336 const title = waiting
337 ? named
338 ? `${only.kind === "monitor" ? "" : `Waiting on ${noun} `}${only.label}`
339 : `Waiting on a ${noun}`
340 : named
341 ? `Running: ${only.label}`
342 : `Running a ${noun}`;
343 return { title, items, waiting };
344 }
345 const counts = new Map<BackgroundWorkKind, number>();
346 for (const item of items) counts.set(item.kind, (counts.get(item.kind) ?? 0) + 1);
347 const groups = Array.from(counts, ([kind, count]) => {
348 const { singular, plural } = BACKGROUND_WORK_KINDS[kind];
349 return `${count} ${count === 1 ? singular : plural}`;
350 });
351 return { title: `${waiting ? "Waiting on" : "Running"} ${joinWithAnd(groups)}`, items, waiting };
352}
353
354export interface ProviderGoalPresentation {
355 readonly title: string;
356 readonly objective: string;
357 readonly usage: string | null;
358 readonly canResume: boolean;
359}
360
361const PROVIDER_GOAL_TITLES: Record<OrchestrationV2ProviderGoal["status"], string> = {
362 active: "Pursuing goal",
363 paused: "Goal paused",
364 blocked: "Goal blocked",
365 usage_limited: "Goal hit a usage limit",
366 budget_limited: "Goal reached its token budget",
367 complete: "Goal complete",
368};
369
370function formatGoalTokens(tokens: number): string {
371 if (tokens < 1_000) return `${tokens}`;
372 if (tokens < 1_000_000) return `${Math.round(tokens / 1_000)}k`;
373 return `${(tokens / 1_000_000).toFixed(1).replace(/\.0$/, "")}m`;
374}
375
376export function presentProviderGoal(
377 goal: OrchestrationV2ProviderGoal,
378 working: boolean,
379): ProviderGoalPresentation {
380 const usage: Array<string> = [];
381 if (goal.tokensUsed !== undefined && goal.tokensUsed > 0) {
382 usage.push(
383 goal.tokenBudget == null
384 ? `${formatGoalTokens(goal.tokensUsed)} tokens`
385 : `${formatGoalTokens(goal.tokensUsed)} / ${formatGoalTokens(goal.tokenBudget)} tokens`,
386 );
387 }
388 if (goal.timeUsedSeconds !== undefined && goal.timeUsedSeconds >= 60) {
389 usage.push(formatDuration(goal.timeUsedSeconds * 1_000));
390 }
391 if (goal.checks !== undefined && goal.checks > 0) {
392 usage.push(`${goal.checks} ${goal.checks === 1 ? "check" : "checks"}`);
393 }
394 return {
395 title: goal.status === "active" && !working ? "Goal set" : PROVIDER_GOAL_TITLES[goal.status],
396 objective: goal.objective,
397 usage: usage.length === 0 ? null : usage.join(" · "),
398 canResume: goal.status !== "active" && goal.status !== "complete",
399 };
400}
401
402export function notificationChildThreadId(
403 source: OrchestrationV2NotificationSource,
404): ThreadId | undefined {
405 switch (source.kind) {
406 case "subagent":
407 case "delegated_task":
408 return source.childThreadId;
409 case "command":
410 case "monitor":
411 case "background_task":
412 case "system":
413 return undefined;
414 default:
415 source satisfies never;
416 return undefined;
417 }
418}