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