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 type ModelSelection,
11 type OrchestrationV2NotificationSource,
12 type OrchestrationV2PendingBackgroundTask,
13 type OrchestrationV2ProviderGoal,
14 type ServerProviderModel,
15 type OrchestrationV2ExecutionNode,
16 type OrchestrationV2ThreadProjection,
17 orchestrationV2RunWorkStartedAt,
18 type ThreadId,
19} from "@t3tools/contracts";
20import {
21 backgroundWorkHoldsCompletion,
22 derivePendingBackgroundWork,
23} from "@t3tools/shared/orchestrationV2PendingBackgroundWork";
24import { getProviderOptionCurrentLabel, getProviderOptionDescriptors } from "@t3tools/shared/model";
25import { formatDuration } from "@t3tools/shared/orchestrationTiming";
26import * as DateTime from "effect/DateTime";
27
28import {
29 threadRuntimeIsActive,
30 type ThreadRunSummary,
31 type ThreadRuntimeSummary,
32} from "./models.ts";
33import { formatSubagentDisplayTitle } from "./subagentDisplay.ts";
34
35const ACTIVITY_RUN_STATUSES = new Set(["preparing", "starting", "running", "waiting"]);
36const INTERRUPTIBLE_RUN_STATUSES = new Set(["preparing", "starting", "running"]);
37
38function latestMatchingRun(
39 projection: OrchestrationV2ThreadProjection,
40 predicate: (run: OrchestrationV2ThreadProjection["runs"][number]) => boolean,
41): OrchestrationV2ThreadProjection["runs"][number] | null {
42 return projection.runs.reduce<OrchestrationV2ThreadProjection["runs"][number] | null>(
43 (latest, candidate) =>
44 predicate(candidate) && (latest === null || candidate.ordinal > latest.ordinal)
45 ? candidate
46 : latest,
47 null,
48 );
49}
50
51function summarizeThreadRun(
52 projection: OrchestrationV2ThreadProjection,
53 run: OrchestrationV2ThreadProjection["runs"][number],
54): ThreadRunSummary {
55 return {
56 runId: run.id,
57 status: run.status,
58 requestedAt: DateTime.formatIso(run.requestedAt),
59 startedAt: run.startedAt === null ? null : DateTime.formatIso(run.startedAt),
60 completedAt: run.completedAt === null ? null : DateTime.formatIso(run.completedAt),
61 assistantMessageId:
62 projection.messages.findLast(
63 (message) => message.runId === run.id && message.role === "assistant",
64 )?.id ?? null,
65 ...(run.sourcePlanRef === undefined ? {} : { sourcePlanRef: run.sourcePlanRef }),
66 };
67}
68
69function presentedUsageLimitRun(
70 projection: OrchestrationV2ThreadProjection,
71): OrchestrationV2ThreadProjection["runs"][number] | null {
72 const providerSession = projection.providerSessions.findLast(
73 (session) => session.providerInstanceId === projection.thread.providerInstanceId,
74 );
75 return usageLimitRunPresentedAsLatest(
76 projection.runs,
77 projection.turnItems,
78 providerSession?.lastError ?? null,
79 );
80}
81
82function presentedLatestRun(
83 projection: OrchestrationV2ThreadProjection,
84): OrchestrationV2ThreadProjection["runs"][number] | null {
85 return presentedUsageLimitRun(projection) ?? latestUnheldRun(projection.runs);
86}
87
88export function deriveLatestThreadRun(
89 projection: OrchestrationV2ThreadProjection,
90): ThreadRunSummary | null {
91 const run = presentedLatestRun(projection);
92 return run === null ? null : summarizeThreadRun(projection, run);
93}
94
95export function deriveThreadActivityRun(
96 projection: OrchestrationV2ThreadProjection,
97): ThreadRunSummary | null {
98 const run =
99 latestMatchingRun(projection, (candidate) => ACTIVITY_RUN_STATUSES.has(candidate.status)) ??
100 presentedLatestRun(projection);
101 return run === null ? null : summarizeThreadRun(projection, run);
102}
103
104/**
105 * Provider-native subagent threads never get app runs: their work is a runless
106 * root turn whose status follows the subagent.
107 */
108export function deriveRunlessWorkStartedAt(
109 projection: OrchestrationV2ThreadProjection,
110): string | null {
111 const status = deriveProviderSubagentStatus(projection);
112 return status !== null && isOrchestrationV2WorkActive(status.status) ? status.startedAt : null;
113}
114
115export interface ProviderSubagentStatus {
116 readonly status: OrchestrationV2ExecutionNode["status"];
117 readonly startedAt: string | null;
118 readonly completedAt: string | null;
119}
120
121export function deriveProviderSubagentStatus(
122 projection: OrchestrationV2ThreadProjection,
123): ProviderSubagentStatus | null {
124 if (!isProviderNativeSubagentThread(projection.thread)) return null;
125 const node = projection.nodes.findLast(
126 (candidate) => candidate.kind === "root_turn" && candidate.runId === null,
127 );
128 if (node === undefined) return null;
129 return {
130 status: node.status,
131 startedAt: node.startedAt === null ? null : DateTime.formatIso(node.startedAt),
132 completedAt: node.completedAt === null ? null : DateTime.formatIso(node.completedAt),
133 };
134}
135
136export function deriveReportedModelSelection(
137 projection: OrchestrationV2ThreadProjection,
138): ModelSelection | null {
139 const providerThread = projection.providerThreads.find(
140 (candidate) =>
141 candidate.id === projection.thread.activeProviderThreadId &&
142 candidate.providerInstanceId === projection.thread.modelSelection.instanceId,
143 );
144 return providerThread?.nativeMetadata?.modelSelection ?? null;
145}
146
147const REASONING_EFFORT_OPTION_IDS = ["reasoningEffort", "effort", "reasoning", "variant"] as const;
148
149export function formatModelSelectionEffort(
150 selection: ModelSelection,
151 models: ReadonlyArray<ServerProviderModel> = [],
152 reportedSelection?: ModelSelection | null,
153): string | null {
154 const caps = models.find((model) => model.slug === selection.model)?.capabilities;
155 if (!caps) return null;
156 const descriptors = getProviderOptionDescriptors({ caps, selections: selection.options });
157 for (const id of REASONING_EFFORT_OPTION_IDS) {
158 const descriptor = descriptors.find((candidate) => candidate.id === id);
159 if (descriptor?.type !== "select") continue;
160 const label = getProviderOptionCurrentLabel(descriptor, selection, reportedSelection);
161 if (label) return label;
162 }
163 return null;
164}
165
166const SUBAGENT_STATUS_LABELS: Record<OrchestrationV2ExecutionNode["status"], string> = {
167 idle: "Idle",
168 pending: "Working",
169 running: "Working",
170 waiting: "Waiting",
171 completed: "Completed",
172 interrupted: "Interrupted",
173 failed: "Failed",
174 cancelled: "Cancelled",
175 rolled_back: "Cancelled",
176};
177
178export function formatProviderSubagentStatus(
179 status: ProviderSubagentStatus | null,
180 nowMs: number,
181): string {
182 if (status === null) return "Starting";
183 const label = SUBAGENT_STATUS_LABELS[status.status];
184 const live = isOrchestrationV2WorkActive(status.status);
185 if (!live && status.status !== "completed") return label;
186 const start = status.startedAt === null ? Number.NaN : Date.parse(status.startedAt);
187 const end = live
188 ? nowMs
189 : status.completedAt === null
190 ? Number.NaN
191 : Date.parse(status.completedAt);
192 if (!Number.isFinite(start) || !Number.isFinite(end)) return label;
193 const elapsed = formatDuration(Math.max(1_000, Math.floor((end - start) / 1_000) * 1_000));
194 return live ? `${label} ${elapsed}` : `${label} in ${elapsed}`;
195}
196
197export function deriveThreadRuntime(
198 projection: OrchestrationV2ThreadProjection,
199): ThreadRuntimeSummary | null {
200 const latestRun = deriveLatestThreadRun(projection);
201 const providerSession = projection.providerSessions.findLast(
202 (session) => session.providerInstanceId === projection.thread.providerInstanceId,
203 );
204 const usageLimitedRun = presentedUsageLimitRun(projection);
205 const latestRunProjection = presentedLatestRun(projection);
206 const activityRun = deriveThreadActivityRun(projection);
207 const liveActivityRun = latestMatchingRun(projection, (run) =>
208 ACTIVITY_RUN_STATUSES.has(run.status),
209 );
210 const backgroundWorkHoldsRun = backgroundWorkHoldsCompletion(
211 derivePendingBackgroundWork({
212 latestRun: latestRunProjection,
213 providerThreads: projection.providerThreads,
214 turnItems: projection.turnItems,
215 activeProviderThreadId: projection.thread.activeProviderThreadId,
216 runs: projection.runs,
217 pullRequests: projection.thread.pullRequests,
218 }),
219 );
220 // A pull request watch can hold a thread that never ran.
221 if (
222 latestRun === null &&
223 projection.thread.activeProviderThreadId === null &&
224 !backgroundWorkHoldsRun
225 ) {
226 return null;
227 }
228 const activeRunId =
229 latestMatchingRun(projection, (run) => INTERRUPTIBLE_RUN_STATUSES.has(run.status))?.id ?? null;
230 return {
231 status: usageLimitedRun
232 ? "failed"
233 : backgroundWorkHoldsRun && latestRunProjection?.status !== "failed"
234 ? "idle"
235 : (activityRun?.status ?? "idle"),
236 activeRunId,
237 activityStartedAt:
238 liveActivityRun === null
239 ? null
240 : DateTime.formatIso(orchestrationV2RunWorkStartedAt(liveActivityRun)),
241 providerInstanceId: projection.thread.providerInstanceId,
242 providerName: providerSession?.driver ?? null,
243 ...threadErrorSummary(
244 latestRootProviderFailure(latestRunProjection, projection.turnItems),
245 providerSession?.lastError ?? null,
246 ),
247 updatedAt: DateTime.formatIso(projection.updatedAt),
248 };
249}
250
251export function threadRuntimeHasInterruptibleRun(
252 runtime: ThreadRuntimeSummary | null | undefined,
253): boolean {
254 return (
255 threadRuntimeIsActive(runtime) &&
256 runtime?.activeRunId !== null &&
257 runtime?.activeRunId !== undefined
258 );
259}
260
261type BackgroundWorkKind = OrchestrationV2PendingBackgroundTask["kind"];
262
263const BACKGROUND_WORK_KINDS: Record<
264 BackgroundWorkKind,
265 { readonly order: number; readonly singular: string; readonly plural: string }
266> = {
267 subagent: { order: 0, singular: "subagent", plural: "subagents" },
268 command: { order: 1, singular: "command", plural: "commands" },
269 monitor: { order: 2, singular: "monitor", plural: "monitors" },
270 background_task: { order: 3, singular: "background task", plural: "background tasks" },
271};
272
273export interface PendingBackgroundWorkItem {
274 readonly taskId: string;
275 readonly kind: BackgroundWorkKind;
276 readonly label: string;
277 readonly childThreadId: ThreadId | undefined;
278}
279
280export interface PendingBackgroundWorkPresentation {
281 readonly title: string;
282 readonly items: ReadonlyArray<PendingBackgroundWorkItem>;
283 readonly waiting: boolean;
284}
285
286function joinWithAnd(parts: ReadonlyArray<string>): string {
287 if (parts.length <= 1) return parts.join("");
288 return `${parts.slice(0, -1).join(", ")} and ${parts.at(-1)}`;
289}
290
291export function presentPendingBackgroundWork(
292 tasks: ReadonlyArray<OrchestrationV2PendingBackgroundTask>,
293): PendingBackgroundWorkPresentation | null {
294 if (tasks.length === 0) return null;
295 const waiting = backgroundWorkHoldsCompletion(tasks);
296 const items = tasks
297 .map((task): PendingBackgroundWorkItem => {
298 const description = task.description?.trim();
299 const label =
300 task.kind === "subagent" && description !== undefined
301 ? formatSubagentDisplayTitle(description).trim()
302 : description;
303 return {
304 taskId: task.taskId,
305 kind: task.kind,
306 label:
307 label === undefined || label.length === 0
308 ? BACKGROUND_WORK_KINDS[task.kind].singular
309 : label,
310 childThreadId: task.kind === "subagent" ? task.childThreadId : undefined,
311 };
312 })
313 // `map` returned a new array; Hermes has no `toSorted`.
314 .sort(
315 (left, right) =>
316 BACKGROUND_WORK_KINDS[left.kind].order - BACKGROUND_WORK_KINDS[right.kind].order,
317 );
318 const [only] = items;
319 if (items.length === 1 && only !== undefined) {
320 const noun = BACKGROUND_WORK_KINDS[only.kind].singular;
321 const named = only.label !== noun;
322 const title = waiting
323 ? named
324 ? `${only.kind === "monitor" ? "" : `Waiting on ${noun} `}${only.label}`
325 : `Waiting on a ${noun}`
326 : named
327 ? `Running: ${only.label}`
328 : `Running a ${noun}`;
329 return { title, items, waiting };
330 }
331 const counts = new Map<BackgroundWorkKind, number>();
332 for (const item of items) counts.set(item.kind, (counts.get(item.kind) ?? 0) + 1);
333 const groups = Array.from(counts, ([kind, count]) => {
334 const { singular, plural } = BACKGROUND_WORK_KINDS[kind];
335 return `${count} ${count === 1 ? singular : plural}`;
336 });
337 return { title: `${waiting ? "Waiting on" : "Running"} ${joinWithAnd(groups)}`, items, waiting };
338}
339
340export interface ProviderGoalPresentation {
341 readonly title: string;
342 readonly objective: string;
343 readonly usage: string | null;
344 readonly canResume: boolean;
345}
346
347const PROVIDER_GOAL_TITLES: Record<OrchestrationV2ProviderGoal["status"], string> = {
348 active: "Pursuing goal",
349 paused: "Goal paused",
350 blocked: "Goal blocked",
351 usage_limited: "Goal hit a usage limit",
352 budget_limited: "Goal reached its token budget",
353 complete: "Goal complete",
354};
355
356function formatGoalTokens(tokens: number): string {
357 if (tokens < 1_000) return `${tokens}`;
358 if (tokens < 1_000_000) return `${Math.round(tokens / 1_000)}k`;
359 return `${(tokens / 1_000_000).toFixed(1).replace(/\.0$/, "")}m`;
360}
361
362export function presentProviderGoal(
363 goal: OrchestrationV2ProviderGoal,
364 working: boolean,
365): ProviderGoalPresentation {
366 const usage: Array<string> = [];
367 if (goal.tokensUsed !== undefined && goal.tokensUsed > 0) {
368 usage.push(
369 goal.tokenBudget == null
370 ? `${formatGoalTokens(goal.tokensUsed)} tokens`
371 : `${formatGoalTokens(goal.tokensUsed)} / ${formatGoalTokens(goal.tokenBudget)} tokens`,
372 );
373 }
374 if (goal.timeUsedSeconds !== undefined && goal.timeUsedSeconds >= 60) {
375 usage.push(formatDuration(goal.timeUsedSeconds * 1_000));
376 }
377 if (goal.checks !== undefined && goal.checks > 0) {
378 usage.push(`${goal.checks} ${goal.checks === 1 ? "check" : "checks"}`);
379 }
380 return {
381 title: goal.status === "active" && !working ? "Goal set" : PROVIDER_GOAL_TITLES[goal.status],
382 objective: goal.objective,
383 usage: usage.length === 0 ? null : usage.join(" · "),
384 canResume: goal.status !== "active" && goal.status !== "complete",
385 };
386}
387
388export function notificationChildThreadId(
389 source: OrchestrationV2NotificationSource,
390): ThreadId | undefined {
391 switch (source.kind) {
392 case "subagent":
393 case "delegated_task":
394 return source.childThreadId;
395 case "command":
396 case "monitor":
397 case "background_task":
398 case "system":
399 return undefined;
400 default:
401 source satisfies never;
402 return undefined;
403 }
404}