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