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