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