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

RestartBackgroundNote.ts

281 lines9.9 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​
23export function cancelledTurnItemWork(item: OrchestrationV2TurnItem): Work | undefined {
24 switch (item.type) {
25 case "subagent":
26 return {
27 kind: "subagent",
28 label: compactLabel(item.title) ?? compactLabel(item.prompt) ?? "subagent",
29 id: item.id,
30 };
31 case "command_execution":
32 return {
33 kind: "shell",
34 label: compactLabel(item.input) ?? compactLabel(item.title) ?? "background command",
35 id: item.id,
36 };
37 case "dynamic_tool": {
38 const monitor =
39 item.input !== null &&
40 typeof item.input === "object" &&
41 Reflect.get(item.input, "persistent") === true;
42 return {
43 kind: monitor ? "monitor" : "task",
44 label: compactLabel(item.title) ?? compactLabel(item.toolName) ?? "background tool",
45 id: item.id,
46 };
47 }
48 default:
49 return undefined;
50 }
52​
53function restartWorkKind(task: OrchestrationV2PendingBackgroundTask): Work["kind"] {
54 switch (task.kind) {
55 case "command":
56 return "shell";
57 case "subagent":
58 return "subagent";
59 case "monitor":
60 return "monitor";
61 case "background_task":
62 return "task";
63 default:
64 task satisfies never;
65 return "task";
66 }
68​
69export function cancelledRosterTaskWork(task: OrchestrationV2PendingBackgroundTask): Work {
70 const kind = restartWorkKind(task);
71 const description = compactLabel(task.description);
72 return {
73 kind,
74 label:
75 compactLabel(
76 description === undefined ? task.taskId : `${description} (id ${task.taskId})`,
77 ) ?? "background task",
78 id: task.taskId,
79 };
81​
82const MAX_NOTE_ENTRIES = 10;
83​
84/**
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");
95​
96type ProviderTurnState = Pick<
97 OrchestrationV2ProviderTurn,
98 "runAttemptId" | "providerThreadId" | "status"
99>;
100​
101export function isRestartNoteSource(
102 source: Pick<OrchestrationV2Run, "status" | "activeAttemptId" | "restartCancelledBackgroundWork">,
103 providerTurns: ReadonlyArray<Pick<ProviderTurnState, "runAttemptId" | "status">>,
104): boolean {
105 return (
106 // A failed or interrupted turn is never continued. Recovery cancels a
107 // waiting run it cannot checkpoint, so a cancelled one still qualifies.
108 (source.status === "completed" ||
109 source.status === "waiting" ||
110 source.status === "cancelled") &&
111 (source.restartCancelledBackgroundWork?.length ?? 0) > 0 &&
112 !providerTurns.some(
113 (turn) => turn.runAttemptId === source.activeAttemptId && turn.status === "cancelled",
114 )
115 );
117​
118/**
119 * A shell does not wake it: most are dev servers that nobody waits on, so their
120 * note waits for the next user message.
121 */
122export function isAwaitedWork(work: Pick<Work, "kind">): boolean {
123 return work.kind !== "shell";
125​
126export function runOutcome(
127 run: Pick<OrchestrationV2Run, "status" | "restartCancelledBackgroundWork">,
128): OrchestrationV2Run["status"] {
129 return (run.status === "completed" || run.status === "cancelled") &&
130 (run.restartCancelledBackgroundWork ?? []).some(isAwaitedWork)
131 ? "interrupted"
132 : run.status;
134​
135export function isRestartContinuationSource(
136 source: Pick<OrchestrationV2Run, "status" | "activeAttemptId" | "restartCancelledBackgroundWork">,
137 providerTurns: ReadonlyArray<Pick<ProviderTurnState, "runAttemptId" | "status">>,
138): boolean {
139 return isRestartNoteSource(source, providerTurns)
140 ? (source.restartCancelledBackgroundWork ?? []).some(isAwaitedWork)
141 : source.status === "cancelled";
143​
144/**
145 * A continuation cut before its provider turn completed may not have delivered
146 * its own note: adapters can announce a running turn before accepting the
147 * prompt. Carry the note forward until a completed turn proves delivery.
148 */
149export function restartContinuationNote(
150 source: OrchestrationV2Run,
151 runs: ReadonlyArray<OrchestrationV2Run>,
152 providerTurns: ReadonlyArray<Pick<ProviderTurnState, "runAttemptId" | "status">>,
153 attempts: ReadonlyArray<Attempt>,
154): { readonly work: ReadonlyArray<Work>; readonly settled: boolean } {
155 const completedAttempts = new Set(
156 providerTurns.filter((turn) => turn.status === "completed").map((turn) => turn.runAttemptId),
157 );
158 const completedRuns = new Set(
159 attempts.filter((attempt) => completedAttempts.has(attempt.id)).map((attempt) => attempt.runId),
160 );
161 let current = source;
162 let work = current.restartCancelledBackgroundWork ?? [];
163 const visited = new Set([current.id]);
164 while (
165 current.restartContinuationOfRunId !== undefined &&
166 !completedRuns.has(current.id) &&
167 !(current.activeAttemptId !== null && completedAttempts.has(current.activeAttemptId))
168 ) {
169 const previous = runs.find((candidate) => candidate.id === current.restartContinuationOfRunId);
170 if (previous === undefined || visited.has(previous.id)) break;
171 visited.add(previous.id);
172 current = previous;
173 work = mergeRestartCancelledBackgroundWork(current.restartCancelledBackgroundWork ?? [], work);
174 }
175 return { work, settled: isRestartNoteSource(current, providerTurns) };
177​
178export function isRestartNoteContinuation(
179 run: Pick<OrchestrationV2Run, "restartContinuationOfRunId">,
180 runs: ReadonlyArray<OrchestrationV2Run>,
181 providerTurns: ReadonlyArray<Pick<ProviderTurnState, "runAttemptId" | "status">>,
182 attempts: ReadonlyArray<Attempt>,
183): boolean {
184 const source =
185 run.restartContinuationOfRunId === undefined
186 ? undefined
187 : runs.find((candidate) => candidate.id === run.restartContinuationOfRunId);
188 return (
189 source !== undefined &&
190 restartContinuationNote(source, runs, providerTurns, attempts).work.length > 0
191 );
193​
194/**
195 * A later completed turn on the same provider thread proves delivery, so the
196 * pending set is derived rather than cleared. Compactions and resumed turns
197 * carry no note, and a rolled-back run left native history, so none of them
198 * counts as delivery.
199 */
200export function pendingRestartCancelledBackgroundWork(input: {
201 readonly runs: ReadonlyArray<OrchestrationV2Run>;
202 readonly providerTurns: ReadonlyArray<ProviderTurnState>;
203 readonly compactionMessageIds: ReadonlySet<string>;
204 readonly run: Pick<
205 OrchestrationV2Run,
206 | "id"
207 | "ordinal"
208 | "completedAt"
209 | "userMessageId"
210 | "providerThreadId"
211 | "restartContinuationOfRunId"
212 | "activeAttemptId"
213 >;
214​
215 readonly attempts: ReadonlyArray<Attempt>;
216}): ReadonlyArray<Work> {
217 const isCompaction = (run: typeof input.run) => input.compactionMessageIds.has(run.userMessageId);
218 if (
219 input.run.providerThreadId === null ||
220 input.run.restartContinuationOfRunId !== undefined ||
221 isCompaction(input.run)
222 )
223 return [];
224 const providerThreadId = input.run.providerThreadId;
225 const deliveredAttemptIds = new Set(
226 input.providerTurns
227 .filter((turn) => turn.providerThreadId === providerThreadId && turn.status === "completed")
228 .map((turn) => turn.runAttemptId),
229 );
230 const sameThread = input.runs.filter((run) => run.providerThreadId === providerThreadId);
231 const prompted = sameThread.filter(
232 (candidate) =>
233 candidate.id !== input.run.id &&
234 candidate.activeAttemptId !== null &&
235 candidate.status !== "rolled_back" &&
236 (deliveredAttemptIds.has(candidate.activeAttemptId) ||
237 input.attempts.some(
238 (attempt) => attempt.runId === candidate.id && deliveredAttemptIds.has(attempt.id),
239 )) &&
240 !isCompaction(candidate) &&
241 (candidate.restartContinuationOfRunId === undefined ||
242 isRestartNoteContinuation(candidate, input.runs, input.providerTurns, input.attempts)),
243 );
244 // A steer restarts this run on a new attempt: an earlier attempt that already
245 // reached the provider delivered the note, so the replacement must not repeat it.
246 const alreadyDelivered = input.attempts.some(
247 (attempt) =>
248 attempt.runId === input.run.id &&
249 attempt.id !== input.run.activeAttemptId &&
250 deliveredAttemptIds.has(attempt.id),
251 );
252 if (alreadyDelivered) return [];
253 return sameThread
254 .filter(
255 (source) =>
256 runRanAfter(input.run, source) &&
257 (source.restartCancelledBackgroundWork?.length ?? 0) > 0 &&
258 !prompted.some((later) => runRanAfter(later, source)),
259 )
260 .reduce<ReadonlyArray<Work>>(
261 (work, source) =>
262 mergeRestartCancelledBackgroundWork(work, source.restartCancelledBackgroundWork ?? []),
263 [],
264 );
266​
267export function mergeRestartCancelledBackgroundWork(
268 current: ReadonlyArray<Work>,
269 added: ReadonlyArray<Work>,
270): ReadonlyArray<Work> {
271 const identity = (entry: Work) => entry.id ?? `${entry.kind}\u0000${entry.label}`;
272 const seen = new Set(current.map(identity));
273 const merged = [...current];
274 for (const entry of added) {
275 const key = identity(entry);
276 if (seen.has(key)) continue;
277 seen.add(key);
278 merged.push(entry);
279 }
280 return merged;