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

RestartBackgroundNote.ts

344 lines12.4 KB

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;
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}`;
29​
30/**
31 * `resumeId` is what the agent resumes a native subagent by, when that is not its
32 * item's native id (a Codex subagent resumes by its own provider thread's id).
33 */
34export function cancelledTurnItemWork(
35 item: OrchestrationV2TurnItem,
36 resumeId?: string,
37): Work | undefined {
38 switch (item.type) {
39 case "subagent": {
40 const nativeId =
41 item.origin === "provider_native" ? (resumeId ?? item.nativeItemRef?.nativeId) : undefined;
42 return {
43 kind: "subagent",
44 label: labelWithId(
45 compactLabel(item.title) === undefined ? item.prompt : item.title,
46 "subagent",
47 nativeId === undefined ? "" : ` (id ${nativeId})`,
48 ),
49 id: item.id,
50 };
51 }
52 case "command_execution":
53 return {
54 kind: "shell",
55 label: compactLabel(item.input) ?? compactLabel(item.title) ?? "background command",
56 id: item.id,
57 };
58 case "dynamic_tool": {
59 const monitor =
60 item.input !== null &&
61 typeof item.input === "object" &&
62 Reflect.get(item.input, "persistent") === true;
63 return {
64 kind: monitor ? "monitor" : "task",
65 label: compactLabel(item.title) ?? compactLabel(item.toolName) ?? "background tool",
66 id: item.id,
67 };
68 }
69 default:
70 return undefined;
71 }
73​
74/**
75 * The provider thread waiting on an item's work. A native subagent can run on
76 * its own child provider thread (Codex), but the turn that started it awaits it.
77 */
78export function awaitingProviderThreadId(
79 item: OrchestrationV2TurnItem,
80 runs: ReadonlyArray<Pick<OrchestrationV2Run, "id" | "providerThreadId">>,
81): OrchestrationV2Run["providerThreadId"] | undefined {
82 const runProviderThreadId = runs.find((run) => run.id === item.runId)?.providerThreadId;
83 return item.type === "subagent" && item.origin === "provider_native"
84 ? (runProviderThreadId ?? item.providerThreadId)
85 : (item.providerThreadId ?? runProviderThreadId);
87​
88function restartWorkKind(task: OrchestrationV2PendingBackgroundTask): Work["kind"] {
89 switch (task.kind) {
90 case "command":
91 return "shell";
92 case "subagent":
93 return "subagent";
94 case "monitor":
95 return "monitor";
96 case "background_task":
97 return "task";
98 default:
99 task satisfies never;
100 return "task";
101 }
103​
104export function cancelledRosterTaskWork(task: OrchestrationV2PendingBackgroundTask): Work {
105 if (task.parentTaskId !== undefined) {
106 return {
107 kind: "subagent",
108 label: labelWithId(task.description, "background task", ` (subagent ${task.parentTaskId})`),
109 id: task.parentTaskId,
110 };
111 }
112 const kind = restartWorkKind(task);
113 const description = compactLabel(task.description);
114 return {
115 kind,
116 label:
117 compactLabel(
118 description === undefined ? task.taskId : `${description} (id ${task.taskId})`,
119 ) ?? "background task",
120 id: task.taskId,
121 };
123​
124const MAX_NOTE_ENTRIES = 10;
125​
126/**
127 * Bounded (entries and label length) so it cannot crowd out the turn's context.
128 */
129export function restartCancelledBackgroundWorkNote(work: ReadonlyArray<Work>): string {
130 const omitted = work.length - MAX_NOTE_ENTRIES;
131 return [
132 "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:",
133 ...work.slice(0, MAX_NOTE_ENTRIES).map((entry) => `- ${entry.kind}: ${entry.label}`),
134 ...(omitted > 0 ? [`- and ${omitted} more`] : []),
135 ].join("\n");
137​
138type ProviderTurnState = Pick<
139 OrchestrationV2ProviderTurn,
140 "runAttemptId" | "providerThreadId" | "status"
141>;
142​
143export function isRestartNoteSource(
144 source: Pick<OrchestrationV2Run, "status" | "activeAttemptId" | "restartCancelledBackgroundWork">,
145 providerTurns: ReadonlyArray<Pick<ProviderTurnState, "runAttemptId" | "status">>,
146): boolean {
147 return (
148 // A failed or interrupted turn is never continued. Recovery cancels a
149 // waiting run it cannot checkpoint, so a cancelled one still qualifies.
150 (source.status === "completed" ||
151 source.status === "waiting" ||
152 source.status === "cancelled") &&
153 (source.restartCancelledBackgroundWork?.length ?? 0) > 0 &&
154 !providerTurns.some(
155 (turn) => turn.runAttemptId === source.activeAttemptId && turn.status === "cancelled",
156 )
157 );
159​
160/**
161 * A shell does not wake it: most are dev servers that nobody waits on, so their
162 * note waits for the next user message.
163 */
164export function isAwaitedWork(work: Pick<Work, "kind">): boolean {
165 return work.kind !== "shell";
167​
168export function runOutcome(
169 run: Pick<OrchestrationV2Run, "status" | "restartCancelledBackgroundWork">,
170): OrchestrationV2Run["status"] {
171 return (run.status === "completed" || run.status === "cancelled") &&
172 (run.restartCancelledBackgroundWork ?? []).some(isAwaitedWork)
173 ? "interrupted"
174 : run.status;
176​
177/**
178 * A run that never reached its provider, such as a provider wake the restart
179 * cut while it was starting: it lost no work and has no turn to continue. A
180 * prepared restart continuation still counts, since it carries its source.
181 */
182export function neverStarted(
183 run: Pick<OrchestrationV2Run, "startedAt" | "restartContinuationOfRunId">,
184): boolean {
185 return run.startedAt === null && run.restartContinuationOfRunId === undefined;
187​
188/**
189 * A run the restart cancelled before it started, so it supersedes nothing. A
190 * run the user stopped before it started still does.
191 */
192export function cancelledBeforeStart(
193 run: Pick<OrchestrationV2Run, "status" | "startedAt" | "restartContinuationOfRunId">,
194): boolean {
195 return run.status === "cancelled" && neverStarted(run);
197​
198export function isRestartContinuationSource(
199 source: Pick<OrchestrationV2Run, "status" | "activeAttemptId" | "restartCancelledBackgroundWork">,
200 providerTurns: ReadonlyArray<Pick<ProviderTurnState, "runAttemptId" | "status">>,
201): boolean {
202 return isRestartNoteSource(source, providerTurns)
203 ? (source.restartCancelledBackgroundWork ?? []).some(isAwaitedWork)
204 : source.status === "cancelled";
206​
207/**
208 * A continuation cut before its provider turn completed may not have delivered
209 * its own note: adapters can announce a running turn before accepting the
210 * prompt. Carry the note forward until a completed turn proves delivery.
211 */
212export function restartContinuationNote(
213 source: OrchestrationV2Run,
214 runs: ReadonlyArray<OrchestrationV2Run>,
215 providerTurns: ReadonlyArray<Pick<ProviderTurnState, "runAttemptId" | "status">>,
216 attempts: ReadonlyArray<Attempt>,
217): { readonly work: ReadonlyArray<Work>; readonly settled: boolean } {
218 const completedAttempts = new Set(
219 providerTurns.filter((turn) => turn.status === "completed").map((turn) => turn.runAttemptId),
220 );
221 const completedRuns = new Set(
222 attempts.filter((attempt) => completedAttempts.has(attempt.id)).map((attempt) => attempt.runId),
223 );
224 let current = source;
225 let work = current.restartCancelledBackgroundWork ?? [];
226 const visited = new Set([current.id]);
227 while (
228 current.restartContinuationOfRunId !== undefined &&
229 !completedRuns.has(current.id) &&
230 !(current.activeAttemptId !== null && completedAttempts.has(current.activeAttemptId))
231 ) {
232 const previous = runs.find((candidate) => candidate.id === current.restartContinuationOfRunId);
233 if (previous === undefined || visited.has(previous.id)) break;
234 visited.add(previous.id);
235 current = previous;
236 work = mergeRestartCancelledBackgroundWork(current.restartCancelledBackgroundWork ?? [], work);
237 }
238 return { work, settled: isRestartNoteSource(current, providerTurns) };
240​
241export function isRestartNoteContinuation(
242 run: Pick<OrchestrationV2Run, "restartContinuationOfRunId">,
243 runs: ReadonlyArray<OrchestrationV2Run>,
244 providerTurns: ReadonlyArray<Pick<ProviderTurnState, "runAttemptId" | "status">>,
245 attempts: ReadonlyArray<Attempt>,
246): boolean {
247 const source =
248 run.restartContinuationOfRunId === undefined
249 ? undefined
250 : runs.find((candidate) => candidate.id === run.restartContinuationOfRunId);
251 return (
252 source !== undefined &&
253 restartContinuationNote(source, runs, providerTurns, attempts).work.length > 0
254 );
256​
257/**
258 * A later completed turn on the same provider thread proves delivery, so the
259 * pending set is derived rather than cleared. Compactions and resumed turns
260 * carry no note, and a rolled-back run left native history, so none of them
261 * counts as delivery.
262 */
263export function pendingRestartCancelledBackgroundWork(input: {
264 readonly runs: ReadonlyArray<OrchestrationV2Run>;
265 readonly providerTurns: ReadonlyArray<ProviderTurnState>;
266 readonly compactionMessageIds: ReadonlySet<string>;
267 readonly run: Pick<
268 OrchestrationV2Run,
269 | "id"
270 | "ordinal"
271 | "completedAt"
272 | "userMessageId"
273 | "providerThreadId"
274 | "restartContinuationOfRunId"
275 | "activeAttemptId"
276 >;
277​
278 readonly attempts: ReadonlyArray<Attempt>;
279}): ReadonlyArray<Work> {
280 const isCompaction = (run: typeof input.run) => input.compactionMessageIds.has(run.userMessageId);
281 if (
282 input.run.providerThreadId === null ||
283 input.run.restartContinuationOfRunId !== undefined ||
284 isCompaction(input.run)
285 )
286 return [];
287 const providerThreadId = input.run.providerThreadId;
288 const deliveredAttemptIds = new Set(
289 input.providerTurns
290 .filter((turn) => turn.providerThreadId === providerThreadId && turn.status === "completed")
291 .map((turn) => turn.runAttemptId),
292 );
293 const sameThread = input.runs.filter((run) => run.providerThreadId === providerThreadId);
294 const prompted = sameThread.filter(
295 (candidate) =>
296 candidate.id !== input.run.id &&
297 candidate.activeAttemptId !== null &&
298 candidate.status !== "rolled_back" &&
299 (deliveredAttemptIds.has(candidate.activeAttemptId) ||
300 input.attempts.some(
301 (attempt) => attempt.runId === candidate.id && deliveredAttemptIds.has(attempt.id),
302 )) &&
303 !isCompaction(candidate) &&
304 (candidate.restartContinuationOfRunId === undefined ||
305 isRestartNoteContinuation(candidate, input.runs, input.providerTurns, input.attempts)),
306 );
307 // A steer restarts this run on a new attempt: an earlier attempt that already
308 // reached the provider delivered the note, so the replacement must not repeat it.
309 const alreadyDelivered = input.attempts.some(
310 (attempt) =>
311 attempt.runId === input.run.id &&
312 attempt.id !== input.run.activeAttemptId &&
313 deliveredAttemptIds.has(attempt.id),
314 );
315 if (alreadyDelivered) return [];
316 return sameThread
317 .filter(
318 (source) =>
319 runRanAfter(input.run, source) &&
320 (source.restartCancelledBackgroundWork?.length ?? 0) > 0 &&
321 !prompted.some((later) => runRanAfter(later, source)),
322 )
323 .reduce<ReadonlyArray<Work>>(
324 (work, source) =>
325 mergeRestartCancelledBackgroundWork(work, source.restartCancelledBackgroundWork ?? []),
326 [],
327 );
329​
330export function mergeRestartCancelledBackgroundWork(
331 current: ReadonlyArray<Work>,
332 added: ReadonlyArray<Work>,
333): ReadonlyArray<Work> {
334 const identity = (entry: Work) => entry.id ?? `${entry.kind}\u0000${entry.label}`;
335 const seen = new Set(current.map(identity));
336 const merged = [...current];
337 for (const entry of added) {
338 const key = identity(entry);
339 if (seen.has(key)) continue;
340 seen.add(key);
341 merged.push(entry);
342 }
343 return merged;