Open History to see the last commit
1import type {
2 OrchestrationV2PendingBackgroundTask,
3 OrchestrationV2ProviderTurn,
4 OrchestrationV2RestartCancelledBackgroundWork,
5 OrchestrationV2Run,
6 OrchestrationV2TurnItem,
7} from "@t3tools/contracts";
8
9type Work = OrchestrationV2RestartCancelledBackgroundWork;
10
11const MAX_LABEL_LENGTH = 160;
12
13function compactLabel(value: unknown): string | undefined {
14 if (typeof value !== "string") return undefined;
15 const text = value.replaceAll(/\s+/g, " ").trim();
16 if (text.length === 0) return undefined;
17 return text.length > MAX_LABEL_LENGTH ? `${text.slice(0, MAX_LABEL_LENGTH - 1)}…` : text;
18}
19
20/** Describes a background-capable turn item that restart recovery cancels. */
21export function cancelledTurnItemWork(item: OrchestrationV2TurnItem): Work | undefined {
22 switch (item.type) {
23 case "subagent":
24 return {
25 kind: "subagent",
26 label: compactLabel(item.title) ?? compactLabel(item.prompt) ?? "subagent",
27 id: item.id,
28 };
29 case "command_execution":
30 return {
31 kind: "shell",
32 label: compactLabel(item.input) ?? compactLabel(item.title) ?? "background command",
33 id: item.id,
34 };
35 case "dynamic_tool": {
36 const monitor =
37 item.input !== null &&
38 typeof item.input === "object" &&
39 Reflect.get(item.input, "persistent") === true;
40 return {
41 kind: monitor ? "monitor" : "task",
42 label: compactLabel(item.title) ?? compactLabel(item.toolName) ?? "background tool",
43 id: item.id,
44 };
45 }
46 default:
47 return undefined;
48 }
49}
50
51function restartWorkKind(task: OrchestrationV2PendingBackgroundTask): Work["kind"] {
52 switch (task.kind) {
53 case "command":
54 return "shell";
55 case "subagent":
56 return "subagent";
57 case "monitor":
58 return "monitor";
59 case "background_task":
60 return "task";
61 default:
62 task satisfies never;
63 return "task";
64 }
65}
66
67/** Describes a provider-reported background task (the provider-thread roster). */
68export function cancelledRosterTaskWork(task: OrchestrationV2PendingBackgroundTask): Work {
69 const kind = restartWorkKind(task);
70 const description = compactLabel(task.description);
71 return {
72 kind,
73 label:
74 compactLabel(
75 description === undefined ? task.taskId : `${description} (id ${task.taskId})`,
76 ) ?? "background task",
77 id: task.taskId,
78 };
79}
80
81const MAX_NOTE_ENTRIES = 10;
82
83/**
84 * Provider-facing text for work the model still expects to hear back from.
85 * Bounded (entries and label length) so it cannot crowd out the turn's context.
86 */
87export function restartCancelledBackgroundWorkNote(work: ReadonlyArray<Work>): string {
88 const omitted = work.length - MAX_NOTE_ENTRIES;
89 return [
90 "Note: the T3 server restarted, and this background work was cancelled before it finished. It will not report back:",
91 ...work.slice(0, MAX_NOTE_ENTRIES).map((entry) => `- ${entry.kind}: ${entry.label}`),
92 ...(omitted > 0 ? [`- and ${omitted} more`] : []),
93 ].join("\n");
94}
95
96type ProviderTurnState = Pick<
97 OrchestrationV2ProviderTurn,
98 "runAttemptId" | "providerThreadId" | "status"
99>;
100
101/**
102 * A run whose turn had settled before the restart cancelled its background
103 * work. Continuing it prompts the provider with the note. A run cut mid-turn
104 * instead resumes that turn, which Codex does natively without a prompt.
105 */
106export function isRestartNoteSource(
107 source: Pick<OrchestrationV2Run, "status" | "activeAttemptId" | "restartCancelledBackgroundWork">,
108 providerTurns: ReadonlyArray<Pick<ProviderTurnState, "runAttemptId" | "status">>,
109): boolean {
110 return (
111 // A failed or interrupted turn is never continued. Recovery cancels a
112 // waiting run it cannot checkpoint, so a cancelled one still qualifies.
113 (source.status === "completed" ||
114 source.status === "waiting" ||
115 source.status === "cancelled") &&
116 (source.restartCancelledBackgroundWork?.length ?? 0) > 0 &&
117 !providerTurns.some(
118 (turn) => turn.runAttemptId === source.activeAttemptId && turn.status === "cancelled",
119 )
120 );
121}
122
123/** A restart continuation whose prompt is the note rather than a resume. */
124export function isRestartNoteContinuation(
125 run: Pick<OrchestrationV2Run, "restartContinuationOfRunId">,
126 runs: ReadonlyArray<OrchestrationV2Run>,
127 providerTurns: ReadonlyArray<Pick<ProviderTurnState, "runAttemptId" | "status">>,
128): boolean {
129 const source =
130 run.restartContinuationOfRunId === undefined
131 ? undefined
132 : runs.find((candidate) => candidate.id === run.restartContinuationOfRunId);
133 return source !== undefined && isRestartNoteSource(source, providerTurns);
134}
135
136/**
137 * Work cancelled by a restart that the run's provider thread has not been told
138 * about yet. The note belongs to the provider thread that lost the work: turns
139 * on another provider (after a switch) neither owe it nor deliver it. A later
140 * run on the same provider thread delivers it once its attempt reaches the
141 * provider, so the pending set is derived rather than cleared. Compactions and
142 * resumed turns carry no note, and a rolled-back run left native history, so
143 * none of them counts as delivery. A note continuation's own prompt is the note.
144 */
145export function pendingRestartCancelledBackgroundWork(input: {
146 readonly runs: ReadonlyArray<OrchestrationV2Run>;
147 readonly providerTurns: ReadonlyArray<ProviderTurnState>;
148 readonly compactionMessageIds: ReadonlySet<string>;
149 readonly run: Pick<
150 OrchestrationV2Run,
151 | "id"
152 | "ordinal"
153 | "userMessageId"
154 | "providerThreadId"
155 | "restartContinuationOfRunId"
156 | "activeAttemptId"
157 >;
158 /** Every attempt id of `run`; a steer replaces the attempt but not the run. */
159 readonly runAttemptIds: ReadonlyArray<OrchestrationV2Run["activeAttemptId"] & string>;
160}): ReadonlyArray<Work> {
161 const isCompaction = (run: typeof input.run) => input.compactionMessageIds.has(run.userMessageId);
162 // The current run prepends the note unless it is a compaction or a
163 // continuation (whose own prompt is the note, or which resumes natively).
164 if (
165 input.run.providerThreadId === null ||
166 input.run.restartContinuationOfRunId !== undefined ||
167 isCompaction(input.run)
168 )
169 return [];
170 const providerThreadId = input.run.providerThreadId;
171 const deliveredAttemptIds = new Set(
172 input.providerTurns
173 .filter((turn) => turn.providerThreadId === providerThreadId)
174 .map((turn) => turn.runAttemptId),
175 );
176 const sameThread = input.runs.filter((run) => run.providerThreadId === providerThreadId);
177 const prompted = sameThread.filter(
178 (candidate) =>
179 candidate.id !== input.run.id &&
180 candidate.activeAttemptId !== null &&
181 candidate.status !== "rolled_back" &&
182 deliveredAttemptIds.has(candidate.activeAttemptId) &&
183 !isCompaction(candidate) &&
184 (candidate.restartContinuationOfRunId === undefined ||
185 isRestartNoteContinuation(candidate, input.runs, input.providerTurns)),
186 );
187 // A steer restarts this run on a new attempt: an earlier attempt that already
188 // reached the provider delivered the note, so the replacement must not repeat it.
189 const alreadyDelivered = input.runAttemptIds.some(
190 (attemptId) => attemptId !== input.run.activeAttemptId && deliveredAttemptIds.has(attemptId),
191 );
192 if (alreadyDelivered) return [];
193 return sameThread
194 .filter(
195 (source) =>
196 source.ordinal < input.run.ordinal &&
197 (source.restartCancelledBackgroundWork?.length ?? 0) > 0 &&
198 !prompted.some((later) => later.ordinal > source.ordinal),
199 )
200 .reduce<ReadonlyArray<Work>>(
201 (work, source) =>
202 mergeRestartCancelledBackgroundWork(work, source.restartCancelledBackgroundWork ?? []),
203 [],
204 );
205}
206
207export function mergeRestartCancelledBackgroundWork(
208 current: ReadonlyArray<Work>,
209 added: ReadonlyArray<Work>,
210): ReadonlyArray<Work> {
211 // Rows recorded before ids existed fall back to kind + label.
212 const identity = (entry: Work) => entry.id ?? `${entry.kind}\u0000${entry.label}`;
213 const seen = new Set(current.map(identity));
214 const merged = [...current];
215 for (const entry of added) {
216 const key = identity(entry);
217 if (seen.has(key)) continue;
218 seen.add(key);
219 merged.push(entry);
220 }
221 return merged;
222}