Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

RestartBackgroundNote.ts

368 lines13.9 KB

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