@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

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