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 === undefined ? "" : ` (id ${nativeId})`,
55 ),
56 id: item.id,
57 };
58 }
59 case "command_execution":
60 return {
61 kind: item.monitor === true ? "monitor" : "shell",
62 label: compactLabel(item.input) ?? compactLabel(item.title) ?? "background command",
63 id: item.id,
64 ...(item.completionWake === "always" ? { awaited: true as const } : {}),
65 };
66 case "dynamic_tool": {
67 const monitor =
68 item.input !== null &&
69 typeof item.input === "object" &&
70 Reflect.get(item.input, "persistent") === true;
71 return {
72 kind: monitor ? "monitor" : "task",
73 label: compactLabel(item.title) ?? compactLabel(item.toolName) ?? "background tool",
74 id: item.id,
75 };
76 }
77 default:
78 return undefined;
79 }
80}
81
82/** Returns the awaiting provider thread; native subagents can run on children while their launching turn awaits them. */
83export function awaitingProviderThreadId(
84 item: OrchestrationV2TurnItem,
85 runs: ReadonlyArray<Pick<OrchestrationV2Run, "id" | "providerThreadId">>,
86): OrchestrationV2Run["providerThreadId"] | undefined {
87 const runProviderThreadId = runs.find((run) => run.id === item.runId)?.providerThreadId;
88 return item.type === "subagent" && item.origin === "provider_native"
89 ? (runProviderThreadId ?? item.providerThreadId)
90 : (item.providerThreadId ?? runProviderThreadId);
91}
92
93function restartWorkKind(task: OrchestrationV2PendingBackgroundTask): Work["kind"] {
94 switch (task.kind) {
95 case "command":
96 return "shell";
97 case "subagent":
98 return "subagent";
99 case "monitor":
100 return "monitor";
101 case "background_task":
102 return "task";
103 default:
104 task satisfies never;
105 return "task";
106 }
107}
108
109export function cancelledRosterTaskWork(task: OrchestrationV2PendingBackgroundTask): Work {
110 if (task.parentTaskId !== undefined) {
111 return {
112 kind: "subagent",
113 label: labelWithId(task.description, "background task", ` (subagent ${task.parentTaskId})`),
114 id: task.parentTaskId,
115 };
116 }
117 const kind = restartWorkKind(task);
118 const description = compactLabel(task.description);
119 return {
120 kind,
121 label:
122 compactLabel(
123 description === undefined ? task.taskId : `${description} (id ${task.taskId})`,
124 ) ?? "background task",
125 id: task.taskId,
126 ...(task.awaited === true ? { awaited: true as const } : {}),
127 };
128}
129
130const MAX_NOTE_ENTRIES = 10;
131
132/** Bounds entries and labels to protect the context budget. */
133export function restartCancelledBackgroundWorkNote(work: ReadonlyArray<Work>): string {
134 const omitted = work.length - MAX_NOTE_ENTRIES;
135 return [
136 "Note: 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:",
137 ...work.slice(0, MAX_NOTE_ENTRIES).map((entry) => `- ${entry.kind}: ${entry.label}`),
138 ...(omitted > 0 ? [`- and ${omitted} more`] : []),
139 ].join("\n");
140}
141
142type ProviderTurnState = Pick<
143 OrchestrationV2ProviderTurn,
144 "runAttemptId" | "providerThreadId" | "status"
145>;
146
147export function isRestartNoteSource(
148 source: Pick<OrchestrationV2Run, "status" | "activeAttemptId" | "restartCancelledBackgroundWork">,
149 providerTurns: ReadonlyArray<Pick<ProviderTurnState, "runAttemptId" | "status">>,
150): boolean {
151 return (
152 // Failed and interrupted turns never continue; recovery-cancelled waiting runs still qualify.
153 (source.status === "completed" ||
154 source.status === "waiting" ||
155 source.status === "cancelled") &&
156 (source.restartCancelledBackgroundWork?.length ?? 0) > 0 &&
157 !providerTurns.some(
158 (turn) => turn.runAttemptId === source.activeAttemptId && turn.status === "cancelled",
159 )
160 );
161}
162
163/**
164 * Matches the Working-section hold: a shell or monitor wakes it only when the agent said it
165 * waits on it. Most are dev servers and their watchdogs, so their note waits for the next
166 * user message.
167 */
168export function isAwaitedWork(work: Pick<Work, "kind" | "awaited">): boolean {
169 return work.awaited === true || (work.kind !== "shell" && work.kind !== "monitor");
170}
171
172export function runOutcome(
173 run: Pick<OrchestrationV2Run, "status" | "restartCancelledBackgroundWork">,
174): OrchestrationV2Run["status"] {
175 return (run.status === "completed" || run.status === "cancelled") &&
176 (run.restartCancelledBackgroundWork ?? []).some(isAwaitedWork)
177 ? "interrupted"
178 : run.status;
179}
180
181/** Unstarted runs have no lost work to continue, except prepared continuations carrying a source run. */
182export function neverStarted(
183 run: Pick<OrchestrationV2Run, "startedAt" | "restartContinuationOfRunId">,
184): boolean {
185 return run.startedAt === null && run.restartContinuationOfRunId === undefined;
186}
187
188/** Restart-cancelled unstarted runs supersede nothing; user-stopped unstarted runs do. */
189export function cancelledBeforeStart(
190 run: Pick<OrchestrationV2Run, "status" | "startedAt" | "restartContinuationOfRunId">,
191): boolean {
192 return run.status === "cancelled" && neverStarted(run);
193}
194
195/** A follow-up task's runs: those tagged with it, and the untagged wakes for subagents they started. */
196export function delegatedTaskRuns(
197 projection: {
198 readonly runs: ReadonlyArray<OrchestrationV2Run>;
199 readonly messages: ReadonlyArray<
200 Pick<OrchestrationV2ConversationMessage, "runId" | "delegatedCompletion">
201 >;
202 },
203 taskId: NodeId,
204): ReadonlyArray<OrchestrationV2Run> {
205 const owned = new Set(
206 projection.runs.filter((run) => run.delegatedTaskId === taskId).map((run) => run.id),
207 );
208 const untagged = new Set(
209 projection.runs.filter((run) => run.delegatedTaskId === undefined).map((run) => run.id),
210 );
211 for (let grew = owned.size > 0; grew;) {
212 grew = false;
213 for (const { runId, delegatedCompletion } of projection.messages) {
214 if (
215 runId === null ||
216 !untagged.has(runId) ||
217 owned.has(runId) ||
218 delegatedCompletion === undefined ||
219 !owned.has(delegatedCompletion.parentRunId)
220 )
221 continue;
222 owned.add(runId);
223 grew = true;
224 }
225 }
226 return projection.runs.filter((run) => owned.has(run.id));
227}
228
229/**
230 * A follow-up task's runs still owe a subagent they started its result, or the child still
231 * awaits background work, as the original task waits on both.
232 */
233export function delegatedTaskAwaitsWork(
234 runs: ReadonlyArray<OrchestrationV2Run>,
235 child: {
236 readonly subagents: ReadonlyArray<
237 Pick<OrchestrationV2Subagent, "runId" | "status" | "completionDelivery">
238 >;
239 readonly providerThreads: ReadonlyArray<
240 Pick<OrchestrationV2ProviderThread, "pendingBackgroundTasks">
241 >;
242 },
243): boolean {
244 const runIds = new Set<string | null>(runs.map((run) => run.id));
245 return (
246 child.subagents.some((task) => runIds.has(task.runId) && subagentHoldsCompletion(task)) ||
247 child.providerThreads.some((thread) =>
248 backgroundWorkHoldsCompletion(thread.pendingBackgroundTasks ?? []),
249 )
250 );
251}
252
253/** A follow-up task's latest run, passing over queued work it no longer waits on, as the original task does. */
254export function delegatedTaskResultRun(
255 runs: ReadonlyArray<OrchestrationV2Run>,
256): OrchestrationV2Run | undefined {
257 const taskRuns = runs.toSorted((a, b) => b.ordinal - a.ordinal);
258 const awaited = taskRuns.filter(
259 (run) => !cancelledBeforeStart(run) && !(run.status === "queued" && run.queueHeld === true),
260 );
261 // Executing work reports the task's state; a reordered queue can finish a newer run before an older one.
262 const executing = awaited.find((run) =>
263 ["preparing", "starting", "running", "waiting"].includes(run.status),
264 );
265 return executing ?? awaited.find((run) => run.status === "queued") ?? awaited[0] ?? taskRuns[0];
266}
267
268/** The provider never accepted this continuation's prompt, so starting it again repeats nothing. */
269export function continuationFailedBeforePrompt(
270 run: Pick<OrchestrationV2Run, "status" | "activeAttemptId" | "restartContinuationOfRunId">,
271 providerTurns: ReadonlyArray<Pick<ProviderTurnState, "runAttemptId">>,
272): boolean {
273 return (
274 run.status === "failed" &&
275 run.restartContinuationOfRunId !== undefined &&
276 !providerTurns.some((turn) => turn.runAttemptId === run.activeAttemptId)
277 );
278}
279
280const CONTINUATION_START_RETRY_DELAYS_MS = [60_000, 180_000];
281
282/** Backoff before restarting a continuation that failed to start, or undefined to let it fail. */
283export function continuationStartRetryDelayMs(
284 run: OrchestrationV2Run,
285 projection: {
286 readonly runs: ReadonlyArray<OrchestrationV2Run>;
287 readonly providerTurns: ReadonlyArray<Pick<ProviderTurnState, "runAttemptId">>;
288 readonly turnItems: Parameters<typeof latestRootProviderFailure>[1];
289 },
290): number | undefined {
291 if (!continuationFailedBeforePrompt(run, projection.providerTurns)) return;
292 // These fail the same way however often they start.
293 const failureClass = latestRootProviderFailure(run, projection.turnItems)?.class;
294 if (
295 failureClass === "usage_limit" ||
296 failureClass === "permission_error" ||
297 failureClass === "validation_error"
298 )
299 return;
300 let failedStarts = 0;
301 for (
302 let current: OrchestrationV2Run | undefined = run;
303 current !== undefined && continuationFailedBeforePrompt(current, projection.providerTurns);
304 current = projection.runs.find(
305 (candidate) => candidate.id === current?.restartContinuationOfRunId,
306 )
307 )
308 failedStarts += 1;
309 return CONTINUATION_START_RETRY_DELAYS_MS[failedStarts - 1];
310}
311
312export function isRestartContinuationSource(
313 source: Pick<OrchestrationV2Run, "status" | "activeAttemptId" | "restartCancelledBackgroundWork">,
314 providerTurns: ReadonlyArray<Pick<ProviderTurnState, "runAttemptId" | "status">>,
315): boolean {
316 return isRestartNoteSource(source, providerTurns)
317 ? (source.restartCancelledBackgroundWork ?? []).some(isAwaitedWork)
318 : source.status === "cancelled";
319}
320
321/** Running does not prove prompt acceptance; carry continuation notes until a completed turn proves delivery. */
322export function restartContinuationNote(
323 source: OrchestrationV2Run,
324 runs: ReadonlyArray<OrchestrationV2Run>,
325 providerTurns: ReadonlyArray<Pick<ProviderTurnState, "runAttemptId" | "status">>,
326 attempts: ReadonlyArray<Attempt>,
327): { readonly work: ReadonlyArray<Work>; readonly settled: boolean } {
328 const completedAttempts = new Set(
329 providerTurns.filter((turn) => turn.status === "completed").map((turn) => turn.runAttemptId),
330 );
331 const completedRuns = new Set(
332 attempts.filter((attempt) => completedAttempts.has(attempt.id)).map((attempt) => attempt.runId),
333 );
334 let current = source;
335 let work = current.restartCancelledBackgroundWork ?? [];
336 const visited = new Set([current.id]);
337 while (
338 current.restartContinuationOfRunId !== undefined &&
339 !completedRuns.has(current.id) &&
340 !(current.activeAttemptId !== null && completedAttempts.has(current.activeAttemptId))
341 ) {
342 const previous = runs.find((candidate) => candidate.id === current.restartContinuationOfRunId);
343 if (previous === undefined || visited.has(previous.id)) break;
344 visited.add(previous.id);
345 current = previous;
346 work = mergeRestartCancelledBackgroundWork(current.restartCancelledBackgroundWork ?? [], work);
347 }
348 return { work, settled: isRestartNoteSource(current, providerTurns) };
349}
350
351export function isRestartNoteContinuation(
352 run: Pick<OrchestrationV2Run, "restartContinuationOfRunId">,
353 runs: ReadonlyArray<OrchestrationV2Run>,
354 providerTurns: ReadonlyArray<Pick<ProviderTurnState, "runAttemptId" | "status">>,
355 attempts: ReadonlyArray<Attempt>,
356): boolean {
357 const source =
358 run.restartContinuationOfRunId === undefined
359 ? undefined
360 : runs.find((candidate) => candidate.id === run.restartContinuationOfRunId);
361 return (
362 source !== undefined &&
363 restartContinuationNote(source, runs, providerTurns, attempts).work.length > 0
364 );
365}
366
367/** Derive delivery from later completed turns on the same provider thread, excluding compactions, resumes, and rolled-back runs. */
368export function pendingRestartCancelledBackgroundWork(input: {
369 readonly runs: ReadonlyArray<OrchestrationV2Run>;
370 readonly providerTurns: ReadonlyArray<ProviderTurnState>;
371 readonly compactionMessageIds: ReadonlySet<string>;
372 readonly run: Pick<
373 OrchestrationV2Run,
374 | "id"
375 | "ordinal"
376 | "completedAt"
377 | "userMessageId"
378 | "providerThreadId"
379 | "restartContinuationOfRunId"
380 | "activeAttemptId"
381 >;
382
383 readonly attempts: ReadonlyArray<Attempt>;
384}): ReadonlyArray<Work> {
385 const isCompaction = (run: typeof input.run) => input.compactionMessageIds.has(run.userMessageId);
386 if (
387 input.run.providerThreadId === null ||
388 input.run.restartContinuationOfRunId !== undefined ||
389 isCompaction(input.run)
390 )
391 return [];
392 const providerThreadId = input.run.providerThreadId;
393 const deliveredAttemptIds = new Set(
394 input.providerTurns
395 .filter((turn) => turn.providerThreadId === providerThreadId && turn.status === "completed")
396 .map((turn) => turn.runAttemptId),
397 );
398 const sameThread = input.runs.filter((run) => run.providerThreadId === providerThreadId);
399 const prompted = sameThread.filter(
400 (candidate) =>
401 candidate.id !== input.run.id &&
402 candidate.activeAttemptId !== null &&
403 candidate.status !== "rolled_back" &&
404 (deliveredAttemptIds.has(candidate.activeAttemptId) ||
405 input.attempts.some(
406 (attempt) => attempt.runId === candidate.id && deliveredAttemptIds.has(attempt.id),
407 )) &&
408 !isCompaction(candidate) &&
409 (candidate.restartContinuationOfRunId === undefined ||
410 isRestartNoteContinuation(candidate, input.runs, input.providerTurns, input.attempts)),
411 );
412 // Earlier attempts may already have delivered the note; a steer's replacement attempt must not repeat it.
413 const alreadyDelivered = input.attempts.some(
414 (attempt) =>
415 attempt.runId === input.run.id &&
416 attempt.id !== input.run.activeAttemptId &&
417 deliveredAttemptIds.has(attempt.id),
418 );
419 if (alreadyDelivered) return [];
420 return sameThread
421 .filter(
422 (source) =>
423 runRanAfter(input.run, source) &&
424 (source.restartCancelledBackgroundWork?.length ?? 0) > 0 &&
425 !prompted.some((later) => runRanAfter(later, source)),
426 )
427 .reduce<ReadonlyArray<Work>>(
428 (work, source) =>
429 mergeRestartCancelledBackgroundWork(work, source.restartCancelledBackgroundWork ?? []),
430 [],
431 );
432}
433
434export function mergeRestartCancelledBackgroundWork(
435 current: ReadonlyArray<Work>,
436 added: ReadonlyArray<Work>,
437): ReadonlyArray<Work> {
438 const identity = (entry: Work) => entry.id ?? `${entry.kind}\u0000${entry.label}`;
439 const seen = new Set(current.map(identity));
440 const merged = [...current];
441 for (const entry of added) {
442 const key = identity(entry);
443 if (seen.has(key)) continue;
444 seen.add(key);
445 merged.push(entry);
446 }
447 return merged;
448}