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

threadExecution.ts

684 lines25.0 KB

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