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

RestartBackgroundNote.ts

276 lines10.3 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): 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 > MAX_LABEL_LENGTH ? `${text.slice(0, MAX_LABEL_LENGTH - 1)}…` : text;
22​
23/** Describes a background-capable turn item that restart recovery cancels. */
24export function cancelledTurnItemWork(item: OrchestrationV2TurnItem): Work | undefined {
25 switch (item.type) {
26 case "subagent":
27 return {
28 kind: "subagent",
29 label: compactLabel(item.title) ?? compactLabel(item.prompt) ?? "subagent",
30 id: item.id,
31 };
32 case "command_execution":
33 return {
34 kind: "shell",
35 label: compactLabel(item.input) ?? compactLabel(item.title) ?? "background command",
36 id: item.id,
37 };
38 case "dynamic_tool": {
39 const monitor =
40 item.input !== null &&
41 typeof item.input === "object" &&
42 Reflect.get(item.input, "persistent") === true;
43 return {
44 kind: monitor ? "monitor" : "task",
45 label: compactLabel(item.title) ?? compactLabel(item.toolName) ?? "background tool",
46 id: item.id,
47 };
48 }
49 default:
50 return undefined;
51 }
53​
54function restartWorkKind(task: OrchestrationV2PendingBackgroundTask): Work["kind"] {
55 switch (task.kind) {
56 case "command":
57 return "shell";
58 case "subagent":
59 return "subagent";
60 case "monitor":
61 return "monitor";
62 case "background_task":
63 return "task";
64 default:
65 task satisfies never;
66 return "task";
67 }
69​
70/** Describes a provider-reported background task (the provider-thread roster). */
71export function cancelledRosterTaskWork(task: OrchestrationV2PendingBackgroundTask): Work {
72 const kind = restartWorkKind(task);
73 const description = compactLabel(task.description);
74 return {
75 kind,
76 label:
77 compactLabel(
78 description === undefined ? task.taskId : `${description} (id ${task.taskId})`,
79 ) ?? "background task",
80 id: task.taskId,
81 };
83​
84const MAX_NOTE_ENTRIES = 10;
85​
86/**
87 * Provider-facing text for work the model still expects to hear back from.
88 * Bounded (entries and label length) so it cannot crowd out the turn's context.
89 */
90export function restartCancelledBackgroundWorkNote(work: ReadonlyArray<Work>): string {
91 const omitted = work.length - MAX_NOTE_ENTRIES;
92 return [
93 "Note: the T3 server restarted, and this background work was cancelled before it finished. It will not report back:",
94 ...work.slice(0, MAX_NOTE_ENTRIES).map((entry) => `- ${entry.kind}: ${entry.label}`),
95 ...(omitted > 0 ? [`- and ${omitted} more`] : []),
96 ].join("\n");
98​
99type ProviderTurnState = Pick<
100 OrchestrationV2ProviderTurn,
101 "runAttemptId" | "providerThreadId" | "status"
102>;
103​
104/**
105 * A run whose turn had settled before the restart cancelled its background
106 * work. Continuing it prompts the provider with the note. A run cut mid-turn
107 * instead resumes that turn, which Codex does natively without a prompt.
108 */
109export function isRestartNoteSource(
110 source: Pick<OrchestrationV2Run, "status" | "activeAttemptId" | "restartCancelledBackgroundWork">,
111 providerTurns: ReadonlyArray<Pick<ProviderTurnState, "runAttemptId" | "status">>,
112): boolean {
113 return (
114 // A failed or interrupted turn is never continued. Recovery cancels a
115 // waiting run it cannot checkpoint, so a cancelled one still qualifies.
116 (source.status === "completed" ||
117 source.status === "waiting" ||
118 source.status === "cancelled") &&
119 (source.restartCancelledBackgroundWork?.length ?? 0) > 0 &&
120 !providerTurns.some(
121 (turn) => turn.runAttemptId === source.activeAttemptId && turn.status === "cancelled",
122 )
123 );
125​
126/**
127 * The note a restart continuation of `source` carries, and whether the turn it
128 * continues had settled (the note is then the whole prompt). A continuation cut
129 * before its provider turn completed may not have delivered its own note:
130 * adapters can announce a running turn before accepting the prompt. Carry the
131 * note forward until a completed turn proves delivery.
132 */
133export function restartContinuationNote(
134 source: OrchestrationV2Run,
135 runs: ReadonlyArray<OrchestrationV2Run>,
136 providerTurns: ReadonlyArray<Pick<ProviderTurnState, "runAttemptId" | "status">>,
137 attempts: ReadonlyArray<Attempt>,
138): { readonly work: ReadonlyArray<Work>; readonly settled: boolean } {
139 const completedAttempts = new Set(
140 providerTurns.filter((turn) => turn.status === "completed").map((turn) => turn.runAttemptId),
141 );
142 const completedRuns = new Set(
143 attempts.filter((attempt) => completedAttempts.has(attempt.id)).map((attempt) => attempt.runId),
144 );
145 let current = source;
146 let work = current.restartCancelledBackgroundWork ?? [];
147 const visited = new Set([current.id]);
148 while (
149 current.restartContinuationOfRunId !== undefined &&
150 !completedRuns.has(current.id) &&
151 !(current.activeAttemptId !== null && completedAttempts.has(current.activeAttemptId))
152 ) {
153 const previous = runs.find((candidate) => candidate.id === current.restartContinuationOfRunId);
154 if (previous === undefined || visited.has(previous.id)) break;
155 visited.add(previous.id);
156 current = previous;
157 work = mergeRestartCancelledBackgroundWork(current.restartCancelledBackgroundWork ?? [], work);
158 }
159 return { work, settled: isRestartNoteSource(current, providerTurns) };
161​
162/**
163 * A restart continuation prompted with the note rather than a native resume.
164 * A turn cut mid-way that lost background work is prompted too, so the note
165 * is delivered with it; only a continuation without a note resumes natively.
166 */
167export function isRestartNoteContinuation(
168 run: Pick<OrchestrationV2Run, "restartContinuationOfRunId">,
169 runs: ReadonlyArray<OrchestrationV2Run>,
170 providerTurns: ReadonlyArray<Pick<ProviderTurnState, "runAttemptId" | "status">>,
171 attempts: ReadonlyArray<Attempt>,
172): boolean {
173 const source =
174 run.restartContinuationOfRunId === undefined
175 ? undefined
176 : runs.find((candidate) => candidate.id === run.restartContinuationOfRunId);
177 return (
178 source !== undefined &&
179 restartContinuationNote(source, runs, providerTurns, attempts).work.length > 0
180 );
182​
183/**
184 * Work cancelled by a restart that the run's provider thread has not been told
185 * about yet. The note belongs to the provider thread that lost the work: turns
186 * on another provider (after a switch) neither owe it nor deliver it. A later
187 * completed turn on the same provider thread proves delivery, so the pending
188 * set is derived rather than cleared. Compactions and
189 * resumed turns carry no note, and a rolled-back run left native history, so
190 * none of them counts as delivery. A note continuation's own prompt is the note.
191 */
192export function pendingRestartCancelledBackgroundWork(input: {
193 readonly runs: ReadonlyArray<OrchestrationV2Run>;
194 readonly providerTurns: ReadonlyArray<ProviderTurnState>;
195 readonly compactionMessageIds: ReadonlySet<string>;
196 readonly run: Pick<
197 OrchestrationV2Run,
198 | "id"
199 | "ordinal"
200 | "completedAt"
201 | "userMessageId"
202 | "providerThreadId"
203 | "restartContinuationOfRunId"
204 | "activeAttemptId"
205 >;
206 /** Include earlier attempts: a steer replaces the attempt but not the run. */
207 readonly attempts: ReadonlyArray<Attempt>;
208}): ReadonlyArray<Work> {
209 const isCompaction = (run: typeof input.run) => input.compactionMessageIds.has(run.userMessageId);
210 // The current run prepends the note unless it is a compaction or a
211 // continuation (whose own prompt is the note, or which resumes natively).
212 if (
213 input.run.providerThreadId === null ||
214 input.run.restartContinuationOfRunId !== undefined ||
215 isCompaction(input.run)
216 )
217 return [];
218 const providerThreadId = input.run.providerThreadId;
219 const deliveredAttemptIds = new Set(
220 input.providerTurns
221 .filter((turn) => turn.providerThreadId === providerThreadId && turn.status === "completed")
222 .map((turn) => turn.runAttemptId),
223 );
224 const sameThread = input.runs.filter((run) => run.providerThreadId === providerThreadId);
225 const prompted = sameThread.filter(
226 (candidate) =>
227 candidate.id !== input.run.id &&
228 candidate.activeAttemptId !== null &&
229 candidate.status !== "rolled_back" &&
230 (deliveredAttemptIds.has(candidate.activeAttemptId) ||
231 input.attempts.some(
232 (attempt) => attempt.runId === candidate.id && deliveredAttemptIds.has(attempt.id),
233 )) &&
234 !isCompaction(candidate) &&
235 (candidate.restartContinuationOfRunId === undefined ||
236 isRestartNoteContinuation(candidate, input.runs, input.providerTurns, input.attempts)),
237 );
238 // A steer restarts this run on a new attempt: an earlier attempt that already
239 // reached the provider delivered the note, so the replacement must not repeat it.
240 const alreadyDelivered = input.attempts.some(
241 (attempt) =>
242 attempt.runId === input.run.id &&
243 attempt.id !== input.run.activeAttemptId &&
244 deliveredAttemptIds.has(attempt.id),
245 );
246 if (alreadyDelivered) return [];
247 return sameThread
248 .filter(
249 (source) =>
250 runRanAfter(input.run, source) &&
251 (source.restartCancelledBackgroundWork?.length ?? 0) > 0 &&
252 !prompted.some((later) => runRanAfter(later, source)),
253 )
254 .reduce<ReadonlyArray<Work>>(
255 (work, source) =>
256 mergeRestartCancelledBackgroundWork(work, source.restartCancelledBackgroundWork ?? []),
257 [],
258 );
260​
261export function mergeRestartCancelledBackgroundWork(
262 current: ReadonlyArray<Work>,
263 added: ReadonlyArray<Work>,
264): ReadonlyArray<Work> {
265 // Rows recorded before ids existed fall back to kind + label.
266 const identity = (entry: Work) => entry.id ?? `${entry.kind}\u0000${entry.label}`;
267 const seen = new Set(current.map(identity));
268 const merged = [...current];
269 for (const entry of added) {
270 const key = identity(entry);
271 if (seen.has(key)) continue;
272 seen.add(key);
273 merged.push(entry);
274 }
275 return merged;