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 { 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
184export function isRestartContinuationSource(
185 source: Pick<OrchestrationV2Run, "status" | "activeAttemptId" | "restartCancelledBackgroundWork">,
186 providerTurns: ReadonlyArray<Pick<ProviderTurnState, "runAttemptId" | "status">>,
187): boolean {
188 return isRestartNoteSource(source, providerTurns)
189 ? (source.restartCancelledBackgroundWork ?? []).some(isAwaitedWork)
190 : source.status === "cancelled";
191}
192
193/** Running does not prove prompt acceptance; carry continuation notes until a completed turn proves delivery. */
194export function restartContinuationNote(
195 source: OrchestrationV2Run,
196 runs: ReadonlyArray<OrchestrationV2Run>,
197 providerTurns: ReadonlyArray<Pick<ProviderTurnState, "runAttemptId" | "status">>,
198 attempts: ReadonlyArray<Attempt>,
199): { readonly work: ReadonlyArray<Work>; readonly settled: boolean } {
200 const completedAttempts = new Set(
201 providerTurns.filter((turn) => turn.status === "completed").map((turn) => turn.runAttemptId),
202 );
203 const completedRuns = new Set(
204 attempts.filter((attempt) => completedAttempts.has(attempt.id)).map((attempt) => attempt.runId),
205 );
206 let current = source;
207 let work = current.restartCancelledBackgroundWork ?? [];
208 const visited = new Set([current.id]);
209 while (
210 current.restartContinuationOfRunId !== undefined &&
211 !completedRuns.has(current.id) &&
212 !(current.activeAttemptId !== null && completedAttempts.has(current.activeAttemptId))
213 ) {
214 const previous = runs.find((candidate) => candidate.id === current.restartContinuationOfRunId);
215 if (previous === undefined || visited.has(previous.id)) break;
216 visited.add(previous.id);
217 current = previous;
218 work = mergeRestartCancelledBackgroundWork(current.restartCancelledBackgroundWork ?? [], work);
219 }
220 return { work, settled: isRestartNoteSource(current, providerTurns) };
221}
222
223export function isRestartNoteContinuation(
224 run: Pick<OrchestrationV2Run, "restartContinuationOfRunId">,
225 runs: ReadonlyArray<OrchestrationV2Run>,
226 providerTurns: ReadonlyArray<Pick<ProviderTurnState, "runAttemptId" | "status">>,
227 attempts: ReadonlyArray<Attempt>,
228): boolean {
229 const source =
230 run.restartContinuationOfRunId === undefined
231 ? undefined
232 : runs.find((candidate) => candidate.id === run.restartContinuationOfRunId);
233 return (
234 source !== undefined &&
235 restartContinuationNote(source, runs, providerTurns, attempts).work.length > 0
236 );
237}
238
239/** Derive delivery from later completed turns on the same provider thread, excluding compactions, resumes, and rolled-back runs. */
240export function pendingRestartCancelledBackgroundWork(input: {
241 readonly runs: ReadonlyArray<OrchestrationV2Run>;
242 readonly providerTurns: ReadonlyArray<ProviderTurnState>;
243 readonly compactionMessageIds: ReadonlySet<string>;
244 readonly run: Pick<
245 OrchestrationV2Run,
246 | "id"
247 | "ordinal"
248 | "completedAt"
249 | "userMessageId"
250 | "providerThreadId"
251 | "restartContinuationOfRunId"
252 | "activeAttemptId"
253 >;
254
255 readonly attempts: ReadonlyArray<Attempt>;
256}): ReadonlyArray<Work> {
257 const isCompaction = (run: typeof input.run) => input.compactionMessageIds.has(run.userMessageId);
258 if (
259 input.run.providerThreadId === null ||
260 input.run.restartContinuationOfRunId !== undefined ||
261 isCompaction(input.run)
262 )
263 return [];
264 const providerThreadId = input.run.providerThreadId;
265 const deliveredAttemptIds = new Set(
266 input.providerTurns
267 .filter((turn) => turn.providerThreadId === providerThreadId && turn.status === "completed")
268 .map((turn) => turn.runAttemptId),
269 );
270 const sameThread = input.runs.filter((run) => run.providerThreadId === providerThreadId);
271 const prompted = sameThread.filter(
272 (candidate) =>
273 candidate.id !== input.run.id &&
274 candidate.activeAttemptId !== null &&
275 candidate.status !== "rolled_back" &&
276 (deliveredAttemptIds.has(candidate.activeAttemptId) ||
277 input.attempts.some(
278 (attempt) => attempt.runId === candidate.id && deliveredAttemptIds.has(attempt.id),
279 )) &&
280 !isCompaction(candidate) &&
281 (candidate.restartContinuationOfRunId === undefined ||
282 isRestartNoteContinuation(candidate, input.runs, input.providerTurns, input.attempts)),
283 );
284 // Earlier attempts may already have delivered the note; a steer's replacement attempt must not repeat it.
285 const alreadyDelivered = input.attempts.some(
286 (attempt) =>
287 attempt.runId === input.run.id &&
288 attempt.id !== input.run.activeAttemptId &&
289 deliveredAttemptIds.has(attempt.id),
290 );
291 if (alreadyDelivered) return [];
292 return sameThread
293 .filter(
294 (source) =>
295 runRanAfter(input.run, source) &&
296 (source.restartCancelledBackgroundWork?.length ?? 0) > 0 &&
297 !prompted.some((later) => runRanAfter(later, source)),
298 )
299 .reduce<ReadonlyArray<Work>>(
300 (work, source) =>
301 mergeRestartCancelledBackgroundWork(work, source.restartCancelledBackgroundWork ?? []),
302 [],
303 );
304}
305
306export function mergeRestartCancelledBackgroundWork(
307 current: ReadonlyArray<Work>,
308 added: ReadonlyArray<Work>,
309): ReadonlyArray<Work> {
310 const identity = (entry: Work) => entry.id ?? `${entry.kind}\u0000${entry.label}`;
311 const seen = new Set(current.map(identity));
312 const merged = [...current];
313 for (const entry of added) {
314 const key = identity(entry);
315 if (seen.has(key)) continue;
316 seen.add(key);
317 merged.push(entry);
318 }
319 return merged;
320}