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