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

RestartBackgroundNote.ts

456 lines17.2 KB

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