Open History to see the last commit
1import { runRanAfter } from "@t3tools/shared/orchestrationV2ThreadError";
2import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
3import {
4 CommandId,
5 isOrchestrationV2WorkActive,
6 latestProviderTurnForAttempt,
7 MessageId,
8 type OrchestrationV2Run,
9 type RunId,
10 type ThreadId,
11} from "@t3tools/contracts";
12import * as DateTime from "effect/DateTime";
13import * as Effect from "effect/Effect";
14import type {
15 ProjectionRecordField,
16 ProjectionRecordFilter,
17 ProjectionRecords,
18 ProjectionRuntimeRecoveryState,
19} from "./ProjectionStore.ts";
20
21import * as ServerSettings from "../serverSettings.ts";
22import { isNativeMaintenanceCommand } from "./CommandPolicy.ts";
23import * as ThreadManagementService from "./ThreadManagementService.ts";
24import {
25 type BackgroundWorkLossCause,
26 awaitingProviderThreadId,
27 cancelledRosterTaskWork,
28 cancelledTurnItemWork,
29 continuationFailedBeforePrompt,
30 isAwaitedWork,
31 isRestartContinuationSource,
32 cancelledBeforeStart,
33 isRestartNoteSource,
34 neverStarted,
35 restartCancelledBackgroundWorkNote,
36 restartContinuationNote,
37} from "./RestartBackgroundNote.ts";
38
39const CONTINUE_PROMPT =
40 "Continue where you left off. Your last turn was cut short, so a command or other action it started may have finished or may still be running. Before you repeat one that changes state, confirm it did not take effect and is not still running; if you cannot tell, say so instead of repeating it.";
41
42const MAX_CONTINUATION_CHAIN = 3;
43const CONTINUATION_LOOP_WINDOW_MS = 5 * 60 * 1_000;
44
45export function restartContinuationBlocked(
46 projection: Pick<
47 ProjectionRuntimeRecoveryState,
48 "thread" | "runtimeRequests" | "providerTurns" | "turnItems"
49 >,
50 source: OrchestrationV2Run,
51 now: DateTime.Utc,
52 settled: boolean,
53): boolean {
54 const { thread } = projection;
55 if (
56 thread.archivedAt !== null ||
57 thread.deletedAt !== null ||
58 thread.settledOverride === "settled" ||
59 (thread.snoozedUntil != null && DateTime.isGreaterThan(thread.snoozedUntil, now))
60 )
61 return true;
62 const turn = latestProviderTurnForAttempt(projection.providerTurns, source.activeAttemptId);
63 if (
64 !settled &&
65 turn !== undefined &&
66 (turn.status === "completed" || turn.status === "failed" || turn.status === "interrupted")
67 )
68 return true;
69 const waitingRequest = projection.runtimeRequests.some(
70 (request) =>
71 request.kind !== "dynamic_tool_call" &&
72 request.kind !== "auth_refresh" &&
73 request.responseCapability.type !== "message" &&
74 (request.status === "pending" ||
75 ((request.status === "expired" || request.status === "cancelled") &&
76 request.responseCapability.type === "not_resumable" &&
77 turn !== undefined &&
78 turn.id === request.providerTurnId)),
79 );
80 if (waitingRequest) return true;
81 return projection.turnItems.some(
82 (item) =>
83 item.type === "secret_request" &&
84 item.runId === source.id &&
85 (item.secretStatus === "pending" ||
86 (item.secretStatus === "cancelled" &&
87 item.completedAt !== null &&
88 source.completedAt !== null &&
89 DateTime.Equivalence(item.completedAt, source.completedAt))),
90 );
91}
92
93/** A Stop from the user, or from the parent that delegated the task, that a restart cut short. */
94export const restartStopRequested = Effect.fn("RestartContinuation.restartStopRequested")(
95 function* <E>(
96 getThreadRecords: <K extends ProjectionRecordField>(
97 threadId: ThreadId,
98 fields: ReadonlyArray<K>,
99 filter: ProjectionRecordFilter,
100 ) => Effect.Effect<ProjectionRecords<K>, E>,
101 thread: Pick<ProjectionRuntimeRecoveryState["thread"], "id" | "lineage" | "forkedFrom">,
102 source: Pick<OrchestrationV2Run, "id" | "delegatedTaskId">,
103 ) {
104 const { turnItems } = yield* getThreadRecords(thread.id, ["turnItems"], {
105 turnItemRunIds: [source.id],
106 turnItemTypes: ["run_interrupt_request"],
107 });
108 if (turnItems.some((item) => item.runId === source.id && item.type === "run_interrupt_request"))
109 return true;
110 const { lineage, forkedFrom } = thread;
111 const taskId =
112 source.delegatedTaskId ?? (forkedFrom?.type === "node" ? forkedFrom.nodeId : undefined);
113 if (
114 lineage.relationshipToParent !== "subagent" ||
115 lineage.parentThreadId === null ||
116 taskId === undefined
117 )
118 return false;
119 const task = (yield* getThreadRecords(lineage.parentThreadId, ["subagents"], {
120 subagentIds: [taskId],
121 })).subagents.find((candidate) => candidate.id === taskId);
122 // A settled task no longer owns later work in its thread.
123 if (
124 task === undefined ||
125 task.runId === null ||
126 task.result !== null ||
127 !isOrchestrationV2WorkActive(task.status)
128 )
129 return false;
130 return (
131 (yield* getThreadRecords(lineage.parentThreadId, ["turnItems"], {
132 turnItemTypes: ["run_interrupt_request"],
133 turnItemRunIds: [task.runId],
134 })).turnItems.length > 0
135 );
136 },
137);
138
139/** App-owned delegations continue in their own threads and report back. */
140function hasOpenAwaitedWork(
141 projection: Pick<ProjectionRuntimeRecoveryState, "runs" | "turnItems">,
142 providerThread: ProjectionRuntimeRecoveryState["providerThreads"][number],
143): boolean {
144 const openItem = projection.turnItems.some((item) => {
145 if (item.status !== "pending" && item.status !== "running" && item.status !== "waiting")
146 return false;
147 if (item.type === "subagent" && item.origin === "app_owned" && item.childThreadId !== null)
148 return false;
149 const work = cancelledTurnItemWork(item);
150 return (
151 work !== undefined &&
152 isAwaitedWork(work) &&
153 awaitingProviderThreadId(item, projection.runs) === providerThread.id
154 );
155 });
156 return (
157 openItem ||
158 (providerThread.ownerNodeId === null &&
159 (providerThread.pendingBackgroundTasks ?? []).some((task) =>
160 isAwaitedWork(cancelledRosterTaskWork(task)),
161 ))
162 );
163}
164
165/** Settled runs require a live session so stale crash records cannot wake them. */
166export function restartContinuationRun(
167 projection: Pick<
168 ProjectionRuntimeRecoveryState,
169 | "thread"
170 | "runs"
171 | "providerThreads"
172 | "providerSessions"
173 | "providerTurns"
174 | "runtimeRequests"
175 | "turnItems"
176 >,
177 now: DateTime.Utc,
178): OrchestrationV2Run | undefined {
179 const run = projection.runs.reduce<OrchestrationV2Run | undefined>(
180 (latest, candidate) =>
181 candidate.status !== "queued" &&
182 !neverStarted(candidate) &&
183 (!latest || runRanAfter(candidate, latest))
184 ? candidate
185 : latest,
186 undefined,
187 );
188 if (!run) return;
189 const preparedContinuation =
190 run.status === "starting" && run.restartContinuationOfRunId !== undefined;
191 const settled = run.status === "completed" || run.status === "waiting";
192 if (run.status !== "running" && !preparedContinuation && !settled) return;
193 if (restartContinuationBlocked(projection, run, now, settled)) return;
194 const liveTurnRequired = !preparedContinuation && !settled;
195 if (projection.thread.providerInstanceId !== run.providerInstanceId) return;
196 const providerThread = projection.providerThreads.find(
197 (thread) => thread.id === run.providerThreadId,
198 );
199 if (
200 !providerThread ||
201 providerThread.appThreadId !== projection.thread.id ||
202 providerThread.ownerNodeId !== null ||
203 providerThread.providerInstanceId !== run.providerInstanceId ||
204 providerThread.nativeThreadRef?.nativeId == null ||
205 providerThread.nativeThreadRef.strength !== "strong" ||
206 providerThread.nativeThreadRef.driver !== providerThread.driver ||
207 (liveTurnRequired && providerThread.status !== "active") ||
208 providerThread.status === "closed" ||
209 providerThread.status === "archived"
210 )
211 return;
212 const session = projection.providerSessions.find(
213 (candidate) => candidate.id === providerThread.providerSessionId,
214 );
215 // Adapters remain ready during turns; only stopped or failed sessions rule out liveness.
216 if (
217 session === undefined ||
218 session.providerInstanceId !== run.providerInstanceId ||
219 session.driver !== providerThread.driver ||
220 (!preparedContinuation && (session.status === "stopped" || session.status === "error"))
221 )
222 return;
223 if (settled) return hasOpenAwaitedWork(projection, providerThread) ? run : undefined;
224 if (
225 liveTurnRequired &&
226 !projection.providerTurns.some(
227 (turn) =>
228 turn.providerThreadId === providerThread.id &&
229 turn.runAttemptId === run.activeAttemptId &&
230 turn.status === "running",
231 )
232 )
233 return;
234 return run;
235}
236
237export const continueRestartedRun = Effect.fn("RestartContinuation.continueRestartedRun")(
238 function* (input: {
239 readonly threadId: ThreadId;
240 readonly sourceRunId: RunId;
241 readonly processLossCount?: number;
242 readonly cause?: BackgroundWorkLossCause;
243 }) {
244 const settings = yield* ServerSettings.ServerSettingsService;
245 const enabled = yield* settings.getSettings.pipe(Effect.orElseSucceed(() => null));
246 if (!enabled) return;
247 const threads = yield* ThreadManagementService.ThreadManagementService;
248 const messageId = MessageId.make(`message:restart-continuation:${input.sourceRunId}`);
249 const projection = yield* threads.getThreadRecords(
250 input.threadId,
251 ["messages", "runs", "providerTurns", "attempts", "runtimeRequests", "turnItems"],
252 { messageIds: [messageId], turnItemTypes: ["secret_request"] },
253 );
254 if (
255 !resolveProjectSettings(enabled, projection.thread.projectId).settings
256 .continueThreadsAfterServerUpdate
257 )
258 return;
259 if (projection.messages.some((message) => message.id === messageId)) return;
260 const source = projection.runs.find((run) => run.id === input.sourceRunId);
261 if (
262 !source ||
263 !(
264 isRestartContinuationSource(source, projection.providerTurns) ||
265 continuationFailedBeforePrompt(source, projection.providerTurns)
266 ) ||
267 restartContinuationBlocked(
268 projection,
269 source,
270 yield* DateTime.now,
271 isRestartNoteSource(source, projection.providerTurns),
272 )
273 )
274 return;
275 if (
276 projection.runs.some(
277 (run) =>
278 run.id !== source.id &&
279 run.status !== "queued" &&
280 !cancelledBeforeStart(run) &&
281 runRanAfter(run, source),
282 )
283 )
284 return;
285 if (projection.thread.providerInstanceId !== source.providerInstanceId) return;
286 // A turn that keeps crashing the server would otherwise restart it forever.
287 let chainLength = 0;
288 const loopWindowStart =
289 DateTime.toEpochMillis(source.completedAt ?? source.requestedAt) -
290 CONTINUATION_LOOP_WINDOW_MS;
291 for (
292 let run: OrchestrationV2Run | undefined = source;
293 run?.restartContinuationOfRunId !== undefined && chainLength < MAX_CONTINUATION_CHAIN;
294 run = projection.runs.find((candidate) => candidate.id === run?.restartContinuationOfRunId)
295 ) {
296 if (DateTime.toEpochMillis(run.requestedAt) < loopWindowStart) break;
297 chainLength += 1;
298 }
299 if (
300 input.processLossCount === undefined
301 ? chainLength >= MAX_CONTINUATION_CHAIN
302 : input.processLossCount > MAX_CONTINUATION_CHAIN
303 ) {
304 yield* Effect.logWarning("Not continuing a run restarted too many times in a row", {
305 threadId: input.threadId,
306 sourceRunId: input.sourceRunId,
307 });
308 return;
309 }
310 if (yield* restartStopRequested(threads.getThreadRecords, projection.thread, source)) return;
311 const sourceMessage = (yield* threads.getThreadRecords(input.threadId, ["messages"], {
312 messageIds: [source.userMessageId],
313 })).messages.find((message) => message.id === source.userMessageId);
314 if (sourceMessage !== undefined && isNativeMaintenanceCommand(sourceMessage)) return;
315 const note = restartContinuationNote(
316 source,
317 projection.runs,
318 projection.providerTurns,
319 projection.attempts,
320 );
321 const noteText =
322 note.work.length === 0
323 ? undefined
324 : restartCancelledBackgroundWorkNote(note.work, input.cause);
325 const text =
326 noteText === undefined
327 ? CONTINUE_PROMPT
328 : note.settled
329 ? noteText
330 : `${noteText}\n\n${CONTINUE_PROMPT}`;
331 yield* threads
332 .dispatch({
333 type: "message.dispatch",
334 commandId: CommandId.make(`command:restart-continuation:${input.sourceRunId}`),
335 threadId: input.threadId,
336 messageId,
337 text,
338 notification: {
339 source: { kind: "system" },
340 outcome: "updated",
341 summary:
342 input.cause === "provider_exit"
343 ? "The agent runtime exited and stopped background work"
344 : note.settled
345 ? "T3 Code restarted and stopped background work"
346 : "T3 Code restarted and resumed this turn",
347 detail: text,
348 },
349 attachments: [],
350 modelSelection: source.modelSelection,
351 dispatchMode: { type: "start_immediately" },
352 createdBy: "agent",
353 creationSource: "server",
354 restartContinuationOfRunId: input.sourceRunId,
355 })
356 .pipe(
357 // Disabled instances, and threads above a policy ceiling, cannot resume; still run success
358 // cleanup so delegated children recover without futile retries.
359 Effect.catchTags({
360 ThreadManagementProviderInstanceDisabledError: (error) =>
361 Effect.logInfo("orchestration-v2.restart-continuation.instance-disabled", {
362 threadId: input.threadId,
363 sourceRunId: input.sourceRunId,
364 projectId: error.projectId,
365 instanceId: error.instanceId,
366 }),
367 OrchestratorRuntimeModeAboveCeilingError: () =>
368 Effect.logInfo("orchestration-v2.restart-continuation.above-ceiling", {
369 threadId: input.threadId,
370 sourceRunId: input.sourceRunId,
371 }),
372 }),
373 );
374 },
375 // Declined child continuations still owe parent results; existing continuation runs settle them instead.
376 (effect, input) =>
377 effect.pipe(
378 Effect.andThen(
379 Effect.gen(function* () {
380 const threads = yield* ThreadManagementService.ThreadManagementService;
381 yield* threads.recoverDelegatedTask(input.threadId, { sourceRunId: input.sourceRunId });
382 }),
383 ),
384 ),
385);