Open History to see the last commit
1import type {
2 OrchestrationV2PendingBackgroundTask,
3 OrchestrationV2ProviderTurn,
4 OrchestrationV2RestartCancelledBackgroundWork,
5 OrchestrationV2Run,
6 OrchestrationV2RunAttempt,
7 OrchestrationV2TurnItem,
8} from "@t3tools/contracts";
9import { latestRootProviderFailure, runRanAfter } from "@t3tools/shared/orchestrationV2ThreadError";
10
11type Work = OrchestrationV2RestartCancelledBackgroundWork;
12type Attempt = Pick<OrchestrationV2RunAttempt, "id" | "runId">;
13
14const MAX_LABEL_LENGTH = 160;
15
16function compactLabel(value: unknown, maxLength = MAX_LABEL_LENGTH): string | undefined {
17 if (typeof value !== "string") return undefined;
18 const text = value.replaceAll(/\s+/g, " ").trim();
19 if (text.length === 0) return undefined;
20 return text.length > maxLength ? `${text.slice(0, maxLength - 1)}…` : text;
21}
22
23/** A bounded label that keeps its id suffix whole whenever it fits. */
24function labelWithId(name: unknown, fallback: string, suffix: string): string {
25 const budget = MAX_LABEL_LENGTH - suffix.length;
26 if (budget < 2) return compactLabel(`${fallback}${suffix}`) ?? fallback;
27 return `${compactLabel(name, budget) ?? compactLabel(fallback, budget)}${suffix}`;
28}
29
30/** resumeId overrides the item id for native resume, such as Codex's child provider-thread id. */
31export function cancelledTurnItemWork(
32 item: OrchestrationV2TurnItem,
33 resumeId?: string,
34): Work | undefined {
35 switch (item.type) {
36 case "subagent": {
37 const nativeId =
38 item.origin === "provider_native" ? (resumeId ?? item.nativeItemRef?.nativeId) : undefined;
39 return {
40 kind: "subagent",
41 label: labelWithId(
42 compactLabel(item.title) === undefined ? item.prompt : item.title,
43 "subagent",
44 nativeId === undefined ? "" : ` (id ${nativeId})`,
45 ),
46 id: item.id,
47 };
48 }
49 case "command_execution":
50 return {
51 kind: item.monitor === true ? "monitor" : "shell",
52 label: compactLabel(item.input) ?? compactLabel(item.title) ?? "background command",
53 id: item.id,
54 };
55 case "dynamic_tool": {
56 const monitor =
57 item.input !== null &&
58 typeof item.input === "object" &&
59 Reflect.get(item.input, "persistent") === true;
60 return {
61 kind: monitor ? "monitor" : "task",
62 label: compactLabel(item.title) ?? compactLabel(item.toolName) ?? "background tool",
63 id: item.id,
64 };
65 }
66 default:
67 return undefined;
68 }
69}
70
71/** Returns the awaiting provider thread; native subagents can run on children while their launching turn awaits them. */
72export function awaitingProviderThreadId(
73 item: OrchestrationV2TurnItem,
74 runs: ReadonlyArray<Pick<OrchestrationV2Run, "id" | "providerThreadId">>,
75): OrchestrationV2Run["providerThreadId"] | undefined {
76 const runProviderThreadId = runs.find((run) => run.id === item.runId)?.providerThreadId;
77 return item.type === "subagent" && item.origin === "provider_native"
78 ? (runProviderThreadId ?? item.providerThreadId)
79 : (item.providerThreadId ?? runProviderThreadId);
80}
81
82function restartWorkKind(task: OrchestrationV2PendingBackgroundTask): Work["kind"] {
83 switch (task.kind) {
84 case "command":
85 return "shell";
86 case "subagent":
87 return "subagent";
88 case "monitor":
89 return "monitor";
90 case "background_task":
91 return "task";
92 default:
93 task satisfies never;
94 return "task";
95 }
96}
97
98export function cancelledRosterTaskWork(task: OrchestrationV2PendingBackgroundTask): Work {
99 if (task.parentTaskId !== undefined) {
100 return {
101 kind: "subagent",
102 label: labelWithId(task.description, "background task", ` (subagent ${task.parentTaskId})`),
103 id: task.parentTaskId,
104 };
105 }
106 const kind = restartWorkKind(task);
107 const description = compactLabel(task.description);
108 return {
109 kind,
110 label:
111 compactLabel(
112 description === undefined ? task.taskId : `${description} (id ${task.taskId})`,
113 ) ?? "background task",
114 id: task.taskId,
115 ...(task.awaited === true ? { awaited: true as const } : {}),
116 };
117}
118
119const MAX_NOTE_ENTRIES = 10;
120
121/** Bounds entries and labels to protect the context budget. */
122export function restartCancelledBackgroundWorkNote(work: ReadonlyArray<Work>): string {
123 const omitted = work.length - MAX_NOTE_ENTRIES;
124 return [
125 "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:",
126 ...work.slice(0, MAX_NOTE_ENTRIES).map((entry) => `- ${entry.kind}: ${entry.label}`),
127 ...(omitted > 0 ? [`- and ${omitted} more`] : []),
128 ].join("\n");
129}
130
131type ProviderTurnState = Pick<
132 OrchestrationV2ProviderTurn,
133 "runAttemptId" | "providerThreadId" | "status"
134>;
135
136export function isRestartNoteSource(
137 source: Pick<OrchestrationV2Run, "status" | "activeAttemptId" | "restartCancelledBackgroundWork">,
138 providerTurns: ReadonlyArray<Pick<ProviderTurnState, "runAttemptId" | "status">>,
139): boolean {
140 return (
141 // Failed and interrupted turns never continue; recovery-cancelled waiting runs still qualify.
142 (source.status === "completed" ||
143 source.status === "waiting" ||
144 source.status === "cancelled") &&
145 (source.restartCancelledBackgroundWork?.length ?? 0) > 0 &&
146 !providerTurns.some(
147 (turn) => turn.runAttemptId === source.activeAttemptId && turn.status === "cancelled",
148 )
149 );
150}
151
152/**
153 * Matches the Working-section hold: a shell or monitor wakes it only when the agent said it
154 * waits on it. Most are dev servers and their watchdogs, so their note waits for the next
155 * user message.
156 */
157export function isAwaitedWork(work: Pick<Work, "kind" | "awaited">): boolean {
158 return work.awaited === true || (work.kind !== "shell" && work.kind !== "monitor");
159}
160
161export function runOutcome(
162 run: Pick<OrchestrationV2Run, "status" | "restartCancelledBackgroundWork">,
163): OrchestrationV2Run["status"] {
164 return (run.status === "completed" || run.status === "cancelled") &&
165 (run.restartCancelledBackgroundWork ?? []).some(isAwaitedWork)
166 ? "interrupted"
167 : run.status;
168}
169
170/** Unstarted runs have no lost work to continue, except prepared continuations carrying a source run. */
171export function neverStarted(
172 run: Pick<OrchestrationV2Run, "startedAt" | "restartContinuationOfRunId">,
173): boolean {
174 return run.startedAt === null && run.restartContinuationOfRunId === undefined;
175}
176
177/** Restart-cancelled unstarted runs supersede nothing; user-stopped unstarted runs do. */
178export function cancelledBeforeStart(
179 run: Pick<OrchestrationV2Run, "status" | "startedAt" | "restartContinuationOfRunId">,
180): boolean {
181 return run.status === "cancelled" && neverStarted(run);
182}
183
184/** The provider never accepted this continuation's prompt, so starting it again repeats nothing. */
185export function continuationFailedBeforePrompt(
186 run: Pick<OrchestrationV2Run, "status" | "activeAttemptId" | "restartContinuationOfRunId">,
187 providerTurns: ReadonlyArray<Pick<ProviderTurnState, "runAttemptId">>,
188): boolean {
189 return (
190 run.status === "failed" &&
191 run.restartContinuationOfRunId !== undefined &&
192 !providerTurns.some((turn) => turn.runAttemptId === run.activeAttemptId)
193 );
194}
195
196const CONTINUATION_START_RETRY_DELAYS_MS = [60_000, 180_000];
197
198/** Backoff before restarting a continuation that failed to start, or undefined to let it fail. */
199export function continuationStartRetryDelayMs(
200 run: OrchestrationV2Run,
201 projection: {
202 readonly runs: ReadonlyArray<OrchestrationV2Run>;
203 readonly providerTurns: ReadonlyArray<Pick<ProviderTurnState, "runAttemptId">>;
204 readonly turnItems: Parameters<typeof latestRootProviderFailure>[1];
205 },
206): number | undefined {
207 if (!continuationFailedBeforePrompt(run, projection.providerTurns)) return;
208 // These fail the same way however often they start.
209 const failureClass = latestRootProviderFailure(run, projection.turnItems)?.class;
210 if (
211 failureClass === "usage_limit" ||
212 failureClass === "permission_error" ||
213 failureClass === "validation_error"
214 )
215 return;
216 let failedStarts = 0;
217 for (
218 let current: OrchestrationV2Run | undefined = run;
219 current !== undefined && continuationFailedBeforePrompt(current, projection.providerTurns);
220 current = projection.runs.find(
221 (candidate) => candidate.id === current?.restartContinuationOfRunId,
222 )
223 )
224 failedStarts += 1;
225 return CONTINUATION_START_RETRY_DELAYS_MS[failedStarts - 1];
226}
227
228export function isRestartContinuationSource(
229 source: Pick<OrchestrationV2Run, "status" | "activeAttemptId" | "restartCancelledBackgroundWork">,
230 providerTurns: ReadonlyArray<Pick<ProviderTurnState, "runAttemptId" | "status">>,
231): boolean {
232 return isRestartNoteSource(source, providerTurns)
233 ? (source.restartCancelledBackgroundWork ?? []).some(isAwaitedWork)
234 : source.status === "cancelled";
235}
236
237/** Running does not prove prompt acceptance; carry continuation notes until a completed turn proves delivery. */
238export function restartContinuationNote(
239 source: OrchestrationV2Run,
240 runs: ReadonlyArray<OrchestrationV2Run>,
241 providerTurns: ReadonlyArray<Pick<ProviderTurnState, "runAttemptId" | "status">>,
242 attempts: ReadonlyArray<Attempt>,
243): { readonly work: ReadonlyArray<Work>; readonly settled: boolean } {
244 const completedAttempts = new Set(
245 providerTurns.filter((turn) => turn.status === "completed").map((turn) => turn.runAttemptId),
246 );
247 const completedRuns = new Set(
248 attempts.filter((attempt) => completedAttempts.has(attempt.id)).map((attempt) => attempt.runId),
249 );
250 let current = source;
251 let work = current.restartCancelledBackgroundWork ?? [];
252 const visited = new Set([current.id]);
253 while (
254 current.restartContinuationOfRunId !== undefined &&
255 !completedRuns.has(current.id) &&
256 !(current.activeAttemptId !== null && completedAttempts.has(current.activeAttemptId))
257 ) {
258 const previous = runs.find((candidate) => candidate.id === current.restartContinuationOfRunId);
259 if (previous === undefined || visited.has(previous.id)) break;
260 visited.add(previous.id);
261 current = previous;
262 work = mergeRestartCancelledBackgroundWork(current.restartCancelledBackgroundWork ?? [], work);
263 }
264 return { work, settled: isRestartNoteSource(current, providerTurns) };
265}
266
267export function isRestartNoteContinuation(
268 run: Pick<OrchestrationV2Run, "restartContinuationOfRunId">,
269 runs: ReadonlyArray<OrchestrationV2Run>,
270 providerTurns: ReadonlyArray<Pick<ProviderTurnState, "runAttemptId" | "status">>,
271 attempts: ReadonlyArray<Attempt>,
272): boolean {
273 const source =
274 run.restartContinuationOfRunId === undefined
275 ? undefined
276 : runs.find((candidate) => candidate.id === run.restartContinuationOfRunId);
277 return (
278 source !== undefined &&
279 restartContinuationNote(source, runs, providerTurns, attempts).work.length > 0
280 );
281}
282
283/** Derive delivery from later completed turns on the same provider thread, excluding compactions, resumes, and rolled-back runs. */
284export function pendingRestartCancelledBackgroundWork(input: {
285 readonly runs: ReadonlyArray<OrchestrationV2Run>;
286 readonly providerTurns: ReadonlyArray<ProviderTurnState>;
287 readonly compactionMessageIds: ReadonlySet<string>;
288 readonly run: Pick<
289 OrchestrationV2Run,
290 | "id"
291 | "ordinal"
292 | "completedAt"
293 | "userMessageId"
294 | "providerThreadId"
295 | "restartContinuationOfRunId"
296 | "activeAttemptId"
297 >;
298
299 readonly attempts: ReadonlyArray<Attempt>;
300}): ReadonlyArray<Work> {
301 const isCompaction = (run: typeof input.run) => input.compactionMessageIds.has(run.userMessageId);
302 if (
303 input.run.providerThreadId === null ||
304 input.run.restartContinuationOfRunId !== undefined ||
305 isCompaction(input.run)
306 )
307 return [];
308 const providerThreadId = input.run.providerThreadId;
309 const deliveredAttemptIds = new Set(
310 input.providerTurns
311 .filter((turn) => turn.providerThreadId === providerThreadId && turn.status === "completed")
312 .map((turn) => turn.runAttemptId),
313 );
314 const sameThread = input.runs.filter((run) => run.providerThreadId === providerThreadId);
315 const prompted = sameThread.filter(
316 (candidate) =>
317 candidate.id !== input.run.id &&
318 candidate.activeAttemptId !== null &&
319 candidate.status !== "rolled_back" &&
320 (deliveredAttemptIds.has(candidate.activeAttemptId) ||
321 input.attempts.some(
322 (attempt) => attempt.runId === candidate.id && deliveredAttemptIds.has(attempt.id),
323 )) &&
324 !isCompaction(candidate) &&
325 (candidate.restartContinuationOfRunId === undefined ||
326 isRestartNoteContinuation(candidate, input.runs, input.providerTurns, input.attempts)),
327 );
328 // Earlier attempts may already have delivered the note; a steer's replacement attempt must not repeat it.
329 const alreadyDelivered = input.attempts.some(
330 (attempt) =>
331 attempt.runId === input.run.id &&
332 attempt.id !== input.run.activeAttemptId &&
333 deliveredAttemptIds.has(attempt.id),
334 );
335 if (alreadyDelivered) return [];
336 return sameThread
337 .filter(
338 (source) =>
339 runRanAfter(input.run, source) &&
340 (source.restartCancelledBackgroundWork?.length ?? 0) > 0 &&
341 !prompted.some((later) => runRanAfter(later, source)),
342 )
343 .reduce<ReadonlyArray<Work>>(
344 (work, source) =>
345 mergeRestartCancelledBackgroundWork(work, source.restartCancelledBackgroundWork ?? []),
346 [],
347 );
348}
349
350export function mergeRestartCancelledBackgroundWork(
351 current: ReadonlyArray<Work>,
352 added: ReadonlyArray<Work>,
353): ReadonlyArray<Work> {
354 const identity = (entry: Work) => entry.id ?? `${entry.kind}\u0000${entry.label}`;
355 const seen = new Set(current.map(identity));
356 const merged = [...current];
357 for (const entry of added) {
358 const key = identity(entry);
359 if (seen.has(key)) continue;
360 seen.add(key);
361 merged.push(entry);
362 }
363 return merged;
364}