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 (
148 item.type === "subagent" &&
149 item.origin === "app_owned" &&
150 (item.childThreadId !== null || item.remoteChild !== undefined)
151 )
152 return false;
153 const work = cancelledTurnItemWork(item);
154 return (
155 work !== undefined &&
156 isAwaitedWork(work) &&
157 awaitingProviderThreadId(item, projection.runs) === providerThread.id
158 );
159 });
160 return (
161 openItem ||
162 (providerThread.ownerNodeId === null &&
163 (providerThread.pendingBackgroundTasks ?? []).some((task) =>
164 isAwaitedWork(cancelledRosterTaskWork(task)),
165 ))
166 );
167}
168
169/** Settled runs require a live session so stale crash records cannot wake them. */
170export function restartContinuationRun(
171 projection: Pick<
172 ProjectionRuntimeRecoveryState,
173 | "thread"
174 | "runs"
175 | "providerThreads"
176 | "providerSessions"
177 | "providerTurns"
178 | "runtimeRequests"
179 | "turnItems"
180 >,
181 now: DateTime.Utc,
182): OrchestrationV2Run | undefined {
183 const run = projection.runs.reduce<OrchestrationV2Run | undefined>(
184 (latest, candidate) =>
185 candidate.status !== "queued" &&
186 !neverStarted(candidate) &&
187 (!latest || runRanAfter(candidate, latest))
188 ? candidate
189 : latest,
190 undefined,
191 );
192 if (!run) return;
193 const preparedContinuation =
194 run.status === "starting" && run.restartContinuationOfRunId !== undefined;
195 const settled = run.status === "completed" || run.status === "waiting";
196 if (run.status !== "running" && !preparedContinuation && !settled) return;
197 if (restartContinuationBlocked(projection, run, now, settled)) return;
198 const liveTurnRequired = !preparedContinuation && !settled;
199 if (projection.thread.providerInstanceId !== run.providerInstanceId) return;
200 const providerThread = projection.providerThreads.find(
201 (thread) => thread.id === run.providerThreadId,
202 );
203 if (
204 !providerThread ||
205 providerThread.appThreadId !== projection.thread.id ||
206 providerThread.ownerNodeId !== null ||
207 providerThread.providerInstanceId !== run.providerInstanceId ||
208 providerThread.nativeThreadRef?.nativeId == null ||
209 providerThread.nativeThreadRef.strength !== "strong" ||
210 providerThread.nativeThreadRef.driver !== providerThread.driver ||
211 (liveTurnRequired && providerThread.status !== "active") ||
212 providerThread.status === "closed" ||
213 providerThread.status === "archived"
214 )
215 return;
216 const session = projection.providerSessions.find(
217 (candidate) => candidate.id === providerThread.providerSessionId,
218 );
219 // Adapters remain ready during turns; only stopped or failed sessions rule out liveness.
220 if (
221 session === undefined ||
222 session.providerInstanceId !== run.providerInstanceId ||
223 session.driver !== providerThread.driver ||
224 (!preparedContinuation && (session.status === "stopped" || session.status === "error"))
225 )
226 return;
227 if (settled) return hasOpenAwaitedWork(projection, providerThread) ? run : undefined;
228 if (
229 liveTurnRequired &&
230 !projection.providerTurns.some(
231 (turn) =>
232 turn.providerThreadId === providerThread.id &&
233 turn.runAttemptId === run.activeAttemptId &&
234 turn.status === "running",
235 )
236 )
237 return;
238 return run;
239}
240
241export const continueRestartedRun = Effect.fn("RestartContinuation.continueRestartedRun")(
242 function* (input: {
243 readonly threadId: ThreadId;
244 readonly sourceRunId: RunId;
245 readonly processLossCount?: number;
246 readonly cause?: BackgroundWorkLossCause;
247 }) {
248 const settings = yield* ServerSettings.ServerSettingsService;
249 const enabled = yield* settings.getSettings.pipe(Effect.orElseSucceed(() => null));
250 if (!enabled) return;
251 const threads = yield* ThreadManagementService.ThreadManagementService;
252 const messageId = MessageId.make(`message:restart-continuation:${input.sourceRunId}`);
253 const projection = yield* threads.getThreadRecords(
254 input.threadId,
255 ["messages", "runs", "providerTurns", "attempts", "runtimeRequests", "turnItems"],
256 { messageIds: [messageId], turnItemTypes: ["secret_request"] },
257 );
258 if (
259 !resolveProjectSettings(enabled, projection.thread.projectId).settings
260 .continueThreadsAfterServerUpdate
261 )
262 return;
263 if (projection.messages.some((message) => message.id === messageId)) return;
264 const source = projection.runs.find((run) => run.id === input.sourceRunId);
265 if (
266 !source ||
267 !(
268 isRestartContinuationSource(source, projection.providerTurns) ||
269 continuationFailedBeforePrompt(source, projection.providerTurns)
270 ) ||
271 restartContinuationBlocked(
272 projection,
273 source,
274 yield* DateTime.now,
275 isRestartNoteSource(source, projection.providerTurns),
276 )
277 )
278 return;
279 if (
280 projection.runs.some(
281 (run) =>
282 run.id !== source.id &&
283 run.status !== "queued" &&
284 !cancelledBeforeStart(run) &&
285 runRanAfter(run, source),
286 )
287 )
288 return;
289 if (projection.thread.providerInstanceId !== source.providerInstanceId) return;
290 // A turn that keeps crashing the server would otherwise restart it forever.
291 let chainLength = 0;
292 const loopWindowStart =
293 DateTime.toEpochMillis(source.completedAt ?? source.requestedAt) -
294 CONTINUATION_LOOP_WINDOW_MS;
295 for (
296 let run: OrchestrationV2Run | undefined = source;
297 run?.restartContinuationOfRunId !== undefined && chainLength < MAX_CONTINUATION_CHAIN;
298 run = projection.runs.find((candidate) => candidate.id === run?.restartContinuationOfRunId)
299 ) {
300 if (DateTime.toEpochMillis(run.requestedAt) < loopWindowStart) break;
301 chainLength += 1;
302 }
303 if (
304 input.processLossCount === undefined
305 ? chainLength >= MAX_CONTINUATION_CHAIN
306 : input.processLossCount > MAX_CONTINUATION_CHAIN
307 ) {
308 yield* Effect.logWarning("Not continuing a run restarted too many times in a row", {
309 threadId: input.threadId,
310 sourceRunId: input.sourceRunId,
311 });
312 return;
313 }
314 if (yield* restartStopRequested(threads.getThreadRecords, projection.thread, source)) return;
315 const sourceMessage = (yield* threads.getThreadRecords(input.threadId, ["messages"], {
316 messageIds: [source.userMessageId],
317 })).messages.find((message) => message.id === source.userMessageId);
318 if (sourceMessage !== undefined && isNativeMaintenanceCommand(sourceMessage)) return;
319 const note = restartContinuationNote(
320 source,
321 projection.runs,
322 projection.providerTurns,
323 projection.attempts,
324 );
325 const noteText =
326 note.work.length === 0
327 ? undefined
328 : restartCancelledBackgroundWorkNote(note.work, input.cause);
329 const text =
330 noteText === undefined
331 ? CONTINUE_PROMPT
332 : note.settled
333 ? noteText
334 : `${noteText}\n\n${CONTINUE_PROMPT}`;
335 yield* threads
336 .dispatch({
337 type: "message.dispatch",
338 commandId: CommandId.make(`command:restart-continuation:${input.sourceRunId}`),
339 threadId: input.threadId,
340 messageId,
341 text,
342 notification: {
343 source: { kind: "system" },
344 outcome: "updated",
345 summary:
346 input.cause === "provider_exit"
347 ? "The agent runtime exited and stopped background work"
348 : note.settled
349 ? "T3 Code restarted and stopped background work"
350 : "T3 Code restarted and resumed this turn",
351 detail: text,
352 },
353 attachments: [],
354 modelSelection: source.modelSelection,
355 dispatchMode: { type: "start_immediately" },
356 createdBy: "agent",
357 creationSource: "server",
358 restartContinuationOfRunId: input.sourceRunId,
359 })
360 .pipe(
361 // Disabled instances, and threads above a policy ceiling, cannot resume; still run success
362 // cleanup so delegated children recover without futile retries.
363 Effect.catchTags({
364 ThreadManagementProviderInstanceDisabledError: (error) =>
365 Effect.logInfo("orchestration-v2.restart-continuation.instance-disabled", {
366 threadId: input.threadId,
367 sourceRunId: input.sourceRunId,
368 projectId: error.projectId,
369 instanceId: error.instanceId,
370 }),
371 OrchestratorRuntimeModeAboveCeilingError: () =>
372 Effect.logInfo("orchestration-v2.restart-continuation.above-ceiling", {
373 threadId: input.threadId,
374 sourceRunId: input.sourceRunId,
375 }),
376 }),
377 );
378 },
379 // Declined child continuations still owe parent results; existing continuation runs settle them instead.
380 (effect, input) =>
381 effect.pipe(
382 Effect.andThen(
383 Effect.gen(function* () {
384 const threads = yield* ThreadManagementService.ThreadManagementService;
385 yield* threads.recoverDelegatedTask(input.threadId, { sourceRunId: input.sourceRunId });
386 }),
387 ),
388 ),
389);