Open History to see the last commit
1import {
2 latestExecutedRun,
3 latestRootProviderFailure,
4 latestRootProviderFailureItem,
5 latestUnheldRun,
6 threadErrorSummary,
7 usageLimitRunPresentedAsLatest,
8} from "@t3tools/shared/orchestrationV2ThreadError";
9import {
10 isOrchestrationV2WorkActive,
11 isProviderNativeSubagentThread,
12 latestProviderTurnForAttempt,
13 PROVIDER_DISPLAY_NAMES,
14 type ModelSelection,
15 type ProviderDriverKind,
16 type ProviderInstanceId,
17 type OrchestrationV2NotificationSource,
18 type OrchestrationV2PendingBackgroundTask,
19 type OrchestrationV2ProviderGoal,
20 type OrchestrationV2ProviderSession,
21 type ProviderOptionDescriptor,
22 type ServerProvider,
23 type ServerProviderModel,
24 type OrchestrationV2ExecutionNode,
25 type OrchestrationV2LimitRecovery,
26 type OrchestrationV2ThreadProjection,
27 orchestrationV2RunWorkStartedAt,
28 type RunId,
29 type ThreadId,
30} from "@t3tools/contracts";
31import {
32 backgroundWorkHoldsCompletion,
33 derivePendingBackgroundWork,
34} from "@t3tools/shared/orchestrationV2PendingBackgroundWork";
35import {
36 DEFAULT_VARIANT_CHOICE_ID,
37 getModelSelectionStringOptionValue,
38 getProviderOptionCurrentLabel,
39 getProviderOptionStatedValue,
40 resolveSelectableModel,
41 withLegacyUltracodeEffort,
42} from "@t3tools/shared/model";
43import { unsentManualContinuationSource } from "@t3tools/shared/orchestrationV2ManualContinuation";
44import { formatDuration } from "@t3tools/shared/orchestrationTimingCopy";
45import * as DateTime from "effect/DateTime";
46
47import {
48 threadRuntimeIsActive,
49 type ThreadRunSummary,
50 type ThreadRuntimeSummary,
51 type ThreadStructure,
52 type ThreadStructureRuntime,
53 type ThreadStructureTurnItem,
54} from "./models.ts";
55import { commandDisplayText } from "../work-log/commandLabel.ts";
56import { formatSubagentDisplayTitle } from "./subagentDisplay.ts";
57import { mFallback, msg, plural, part, type Msg } from "gt-i18n";
58import { markedTextEnglish } from "../errors/translatable.ts";
59import type { M } from "gt-i18n";
60
61const ACTIVITY_RUN_STATUSES = new Set(["preparing", "starting", "running", "waiting"]);
62const INTERRUPTIBLE_RUN_STATUSES = new Set(["preparing", "starting", "running"]);
63// Preparing runs show their workspace setup instead.
64const PROVIDER_STARTING_RUN_STATUSES = new Set(["starting", "running"]);
65const LIVE_PROVIDER_SESSION_STATUSES = new Set(["ready", "running", "waiting"]);
66
67/** The startup a send to this instance waits on, or null when its session is live and idle. */
68export function pendingProviderStartup(
69 projection: ThreadStructure | null,
70 instanceId: ProviderInstanceId,
71): { readonly phase: string | undefined } | null {
72 const session = projection?.providerSessions.findLast(
73 (candidate) => candidate.providerInstanceId === instanceId,
74 );
75 const phase = projection === null ? undefined : startupPhaseFor(projection, session);
76 return phase !== undefined || sessionNeedsLaunch(session) ? { phase } : null;
77}
78
79function sessionNeedsLaunch(session: Pick<OrchestrationV2ProviderSession, "status"> | undefined) {
80 return session === undefined || !LIVE_PROVIDER_SESSION_STATUSES.has(session.status);
81}
82
83const EMPTY_EXTENSION_STATUSES: NonNullable<OrchestrationV2ProviderSession["extensionStatuses"]> =
84 [];
85
86/** Only the selected provider's current session can supply transient extension status. */
87export function deriveProviderExtensionStatuses(
88 projection:
89 | (Pick<ThreadStructure, "thread"> & {
90 readonly providerThreads: ReadonlyArray<
91 Pick<
92 ThreadStructure["providerThreads"][number],
93 "id" | "providerSessionId" | "providerInstanceId"
94 >
95 >;
96 readonly providerSessions: ReadonlyArray<
97 Pick<
98 OrchestrationV2ProviderSession,
99 "id" | "providerInstanceId" | "status" | "extensionStatuses"
100 >
101 >;
102 })
103 | null,
104) {
105 if (projection === null) return EMPTY_EXTENSION_STATUSES;
106 const instanceId = projection.thread.modelSelection.instanceId;
107 const activeThread = projection.providerThreads.find(
108 (thread) => thread.id === projection.thread.activeProviderThreadId,
109 );
110 if (activeThread !== undefined && activeThread.providerInstanceId !== instanceId)
111 return EMPTY_EXTENSION_STATUSES;
112 const session = projection.providerSessions.findLast(
113 (session) =>
114 session.providerInstanceId === instanceId &&
115 (activeThread === undefined || session.id === activeThread.providerSessionId),
116 );
117 return session === undefined || session.status === "stopped"
118 ? EMPTY_EXTENSION_STATUSES
119 : (session.extensionStatuses ?? EMPTY_EXTENSION_STATUSES);
120}
121
122function latestMatchingRun(
123 projection: ThreadStructure,
124 predicate: (run: OrchestrationV2ThreadProjection["runs"][number]) => boolean,
125): OrchestrationV2ThreadProjection["runs"][number] | null {
126 return projection.runs.reduce<OrchestrationV2ThreadProjection["runs"][number] | null>(
127 (latest, candidate) =>
128 predicate(candidate) && (latest === null || candidate.ordinal > latest.ordinal)
129 ? candidate
130 : latest,
131 null,
132 );
133}
134
135// Phases a provider can report while it prepares a turn; an unknown one keeps the plain label.
136function providerStartingPhase(phase: string | undefined, provider: string) {
137 switch (phase) {
138 case "plugins":
139 return msg`Loading ${{ provider }} plugins`;
140 case "mcp":
141 return msg`Starting ${{ provider }} MCP servers`;
142 case "hooks":
143 return msg`Loading ${{ provider }} hooks`;
144 case "skills":
145 return msg`Loading ${{ provider }} rules and skills`;
146 case "resume":
147 return msg`Resuming ${{ provider }} session`;
148 case "connecting":
149 return msg`Connecting to ${{ provider }}`;
150 default:
151 return msg`Starting ${{ provider }}`;
152 }
153}
154
155/** The instances a client knows, so a run names its provider before the provider session exists. */
156export type ProviderDrivers = ReadonlyArray<Pick<ServerProvider, "instanceId" | "driver">>;
157
158/** A provider that has not produced output yet: its logo, and the step it reports. */
159export function presentProviderStarting(input: {
160 readonly instanceId: ProviderInstanceId;
161 readonly driver: ProviderDriverKind | undefined;
162 readonly phase?: string | undefined;
163}): Pick<
164 ThreadRunSummary,
165 "providerStartingLabel" | "providerStartingLabelMsg" | "providerStarting"
166> {
167 const name = input.driver === undefined ? undefined : PROVIDER_DISPLAY_NAMES[input.driver];
168 const label =
169 name === undefined
170 ? msg({ context: "a provider is launching" })`Starting`
171 : providerStartingPhase(input.phase, name);
172 return {
173 providerStartingLabel: markedTextEnglish([label]),
174 providerStartingLabelMsg: label,
175 ...(input.driver === undefined
176 ? {}
177 : { providerStarting: { instanceId: input.instanceId, driver: input.driver } }),
178 };
179}
180
181// A session shared by several threads names the one thread its phase describes.
182function startupPhaseFor(
183 projection: ThreadStructure,
184 session: OrchestrationV2ProviderSession | undefined,
185) {
186 return session?.startupPhaseThreadId === undefined ||
187 session.startupPhaseThreadId === projection.thread.id
188 ? session?.startupPhase
189 : undefined;
190}
191
192function providerStarting(
193 run: OrchestrationV2ThreadProjection["runs"][number],
194 session: OrchestrationV2ProviderSession | undefined,
195 phase: string | undefined,
196 providers: ProviderDrivers | undefined,
197) {
198 return presentProviderStarting({
199 instanceId: run.providerInstanceId,
200 driver:
201 session?.driver ??
202 providers?.find((provider) => provider.instanceId === run.providerInstanceId)?.driver,
203 phase,
204 });
205}
206
207// A phase only describes a run that has not answered yet.
208function runHasProviderOutput(projection: ThreadStructure, runId: RunId) {
209 return projection.turnItems.some(
210 (item) => item.runId === runId && item.providerTurnId !== null && item.type !== "user_message",
211 );
212}
213
214function summarizeThreadRun(
215 projection: ThreadStructure,
216 run: OrchestrationV2ThreadProjection["runs"][number],
217 providers?: ProviderDrivers,
218): ThreadRunSummary {
219 const turnStatus = ACTIVITY_RUN_STATUSES.has(run.status)
220 ? latestProviderTurnForAttempt(projection.providerTurns, run.activeAttemptId)?.status
221 : undefined;
222 const session = projection.providerSessions.findLast(
223 (candidate) => candidate.providerInstanceId === run.providerInstanceId,
224 );
225 const phase = startupPhaseFor(projection, session);
226 return {
227 runId: run.id,
228 status: run.status,
229 requestedAt: DateTime.formatIso(run.requestedAt),
230 startedAt: run.startedAt === null ? null : DateTime.formatIso(run.startedAt),
231 completedAt: run.completedAt === null ? null : DateTime.formatIso(run.completedAt),
232 assistantMessageId:
233 projection.messages.findLast(
234 (message) => message.runId === run.id && message.role === "assistant",
235 )?.id ?? null,
236 // A run counts as running before its provider opens, which can take minutes. A live
237 // session reaches its turn at once unless it reports a slow step, and some providers
238 // keep reporting that step after their turn opens, until the first output.
239 ...(turnStatus === undefined
240 ? PROVIDER_STARTING_RUN_STATUSES.has(run.status) &&
241 (phase !== undefined || sessionNeedsLaunch(session))
242 ? providerStarting(run, session, phase, providers)
243 : {}
244 : turnStatus === "pending" || turnStatus === "running"
245 ? phase === undefined || runHasProviderOutput(projection, run.id)
246 ? {}
247 : providerStarting(run, session, phase, providers)
248 : { turnEnded: true }),
249 ...(run.sourcePlanRef === undefined ? {} : { sourcePlanRef: run.sourcePlanRef }),
250 };
251}
252
253function presentedUsageLimitRun(
254 projection: ThreadStructure,
255): OrchestrationV2ThreadProjection["runs"][number] | null {
256 const providerSession = projection.providerSessions.findLast(
257 (session) => session.providerInstanceId === projection.thread.providerInstanceId,
258 );
259 return usageLimitRunPresentedAsLatest(
260 projection.runs,
261 projection.turnItems,
262 providerSession?.lastError ?? null,
263 );
264}
265
266function presentedLatestRun(
267 projection: ThreadStructure,
268): OrchestrationV2ThreadProjection["runs"][number] | null {
269 return presentedUsageLimitRun(projection) ?? latestUnheldRun(projection.runs);
270}
271
272export function deriveLatestThreadRun(projection: ThreadStructure): ThreadRunSummary | null {
273 const run = presentedLatestRun(projection);
274 return run === null ? null : summarizeThreadRun(projection, run);
275}
276
277export function deriveThreadActivityRun(
278 projection: ThreadStructure,
279 providers?: ProviderDrivers,
280): ThreadRunSummary | null {
281 const run =
282 latestMatchingRun(projection, (candidate) => ACTIVITY_RUN_STATUSES.has(candidate.status)) ??
283 presentedLatestRun(projection);
284 return run === null ? null : summarizeThreadRun(projection, run, providers);
285}
286
287/**
288 * Provider-native subagent threads never get app runs: their work is a runless
289 * root turn whose status follows the subagent.
290 */
291export function deriveRunlessWorkStartedAt(projection: ThreadStructure): string | null {
292 const status = deriveProviderSubagentStatus(projection);
293 return status !== null && isOrchestrationV2WorkActive(status.status) ? status.startedAt : null;
294}
295
296export interface ProviderSubagentStatus {
297 readonly status: OrchestrationV2ExecutionNode["status"];
298 readonly startedAt: string | null;
299 readonly completedAt: string | null;
300}
301
302export function deriveProviderSubagentStatus(
303 projection: ThreadStructure,
304): ProviderSubagentStatus | null {
305 if (!isProviderNativeSubagentThread(projection.thread)) return null;
306 const node = projection.nodes.findLast(
307 (candidate) => candidate.kind === "root_turn" && candidate.runId === null,
308 );
309 if (node === undefined) return null;
310 return {
311 status: node.status,
312 startedAt: node.startedAt === null ? null : DateTime.formatIso(node.startedAt),
313 completedAt: node.completedAt === null ? null : DateTime.formatIso(node.completedAt),
314 };
315}
316
317export function deriveReportedModelSelection(projection: ThreadStructure): ModelSelection | null {
318 const providerThread = projection.providerThreads.find(
319 (candidate) =>
320 candidate.id === projection.thread.activeProviderThreadId &&
321 candidate.providerInstanceId === projection.thread.modelSelection.instanceId,
322 );
323 return providerThread?.nativeMetadata?.modelSelection ?? null;
324}
325
326export const REASONING_EFFORT_OPTION_IDS: ReadonlyArray<string> = [
327 "reasoningEffort",
328 "effort",
329 "reasoning",
330 "variant",
331 "reasoning_effort",
332 "thinking_level",
333 "thought_level",
334];
335
336export function formatModelSelectionEffort(
337 selection: ModelSelection,
338 models: ReadonlyArray<ServerProviderModel> = [],
339 reportedSelection?: ModelSelection | null,
340): string | null {
341 const caps = models.find((model) => model.slug === selection.model)?.capabilities;
342 if (!caps) return null;
343 const options = withLegacyUltracodeEffort(caps.optionDescriptors, selection.options);
344 const current = options ? { ...selection, options } : selection;
345 const selectDescriptors = (caps.optionDescriptors ?? []).filter(
346 (candidate) => candidate.type === "select",
347 );
348 const reasoningDescriptors = [
349 ...selectDescriptors.filter((candidate) => candidate.role === "reasoning"),
350 ...REASONING_EFFORT_OPTION_IDS.flatMap((id) => {
351 const descriptor = selectDescriptors.find(
352 (candidate) => candidate.id === id && candidate.role !== "reasoning",
353 );
354 return descriptor ? [descriptor] : [];
355 }),
356 ];
357 for (const descriptor of reasoningDescriptors) {
358 const value = getProviderOptionStatedValue(descriptor.id, current, reportedSelection);
359 if (value === undefined && descriptor.id !== "variant") continue;
360 if (typeof value === "boolean") continue;
361 // Bypass picker normalization so an obsolete choice cannot become a catalog default.
362 const label = getProviderOptionCurrentLabel(
363 { ...descriptor, currentValue: value },
364 current,
365 reportedSelection,
366 );
367 if (label) return label;
368 }
369 return null;
370}
371
372/** A reported model the picker catalog does not know, such as `claude-opus-5[1m]`, keeps its raw effort. */
373export function formatSubagentEffort(input: {
374 readonly modelSlug: string | null;
375 readonly modelSelection: ModelSelection | undefined;
376 readonly provider: Pick<ServerProvider, "driver" | "models"> | undefined;
377}): string | null {
378 const { modelSlug, modelSelection: selection, provider } = input;
379 if (!provider || !selection || !modelSlug) return null;
380 const selectionSlug =
381 resolveSelectableModel(provider.driver, selection.model, provider.models) ??
382 selection.model.trim();
383 if (selectionSlug !== modelSlug) return null;
384 if (provider.models.some((model) => model.slug === modelSlug)) {
385 return formatModelSelectionEffort({ ...selection, model: modelSlug }, provider.models);
386 }
387 return readSelectedEffortValue(selection);
388}
389
390/** The raw saved effort, preferring the option the model marks as its reasoning control. */
391export function readSelectedEffortValue(
392 selection: ModelSelection | undefined,
393 descriptors: ReadonlyArray<ProviderOptionDescriptor> = [],
394): string | null {
395 const ids = [
396 ...descriptors.flatMap((descriptor) =>
397 descriptor.type === "select" && descriptor.role === "reasoning" ? [descriptor.id] : [],
398 ),
399 ...REASONING_EFFORT_OPTION_IDS,
400 ];
401 return (
402 ids
403 .map((id) => getModelSelectionStringOptionValue(selection, id))
404 .find((value) => value && value !== DEFAULT_VARIANT_CHOICE_ID) ?? null
405 );
406}
407
408const SUBAGENT_STATUS_LABELS: Record<OrchestrationV2ExecutionNode["status"], string> = {
409 idle: msg("Idle"),
410 pending: msg("Working"),
411 running: msg("Working"),
412 waiting: msg("Waiting"),
413 completed: msg("Completed"),
414 interrupted: msg("Interrupted"),
415 failed: msg("Failed"),
416 cancelled: msg("Cancelled"),
417 rolled_back: msg("Cancelled"),
418};
419
420export function formatProviderSubagentStatus(
421 status: ProviderSubagentStatus | null,
422 nowMs: number,
423 resolve: M = mFallback,
424): string {
425 if (status === null) return resolve(msg("Starting"));
426 const label = resolve(SUBAGENT_STATUS_LABELS[status.status]);
427 const live = isOrchestrationV2WorkActive(status.status);
428 if (!live && status.status !== "completed") return label;
429 const start = status.startedAt === null ? Number.NaN : Date.parse(status.startedAt);
430 const end = live
431 ? nowMs
432 : status.completedAt === null
433 ? Number.NaN
434 : Date.parse(status.completedAt);
435 if (!Number.isFinite(start) || !Number.isFinite(end)) return label;
436 const elapsed = formatDuration(
437 Math.max(1_000, Math.floor((end - start) / 1_000) * 1_000),
438 resolve,
439 );
440 return live
441 ? resolve(msg`${{ label }} ${{ elapsed }}`)
442 : resolve(msg`${{ label }} in ${{ elapsed }}`);
443}
444
445/** The run a manual continuation resumes; the server holds the queue until it does. */
446export function deriveResumableRunId(
447 projection: Pick<
448 ThreadStructure,
449 "runs" | "turnItems" | "attempts" | "providerTurns" | "providerThreads" | "providerSessions"
450 >,
451 runtime: Pick<ThreadStructureRuntime, "lastErrorClass"> | null,
452): RunId | null {
453 const run = latestExecutedRun(projection.runs);
454 const resumable =
455 run?.status === "interrupted" ||
456 (run?.status === "failed" &&
457 runtime?.lastErrorClass === "usage_limit" &&
458 latestRootProviderFailure(run, projection.turnItems)?.class === "usage_limit");
459 if (!resumable) return null;
460 // Without native resume the server can only resend a message the provider never received.
461 if (
462 runProviderSession(projection, run)?.capabilities.turns.supportsNativeResume === false &&
463 unsentManualContinuationSource({ manualContinuationOfRunId: run.id }, projection) === undefined
464 ) {
465 return null;
466 }
467 return run.id;
468}
469
470function runProviderSession(
471 projection: Pick<ThreadStructure, "providerThreads" | "providerSessions">,
472 run: ThreadStructure["runs"][number],
473) {
474 const sessionId = projection.providerThreads.find(
475 (thread) => thread.id === run.providerThreadId,
476 )?.providerSessionId;
477 return sessionId == null
478 ? projection.providerSessions.findLast(
479 (session) => session.providerInstanceId === run.providerInstanceId,
480 )
481 : projection.providerSessions.find((session) => session.id === sessionId);
482}
483
484/**
485 * Whether Resume can start: the run's continuation, else the held queue. The server refuses that
486 * continuation while any request is pending, so the queue must not be released in its place.
487 */
488export function canResumeThread(
489 projection: Pick<ThreadStructure, "runtimeRequests">,
490 resumableRunId: RunId | null,
491 queueHeld: boolean,
492): boolean {
493 if (resumableRunId === null) return queueHeld;
494 return !projection.runtimeRequests.some((request) => request.status === "pending");
495}
496
497export function deriveThreadRuntime(
498 projection: ThreadStructure & Pick<OrchestrationV2ThreadProjection, "updatedAt">,
499): ThreadRuntimeSummary | null {
500 const runtime = deriveThreadStructureRuntime(projection);
501 return runtime === null
502 ? null
503 : { ...runtime, updatedAt: DateTime.formatIso(projection.updatedAt) };
504}
505
506/** The runtime summary a thread's structure determines: all of it but `updatedAt`. */
507export function deriveThreadStructureRuntime(
508 projection: ThreadStructure,
509): ThreadStructureRuntime | null {
510 const latestRun = deriveLatestThreadRun(projection);
511 const providerSession = projection.providerSessions.findLast(
512 (session) => session.providerInstanceId === projection.thread.providerInstanceId,
513 );
514 const usageLimitedRun = presentedUsageLimitRun(projection);
515 const latestRunProjection = presentedLatestRun(projection);
516 const activityRun = deriveThreadActivityRun(projection);
517 const liveActivityRun = latestMatchingRun(projection, (run) =>
518 ACTIVITY_RUN_STATUSES.has(run.status),
519 );
520 const backgroundWorkHoldsRun = backgroundWorkHoldsCompletion(
521 derivePendingBackgroundWork({
522 latestRun: latestRunProjection,
523 providerThreads: projection.providerThreads,
524 turnItems: projection.turnItems,
525 activeProviderThreadId: projection.thread.activeProviderThreadId,
526 runs: projection.runs,
527 pullRequests: projection.thread.pullRequests,
528 }),
529 );
530 // A pull request watch can hold a thread that never ran.
531 if (latestRun === null && !backgroundWorkHoldsRun) return null;
532 const activeRunId =
533 latestMatchingRun(projection, (run) => INTERRUPTIBLE_RUN_STATUSES.has(run.status))?.id ?? null;
534 const failureItem = latestRootProviderFailureItem(latestRunProjection, projection.turnItems);
535 const sessionError = providerSession?.lastError ?? null;
536 return {
537 status: usageLimitedRun
538 ? "failed"
539 : backgroundWorkHoldsRun && latestRunProjection?.status !== "failed"
540 ? "idle"
541 : (activityRun?.status ?? "idle"),
542 activeRunId,
543 activityStartedAt:
544 liveActivityRun === null
545 ? null
546 : DateTime.formatIso(orchestrationV2RunWorkStartedAt(liveActivityRun)),
547 providerInstanceId: projection.thread.providerInstanceId,
548 providerName: providerSession?.driver ?? null,
549 ...threadErrorSummary(failureItem?.failure ?? null, sessionError),
550 lastErrorSource: threadErrorSource(failureItem, sessionError, projection),
551 };
552}
553
554const isoOrEmpty = (at: DateTime.Utc | null) => (at === null ? "" : DateTime.formatIso(at));
555
556/**
557 * A session error belongs to the latest ended run, as that run's failure when the text matches.
558 * Session timestamps are not used: providers rewrite them on unrelated updates.
559 */
560function threadErrorSource(
561 failureItem: ReturnType<typeof latestRootProviderFailureItem>,
562 sessionError: string | null,
563 projection: Pick<ThreadStructure, "runs" | "turnItems">,
564): string | null {
565 const itemSource = (item: NonNullable<typeof failureItem>) =>
566 `${item.id}@${isoOrEmpty(item.completedAt)}`;
567 if (
568 failureItem !== null &&
569 (sessionError === null || sessionError === failureItem.failure.message)
570 ) {
571 return itemSource(failureItem);
572 }
573 if (sessionError === null) return null;
574 let ended: ThreadStructure["runs"][number] | null = null;
575 for (const run of projection.runs) {
576 if (run.status !== "failed" && run.status !== "completed") continue;
577 if (ended === null || run.ordinal > ended.ordinal) ended = run;
578 }
579 if (ended === null) return null;
580 const endedFailure =
581 failureItem?.runId === ended.id
582 ? failureItem
583 : latestRootProviderFailureItem(ended, projection.turnItems);
584 return endedFailure?.failure.message === sessionError
585 ? itemSource(endedFailure)
586 : `${ended.id}@${isoOrEmpty(ended.completedAt)}`;
587}
588
589export interface UsageLimitNoticeRows {
590 readonly itemIds: ReadonlySet<ThreadStructureTurnItem["id"]>;
591 /** Hidden only when its text reads as the provider's limit message; see PROVIDER_LIMIT_NOTICE. */
592 readonly providerNoticeItemId: ThreadStructureTurnItem["id"] | null;
593}
594
595// Claude Code's own limit messages, such as "You've hit your 5-hour limit · resets 7:10am".
596const PROVIDER_LIMIT_NOTICE =
597 /^(?: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;
598
599/**
600 * The timeline rows that repeat a usage-limit pause while its recovery notice shows: the run's
601 * limit failure, Claude's pause notices, and the provider's own limit message. They return to
602 * history once another run executes.
603 */
604export function deriveUsageLimitNoticeRows(
605 projection: ThreadStructure,
606): UsageLimitNoticeRows | null {
607 const runtime = deriveThreadStructureRuntime(projection);
608 const run = presentedLatestRun(projection);
609 if (runtime?.status !== "failed" || runtime.lastErrorClass !== "usage_limit" || run === null) {
610 return null;
611 }
612 const failure = latestRootProviderFailure(run, projection.turnItems);
613 const itemIds = new Set<ThreadStructureTurnItem["id"]>();
614 let failedProviderTurnId: ThreadStructureTurnItem["providerTurnId"] = null;
615 for (const item of projection.turnItems) {
616 if (item.runId !== run.id) continue;
617 if (
618 item.type === "error" &&
619 item.status === "failed" &&
620 item.nodeId === run.rootNodeId &&
621 item.failure.class === "usage_limit"
622 ) {
623 itemIds.add(item.id);
624 if (item.failure === failure) failedProviderTurnId = item.providerTurnId;
625 }
626 }
627 let providerNotice: ThreadStructureTurnItem | null = null;
628 if (failedProviderTurnId !== null) {
629 for (const item of projection.turnItems) {
630 if (item.runId !== run.id || item.providerTurnId !== failedProviderTurnId) continue;
631 if (
632 item.type === "system_notice" &&
633 item.nodeId === run.rootNodeId &&
634 item.parentItemId === null &&
635 item.nativeItemRef?.driver === "claudeAgent" &&
636 item.nativeItemRef.nativeId?.startsWith(`usage-limit:${failedProviderTurnId}:`) === true
637 ) {
638 itemIds.add(item.id);
639 }
640 if (
641 item.type === "assistant_message" &&
642 item.parentItemId === null &&
643 (providerNotice === null || item.ordinal > providerNotice.ordinal)
644 ) {
645 providerNotice = item;
646 }
647 }
648 }
649 return { itemIds, providerNoticeItemId: providerNotice?.id ?? null };
650}
651
652export function withoutUsageLimitNoticeRows<
653 Row extends OrchestrationV2ThreadProjection["visibleTurnItems"][number],
654>(rows: ReadonlyArray<Row>, notice: UsageLimitNoticeRows | null): ReadonlyArray<Row> {
655 if (notice === null) return rows;
656 const hidden = ({ item }: Row) =>
657 notice.itemIds.has(item.id) ||
658 (item.id === notice.providerNoticeItemId &&
659 item.type === "assistant_message" &&
660 PROVIDER_LIMIT_NOTICE.test(item.text.trim()));
661 return rows.some(hidden) ? rows.filter((row) => !hidden(row)) : rows;
662}
663
664/** Whether a usage-limit recovery holds the thread's snooze, so its notice offers Wake now. */
665export function limitRecoveryOwnsSnooze(input: {
666 readonly runId: RunId | null | undefined;
667 readonly resetAt: string | null | undefined;
668 readonly recovery: OrchestrationV2LimitRecovery | null | undefined;
669 readonly snoozedUntil: string | null | undefined;
670}): boolean {
671 const { runId, resetAt, recovery, snoozedUntil } = input;
672 return (
673 recovery?.snooze === true &&
674 runId != null &&
675 recovery.runId === runId &&
676 resetAt != null &&
677 recovery.resetAt === resetAt &&
678 snoozedUntil != null &&
679 Date.parse(snoozedUntil) === Date.parse(resetAt)
680 );
681}
682
683export function threadRuntimeHasInterruptibleRun(
684 runtime: ThreadStructureRuntime | null | undefined,
685): boolean {
686 return (
687 threadRuntimeIsActive(runtime) &&
688 runtime?.activeRunId !== null &&
689 runtime?.activeRunId !== undefined
690 );
691}
692
693type BackgroundWorkKind = OrchestrationV2PendingBackgroundTask["kind"];
694
695const BACKGROUND_WORK_KINDS: Record<
696 BackgroundWorkKind,
697 {
698 readonly order: number;
699 readonly singular: string;
700 readonly count: (values: { count: number }) => string | Msg;
701 }
702> = {
703 subagent: {
704 order: 0,
705 singular: msg("subagent"),
706 count: ({ count }: { count: number }) =>
707 msg`${plural(
708 { count },
709 {
710 one: part`${{ count }} subagent`,
711 other: part`${{ count }} subagents`,
712 },
713 )}`,
714 },
715 command: {
716 order: 1,
717 singular: msg("command"),
718 count: ({ count }: { count: number }) =>
719 msg`${plural(
720 { count },
721 {
722 one: part`${{ count }} command`,
723 other: part`${{ count }} commands`,
724 },
725 )}`,
726 },
727 monitor: {
728 order: 2,
729 singular: msg("monitor"),
730 count: ({ count }: { count: number }) =>
731 msg`${plural(
732 { count },
733 {
734 one: part`${{ count }} monitor`,
735 other: part`${{ count }} monitors`,
736 },
737 )}`,
738 },
739 background_task: {
740 order: 3,
741 singular: msg("background task"),
742 count: ({ count }: { count: number }) =>
743 msg`${plural(
744 { count },
745 {
746 one: part`${{ count }} background task`,
747 other: part`${{ count }} background tasks`,
748 },
749 )}`,
750 },
751};
752
753export interface RunStopPresentation {
754 /** `unresponsive`: the provider did not confirm the stop in time, so Force stop is offered. */
755 readonly state: "stopping" | "unresponsive";
756 readonly runId: ThreadStructure["runs"][number]["id"];
757 readonly requestedAt: string;
758 /** The run already ended; the Stop targeted its background work. */
759 readonly background: boolean;
760}
761
762/**
763 * A Stop the provider has not finished yet. It stays `stopping` while the agent winds down,
764 * since some providers confirm the request before the turn actually ends. On a run that
765 * already ended, only an unanswered Stop of its background work counts.
766 */
767export function presentRunStop(
768 projection: Pick<ThreadStructure, "runs" | "turnItems">,
769): RunStopPresentation | null {
770 let active: ThreadStructure["runs"][number] | null = null;
771 let latest: ThreadStructure["runs"][number] | null = null;
772 for (const candidate of projection.runs) {
773 // Queued follow-ups never ran, so they hold no Stop of their own.
774 if (candidate.status !== "queued" && candidate.ordinal > (latest?.ordinal ?? -1))
775 latest = candidate;
776 if (
777 INTERRUPTIBLE_RUN_STATUSES.has(candidate.status) &&
778 candidate.ordinal > (active?.ordinal ?? -1)
779 )
780 active = candidate;
781 }
782 const run = active ?? latest;
783 if (run === null) return null;
784 let request:
785 | Extract<ThreadStructure["turnItems"][number], { type: "run_interrupt_request" }>
786 | undefined;
787 for (const item of projection.turnItems) {
788 if (item.runId !== run.id || item.status === "cancelled") continue;
789 if (item.type === "run_interrupt_result") return null;
790 if (item.type === "run_interrupt_request") request = item;
791 }
792 if (request === undefined || (active === null && request.unresponsiveAt === undefined))
793 return null;
794 return {
795 state: request.unresponsiveAt === undefined ? "stopping" : "unresponsive",
796 runId: run.id,
797 requestedAt: DateTime.formatIso(request.startedAt ?? request.updatedAt),
798 background: active === null,
799 };
800}
801
802export interface PendingBackgroundWorkItem {
803 readonly taskId: string;
804 readonly kind: BackgroundWorkKind;
805 readonly label: string;
806 readonly childThreadId: ThreadId | undefined;
807}
808
809export interface PendingBackgroundWorkPresentation {
810 readonly title: string;
811 readonly items: ReadonlyArray<PendingBackgroundWorkItem>;
812 readonly waiting: boolean;
813}
814
815function joinWithAnd(parts: ReadonlyArray<string>, resolve: M): string {
816 if (parts.length <= 1) return parts.join("");
817 return resolve(msg`${{ items: parts.slice(0, -1).join(", ") }} and ${{ last: parts.at(-1)! }}`);
818}
819
820// The Claude adapter forces a stuck query closed after 10 seconds.
821export const BACKGROUND_WORK_STOP_RETRY_AFTER_MS = 10_000;
822
823export interface BackgroundWorkStopRequest {
824 readonly threadKey: string;
825 readonly taskIds: ReadonlyArray<string>;
826 readonly retryAt: number | null;
827}
828
829/** Acceptance does not end the tasks, so an accepted Stop stays pending while they are listed. */
830export function isBackgroundWorkStopPending(
831 request: BackgroundWorkStopRequest | null,
832 threadKey: string,
833 tasks: ReadonlyArray<Pick<OrchestrationV2PendingBackgroundTask, "taskId">>,
834 retryExpired: boolean,
835): boolean {
836 if (request === null || request.threadKey !== threadKey || retryExpired) return false;
837 return request.retryAt === null || tasks.some((task) => request.taskIds.includes(task.taskId));
838}
839
840export function presentPendingBackgroundWork(
841 tasks: ReadonlyArray<OrchestrationV2PendingBackgroundTask>,
842 resolve: M = mFallback,
843): PendingBackgroundWorkPresentation | null {
844 if (tasks.length === 0) return null;
845 const waiting = backgroundWorkHoldsCompletion(tasks);
846 const items = tasks
847 .map((task): PendingBackgroundWorkItem => {
848 const description = task.description?.trim();
849 const label =
850 description === undefined
851 ? undefined
852 : task.kind === "subagent"
853 ? formatSubagentDisplayTitle(description).trim()
854 : task.kind === "command" || task.kind === "monitor"
855 ? commandDisplayText(description)
856 : description;
857 return {
858 taskId: task.taskId,
859 kind: task.kind,
860 label:
861 label === undefined || label.length === 0
862 ? resolve(BACKGROUND_WORK_KINDS[task.kind].singular)
863 : label,
864 childThreadId: task.kind === "subagent" ? task.childThreadId : undefined,
865 };
866 })
867 // `map` returned a new array; Hermes has no `toSorted`.
868 .sort(
869 (left, right) =>
870 BACKGROUND_WORK_KINDS[left.kind].order - BACKGROUND_WORK_KINDS[right.kind].order,
871 );
872 const [only] = items;
873 if (items.length === 1 && only !== undefined) {
874 const noun = resolve(BACKGROUND_WORK_KINDS[only.kind].singular);
875 const named = only.label !== noun;
876 const title = named
877 ? waiting
878 ? resolve(msg`Waiting · ${{ label: only.label }}`)
879 : resolve(msg`Running · ${{ label: only.label }}`)
880 : backgroundWorkSingleTitle(only.kind, waiting, resolve);
881 return { title, items, waiting };
882 }
883 const counts = new Map<BackgroundWorkKind, number>();
884 for (const item of items) counts.set(item.kind, (counts.get(item.kind) ?? 0) + 1);
885 const groups = joinWithAnd(
886 Array.from(counts, ([kind, count]) => resolve(BACKGROUND_WORK_KINDS[kind].count({ count }))),
887 resolve,
888 );
889 return {
890 title: waiting ? resolve(msg`Waiting on ${{ groups }}`) : resolve(msg`Running ${{ groups }}`),
891 items,
892 waiting,
893 };
894}
895
896function backgroundWorkSingleTitle(kind: BackgroundWorkKind, waiting: boolean, resolve: M): string {
897 switch (kind) {
898 case "subagent":
899 return waiting ? resolve(msg("Waiting on a subagent")) : resolve(msg("Running a subagent"));
900 case "command":
901 return waiting ? resolve(msg("Waiting on a command")) : resolve(msg("Running a command"));
902 case "monitor":
903 return waiting ? resolve(msg("Waiting on a monitor")) : resolve(msg("Running a monitor"));
904 case "background_task":
905 return waiting
906 ? resolve(msg("Waiting on a background task"))
907 : resolve(msg("Running a background task"));
908 }
909}
910
911export interface ProviderGoalPresentation {
912 readonly title: string;
913 readonly objective: string;
914 readonly usage: string | null;
915 readonly canResume: boolean;
916}
917
918const PROVIDER_GOAL_TITLES: Record<OrchestrationV2ProviderGoal["status"], string> = {
919 active: msg("Pursuing goal"),
920 paused: msg("Goal paused"),
921 blocked: msg("Goal blocked"),
922 usage_limited: msg("Goal hit a usage limit"),
923 budget_limited: msg("Goal reached its token budget"),
924 complete: msg("Goal complete"),
925};
926
927function formatGoalTokens(tokens: number): string {
928 if (tokens < 1_000) return `${tokens}`;
929 const thousands = Math.round(tokens / 1_000);
930 if (thousands < 1_000) return `${thousands}k`;
931 return `${(tokens / 1_000_000).toFixed(1).replace(/\.0$/, "")}m`;
932}
933
934export function presentProviderGoal(
935 goal: OrchestrationV2ProviderGoal,
936 working: boolean,
937 resolve: M = mFallback,
938): ProviderGoalPresentation {
939 const usage: Array<string> = [];
940 if (goal.tokensUsed !== undefined && goal.tokensUsed > 0) {
941 usage.push(
942 goal.tokenBudget == null
943 ? resolve(msg`${{ used: formatGoalTokens(goal.tokensUsed) }} tokens`)
944 : resolve(
945 msg`${{ used: formatGoalTokens(goal.tokensUsed) }} / ${{ budget: formatGoalTokens(goal.tokenBudget) }} tokens`,
946 ),
947 );
948 }
949 if (goal.timeUsedSeconds !== undefined && goal.timeUsedSeconds >= 60) {
950 usage.push(formatDuration(goal.timeUsedSeconds * 1_000, resolve));
951 }
952 if (goal.checks !== undefined && goal.checks > 0) {
953 usage.push(
954 resolve(
955 msg`${plural(
956 { count: goal.checks },
957 {
958 one: part`${{ count: goal.checks }} check`,
959 other: part`${{ count: goal.checks }} checks`,
960 },
961 )}`,
962 ),
963 );
964 }
965 return {
966 title:
967 goal.status === "active" && !working
968 ? resolve(msg("Goal set"))
969 : resolve(PROVIDER_GOAL_TITLES[goal.status]),
970 objective: goal.objective,
971 usage: usage.length === 0 ? null : usage.join(" · "),
972 canResume: goal.status !== "active" && goal.status !== "complete",
973 };
974}
975
976export function notificationChildThreadId(
977 source: OrchestrationV2NotificationSource,
978): ThreadId | undefined {
979 switch (source.kind) {
980 case "subagent":
981 case "delegated_task":
982 return source.childThreadId;
983 case "command":
984 case "monitor":
985 case "background_task":
986 case "system":
987 return undefined;
988 default:
989 source satisfies never;
990 return undefined;
991 }
992}