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