Open History to see the last commit
1import {
2 latestExecutedRun,
3 latestRootProviderFailure,
4 latestUnheldRun,
5 threadErrorSummary,
6 usageLimitRunPresentedAsLatest,
7} from "@t3tools/shared/orchestrationV2ThreadError";
8import {
9 isOrchestrationV2WorkActive,
10 isProviderNativeSubagentThread,
11 latestProviderTurnForAttempt,
12 PROVIDER_DISPLAY_NAMES,
13 type ModelSelection,
14 type OrchestrationV2NotificationSource,
15 type OrchestrationV2PendingBackgroundTask,
16 type OrchestrationV2ProviderGoal,
17 type OrchestrationV2ProviderSession,
18 type ServerProvider,
19 type ServerProviderModel,
20 type OrchestrationV2ExecutionNode,
21 type OrchestrationV2LimitRecovery,
22 type OrchestrationV2ThreadProjection,
23 orchestrationV2RunWorkStartedAt,
24 type RunId,
25 type ThreadId,
26} from "@t3tools/contracts";
27import {
28 backgroundWorkHoldsCompletion,
29 derivePendingBackgroundWork,
30} from "@t3tools/shared/orchestrationV2PendingBackgroundWork";
31import {
32 getModelSelectionStringOptionValue,
33 getProviderOptionCurrentLabel,
34 getProviderOptionStatedValue,
35 resolveSelectableModel,
36 withLegacyUltracodeEffort,
37} from "@t3tools/shared/model";
38import { formatDuration } from "@t3tools/shared/orchestrationTiming";
39import * as DateTime from "effect/DateTime";
40
41import {
42 threadRuntimeIsActive,
43 type ThreadRunSummary,
44 type ThreadRuntimeSummary,
45 type ThreadStructure,
46 type ThreadStructureRuntime,
47 type ThreadStructureTurnItem,
48} from "./models.ts";
49import { commandDisplayText } from "../work-log/commandLabel.ts";
50import { formatSubagentDisplayTitle } from "./subagentDisplay.ts";
51
52const ACTIVITY_RUN_STATUSES = new Set(["preparing", "starting", "running", "waiting"]);
53const INTERRUPTIBLE_RUN_STATUSES = new Set(["preparing", "starting", "running"]);
54// Preparing runs show their workspace setup instead.
55const PROVIDER_STARTING_RUN_STATUSES = new Set(["starting", "running"]);
56
57const EMPTY_EXTENSION_STATUSES: NonNullable<OrchestrationV2ProviderSession["extensionStatuses"]> =
58 [];
59
60/** Only the selected provider's current session can supply transient extension status. */
61export function deriveProviderExtensionStatuses(
62 projection:
63 | (Pick<ThreadStructure, "thread"> & {
64 readonly providerThreads: ReadonlyArray<
65 Pick<
66 ThreadStructure["providerThreads"][number],
67 "id" | "providerSessionId" | "providerInstanceId"
68 >
69 >;
70 readonly providerSessions: ReadonlyArray<
71 Pick<
72 OrchestrationV2ProviderSession,
73 "id" | "providerInstanceId" | "status" | "extensionStatuses"
74 >
75 >;
76 })
77 | null,
78) {
79 if (projection === null) return EMPTY_EXTENSION_STATUSES;
80 const instanceId = projection.thread.modelSelection.instanceId;
81 const activeThread = projection.providerThreads.find(
82 (thread) => thread.id === projection.thread.activeProviderThreadId,
83 );
84 if (activeThread !== undefined && activeThread.providerInstanceId !== instanceId)
85 return EMPTY_EXTENSION_STATUSES;
86 const session = projection.providerSessions.findLast(
87 (session) =>
88 session.providerInstanceId === instanceId &&
89 (activeThread === undefined || session.id === activeThread.providerSessionId),
90 );
91 return session === undefined || session.status === "stopped"
92 ? EMPTY_EXTENSION_STATUSES
93 : (session.extensionStatuses ?? EMPTY_EXTENSION_STATUSES);
94}
95
96function latestMatchingRun(
97 projection: ThreadStructure,
98 predicate: (run: OrchestrationV2ThreadProjection["runs"][number]) => boolean,
99): OrchestrationV2ThreadProjection["runs"][number] | null {
100 return projection.runs.reduce<OrchestrationV2ThreadProjection["runs"][number] | null>(
101 (latest, candidate) =>
102 predicate(candidate) && (latest === null || candidate.ordinal > latest.ordinal)
103 ? candidate
104 : latest,
105 null,
106 );
107}
108
109function providerStartingLabel(
110 projection: ThreadStructure,
111 run: OrchestrationV2ThreadProjection["runs"][number],
112): string {
113 const driver = projection.providerSessions.findLast(
114 (session) => session.providerInstanceId === run.providerInstanceId,
115 )?.driver;
116 const name = driver === undefined ? undefined : PROVIDER_DISPLAY_NAMES[driver];
117 return name === undefined ? "Starting" : `Starting ${name}`;
118}
119
120function summarizeThreadRun(
121 projection: ThreadStructure,
122 run: OrchestrationV2ThreadProjection["runs"][number],
123): ThreadRunSummary {
124 const turnStatus = ACTIVITY_RUN_STATUSES.has(run.status)
125 ? latestProviderTurnForAttempt(projection.providerTurns, run.activeAttemptId)?.status
126 : undefined;
127 return {
128 runId: run.id,
129 status: run.status,
130 requestedAt: DateTime.formatIso(run.requestedAt),
131 startedAt: run.startedAt === null ? null : DateTime.formatIso(run.startedAt),
132 completedAt: run.completedAt === null ? null : DateTime.formatIso(run.completedAt),
133 assistantMessageId:
134 projection.messages.findLast(
135 (message) => message.runId === run.id && message.role === "assistant",
136 )?.id ?? null,
137 // A run counts as running before its provider opens; until a turn appears,
138 // the provider can still be launching for minutes.
139 ...(turnStatus === undefined
140 ? PROVIDER_STARTING_RUN_STATUSES.has(run.status)
141 ? { providerStartingLabel: providerStartingLabel(projection, run) }
142 : {}
143 : turnStatus === "pending" || turnStatus === "running"
144 ? {}
145 : { turnEnded: true }),
146 ...(run.sourcePlanRef === undefined ? {} : { sourcePlanRef: run.sourcePlanRef }),
147 };
148}
149
150function presentedUsageLimitRun(
151 projection: ThreadStructure,
152): OrchestrationV2ThreadProjection["runs"][number] | null {
153 const providerSession = projection.providerSessions.findLast(
154 (session) => session.providerInstanceId === projection.thread.providerInstanceId,
155 );
156 return usageLimitRunPresentedAsLatest(
157 projection.runs,
158 projection.turnItems,
159 providerSession?.lastError ?? null,
160 );
161}
162
163function presentedLatestRun(
164 projection: ThreadStructure,
165): OrchestrationV2ThreadProjection["runs"][number] | null {
166 return presentedUsageLimitRun(projection) ?? latestUnheldRun(projection.runs);
167}
168
169export function deriveLatestThreadRun(projection: ThreadStructure): ThreadRunSummary | null {
170 const run = presentedLatestRun(projection);
171 return run === null ? null : summarizeThreadRun(projection, run);
172}
173
174export function deriveThreadActivityRun(projection: ThreadStructure): ThreadRunSummary | null {
175 const run =
176 latestMatchingRun(projection, (candidate) => ACTIVITY_RUN_STATUSES.has(candidate.status)) ??
177 presentedLatestRun(projection);
178 return run === null ? null : summarizeThreadRun(projection, run);
179}
180
181/**
182 * Provider-native subagent threads never get app runs: their work is a runless
183 * root turn whose status follows the subagent.
184 */
185export function deriveRunlessWorkStartedAt(projection: ThreadStructure): string | null {
186 const status = deriveProviderSubagentStatus(projection);
187 return status !== null && isOrchestrationV2WorkActive(status.status) ? status.startedAt : null;
188}
189
190export interface ProviderSubagentStatus {
191 readonly status: OrchestrationV2ExecutionNode["status"];
192 readonly startedAt: string | null;
193 readonly completedAt: string | null;
194}
195
196export function deriveProviderSubagentStatus(
197 projection: ThreadStructure,
198): ProviderSubagentStatus | null {
199 if (!isProviderNativeSubagentThread(projection.thread)) return null;
200 const node = projection.nodes.findLast(
201 (candidate) => candidate.kind === "root_turn" && candidate.runId === null,
202 );
203 if (node === undefined) return null;
204 return {
205 status: node.status,
206 startedAt: node.startedAt === null ? null : DateTime.formatIso(node.startedAt),
207 completedAt: node.completedAt === null ? null : DateTime.formatIso(node.completedAt),
208 };
209}
210
211export function deriveReportedModelSelection(projection: ThreadStructure): ModelSelection | null {
212 const providerThread = projection.providerThreads.find(
213 (candidate) =>
214 candidate.id === projection.thread.activeProviderThreadId &&
215 candidate.providerInstanceId === projection.thread.modelSelection.instanceId,
216 );
217 return providerThread?.nativeMetadata?.modelSelection ?? null;
218}
219
220export const REASONING_EFFORT_OPTION_IDS: ReadonlyArray<string> = [
221 "reasoningEffort",
222 "effort",
223 "reasoning",
224 "variant",
225 "reasoning_effort",
226 "thinking_level",
227];
228
229export function formatModelSelectionEffort(
230 selection: ModelSelection,
231 models: ReadonlyArray<ServerProviderModel> = [],
232 reportedSelection?: ModelSelection | null,
233): string | null {
234 const caps = models.find((model) => model.slug === selection.model)?.capabilities;
235 if (!caps) return null;
236 const options = withLegacyUltracodeEffort(caps.optionDescriptors, selection.options);
237 const current = options ? { ...selection, options } : selection;
238 for (const id of REASONING_EFFORT_OPTION_IDS) {
239 const descriptor = caps.optionDescriptors?.find((candidate) => candidate.id === id);
240 if (descriptor?.type !== "select") continue;
241 const value = getProviderOptionStatedValue(id, current, reportedSelection);
242 if (value === undefined && id !== "variant") continue;
243 if (typeof value === "boolean") continue;
244 // Bypass picker normalization so an obsolete choice cannot become a catalog default.
245 const label = getProviderOptionCurrentLabel(
246 { ...descriptor, currentValue: value },
247 current,
248 reportedSelection,
249 );
250 if (label) return label;
251 }
252 return null;
253}
254
255/** A reported model the picker catalog does not know, such as `claude-opus-5[1m]`, keeps its raw effort. */
256export function formatSubagentEffort(input: {
257 readonly modelSlug: string | null;
258 readonly modelSelection: ModelSelection | undefined;
259 readonly provider: Pick<ServerProvider, "driver" | "models"> | undefined;
260}): string | null {
261 const { modelSlug, modelSelection: selection, provider } = input;
262 if (!provider || !selection || !modelSlug) return null;
263 const selectionSlug =
264 resolveSelectableModel(provider.driver, selection.model, provider.models) ??
265 selection.model.trim();
266 if (selectionSlug !== modelSlug) return null;
267 if (provider.models.some((model) => model.slug === modelSlug)) {
268 return formatModelSelectionEffort({ ...selection, model: modelSlug }, provider.models);
269 }
270 return (
271 REASONING_EFFORT_OPTION_IDS.map((id) => getModelSelectionStringOptionValue(selection, id)).find(
272 Boolean,
273 ) ?? null
274 );
275}
276
277const SUBAGENT_STATUS_LABELS: Record<OrchestrationV2ExecutionNode["status"], string> = {
278 idle: "Idle",
279 pending: "Working",
280 running: "Working",
281 waiting: "Waiting",
282 completed: "Completed",
283 interrupted: "Interrupted",
284 failed: "Failed",
285 cancelled: "Cancelled",
286 rolled_back: "Cancelled",
287};
288
289export function formatProviderSubagentStatus(
290 status: ProviderSubagentStatus | null,
291 nowMs: number,
292): string {
293 if (status === null) return "Starting";
294 const label = SUBAGENT_STATUS_LABELS[status.status];
295 const live = isOrchestrationV2WorkActive(status.status);
296 if (!live && status.status !== "completed") return label;
297 const start = status.startedAt === null ? Number.NaN : Date.parse(status.startedAt);
298 const end = live
299 ? nowMs
300 : status.completedAt === null
301 ? Number.NaN
302 : Date.parse(status.completedAt);
303 if (!Number.isFinite(start) || !Number.isFinite(end)) return label;
304 const elapsed = formatDuration(Math.max(1_000, Math.floor((end - start) / 1_000) * 1_000));
305 return live ? `${label} ${elapsed}` : `${label} in ${elapsed}`;
306}
307
308/** The run a manual continuation resumes; the server holds the queue until it does. */
309export function deriveResumableRunId(
310 projection: Pick<ThreadStructure, "runs" | "turnItems">,
311 runtime: Pick<ThreadStructureRuntime, "lastErrorClass"> | null,
312): RunId | null {
313 const run = latestExecutedRun(projection.runs);
314 if (run?.status === "interrupted") return run.id;
315 return run?.status === "failed" &&
316 runtime?.lastErrorClass === "usage_limit" &&
317 latestRootProviderFailure(run, projection.turnItems)?.class === "usage_limit"
318 ? run.id
319 : null;
320}
321
322export function deriveThreadRuntime(
323 projection: ThreadStructure & Pick<OrchestrationV2ThreadProjection, "updatedAt">,
324): ThreadRuntimeSummary | null {
325 const runtime = deriveThreadStructureRuntime(projection);
326 return runtime === null
327 ? null
328 : { ...runtime, updatedAt: DateTime.formatIso(projection.updatedAt) };
329}
330
331/** The runtime summary a thread's structure determines: all of it but `updatedAt`. */
332export function deriveThreadStructureRuntime(
333 projection: ThreadStructure,
334): ThreadStructureRuntime | null {
335 const latestRun = deriveLatestThreadRun(projection);
336 const providerSession = projection.providerSessions.findLast(
337 (session) => session.providerInstanceId === projection.thread.providerInstanceId,
338 );
339 const usageLimitedRun = presentedUsageLimitRun(projection);
340 const latestRunProjection = presentedLatestRun(projection);
341 const activityRun = deriveThreadActivityRun(projection);
342 const liveActivityRun = latestMatchingRun(projection, (run) =>
343 ACTIVITY_RUN_STATUSES.has(run.status),
344 );
345 const backgroundWorkHoldsRun = backgroundWorkHoldsCompletion(
346 derivePendingBackgroundWork({
347 latestRun: latestRunProjection,
348 providerThreads: projection.providerThreads,
349 turnItems: projection.turnItems,
350 activeProviderThreadId: projection.thread.activeProviderThreadId,
351 runs: projection.runs,
352 pullRequests: projection.thread.pullRequests,
353 }),
354 );
355 // A pull request watch can hold a thread that never ran.
356 if (
357 latestRun === null &&
358 projection.thread.activeProviderThreadId === null &&
359 !backgroundWorkHoldsRun
360 ) {
361 return null;
362 }
363 const activeRunId =
364 latestMatchingRun(projection, (run) => INTERRUPTIBLE_RUN_STATUSES.has(run.status))?.id ?? null;
365 return {
366 status: usageLimitedRun
367 ? "failed"
368 : backgroundWorkHoldsRun && latestRunProjection?.status !== "failed"
369 ? "idle"
370 : (activityRun?.status ?? "idle"),
371 activeRunId,
372 activityStartedAt:
373 liveActivityRun === null
374 ? null
375 : DateTime.formatIso(orchestrationV2RunWorkStartedAt(liveActivityRun)),
376 providerInstanceId: projection.thread.providerInstanceId,
377 providerName: providerSession?.driver ?? null,
378 ...threadErrorSummary(
379 latestRootProviderFailure(latestRunProjection, projection.turnItems),
380 providerSession?.lastError ?? null,
381 ),
382 };
383}
384
385export interface UsageLimitNoticeRows {
386 readonly itemIds: ReadonlySet<ThreadStructureTurnItem["id"]>;
387 /** Hidden only when its text reads as the provider's limit message; see PROVIDER_LIMIT_NOTICE. */
388 readonly providerNoticeItemId: ThreadStructureTurnItem["id"] | null;
389}
390
391// Claude Code's own limit messages, such as "You've hit your 5-hour limit · resets 7:10am".
392const PROVIDER_LIMIT_NOTICE =
393 /^(?:You[’']ve hit your (?:(?:5-hour|session|weekly|usage) )?limit|You[’']re out of extra usage|Claude AI usage limit reached)(?: · resets (?:[1-9]|1[0-2])(?::[0-5]\d)?(?:am|pm)(?: \([A-Za-z0-9_+-]+(?:\/[A-Za-z0-9_+-]+)*\))?)?\.?$/i;
394
395/**
396 * The timeline rows that repeat a usage-limit pause while its recovery notice shows: the run's
397 * limit failure, Claude's pause notices, and the provider's own limit message. They return to
398 * history once another run executes.
399 */
400export function deriveUsageLimitNoticeRows(
401 projection: ThreadStructure,
402): UsageLimitNoticeRows | null {
403 const runtime = deriveThreadStructureRuntime(projection);
404 const run = presentedLatestRun(projection);
405 if (runtime?.status !== "failed" || runtime.lastErrorClass !== "usage_limit" || run === null) {
406 return null;
407 }
408 const failure = latestRootProviderFailure(run, projection.turnItems);
409 const itemIds = new Set<ThreadStructureTurnItem["id"]>();
410 let failedProviderTurnId: ThreadStructureTurnItem["providerTurnId"] = null;
411 for (const item of projection.turnItems) {
412 if (item.runId !== run.id) continue;
413 if (
414 item.type === "error" &&
415 item.status === "failed" &&
416 item.nodeId === run.rootNodeId &&
417 item.failure.class === "usage_limit"
418 ) {
419 itemIds.add(item.id);
420 if (item.failure === failure) failedProviderTurnId = item.providerTurnId;
421 }
422 }
423 let providerNotice: ThreadStructureTurnItem | null = null;
424 if (failedProviderTurnId !== null) {
425 for (const item of projection.turnItems) {
426 if (item.runId !== run.id || item.providerTurnId !== failedProviderTurnId) continue;
427 if (
428 item.type === "system_notice" &&
429 item.nodeId === run.rootNodeId &&
430 item.parentItemId === null &&
431 item.nativeItemRef?.driver === "claudeAgent" &&
432 item.nativeItemRef.nativeId?.startsWith(`usage-limit:${failedProviderTurnId}:`) === true
433 ) {
434 itemIds.add(item.id);
435 }
436 if (
437 item.type === "assistant_message" &&
438 item.parentItemId === null &&
439 (providerNotice === null || item.ordinal > providerNotice.ordinal)
440 ) {
441 providerNotice = item;
442 }
443 }
444 }
445 return { itemIds, providerNoticeItemId: providerNotice?.id ?? null };
446}
447
448export function withoutUsageLimitNoticeRows<
449 Row extends OrchestrationV2ThreadProjection["visibleTurnItems"][number],
450>(rows: ReadonlyArray<Row>, notice: UsageLimitNoticeRows | null): ReadonlyArray<Row> {
451 if (notice === null) return rows;
452 const hidden = ({ item }: Row) =>
453 notice.itemIds.has(item.id) ||
454 (item.id === notice.providerNoticeItemId &&
455 item.type === "assistant_message" &&
456 PROVIDER_LIMIT_NOTICE.test(item.text.trim()));
457 return rows.some(hidden) ? rows.filter((row) => !hidden(row)) : rows;
458}
459
460/** Whether a usage-limit recovery holds the thread's snooze, so its notice offers Wake now. */
461export function limitRecoveryOwnsSnooze(input: {
462 readonly runId: RunId | null | undefined;
463 readonly resetAt: string | null | undefined;
464 readonly recovery: OrchestrationV2LimitRecovery | null | undefined;
465 readonly snoozedUntil: string | null | undefined;
466}): boolean {
467 const { runId, resetAt, recovery, snoozedUntil } = input;
468 return (
469 recovery?.snooze === true &&
470 runId != null &&
471 recovery.runId === runId &&
472 resetAt != null &&
473 recovery.resetAt === resetAt &&
474 snoozedUntil != null &&
475 Date.parse(snoozedUntil) === Date.parse(resetAt)
476 );
477}
478
479export function threadRuntimeHasInterruptibleRun(
480 runtime: ThreadStructureRuntime | null | undefined,
481): boolean {
482 return (
483 threadRuntimeIsActive(runtime) &&
484 runtime?.activeRunId !== null &&
485 runtime?.activeRunId !== undefined
486 );
487}
488
489type BackgroundWorkKind = OrchestrationV2PendingBackgroundTask["kind"];
490
491const BACKGROUND_WORK_KINDS: Record<
492 BackgroundWorkKind,
493 { readonly order: number; readonly singular: string; readonly plural: string }
494> = {
495 subagent: { order: 0, singular: "subagent", plural: "subagents" },
496 command: { order: 1, singular: "command", plural: "commands" },
497 monitor: { order: 2, singular: "monitor", plural: "monitors" },
498 background_task: { order: 3, singular: "background task", plural: "background tasks" },
499};
500
501export interface RunStopPresentation {
502 /** `unresponsive`: the provider did not confirm the stop in time, so Force stop is offered. */
503 readonly state: "stopping" | "unresponsive";
504 readonly runId: ThreadStructure["runs"][number]["id"];
505 readonly requestedAt: string;
506 /** The run already ended; the Stop targeted its background work. */
507 readonly background: boolean;
508}
509
510/**
511 * A Stop the provider has not finished yet. It stays `stopping` while the agent winds down,
512 * since some providers confirm the request before the turn actually ends. On a run that
513 * already ended, only an unanswered Stop of its background work counts.
514 */
515export function presentRunStop(
516 projection: Pick<ThreadStructure, "runs" | "turnItems">,
517): RunStopPresentation | null {
518 let active: ThreadStructure["runs"][number] | null = null;
519 let latest: ThreadStructure["runs"][number] | null = null;
520 for (const candidate of projection.runs) {
521 // Queued follow-ups never ran, so they hold no Stop of their own.
522 if (candidate.status !== "queued" && candidate.ordinal > (latest?.ordinal ?? -1))
523 latest = candidate;
524 if (
525 INTERRUPTIBLE_RUN_STATUSES.has(candidate.status) &&
526 candidate.ordinal > (active?.ordinal ?? -1)
527 )
528 active = candidate;
529 }
530 const run = active ?? latest;
531 if (run === null) return null;
532 let request:
533 | Extract<ThreadStructure["turnItems"][number], { type: "run_interrupt_request" }>
534 | undefined;
535 for (const item of projection.turnItems) {
536 if (item.runId !== run.id) continue;
537 if (item.type === "run_interrupt_result") return null;
538 if (item.type === "run_interrupt_request") request = item;
539 }
540 if (request === undefined || (active === null && request.unresponsiveAt === undefined))
541 return null;
542 return {
543 state: request.unresponsiveAt === undefined ? "stopping" : "unresponsive",
544 runId: run.id,
545 requestedAt: DateTime.formatIso(request.startedAt ?? request.updatedAt),
546 background: active === null,
547 };
548}
549
550export interface PendingBackgroundWorkItem {
551 readonly taskId: string;
552 readonly kind: BackgroundWorkKind;
553 readonly label: string;
554 readonly childThreadId: ThreadId | undefined;
555}
556
557export interface PendingBackgroundWorkPresentation {
558 readonly title: string;
559 readonly items: ReadonlyArray<PendingBackgroundWorkItem>;
560 readonly waiting: boolean;
561}
562
563function joinWithAnd(parts: ReadonlyArray<string>): string {
564 if (parts.length <= 1) return parts.join("");
565 return `${parts.slice(0, -1).join(", ")} and ${parts.at(-1)}`;
566}
567
568// The Claude adapter forces a stuck query closed after 10 seconds.
569export const BACKGROUND_WORK_STOP_RETRY_AFTER_MS = 10_000;
570
571export interface BackgroundWorkStopRequest {
572 readonly threadKey: string;
573 readonly taskIds: ReadonlyArray<string>;
574 readonly retryAt: number | null;
575}
576
577/** Acceptance does not end the tasks, so an accepted Stop stays pending while they are listed. */
578export function isBackgroundWorkStopPending(
579 request: BackgroundWorkStopRequest | null,
580 threadKey: string,
581 tasks: ReadonlyArray<Pick<OrchestrationV2PendingBackgroundTask, "taskId">>,
582 retryExpired: boolean,
583): boolean {
584 if (request === null || request.threadKey !== threadKey || retryExpired) return false;
585 return request.retryAt === null || tasks.some((task) => request.taskIds.includes(task.taskId));
586}
587
588export function presentPendingBackgroundWork(
589 tasks: ReadonlyArray<OrchestrationV2PendingBackgroundTask>,
590): PendingBackgroundWorkPresentation | null {
591 if (tasks.length === 0) return null;
592 const waiting = backgroundWorkHoldsCompletion(tasks);
593 const items = tasks
594 .map((task): PendingBackgroundWorkItem => {
595 const description = task.description?.trim();
596 const label =
597 description === undefined
598 ? undefined
599 : task.kind === "subagent"
600 ? formatSubagentDisplayTitle(description).trim()
601 : task.kind === "command" || task.kind === "monitor"
602 ? commandDisplayText(description)
603 : description;
604 return {
605 taskId: task.taskId,
606 kind: task.kind,
607 label:
608 label === undefined || label.length === 0
609 ? BACKGROUND_WORK_KINDS[task.kind].singular
610 : label,
611 childThreadId: task.kind === "subagent" ? task.childThreadId : undefined,
612 };
613 })
614 // `map` returned a new array; Hermes has no `toSorted`.
615 .sort(
616 (left, right) =>
617 BACKGROUND_WORK_KINDS[left.kind].order - BACKGROUND_WORK_KINDS[right.kind].order,
618 );
619 const [only] = items;
620 if (items.length === 1 && only !== undefined) {
621 const noun = BACKGROUND_WORK_KINDS[only.kind].singular;
622 const named = only.label !== noun;
623 const title = named
624 ? `${waiting ? "Waiting" : "Running"} · ${only.label}`
625 : waiting
626 ? `Waiting on a ${noun}`
627 : `Running a ${noun}`;
628 return { title, items, waiting };
629 }
630 const counts = new Map<BackgroundWorkKind, number>();
631 for (const item of items) counts.set(item.kind, (counts.get(item.kind) ?? 0) + 1);
632 const groups = Array.from(counts, ([kind, count]) => {
633 const { singular, plural } = BACKGROUND_WORK_KINDS[kind];
634 return `${count} ${count === 1 ? singular : plural}`;
635 });
636 return { title: `${waiting ? "Waiting on" : "Running"} ${joinWithAnd(groups)}`, items, waiting };
637}
638
639export interface ProviderGoalPresentation {
640 readonly title: string;
641 readonly objective: string;
642 readonly usage: string | null;
643 readonly canResume: boolean;
644}
645
646const PROVIDER_GOAL_TITLES: Record<OrchestrationV2ProviderGoal["status"], string> = {
647 active: "Pursuing goal",
648 paused: "Goal paused",
649 blocked: "Goal blocked",
650 usage_limited: "Goal hit a usage limit",
651 budget_limited: "Goal reached its token budget",
652 complete: "Goal complete",
653};
654
655function formatGoalTokens(tokens: number): string {
656 if (tokens < 1_000) return `${tokens}`;
657 const thousands = Math.round(tokens / 1_000);
658 if (thousands < 1_000) return `${thousands}k`;
659 return `${(tokens / 1_000_000).toFixed(1).replace(/\.0$/, "")}m`;
660}
661
662export function presentProviderGoal(
663 goal: OrchestrationV2ProviderGoal,
664 working: boolean,
665): ProviderGoalPresentation {
666 const usage: Array<string> = [];
667 if (goal.tokensUsed !== undefined && goal.tokensUsed > 0) {
668 usage.push(
669 goal.tokenBudget == null
670 ? `${formatGoalTokens(goal.tokensUsed)} tokens`
671 : `${formatGoalTokens(goal.tokensUsed)} / ${formatGoalTokens(goal.tokenBudget)} tokens`,
672 );
673 }
674 if (goal.timeUsedSeconds !== undefined && goal.timeUsedSeconds >= 60) {
675 usage.push(formatDuration(goal.timeUsedSeconds * 1_000));
676 }
677 if (goal.checks !== undefined && goal.checks > 0) {
678 usage.push(`${goal.checks} ${goal.checks === 1 ? "check" : "checks"}`);
679 }
680 return {
681 title: goal.status === "active" && !working ? "Goal set" : PROVIDER_GOAL_TITLES[goal.status],
682 objective: goal.objective,
683 usage: usage.length === 0 ? null : usage.join(" · "),
684 canResume: goal.status !== "active" && goal.status !== "complete",
685 };
686}
687
688export function notificationChildThreadId(
689 source: OrchestrationV2NotificationSource,
690): ThreadId | undefined {
691 switch (source.kind) {
692 case "subagent":
693 case "delegated_task":
694 return source.childThreadId;
695 case "command":
696 case "monitor":
697 case "background_task":
698 case "system":
699 return undefined;
700 default:
701 source satisfies never;
702 return undefined;
703 }
704}