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