Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

threadExecution.ts

685 lines25.1 KB

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