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

threadExecution.ts

894 lines32.7 KB

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