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

threadExecution.ts

687 lines25.1 KB

1import {
2 latestExecutedRun,
3 latestRootProviderFailure,
4 latestUnheldRun,
5 threadErrorSummary,
6 usageLimitBlockedRun,
7 usageLimitRunPresentedAsLatest,
8} 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 =
295 usageLimitBlockedRun(projection.runs, projection.turnItems, null) ??
296 latestExecutedRun(projection.runs);
297 if (run?.status === "interrupted") return run.id;
298 return run?.status === "failed" &&
299 runtime?.lastErrorClass === "usage_limit" &&
300 latestRootProviderFailure(run, projection.turnItems)?.class === "usage_limit"
301 ? run.id
302 : null;
304​
305export function deriveThreadRuntime(
306 projection: ThreadStructure & Pick<OrchestrationV2ThreadProjection, "updatedAt">,
307): ThreadRuntimeSummary | null {
308 const runtime = deriveThreadStructureRuntime(projection);
309 return runtime === null
310 ? null
311 : { ...runtime, updatedAt: DateTime.formatIso(projection.updatedAt) };
313​
314/** The runtime summary a thread's structure determines: all of it but `updatedAt`. */
315export function deriveThreadStructureRuntime(
316 projection: ThreadStructure,
317): ThreadStructureRuntime | null {
318 const latestRun = deriveLatestThreadRun(projection);
319 const providerSession = projection.providerSessions.findLast(
320 (session) => session.providerInstanceId === projection.thread.providerInstanceId,
321 );
322 const usageLimitedRun = presentedUsageLimitRun(projection);
323 const latestRunProjection = presentedLatestRun(projection);
324 const activityRun = deriveThreadActivityRun(projection);
325 const liveActivityRun = latestMatchingRun(projection, (run) =>
326 ACTIVITY_RUN_STATUSES.has(run.status),
327 );
328 const backgroundWorkHoldsRun = backgroundWorkHoldsCompletion(
329 derivePendingBackgroundWork({
330 latestRun: latestRunProjection,
331 providerThreads: projection.providerThreads,
332 turnItems: projection.turnItems,
333 activeProviderThreadId: projection.thread.activeProviderThreadId,
334 runs: projection.runs,
335 pullRequests: projection.thread.pullRequests,
336 }),
337 );
338 // A pull request watch can hold a thread that never ran.
339 if (
340 latestRun === null &&
341 projection.thread.activeProviderThreadId === null &&
342 !backgroundWorkHoldsRun
343 ) {
344 return null;
345 }
346 const activeRunId =
347 latestMatchingRun(projection, (run) => INTERRUPTIBLE_RUN_STATUSES.has(run.status))?.id ?? null;
348 return {
349 status: usageLimitedRun
350 ? "failed"
351 : backgroundWorkHoldsRun && latestRunProjection?.status !== "failed"
352 ? "idle"
353 : (activityRun?.status ?? "idle"),
354 activeRunId,
355 activityStartedAt:
356 liveActivityRun === null
357 ? null
358 : DateTime.formatIso(orchestrationV2RunWorkStartedAt(liveActivityRun)),
359 providerInstanceId: projection.thread.providerInstanceId,
360 providerName: providerSession?.driver ?? null,
361 ...threadErrorSummary(
362 latestRootProviderFailure(latestRunProjection, projection.turnItems),
363 providerSession?.lastError ?? null,
364 ),
365 };
367​
368export interface UsageLimitNoticeRows {
369 readonly itemIds: ReadonlySet<ThreadStructureTurnItem["id"]>;
370 /** Hidden only when its text reads as the provider's limit message; see PROVIDER_LIMIT_NOTICE. */
371 readonly providerNoticeItemId: ThreadStructureTurnItem["id"] | null;
373​
374// Claude Code's own limit messages, such as "You've hit your 5-hour limit · resets 7:10am".
375const PROVIDER_LIMIT_NOTICE =
376 /^(?: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;
377​
378/**
379 * The timeline rows that repeat a usage-limit pause while its recovery notice shows: the run's
380 * limit failure, Claude's pause notices, and the provider's own limit message. They return to
381 * history once another run executes.
382 */
383export function deriveUsageLimitNoticeRows(
384 projection: ThreadStructure,
385): UsageLimitNoticeRows | null {
386 const runtime = deriveThreadStructureRuntime(projection);
387 const run = presentedLatestRun(projection);
388 if (runtime?.status !== "failed" || runtime.lastErrorClass !== "usage_limit" || run === null) {
389 return null;
390 }
391 const failure = latestRootProviderFailure(run, projection.turnItems);
392 const itemIds = new Set<ThreadStructureTurnItem["id"]>();
393 let failedProviderTurnId: ThreadStructureTurnItem["providerTurnId"] = null;
394 for (const item of projection.turnItems) {
395 if (item.runId !== run.id) continue;
396 if (
397 item.type === "error" &&
398 item.status === "failed" &&
399 item.nodeId === run.rootNodeId &&
400 item.failure.class === "usage_limit"
401 ) {
402 itemIds.add(item.id);
403 if (item.failure === failure) failedProviderTurnId = item.providerTurnId;
404 }
405 }
406 let providerNotice: ThreadStructureTurnItem | null = null;
407 if (failedProviderTurnId !== null) {
408 for (const item of projection.turnItems) {
409 if (item.runId !== run.id || item.providerTurnId !== failedProviderTurnId) continue;
410 if (
411 item.type === "system_notice" &&
412 item.nodeId === run.rootNodeId &&
413 item.parentItemId === null &&
414 item.nativeItemRef?.driver === "claudeAgent" &&
415 item.nativeItemRef.nativeId?.startsWith(`usage-limit:${failedProviderTurnId}:`) === true
416 ) {
417 itemIds.add(item.id);
418 }
419 if (
420 item.type === "assistant_message" &&
421 item.parentItemId === null &&
422 (providerNotice === null || item.ordinal > providerNotice.ordinal)
423 ) {
424 providerNotice = item;
425 }
426 }
427 }
428 return { itemIds, providerNoticeItemId: providerNotice?.id ?? null };
430​
431export function withoutUsageLimitNoticeRows<
432 Row extends OrchestrationV2ThreadProjection["visibleTurnItems"][number],
433>(rows: ReadonlyArray<Row>, notice: UsageLimitNoticeRows | null): ReadonlyArray<Row> {
434 if (notice === null) return rows;
435 const hidden = ({ item }: Row) =>
436 notice.itemIds.has(item.id) ||
437 (item.id === notice.providerNoticeItemId &&
438 item.type === "assistant_message" &&
439 PROVIDER_LIMIT_NOTICE.test(item.text.trim()));
440 return rows.some(hidden) ? rows.filter((row) => !hidden(row)) : rows;
442​
443/** Whether a usage-limit recovery holds the thread's snooze, so its notice offers Wake now. */
444export function limitRecoveryOwnsSnooze(input: {
445 readonly runId: RunId | null | undefined;
446 readonly resetAt: string | null | undefined;
447 readonly recovery: OrchestrationV2LimitRecovery | null | undefined;
448 readonly snoozedUntil: string | null | undefined;
449}): boolean {
450 const { runId, resetAt, recovery, snoozedUntil } = input;
451 return (
452 recovery?.snooze === true &&
453 runId != null &&
454 recovery.runId === runId &&
455 resetAt != null &&
456 recovery.resetAt === resetAt &&
457 snoozedUntil != null &&
458 Date.parse(snoozedUntil) === Date.parse(resetAt)
459 );
461​
462export function threadRuntimeHasInterruptibleRun(
463 runtime: ThreadStructureRuntime | null | undefined,
464): boolean {
465 return (
466 threadRuntimeIsActive(runtime) &&
467 runtime?.activeRunId !== null &&
468 runtime?.activeRunId !== undefined
469 );
471​
472type BackgroundWorkKind = OrchestrationV2PendingBackgroundTask["kind"];
473​
474const BACKGROUND_WORK_KINDS: Record<
475 BackgroundWorkKind,
476 { readonly order: number; readonly singular: string; readonly plural: string }
477> = {
478 subagent: { order: 0, singular: "subagent", plural: "subagents" },
479 command: { order: 1, singular: "command", plural: "commands" },
480 monitor: { order: 2, singular: "monitor", plural: "monitors" },
481 background_task: { order: 3, singular: "background task", plural: "background tasks" },
482};
483​
484export interface RunStopPresentation {
485 /** `unresponsive`: the provider did not confirm the stop in time, so Force stop is offered. */
486 readonly state: "stopping" | "unresponsive";
487 readonly runId: ThreadStructure["runs"][number]["id"];
488 readonly requestedAt: string;
489 /** The run already ended; the Stop targeted its background work. */
490 readonly background: boolean;
492​
493/**
494 * A Stop the provider has not finished yet. It stays `stopping` while the agent winds down,
495 * since some providers confirm the request before the turn actually ends. On a run that
496 * already ended, only an unanswered Stop of its background work counts.
497 */
498export function presentRunStop(
499 projection: Pick<ThreadStructure, "runs" | "turnItems">,
500): RunStopPresentation | null {
501 let active: ThreadStructure["runs"][number] | null = null;
502 let latest: ThreadStructure["runs"][number] | null = null;
503 for (const candidate of projection.runs) {
504 // Queued follow-ups never ran, so they hold no Stop of their own.
505 if (candidate.status !== "queued" && candidate.ordinal > (latest?.ordinal ?? -1))
506 latest = candidate;
507 if (
508 INTERRUPTIBLE_RUN_STATUSES.has(candidate.status) &&
509 candidate.ordinal > (active?.ordinal ?? -1)
510 )
511 active = candidate;
512 }
513 const run = active ?? latest;
514 if (run === null) return null;
515 let request:
516 | Extract<ThreadStructure["turnItems"][number], { type: "run_interrupt_request" }>
517 | undefined;
518 for (const item of projection.turnItems) {
519 if (item.runId !== run.id) continue;
520 if (item.type === "run_interrupt_result") return null;
521 if (item.type === "run_interrupt_request") request = item;
522 }
523 if (request === undefined || (active === null && request.unresponsiveAt === undefined))
524 return null;
525 return {
526 state: request.unresponsiveAt === undefined ? "stopping" : "unresponsive",
527 runId: run.id,
528 requestedAt: DateTime.formatIso(request.startedAt ?? request.updatedAt),
529 background: active === null,
530 };
532​
533export interface PendingBackgroundWorkItem {
534 readonly taskId: string;
535 readonly kind: BackgroundWorkKind;
536 readonly label: string;
537 readonly childThreadId: ThreadId | undefined;
539​
540export interface PendingBackgroundWorkPresentation {
541 readonly title: string;
542 readonly items: ReadonlyArray<PendingBackgroundWorkItem>;
543 readonly waiting: boolean;
545​
546function joinWithAnd(parts: ReadonlyArray<string>): string {
547 if (parts.length <= 1) return parts.join("");
548 return `${parts.slice(0, -1).join(", ")} and ${parts.at(-1)}`;
550​
551// The Claude adapter forces a stuck query closed after 10 seconds.
552export const BACKGROUND_WORK_STOP_RETRY_AFTER_MS = 10_000;
553​
554export interface BackgroundWorkStopRequest {
555 readonly threadKey: string;
556 readonly taskIds: ReadonlyArray<string>;
557 readonly retryAt: number | null;
559​
560/** Acceptance does not end the tasks, so an accepted Stop stays pending while they are listed. */
561export function isBackgroundWorkStopPending(
562 request: BackgroundWorkStopRequest | null,
563 threadKey: string,
564 tasks: ReadonlyArray<Pick<OrchestrationV2PendingBackgroundTask, "taskId">>,
565 retryExpired: boolean,
566): boolean {
567 if (request === null || request.threadKey !== threadKey || retryExpired) return false;
568 return request.retryAt === null || tasks.some((task) => request.taskIds.includes(task.taskId));
570​
571export function presentPendingBackgroundWork(
572 tasks: ReadonlyArray<OrchestrationV2PendingBackgroundTask>,
573): PendingBackgroundWorkPresentation | null {
574 if (tasks.length === 0) return null;
575 const waiting = backgroundWorkHoldsCompletion(tasks);
576 const items = tasks
577 .map((task): PendingBackgroundWorkItem => {
578 const description = task.description?.trim();
579 const label =
580 description === undefined
581 ? undefined
582 : task.kind === "subagent"
583 ? formatSubagentDisplayTitle(description).trim()
584 : task.kind === "command" || task.kind === "monitor"
585 ? commandDisplayText(description)
586 : description;
587 return {
588 taskId: task.taskId,
589 kind: task.kind,
590 label:
591 label === undefined || label.length === 0
592 ? BACKGROUND_WORK_KINDS[task.kind].singular
593 : label,
594 childThreadId: task.kind === "subagent" ? task.childThreadId : undefined,
595 };
596 })
597 // `map` returned a new array; Hermes has no `toSorted`.
598 .sort(
599 (left, right) =>
600 BACKGROUND_WORK_KINDS[left.kind].order - BACKGROUND_WORK_KINDS[right.kind].order,
601 );
602 const [only] = items;
603 if (items.length === 1 && only !== undefined) {
604 const noun = BACKGROUND_WORK_KINDS[only.kind].singular;
605 const named = only.label !== noun;
606 const title = named
607 ? `${waiting ? "Waiting" : "Running"} · ${only.label}`
608 : waiting
609 ? `Waiting on a ${noun}`
610 : `Running a ${noun}`;
611 return { title, items, waiting };
612 }
613 const counts = new Map<BackgroundWorkKind, number>();
614 for (const item of items) counts.set(item.kind, (counts.get(item.kind) ?? 0) + 1);
615 const groups = Array.from(counts, ([kind, count]) => {
616 const { singular, plural } = BACKGROUND_WORK_KINDS[kind];
617 return `${count} ${count === 1 ? singular : plural}`;
618 });
619 return { title: `${waiting ? "Waiting on" : "Running"} ${joinWithAnd(groups)}`, items, waiting };
621​
622export interface ProviderGoalPresentation {
623 readonly title: string;
624 readonly objective: string;
625 readonly usage: string | null;
626 readonly canResume: boolean;
628​
629const PROVIDER_GOAL_TITLES: Record<OrchestrationV2ProviderGoal["status"], string> = {
630 active: "Pursuing goal",
631 paused: "Goal paused",
632 blocked: "Goal blocked",
633 usage_limited: "Goal hit a usage limit",
634 budget_limited: "Goal reached its token budget",
635 complete: "Goal complete",
636};
637​
638function formatGoalTokens(tokens: number): string {
639 if (tokens < 1_000) return `${tokens}`;
640 const thousands = Math.round(tokens / 1_000);
641 if (thousands < 1_000) return `${thousands}k`;
642 return `${(tokens / 1_000_000).toFixed(1).replace(/\.0$/, "")}m`;
644​
645export function presentProviderGoal(
646 goal: OrchestrationV2ProviderGoal,
647 working: boolean,
648): ProviderGoalPresentation {
649 const usage: Array<string> = [];
650 if (goal.tokensUsed !== undefined && goal.tokensUsed > 0) {
651 usage.push(
652 goal.tokenBudget == null
653 ? `${formatGoalTokens(goal.tokensUsed)} tokens`
654 : `${formatGoalTokens(goal.tokensUsed)} / ${formatGoalTokens(goal.tokenBudget)} tokens`,
655 );
656 }
657 if (goal.timeUsedSeconds !== undefined && goal.timeUsedSeconds >= 60) {
658 usage.push(formatDuration(goal.timeUsedSeconds * 1_000));
659 }
660 if (goal.checks !== undefined && goal.checks > 0) {
661 usage.push(`${goal.checks} ${goal.checks === 1 ? "check" : "checks"}`);
662 }
663 return {
664 title: goal.status === "active" && !working ? "Goal set" : PROVIDER_GOAL_TITLES[goal.status],
665 objective: goal.objective,
666 usage: usage.length === 0 ? null : usage.join(" · "),
667 canResume: goal.status !== "active" && goal.status !== "complete",
668 };
670​
671export function notificationChildThreadId(
672 source: OrchestrationV2NotificationSource,
673): ThreadId | undefined {
674 switch (source.kind) {
675 case "subagent":
676 case "delegated_task":
677 return source.childThreadId;
678 case "command":
679 case "monitor":
680 case "background_task":
681 case "system":
682 return undefined;
683 default:
684 source satisfies never;
685 return undefined;
686 }