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 } from "gt-i18n";
58import { markedTextEnglish } from "../errors/translatable.ts";
59import type { MFunctionType } from "gt-i18n/types";
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", { provider });
140 case "mcp":
141 return msg("Starting {provider} MCP servers", { provider });
142 case "hooks":
143 return msg("Loading {provider} hooks", { provider });
144 case "skills":
145 return msg("Loading {provider} rules and skills", { provider });
146 case "resume":
147 return msg("Resuming {provider} session", { provider });
148 case "connecting":
149 return msg("Connecting to {provider}", { provider });
150 default:
151 return msg("Starting {provider}", { 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("Starting", { $context: "a provider is launching" })
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: MFunctionType = 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}", { label, elapsed }))
442 : resolve(msg("{label} in {elapsed}", { label, 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 { readonly order: number; readonly singular: string; readonly count: string }
698> = {
699 subagent: {
700 order: 0,
701 singular: msg("subagent"),
702 count: msg("{count, plural, one {{count} subagent} other {{count} subagents}}"),
703 },
704 command: {
705 order: 1,
706 singular: msg("command"),
707 count: msg("{count, plural, one {{count} command} other {{count} commands}}"),
708 },
709 monitor: {
710 order: 2,
711 singular: msg("monitor"),
712 count: msg("{count, plural, one {{count} monitor} other {{count} monitors}}"),
713 },
714 background_task: {
715 order: 3,
716 singular: msg("background task"),
717 count: msg("{count, plural, one {{count} background task} other {{count} background tasks}}"),
718 },
719};
720
721export interface RunStopPresentation {
722 /** `unresponsive`: the provider did not confirm the stop in time, so Force stop is offered. */
723 readonly state: "stopping" | "unresponsive";
724 readonly runId: ThreadStructure["runs"][number]["id"];
725 readonly requestedAt: string;
726 /** The run already ended; the Stop targeted its background work. */
727 readonly background: boolean;
728}
729
730/**
731 * A Stop the provider has not finished yet. It stays `stopping` while the agent winds down,
732 * since some providers confirm the request before the turn actually ends. On a run that
733 * already ended, only an unanswered Stop of its background work counts.
734 */
735export function presentRunStop(
736 projection: Pick<ThreadStructure, "runs" | "turnItems">,
737): RunStopPresentation | null {
738 let active: ThreadStructure["runs"][number] | null = null;
739 let latest: ThreadStructure["runs"][number] | null = null;
740 for (const candidate of projection.runs) {
741 // Queued follow-ups never ran, so they hold no Stop of their own.
742 if (candidate.status !== "queued" && candidate.ordinal > (latest?.ordinal ?? -1))
743 latest = candidate;
744 if (
745 INTERRUPTIBLE_RUN_STATUSES.has(candidate.status) &&
746 candidate.ordinal > (active?.ordinal ?? -1)
747 )
748 active = candidate;
749 }
750 const run = active ?? latest;
751 if (run === null) return null;
752 let request:
753 | Extract<ThreadStructure["turnItems"][number], { type: "run_interrupt_request" }>
754 | undefined;
755 for (const item of projection.turnItems) {
756 if (item.runId !== run.id || item.status === "cancelled") continue;
757 if (item.type === "run_interrupt_result") return null;
758 if (item.type === "run_interrupt_request") request = item;
759 }
760 if (request === undefined || (active === null && request.unresponsiveAt === undefined))
761 return null;
762 return {
763 state: request.unresponsiveAt === undefined ? "stopping" : "unresponsive",
764 runId: run.id,
765 requestedAt: DateTime.formatIso(request.startedAt ?? request.updatedAt),
766 background: active === null,
767 };
768}
769
770export interface PendingBackgroundWorkItem {
771 readonly taskId: string;
772 readonly kind: BackgroundWorkKind;
773 readonly label: string;
774 readonly childThreadId: ThreadId | undefined;
775}
776
777export interface PendingBackgroundWorkPresentation {
778 readonly title: string;
779 readonly items: ReadonlyArray<PendingBackgroundWorkItem>;
780 readonly waiting: boolean;
781}
782
783function joinWithAnd(parts: ReadonlyArray<string>, resolve: MFunctionType): string {
784 if (parts.length <= 1) return parts.join("");
785 return resolve(
786 msg("{items} and {last}", { items: parts.slice(0, -1).join(", "), last: parts.at(-1)! }),
787 );
788}
789
790// The Claude adapter forces a stuck query closed after 10 seconds.
791export const BACKGROUND_WORK_STOP_RETRY_AFTER_MS = 10_000;
792
793export interface BackgroundWorkStopRequest {
794 readonly threadKey: string;
795 readonly taskIds: ReadonlyArray<string>;
796 readonly retryAt: number | null;
797}
798
799/** Acceptance does not end the tasks, so an accepted Stop stays pending while they are listed. */
800export function isBackgroundWorkStopPending(
801 request: BackgroundWorkStopRequest | null,
802 threadKey: string,
803 tasks: ReadonlyArray<Pick<OrchestrationV2PendingBackgroundTask, "taskId">>,
804 retryExpired: boolean,
805): boolean {
806 if (request === null || request.threadKey !== threadKey || retryExpired) return false;
807 return request.retryAt === null || tasks.some((task) => request.taskIds.includes(task.taskId));
808}
809
810export function presentPendingBackgroundWork(
811 tasks: ReadonlyArray<OrchestrationV2PendingBackgroundTask>,
812 resolve: MFunctionType = mFallback,
813): PendingBackgroundWorkPresentation | null {
814 if (tasks.length === 0) return null;
815 const waiting = backgroundWorkHoldsCompletion(tasks);
816 const items = tasks
817 .map((task): PendingBackgroundWorkItem => {
818 const description = task.description?.trim();
819 const label =
820 description === undefined
821 ? undefined
822 : task.kind === "subagent"
823 ? formatSubagentDisplayTitle(description).trim()
824 : task.kind === "command" || task.kind === "monitor"
825 ? commandDisplayText(description)
826 : description;
827 return {
828 taskId: task.taskId,
829 kind: task.kind,
830 label:
831 label === undefined || label.length === 0
832 ? resolve(BACKGROUND_WORK_KINDS[task.kind].singular)
833 : label,
834 childThreadId: task.kind === "subagent" ? task.childThreadId : undefined,
835 };
836 })
837 // `map` returned a new array; Hermes has no `toSorted`.
838 .sort(
839 (left, right) =>
840 BACKGROUND_WORK_KINDS[left.kind].order - BACKGROUND_WORK_KINDS[right.kind].order,
841 );
842 const [only] = items;
843 if (items.length === 1 && only !== undefined) {
844 const noun = resolve(BACKGROUND_WORK_KINDS[only.kind].singular);
845 const named = only.label !== noun;
846 const title = named
847 ? waiting
848 ? resolve(msg("Waiting · {label}", { label: only.label }))
849 : resolve(msg("Running · {label}", { label: only.label }))
850 : backgroundWorkSingleTitle(only.kind, waiting, resolve);
851 return { title, items, waiting };
852 }
853 const counts = new Map<BackgroundWorkKind, number>();
854 for (const item of items) counts.set(item.kind, (counts.get(item.kind) ?? 0) + 1);
855 const groups = joinWithAnd(
856 Array.from(counts, ([kind, count]) => resolve(BACKGROUND_WORK_KINDS[kind].count, { count })),
857 resolve,
858 );
859 return {
860 title: waiting
861 ? resolve(msg("Waiting on {groups}", { groups }))
862 : resolve(msg("Running {groups}", { groups })),
863 items,
864 waiting,
865 };
866}
867
868function backgroundWorkSingleTitle(
869 kind: BackgroundWorkKind,
870 waiting: boolean,
871 resolve: MFunctionType,
872): string {
873 switch (kind) {
874 case "subagent":
875 return waiting ? resolve(msg("Waiting on a subagent")) : resolve(msg("Running a subagent"));
876 case "command":
877 return waiting ? resolve(msg("Waiting on a command")) : resolve(msg("Running a command"));
878 case "monitor":
879 return waiting ? resolve(msg("Waiting on a monitor")) : resolve(msg("Running a monitor"));
880 case "background_task":
881 return waiting
882 ? resolve(msg("Waiting on a background task"))
883 : resolve(msg("Running a background task"));
884 }
885}
886
887export interface ProviderGoalPresentation {
888 readonly title: string;
889 readonly objective: string;
890 readonly usage: string | null;
891 readonly canResume: boolean;
892}
893
894const PROVIDER_GOAL_TITLES: Record<OrchestrationV2ProviderGoal["status"], string> = {
895 active: msg("Pursuing goal"),
896 paused: msg("Goal paused"),
897 blocked: msg("Goal blocked"),
898 usage_limited: msg("Goal hit a usage limit"),
899 budget_limited: msg("Goal reached its token budget"),
900 complete: msg("Goal complete"),
901};
902
903function formatGoalTokens(tokens: number): string {
904 if (tokens < 1_000) return `${tokens}`;
905 const thousands = Math.round(tokens / 1_000);
906 if (thousands < 1_000) return `${thousands}k`;
907 return `${(tokens / 1_000_000).toFixed(1).replace(/\.0$/, "")}m`;
908}
909
910export function presentProviderGoal(
911 goal: OrchestrationV2ProviderGoal,
912 working: boolean,
913 resolve: MFunctionType = mFallback,
914): ProviderGoalPresentation {
915 const usage: Array<string> = [];
916 if (goal.tokensUsed !== undefined && goal.tokensUsed > 0) {
917 usage.push(
918 goal.tokenBudget == null
919 ? resolve(msg("{used} tokens", { used: formatGoalTokens(goal.tokensUsed) }))
920 : resolve(
921 msg("{used} / {budget} tokens", {
922 used: formatGoalTokens(goal.tokensUsed),
923 budget: formatGoalTokens(goal.tokenBudget),
924 }),
925 ),
926 );
927 }
928 if (goal.timeUsedSeconds !== undefined && goal.timeUsedSeconds >= 60) {
929 usage.push(formatDuration(goal.timeUsedSeconds * 1_000, resolve));
930 }
931 if (goal.checks !== undefined && goal.checks > 0) {
932 usage.push(
933 resolve(
934 msg("{count, plural, one {{count} check} other {{count} checks}}", { count: goal.checks }),
935 ),
936 );
937 }
938 return {
939 title:
940 goal.status === "active" && !working
941 ? resolve(msg("Goal set"))
942 : resolve(PROVIDER_GOAL_TITLES[goal.status]),
943 objective: goal.objective,
944 usage: usage.length === 0 ? null : usage.join(" · "),
945 canResume: goal.status !== "active" && goal.status !== "complete",
946 };
947}
948
949export function notificationChildThreadId(
950 source: OrchestrationV2NotificationSource,
951): ThreadId | undefined {
952 switch (source.kind) {
953 case "subagent":
954 case "delegated_task":
955 return source.childThreadId;
956 case "command":
957 case "monitor":
958 case "background_task":
959 case "system":
960 return undefined;
961 default:
962 source satisfies never;
963 return undefined;
964 }
965}