Open History to see the last commit
1import {
2 isDeliveredProviderTurn,
3 type NodeId,
4 type OrchestrationV2ConversationMessage,
5 type OrchestrationV2PendingBackgroundTask,
6 type OrchestrationV2ProviderThread,
7 type OrchestrationV2ProviderTurn,
8 type OrchestrationV2RestartCancelledBackgroundWork,
9 type OrchestrationV2Run,
10 type OrchestrationV2RunAttempt,
11 type OrchestrationV2Subagent,
12 type OrchestrationV2TurnItem,
13} from "@t3tools/contracts";
14import { subagentHoldsCompletion } from "@t3tools/provider-core/server/subagentProjection";
15import { backgroundWorkHoldsCompletion } from "@t3tools/shared/orchestrationV2PendingBackgroundWork";
16import { latestRootProviderFailure, runRanAfter } from "@t3tools/shared/orchestrationV2ThreadError";
17
18type Work = OrchestrationV2RestartCancelledBackgroundWork;
19type Attempt = Pick<OrchestrationV2RunAttempt, "id" | "runId">;
20
21const MAX_LABEL_LENGTH = 160;
22
23function compactLabel(value: unknown, maxLength = MAX_LABEL_LENGTH): string | undefined {
24 if (typeof value !== "string") return undefined;
25 const text = value.replaceAll(/\s+/g, " ").trim();
26 if (text.length === 0) return undefined;
27 if (text.length <= maxLength) return text;
28 // Half an emoji serializes to a lone surrogate escape, which provider JSON parsers reject.
29 const last = text.charCodeAt(maxLength - 2);
30 const end = last >= 0xd800 && last <= 0xdbff ? maxLength - 2 : maxLength - 1;
31 return `${text.slice(0, end)}…`;
32}
33
34/** A bounded label that keeps its id suffix whole whenever it fits. */
35function labelWithId(name: unknown, fallback: string, suffix: string): string {
36 const budget = MAX_LABEL_LENGTH - suffix.length;
37 if (budget < 2) return compactLabel(`${fallback}${suffix}`) ?? fallback;
38 return `${compactLabel(name, budget) ?? compactLabel(fallback, budget)}${suffix}`;
39}
40
41/** resumeId overrides the item id for native resume, such as Codex's child provider-thread id. */
42export function cancelledTurnItemWork(
43 item: OrchestrationV2TurnItem,
44 resumeId?: string,
45): Work | undefined {
46 switch (item.type) {
47 case "subagent": {
48 const nativeId =
49 item.origin === "provider_native" ? (resumeId ?? item.nativeItemRef?.nativeId) : undefined;
50 return {
51 kind: "subagent",
52 label: labelWithId(
53 compactLabel(item.title) === undefined ? item.prompt : item.title,
54 "subagent",
55 nativeId == null
56 ? ""
57 : item.nativeItemRef?.driver === "claudeAgent"
58 ? ` (id ${nativeId}; resume it with SendMessage to '${nativeId}')`
59 : ` (id ${nativeId})`,
60 ),
61 id: item.id,
62 };
63 }
64 case "command_execution":
65 return {
66 kind: item.monitor === true ? "monitor" : "shell",
67 label: compactLabel(item.input) ?? compactLabel(item.title) ?? "background command",
68 id: item.id,
69 ...(item.completionWake === "always" ? { awaited: true as const } : {}),
70 };
71 case "dynamic_tool": {
72 const monitor =
73 item.input !== null &&
74 typeof item.input === "object" &&
75 Reflect.get(item.input, "persistent") === true;
76 return {
77 kind: monitor ? "monitor" : "task",
78 label: compactLabel(item.title) ?? compactLabel(item.toolName) ?? "background tool",
79 id: item.id,
80 };
81 }
82 default:
83 return undefined;
84 }
85}
86
87/** Returns the awaiting provider thread; native subagents can run on children while their launching turn awaits them. */
88export function awaitingProviderThreadId(
89 item: OrchestrationV2TurnItem,
90 runs: ReadonlyArray<Pick<OrchestrationV2Run, "id" | "providerThreadId">>,
91): OrchestrationV2Run["providerThreadId"] | undefined {
92 const runProviderThreadId = runs.find((run) => run.id === item.runId)?.providerThreadId;
93 return item.type === "subagent" && item.origin === "provider_native"
94 ? (runProviderThreadId ?? item.providerThreadId)
95 : (item.providerThreadId ?? runProviderThreadId);
96}
97
98function restartWorkKind(task: OrchestrationV2PendingBackgroundTask): Work["kind"] {
99 switch (task.kind) {
100 case "command":
101 return "shell";
102 case "subagent":
103 return "subagent";
104 case "monitor":
105 return "monitor";
106 case "background_task":
107 return "task";
108 default:
109 task satisfies never;
110 return "task";
111 }
112}
113
114export function cancelledRosterTaskWork(task: OrchestrationV2PendingBackgroundTask): Work {
115 if (task.parentTaskId !== undefined) {
116 return {
117 kind: "subagent",
118 label: labelWithId(task.description, "background task", ` (subagent ${task.parentTaskId})`),
119 id: task.parentTaskId,
120 };
121 }
122 const kind = restartWorkKind(task);
123 const description = compactLabel(task.description);
124 return {
125 kind,
126 label:
127 compactLabel(
128 description === undefined ? task.taskId : `${description} (id ${task.taskId})`,
129 ) ?? "background task",
130 id: task.taskId,
131 ...(task.awaited === true ? { awaited: true as const } : {}),
132 };
133}
134
135const MAX_NOTE_ENTRIES = 10;
136
137/** Why background work stopped: a T3 server restart, or the provider process exiting under a live server. */
138export type BackgroundWorkLossCause = "server_restart" | "provider_exit";
139
140/** Bounds entries and labels to protect the context budget. */
141export function restartCancelledBackgroundWorkNote(
142 work: ReadonlyArray<Work>,
143 cause: BackgroundWorkLossCause = "server_restart",
144): string {
145 const omitted = work.length - MAX_NOTE_ENTRIES;
146 return [
147 `Note: ${cause === "provider_exit" ? "the agent runtime process exited" : "the T3 server restarted"}, and this background work was cancelled before it finished. It will not report back on its own, so resume or restart what you still need and wait for its result:`,
148 ...work.slice(0, MAX_NOTE_ENTRIES).map((entry) => `- ${entry.kind}: ${entry.label}`),
149 ...(omitted > 0 ? [`- and ${omitted} more`] : []),
150 ].join("\n");
151}
152
153type ProviderTurnState = Pick<
154 OrchestrationV2ProviderTurn,
155 "runAttemptId" | "providerThreadId" | "status" | "promptDropped"
156>;
157
158export function isRestartNoteSource(
159 source: Pick<OrchestrationV2Run, "status" | "activeAttemptId" | "restartCancelledBackgroundWork">,
160 providerTurns: ReadonlyArray<Pick<ProviderTurnState, "runAttemptId" | "status">>,
161): boolean {
162 return isNoteSource(source, (attemptId) =>
163 providerTurns.some((turn) => turn.runAttemptId === attemptId && turn.status === "cancelled"),
164 );
165}
166
167function isNoteSource(
168 source: Pick<OrchestrationV2Run, "status" | "activeAttemptId" | "restartCancelledBackgroundWork">,
169 attemptCancelled: (attemptId: OrchestrationV2Run["activeAttemptId"]) => boolean,
170): boolean {
171 return (
172 // Failed and interrupted turns never continue; recovery-cancelled waiting runs still qualify.
173 (source.status === "completed" ||
174 source.status === "waiting" ||
175 source.status === "cancelled") &&
176 (source.restartCancelledBackgroundWork?.length ?? 0) > 0 &&
177 !attemptCancelled(source.activeAttemptId)
178 );
179}
180
181/**
182 * Matches the Working-section hold: a shell or monitor wakes it only when the agent said it
183 * waits on it. Most are dev servers and their watchdogs, so their note waits for the next
184 * user message.
185 */
186export function isAwaitedWork(work: Pick<Work, "kind" | "awaited">): boolean {
187 return work.awaited === true || (work.kind !== "shell" && work.kind !== "monitor");
188}
189
190export function runOutcome(
191 run: Pick<OrchestrationV2Run, "status" | "restartCancelledBackgroundWork">,
192): OrchestrationV2Run["status"] {
193 return (run.status === "completed" || run.status === "cancelled") &&
194 (run.restartCancelledBackgroundWork ?? []).some(isAwaitedWork)
195 ? "interrupted"
196 : run.status;
197}
198
199/** The run whose continuation carries a provider thread's lost background work. */
200export function latestStartedRun(
201 runs: ReadonlyArray<OrchestrationV2Run>,
202 providerThreadId: OrchestrationV2Run["providerThreadId"],
203): OrchestrationV2Run | undefined {
204 return runs.reduce<OrchestrationV2Run | undefined>(
205 (latest, run) =>
206 run.providerThreadId === providerThreadId &&
207 run.status !== "queued" &&
208 run.status !== "rolled_back" &&
209 !neverStarted(run) &&
210 (latest === undefined || runRanAfter(run, latest))
211 ? run
212 : latest,
213 undefined,
214 );
215}
216
217/** Unstarted runs have no lost work to continue, except prepared continuations carrying a source run. */
218export function neverStarted(
219 run: Pick<OrchestrationV2Run, "startedAt" | "restartContinuationOfRunId">,
220): boolean {
221 return run.startedAt === null && run.restartContinuationOfRunId === undefined;
222}
223
224/** Restart-cancelled unstarted runs supersede nothing; user-stopped unstarted runs do. */
225export function cancelledBeforeStart(
226 run: Pick<OrchestrationV2Run, "status" | "startedAt" | "restartContinuationOfRunId">,
227): boolean {
228 return run.status === "cancelled" && neverStarted(run);
229}
230
231/** A follow-up task's runs: those tagged with it, and the untagged wakes for subagents they started. */
232export function delegatedTaskRuns(
233 projection: {
234 readonly runs: ReadonlyArray<OrchestrationV2Run>;
235 readonly messages: ReadonlyArray<
236 Pick<OrchestrationV2ConversationMessage, "runId" | "delegatedCompletion">
237 >;
238 },
239 taskId: NodeId,
240): ReadonlyArray<OrchestrationV2Run> {
241 const owned = new Set(
242 projection.runs.filter((run) => run.delegatedTaskId === taskId).map((run) => run.id),
243 );
244 const untagged = new Set(
245 projection.runs.filter((run) => run.delegatedTaskId === undefined).map((run) => run.id),
246 );
247 for (let grew = owned.size > 0; grew;) {
248 grew = false;
249 for (const { runId, delegatedCompletion } of projection.messages) {
250 if (
251 runId === null ||
252 !untagged.has(runId) ||
253 owned.has(runId) ||
254 delegatedCompletion === undefined ||
255 !owned.has(delegatedCompletion.parentRunId)
256 )
257 continue;
258 owned.add(runId);
259 grew = true;
260 }
261 }
262 return projection.runs.filter((run) => owned.has(run.id));
263}
264
265/**
266 * A follow-up task's runs still owe a subagent they started its result, or still await
267 * background work they started, as the original task waits on both.
268 */
269export function delegatedTaskAwaitsWork(
270 runs: ReadonlyArray<OrchestrationV2Run>,
271 child: {
272 readonly subagents: ReadonlyArray<
273 Pick<OrchestrationV2Subagent, "runId" | "status" | "completionDelivery">
274 >;
275 readonly providerThreads: ReadonlyArray<
276 Pick<OrchestrationV2ProviderThread, "pendingBackgroundTasks">
277 >;
278 },
279): boolean {
280 const runIds = new Set<string | null>(runs.map((run) => run.id));
281 return (
282 child.subagents.some((task) => runIds.has(task.runId) && subagentHoldsCompletion(task)) ||
283 child.providerThreads.some((thread) =>
284 backgroundWorkHoldsCompletion(
285 (thread.pendingBackgroundTasks ?? []).filter(
286 (task) => task.runId !== undefined && runIds.has(task.runId),
287 ),
288 ),
289 )
290 );
291}
292
293/** A follow-up task's latest run, passing over queued work it no longer waits on, as the original task does. */
294export function delegatedTaskResultRun(
295 runs: ReadonlyArray<OrchestrationV2Run>,
296): OrchestrationV2Run | undefined {
297 const taskRuns = runs.toSorted((a, b) => b.ordinal - a.ordinal);
298 const awaited = taskRuns.filter(
299 (run) => !cancelledBeforeStart(run) && !(run.status === "queued" && run.queueHeld === true),
300 );
301 // Executing work reports the task's state; a reordered queue can finish a newer run before an older one.
302 const executing = awaited.find((run) =>
303 ["preparing", "starting", "running", "waiting"].includes(run.status),
304 );
305 return executing ?? awaited.find((run) => run.status === "queued") ?? awaited[0] ?? taskRuns[0];
306}
307
308/** The provider never accepted this continuation's prompt, so starting it again repeats nothing. */
309export function continuationFailedBeforePrompt(
310 run: Pick<OrchestrationV2Run, "status" | "activeAttemptId" | "restartContinuationOfRunId">,
311 providerTurns: ReadonlyArray<Pick<ProviderTurnState, "runAttemptId" | "promptDropped">>,
312): boolean {
313 return (
314 run.status === "failed" &&
315 run.restartContinuationOfRunId !== undefined &&
316 !providerTurns.some(
317 (turn) => turn.runAttemptId === run.activeAttemptId && isDeliveredProviderTurn(turn),
318 )
319 );
320}
321
322const CONTINUATION_START_RETRY_DELAYS_MS = [60_000, 180_000];
323
324/** Backoff before restarting a continuation that failed to start, or undefined to let it fail. */
325export function continuationStartRetryDelayMs(
326 run: OrchestrationV2Run,
327 projection: {
328 readonly runs: ReadonlyArray<OrchestrationV2Run>;
329 readonly providerTurns: ReadonlyArray<
330 Pick<ProviderTurnState, "runAttemptId" | "promptDropped">
331 >;
332 readonly turnItems: Parameters<typeof latestRootProviderFailure>[1];
333 },
334): number | undefined {
335 if (!continuationFailedBeforePrompt(run, projection.providerTurns)) return;
336 // These fail the same way however often they start.
337 const failureClass = latestRootProviderFailure(run, projection.turnItems)?.class;
338 if (
339 failureClass === "usage_limit" ||
340 failureClass === "permission_error" ||
341 failureClass === "validation_error"
342 )
343 return;
344 let failedStarts = 0;
345 for (
346 let current: OrchestrationV2Run | undefined = run;
347 current !== undefined && continuationFailedBeforePrompt(current, projection.providerTurns);
348 current = projection.runs.find(
349 (candidate) => candidate.id === current?.restartContinuationOfRunId,
350 )
351 )
352 failedStarts += 1;
353 return CONTINUATION_START_RETRY_DELAYS_MS[failedStarts - 1];
354}
355
356export function isRestartContinuationSource(
357 source: Pick<OrchestrationV2Run, "status" | "activeAttemptId" | "restartCancelledBackgroundWork">,
358 providerTurns: ReadonlyArray<Pick<ProviderTurnState, "runAttemptId" | "status">>,
359): boolean {
360 return isRestartNoteSource(source, providerTurns)
361 ? (source.restartCancelledBackgroundWork ?? []).some(isAwaitedWork)
362 : source.status === "cancelled";
363}
364
365/** Built once per call so long threads are read a bounded number of times, not once per run. */
366function continuationLookup(
367 runs: ReadonlyArray<OrchestrationV2Run>,
368 providerTurns: ReadonlyArray<Pick<ProviderTurnState, "runAttemptId" | "status">>,
369 attempts: ReadonlyArray<Attempt>,
370) {
371 const runsById = new Map<string, OrchestrationV2Run>();
372 for (const run of runs) if (!runsById.has(run.id)) runsById.set(run.id, run);
373 const completedAttempts = new Set<string | null>();
374 const cancelledAttempts = new Set<string | null>();
375 for (const turn of providerTurns) {
376 if (turn.status === "completed") completedAttempts.add(turn.runAttemptId);
377 else if (turn.status === "cancelled") cancelledAttempts.add(turn.runAttemptId);
378 }
379 const completedRuns = new Set<string>();
380 for (const attempt of attempts)
381 if (completedAttempts.has(attempt.id)) completedRuns.add(attempt.runId);
382 return { runsById, completedAttempts, cancelledAttempts, completedRuns };
383}
384
385type ContinuationLookup = ReturnType<typeof continuationLookup>;
386
387/** Running does not prove prompt acceptance; carry continuation notes until a completed turn proves delivery. */
388export function restartContinuationNote(
389 source: OrchestrationV2Run,
390 runs: ReadonlyArray<OrchestrationV2Run>,
391 providerTurns: ReadonlyArray<Pick<ProviderTurnState, "runAttemptId" | "status">>,
392 attempts: ReadonlyArray<Attempt>,
393): { readonly work: ReadonlyArray<Work>; readonly settled: boolean } {
394 return continuationNote(source, continuationLookup(runs, providerTurns, attempts));
395}
396
397function continuationNote(
398 source: OrchestrationV2Run,
399 { runsById, completedAttempts, cancelledAttempts, completedRuns }: ContinuationLookup,
400): { readonly work: ReadonlyArray<Work>; readonly settled: boolean } {
401 let current = source;
402 let work = current.restartCancelledBackgroundWork ?? [];
403 const visited = new Set([current.id]);
404 while (
405 current.restartContinuationOfRunId !== undefined &&
406 !completedRuns.has(current.id) &&
407 !(current.activeAttemptId !== null && completedAttempts.has(current.activeAttemptId))
408 ) {
409 const previous = runsById.get(current.restartContinuationOfRunId);
410 if (previous === undefined || visited.has(previous.id)) break;
411 visited.add(previous.id);
412 current = previous;
413 work = mergeRestartCancelledBackgroundWork(current.restartCancelledBackgroundWork ?? [], work);
414 }
415 return {
416 work,
417 settled: isNoteSource(current, (attemptId) => cancelledAttempts.has(attemptId)),
418 };
419}
420
421export function isRestartNoteContinuation(
422 run: Pick<OrchestrationV2Run, "restartContinuationOfRunId">,
423 runs: ReadonlyArray<OrchestrationV2Run>,
424 providerTurns: ReadonlyArray<Pick<ProviderTurnState, "runAttemptId" | "status">>,
425 attempts: ReadonlyArray<Attempt>,
426): boolean {
427 return (
428 run.restartContinuationOfRunId !== undefined &&
429 isNoteContinuation(run, continuationLookup(runs, providerTurns, attempts))
430 );
431}
432
433function isNoteContinuation(
434 run: Pick<OrchestrationV2Run, "restartContinuationOfRunId">,
435 lookup: ContinuationLookup,
436): boolean {
437 const source =
438 run.restartContinuationOfRunId === undefined
439 ? undefined
440 : lookup.runsById.get(run.restartContinuationOfRunId);
441 return source !== undefined && continuationNote(source, lookup).work.length > 0;
442}
443
444/** Derive delivery from later completed turns on the same provider thread, excluding compactions, resumes, and rolled-back runs. */
445export function pendingRestartCancelledBackgroundWork(input: {
446 readonly runs: ReadonlyArray<OrchestrationV2Run>;
447 readonly providerTurns: ReadonlyArray<ProviderTurnState>;
448 /** Called only when an earlier run on the provider thread carries restart-note work. */
449 readonly compactionMessageIds: () => ReadonlySet<string>;
450 readonly run: Pick<
451 OrchestrationV2Run,
452 | "id"
453 | "ordinal"
454 | "completedAt"
455 | "userMessageId"
456 | "providerThreadId"
457 | "restartContinuationOfRunId"
458 | "activeAttemptId"
459 >;
460
461 readonly attempts: ReadonlyArray<Attempt>;
462}): ReadonlyArray<Work> {
463 if (input.run.providerThreadId === null || input.run.restartContinuationOfRunId !== undefined)
464 return [];
465 const providerThreadId = input.run.providerThreadId;
466 const sameThread = input.runs.filter((run) => run.providerThreadId === providerThreadId);
467 const sources = sameThread.filter(
468 (source) =>
469 (source.restartCancelledBackgroundWork?.length ?? 0) > 0 && runRanAfter(input.run, source),
470 );
471 // Threads whose server never restarted carry no notes; skip every other lookup for them.
472 if (sources.length === 0) return [];
473 const compactionMessageIds = input.compactionMessageIds();
474 const isCompaction = (run: typeof input.run) => compactionMessageIds.has(run.userMessageId);
475 if (isCompaction(input.run)) return [];
476 const deliveredAttemptIds = new Set(
477 input.providerTurns
478 .filter((turn) => turn.providerThreadId === providerThreadId && turn.status === "completed")
479 .map((turn) => turn.runAttemptId),
480 );
481 // Earlier attempts may already have delivered the note; a steer's replacement attempt must not repeat it.
482 const alreadyDelivered = input.attempts.some(
483 (attempt) =>
484 attempt.runId === input.run.id &&
485 attempt.id !== input.run.activeAttemptId &&
486 deliveredAttemptIds.has(attempt.id),
487 );
488 if (alreadyDelivered) return [];
489 const deliveredRunIds = new Set<string>();
490 for (const attempt of input.attempts)
491 if (deliveredAttemptIds.has(attempt.id)) deliveredRunIds.add(attempt.runId);
492 let lookup: ContinuationLookup | undefined;
493 // runRanAfter is a total order, so a source precedes some prompted run iff it precedes the latest one.
494 let latestPrompted: OrchestrationV2Run | undefined;
495 for (const candidate of sameThread) {
496 if (
497 candidate.id !== input.run.id &&
498 candidate.activeAttemptId !== null &&
499 candidate.status !== "rolled_back" &&
500 (deliveredAttemptIds.has(candidate.activeAttemptId) || deliveredRunIds.has(candidate.id)) &&
501 !isCompaction(candidate) &&
502 (candidate.restartContinuationOfRunId === undefined ||
503 isNoteContinuation(
504 candidate,
505 (lookup ??= continuationLookup(input.runs, input.providerTurns, input.attempts)),
506 )) &&
507 (latestPrompted === undefined || runRanAfter(candidate, latestPrompted))
508 )
509 latestPrompted = candidate;
510 }
511 return sources
512 .filter((source) => latestPrompted === undefined || !runRanAfter(latestPrompted, source))
513 .reduce<ReadonlyArray<Work>>(
514 (work, source) =>
515 mergeRestartCancelledBackgroundWork(work, source.restartCancelledBackgroundWork ?? []),
516 [],
517 );
518}
519
520export function mergeRestartCancelledBackgroundWork(
521 current: ReadonlyArray<Work>,
522 added: ReadonlyArray<Work>,
523): ReadonlyArray<Work> {
524 const identity = (entry: Work) => entry.id ?? `${entry.kind}\u0000${entry.label}`;
525 const seen = new Set(current.map(identity));
526 const merged = [...current];
527 for (const entry of added) {
528 const key = identity(entry);
529 if (seen.has(key)) continue;
530 seen.add(key);
531 merged.push(entry);
532 }
533 return merged;
534}