Open History to see the last commit
1import { runRanAfter } from "@t3tools/shared/orchestrationV2ThreadError";
2import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
3import {
4 CommandId,
5 latestProviderTurnForAttempt,
6 MessageId,
7 type OrchestrationV2Run,
8 type RunId,
9 type ThreadId,
10} from "@t3tools/contracts";
11import * as DateTime from "effect/DateTime";
12import * as Effect from "effect/Effect";
13import type { ProjectionRuntimeRecoveryState } from "./ProjectionStore.ts";
14
15import * as ServerSettings from "../serverSettings.ts";
16import { isNativeMaintenanceCommand } from "./CommandPolicy.ts";
17import * as ThreadManagementService from "./ThreadManagementService.ts";
18import {
19 awaitingProviderThreadId,
20 cancelledRosterTaskWork,
21 cancelledTurnItemWork,
22 isAwaitedWork,
23 isRestartContinuationSource,
24 cancelledBeforeStart,
25 isRestartNoteSource,
26 neverStarted,
27 restartCancelledBackgroundWorkNote,
28 restartContinuationNote,
29} from "./RestartBackgroundNote.ts";
30
31const CONTINUE_PROMPT = "Continue where you left off.";
32
33const MAX_CONTINUATION_CHAIN = 3;
34const CONTINUATION_LOOP_WINDOW_MS = 5 * 60 * 1_000;
35
36function restartContinuationBlocked(
37 projection: Pick<
38 ProjectionRuntimeRecoveryState,
39 "thread" | "runtimeRequests" | "providerTurns" | "turnItems"
40 >,
41 source: OrchestrationV2Run,
42 now: DateTime.Utc,
43 settled: boolean,
44): boolean {
45 const { thread } = projection;
46 if (
47 thread.archivedAt !== null ||
48 thread.deletedAt !== null ||
49 thread.settledOverride === "settled" ||
50 (thread.snoozedUntil != null && DateTime.isGreaterThan(thread.snoozedUntil, now))
51 )
52 return true;
53 const turn = latestProviderTurnForAttempt(projection.providerTurns, source.activeAttemptId);
54 if (
55 !settled &&
56 turn !== undefined &&
57 (turn.status === "completed" || turn.status === "failed" || turn.status === "interrupted")
58 )
59 return true;
60 const waitingRequest = projection.runtimeRequests.some(
61 (request) =>
62 request.kind !== "dynamic_tool_call" &&
63 request.kind !== "auth_refresh" &&
64 request.responseCapability.type !== "message" &&
65 (request.status === "pending" ||
66 ((request.status === "expired" || request.status === "cancelled") &&
67 request.responseCapability.type === "not_resumable" &&
68 turn !== undefined &&
69 turn.id === request.providerTurnId)),
70 );
71 if (waitingRequest) return true;
72 return projection.turnItems.some(
73 (item) =>
74 item.type === "secret_request" &&
75 item.runId === source.id &&
76 (item.secretStatus === "pending" ||
77 (item.secretStatus === "cancelled" &&
78 item.completedAt !== null &&
79 source.completedAt !== null &&
80 DateTime.Equivalence(item.completedAt, source.completedAt))),
81 );
82}
83
84/**
85 * App-owned delegations are not counted: their own threads continue and report
86 * back.
87 */
88function hasOpenAwaitedWork(
89 projection: Pick<ProjectionRuntimeRecoveryState, "runs" | "turnItems">,
90 providerThread: ProjectionRuntimeRecoveryState["providerThreads"][number],
91): boolean {
92 const openItem = projection.turnItems.some((item) => {
93 if (item.status !== "pending" && item.status !== "running" && item.status !== "waiting")
94 return false;
95 if (item.type === "subagent" && item.origin === "app_owned" && item.childThreadId !== null)
96 return false;
97 const work = cancelledTurnItemWork(item);
98 return (
99 work !== undefined &&
100 isAwaitedWork(work) &&
101 awaitingProviderThreadId(item, projection.runs) === providerThread.id
102 );
103 });
104 return (
105 openItem ||
106 (providerThread.ownerNodeId === null &&
107 (providerThread.pendingBackgroundTasks ?? []).some((task) =>
108 isAwaitedWork(cancelledRosterTaskWork(task)),
109 ))
110 );
111}
112
113/**
114 * A settled run needs a live session, so stale records from an older crash
115 * never wake it.
116 */
117export function restartContinuationRun(
118 projection: Pick<
119 ProjectionRuntimeRecoveryState,
120 | "thread"
121 | "runs"
122 | "providerThreads"
123 | "providerSessions"
124 | "providerTurns"
125 | "runtimeRequests"
126 | "turnItems"
127 >,
128 now: DateTime.Utc,
129): OrchestrationV2Run | undefined {
130 const run = projection.runs.reduce<OrchestrationV2Run | undefined>(
131 (latest, candidate) =>
132 candidate.status !== "queued" &&
133 !neverStarted(candidate) &&
134 (!latest || runRanAfter(candidate, latest))
135 ? candidate
136 : latest,
137 undefined,
138 );
139 if (!run) return;
140 const preparedContinuation =
141 run.status === "starting" && run.restartContinuationOfRunId !== undefined;
142 const settled = run.status === "completed" || run.status === "waiting";
143 if (run.status !== "running" && !preparedContinuation && !settled) return;
144 if (restartContinuationBlocked(projection, run, now, settled)) return;
145 const liveTurnRequired = !preparedContinuation && !settled;
146 if (projection.thread.providerInstanceId !== run.providerInstanceId) return;
147 const providerThread = projection.providerThreads.find(
148 (thread) => thread.id === run.providerThreadId,
149 );
150 if (
151 !providerThread ||
152 providerThread.appThreadId !== projection.thread.id ||
153 providerThread.ownerNodeId !== null ||
154 providerThread.providerInstanceId !== run.providerInstanceId ||
155 providerThread.nativeThreadRef?.nativeId == null ||
156 providerThread.nativeThreadRef.strength !== "strong" ||
157 providerThread.nativeThreadRef.driver !== providerThread.driver ||
158 (liveTurnRequired && providerThread.status !== "active") ||
159 providerThread.status === "closed" ||
160 providerThread.status === "archived"
161 )
162 return;
163 const session = projection.providerSessions.find(
164 (candidate) => candidate.id === providerThread.providerSessionId,
165 );
166 // Most adapters keep a live session "ready" through its turns, so only a
167 // stopped or failed session rules out a live turn.
168 if (
169 session === undefined ||
170 session.providerInstanceId !== run.providerInstanceId ||
171 session.driver !== providerThread.driver ||
172 (!preparedContinuation && (session.status === "stopped" || session.status === "error"))
173 )
174 return;
175 if (settled) return hasOpenAwaitedWork(projection, providerThread) ? run : undefined;
176 if (
177 liveTurnRequired &&
178 !projection.providerTurns.some(
179 (turn) =>
180 turn.providerThreadId === providerThread.id &&
181 turn.runAttemptId === run.activeAttemptId &&
182 turn.status === "running",
183 )
184 )
185 return;
186 return run;
187}
188
189export const continueRestartedRun = Effect.fn("RestartContinuation.continueRestartedRun")(
190 function* (input: { readonly threadId: ThreadId; readonly sourceRunId: RunId }) {
191 const settings = yield* ServerSettings.ServerSettingsService;
192 const enabled = yield* settings.getSettings.pipe(Effect.orElseSucceed(() => null));
193 if (!enabled) return;
194 const threads = yield* ThreadManagementService.ThreadManagementService;
195 const messageId = MessageId.make(`message:restart-continuation:${input.sourceRunId}`);
196 const projection = yield* threads.getThreadRecords(
197 input.threadId,
198 ["messages", "runs", "providerTurns", "attempts", "runtimeRequests", "turnItems"],
199 { messageIds: [messageId], turnItemTypes: ["secret_request"] },
200 );
201 if (
202 !resolveProjectSettings(enabled, projection.thread.projectId).settings
203 .continueThreadsAfterServerUpdate
204 )
205 return;
206 if (projection.messages.some((message) => message.id === messageId)) return;
207 const source = projection.runs.find((run) => run.id === input.sourceRunId);
208 if (
209 !source ||
210 !isRestartContinuationSource(source, projection.providerTurns) ||
211 restartContinuationBlocked(
212 projection,
213 source,
214 yield* DateTime.now,
215 isRestartNoteSource(source, projection.providerTurns),
216 )
217 )
218 return;
219 if (
220 projection.runs.some(
221 (run) =>
222 run.id !== source.id &&
223 run.status !== "queued" &&
224 !cancelledBeforeStart(run) &&
225 runRanAfter(run, source),
226 )
227 )
228 return;
229 if (projection.thread.providerInstanceId !== source.providerInstanceId) return;
230 // A turn that keeps crashing the server would otherwise restart it forever.
231 let chainLength = 0;
232 const loopWindowStart =
233 DateTime.toEpochMillis(source.completedAt ?? source.requestedAt) -
234 CONTINUATION_LOOP_WINDOW_MS;
235 for (
236 let run: OrchestrationV2Run | undefined = source;
237 run?.restartContinuationOfRunId !== undefined && chainLength < MAX_CONTINUATION_CHAIN;
238 run = projection.runs.find((candidate) => candidate.id === run?.restartContinuationOfRunId)
239 ) {
240 if (DateTime.toEpochMillis(run.requestedAt) < loopWindowStart) break;
241 chainLength += 1;
242 }
243 if (chainLength >= MAX_CONTINUATION_CHAIN) {
244 yield* Effect.logWarning("Not continuing a run restarted too many times in a row", {
245 threadId: input.threadId,
246 sourceRunId: input.sourceRunId,
247 });
248 return;
249 }
250 const sourceRecords = yield* threads.getThreadRecords(
251 input.threadId,
252 ["messages", "turnItems"],
253 {
254 messageIds: [source.userMessageId],
255 turnItemRunIds: [source.id],
256 turnItemTypes: ["run_interrupt_request"],
257 },
258 );
259 if (
260 sourceRecords.turnItems.some(
261 (item) => item.runId === source.id && item.type === "run_interrupt_request",
262 )
263 )
264 return;
265 const sourceMessage = sourceRecords.messages.find(
266 (message) => message.id === source.userMessageId,
267 );
268 if (sourceMessage !== undefined && isNativeMaintenanceCommand(sourceMessage)) return;
269 const note = restartContinuationNote(
270 source,
271 projection.runs,
272 projection.providerTurns,
273 projection.attempts,
274 );
275 const noteText =
276 note.work.length === 0 ? undefined : restartCancelledBackgroundWorkNote(note.work);
277 const text =
278 noteText === undefined
279 ? CONTINUE_PROMPT
280 : note.settled
281 ? noteText
282 : `${noteText}\n\n${CONTINUE_PROMPT}`;
283 yield* threads
284 .dispatch({
285 type: "message.dispatch",
286 commandId: CommandId.make(`command:restart-continuation:${input.sourceRunId}`),
287 threadId: input.threadId,
288 messageId,
289 text,
290 notification: {
291 source: { kind: "system" },
292 outcome: "updated",
293 summary: note.settled
294 ? "T3 Code restarted and stopped background work"
295 : "T3 Code restarted and resumed this turn",
296 detail: text,
297 },
298 attachments: [],
299 modelSelection: source.modelSelection,
300 dispatchMode: { type: "start_immediately" },
301 createdBy: "agent",
302 creationSource: "server",
303 restartContinuationOfRunId: input.sourceRunId,
304 })
305 .pipe(
306 // The project turned this instance off since the restart. No turn
307 // resumes, and the success path below still runs so a delegated
308 // child waiting on this run is recovered immediately instead of
309 // after EffectWorker exhausts its retries on a refusal that will
310 // not change.
311 Effect.catchTags({
312 ThreadManagementProviderInstanceDisabledError: (error) =>
313 Effect.logInfo("orchestration-v2.restart-continuation.instance-disabled", {
314 threadId: input.threadId,
315 sourceRunId: input.sourceRunId,
316 projectId: error.projectId,
317 instanceId: error.instanceId,
318 }),
319 }),
320 );
321 },
322 // A delegated child this declined to continue still owes its parent a
323 // result. Once a continuation run exists this is a no-op; that run settles it.
324 (effect, input) =>
325 effect.pipe(
326 Effect.andThen(
327 Effect.gen(function* () {
328 const threads = yield* ThreadManagementService.ThreadManagementService;
329 yield* threads.recoverDelegatedTask(input.threadId, input.sourceRunId);
330 }),
331 ),
332 ),
333);