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

RestartContinuation.ts

321 lines11.4 KB

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 );
83​
84/** App-owned delegations continue in their own threads and report back. */
85function hasOpenAwaitedWork(
86 projection: Pick<ProjectionRuntimeRecoveryState, "runs" | "turnItems">,
87 providerThread: ProjectionRuntimeRecoveryState["providerThreads"][number],
88): boolean {
89 const openItem = projection.turnItems.some((item) => {
90 if (item.status !== "pending" && item.status !== "running" && item.status !== "waiting")
91 return false;
92 if (item.type === "subagent" && item.origin === "app_owned" && item.childThreadId !== null)
93 return false;
94 const work = cancelledTurnItemWork(item);
95 return (
96 work !== undefined &&
97 isAwaitedWork(work) &&
98 awaitingProviderThreadId(item, projection.runs) === providerThread.id
99 );
100 });
101 return (
102 openItem ||
103 (providerThread.ownerNodeId === null &&
104 (providerThread.pendingBackgroundTasks ?? []).some((task) =>
105 isAwaitedWork(cancelledRosterTaskWork(task)),
106 ))
107 );
109​
110/** Settled runs require a live session so stale crash records cannot wake them. */
111export function restartContinuationRun(
112 projection: Pick<
113 ProjectionRuntimeRecoveryState,
114 | "thread"
115 | "runs"
116 | "providerThreads"
117 | "providerSessions"
118 | "providerTurns"
119 | "runtimeRequests"
120 | "turnItems"
121 >,
122 now: DateTime.Utc,
123): OrchestrationV2Run | undefined {
124 const run = projection.runs.reduce<OrchestrationV2Run | undefined>(
125 (latest, candidate) =>
126 candidate.status !== "queued" &&
127 !neverStarted(candidate) &&
128 (!latest || runRanAfter(candidate, latest))
129 ? candidate
130 : latest,
131 undefined,
132 );
133 if (!run) return;
134 const preparedContinuation =
135 run.status === "starting" && run.restartContinuationOfRunId !== undefined;
136 const settled = run.status === "completed" || run.status === "waiting";
137 if (run.status !== "running" && !preparedContinuation && !settled) return;
138 if (restartContinuationBlocked(projection, run, now, settled)) return;
139 const liveTurnRequired = !preparedContinuation && !settled;
140 if (projection.thread.providerInstanceId !== run.providerInstanceId) return;
141 const providerThread = projection.providerThreads.find(
142 (thread) => thread.id === run.providerThreadId,
143 );
144 if (
145 !providerThread ||
146 providerThread.appThreadId !== projection.thread.id ||
147 providerThread.ownerNodeId !== null ||
148 providerThread.providerInstanceId !== run.providerInstanceId ||
149 providerThread.nativeThreadRef?.nativeId == null ||
150 providerThread.nativeThreadRef.strength !== "strong" ||
151 providerThread.nativeThreadRef.driver !== providerThread.driver ||
152 (liveTurnRequired && providerThread.status !== "active") ||
153 providerThread.status === "closed" ||
154 providerThread.status === "archived"
155 )
156 return;
157 const session = projection.providerSessions.find(
158 (candidate) => candidate.id === providerThread.providerSessionId,
159 );
160 // Adapters remain ready during turns; only stopped or failed sessions rule out liveness.
161 if (
162 session === undefined ||
163 session.providerInstanceId !== run.providerInstanceId ||
164 session.driver !== providerThread.driver ||
165 (!preparedContinuation && (session.status === "stopped" || session.status === "error"))
166 )
167 return;
168 if (settled) return hasOpenAwaitedWork(projection, providerThread) ? run : undefined;
169 if (
170 liveTurnRequired &&
171 !projection.providerTurns.some(
172 (turn) =>
173 turn.providerThreadId === providerThread.id &&
174 turn.runAttemptId === run.activeAttemptId &&
175 turn.status === "running",
176 )
177 )
178 return;
179 return run;
181​
182export const continueRestartedRun = Effect.fn("RestartContinuation.continueRestartedRun")(
183 function* (input: { readonly threadId: ThreadId; readonly sourceRunId: RunId }) {
184 const settings = yield* ServerSettings.ServerSettingsService;
185 const enabled = yield* settings.getSettings.pipe(Effect.orElseSucceed(() => null));
186 if (!enabled) return;
187 const threads = yield* ThreadManagementService.ThreadManagementService;
188 const messageId = MessageId.make(`message:restart-continuation:${input.sourceRunId}`);
189 const projection = yield* threads.getThreadRecords(
190 input.threadId,
191 ["messages", "runs", "providerTurns", "attempts", "runtimeRequests", "turnItems"],
192 { messageIds: [messageId], turnItemTypes: ["secret_request"] },
193 );
194 if (
195 !resolveProjectSettings(enabled, projection.thread.projectId).settings
196 .continueThreadsAfterServerUpdate
197 )
198 return;
199 if (projection.messages.some((message) => message.id === messageId)) return;
200 const source = projection.runs.find((run) => run.id === input.sourceRunId);
201 if (
202 !source ||
203 !isRestartContinuationSource(source, projection.providerTurns) ||
204 restartContinuationBlocked(
205 projection,
206 source,
207 yield* DateTime.now,
208 isRestartNoteSource(source, projection.providerTurns),
209 )
210 )
211 return;
212 if (
213 projection.runs.some(
214 (run) =>
215 run.id !== source.id &&
216 run.status !== "queued" &&
217 !cancelledBeforeStart(run) &&
218 runRanAfter(run, source),
219 )
220 )
221 return;
222 if (projection.thread.providerInstanceId !== source.providerInstanceId) return;
223 // A turn that keeps crashing the server would otherwise restart it forever.
224 let chainLength = 0;
225 const loopWindowStart =
226 DateTime.toEpochMillis(source.completedAt ?? source.requestedAt) -
227 CONTINUATION_LOOP_WINDOW_MS;
228 for (
229 let run: OrchestrationV2Run | undefined = source;
230 run?.restartContinuationOfRunId !== undefined && chainLength < MAX_CONTINUATION_CHAIN;
231 run = projection.runs.find((candidate) => candidate.id === run?.restartContinuationOfRunId)
232 ) {
233 if (DateTime.toEpochMillis(run.requestedAt) < loopWindowStart) break;
234 chainLength += 1;
235 }
236 if (chainLength >= MAX_CONTINUATION_CHAIN) {
237 yield* Effect.logWarning("Not continuing a run restarted too many times in a row", {
238 threadId: input.threadId,
239 sourceRunId: input.sourceRunId,
240 });
241 return;
242 }
243 const sourceRecords = yield* threads.getThreadRecords(
244 input.threadId,
245 ["messages", "turnItems"],
246 {
247 messageIds: [source.userMessageId],
248 turnItemRunIds: [source.id],
249 turnItemTypes: ["run_interrupt_request"],
250 },
251 );
252 if (
253 sourceRecords.turnItems.some(
254 (item) => item.runId === source.id && item.type === "run_interrupt_request",
255 )
256 )
257 return;
258 const sourceMessage = sourceRecords.messages.find(
259 (message) => message.id === source.userMessageId,
260 );
261 if (sourceMessage !== undefined && isNativeMaintenanceCommand(sourceMessage)) return;
262 const note = restartContinuationNote(
263 source,
264 projection.runs,
265 projection.providerTurns,
266 projection.attempts,
267 );
268 const noteText =
269 note.work.length === 0 ? undefined : restartCancelledBackgroundWorkNote(note.work);
270 const text =
271 noteText === undefined
272 ? CONTINUE_PROMPT
273 : note.settled
274 ? noteText
275 : `${noteText}\n\n${CONTINUE_PROMPT}`;
276 yield* threads
277 .dispatch({
278 type: "message.dispatch",
279 commandId: CommandId.make(`command:restart-continuation:${input.sourceRunId}`),
280 threadId: input.threadId,
281 messageId,
282 text,
283 notification: {
284 source: { kind: "system" },
285 outcome: "updated",
286 summary: note.settled
287 ? "T3 Code restarted and stopped background work"
288 : "T3 Code restarted and resumed this turn",
289 detail: text,
290 },
291 attachments: [],
292 modelSelection: source.modelSelection,
293 dispatchMode: { type: "start_immediately" },
294 createdBy: "agent",
295 creationSource: "server",
296 restartContinuationOfRunId: input.sourceRunId,
297 })
298 .pipe(
299 // Disabled instances cannot resume; still run success cleanup so delegated children recover without futile retries.
300 Effect.catchTags({
301 ThreadManagementProviderInstanceDisabledError: (error) =>
302 Effect.logInfo("orchestration-v2.restart-continuation.instance-disabled", {
303 threadId: input.threadId,
304 sourceRunId: input.sourceRunId,
305 projectId: error.projectId,
306 instanceId: error.instanceId,
307 }),
308 }),
309 );
310 },
311 // Declined child continuations still owe parent results; existing continuation runs settle them instead.
312 (effect, input) =>
313 effect.pipe(
314 Effect.andThen(
315 Effect.gen(function* () {
316 const threads = yield* ThreadManagementService.ThreadManagementService;
317 yield* threads.recoverDelegatedTask(input.threadId, input.sourceRunId);
318 }),
319 ),
320 ),
321);