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

RestartContinuation.ts

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