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

threadExecution.ts

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