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

RestartContinuation.ts

318 lines11.3 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 cancelledRosterTaskWork,
20 cancelledTurnItemWork,
21 isAwaitedWork,
22 isRestartContinuationSource,
23 isRestartNoteSource,
24 restartCancelledBackgroundWorkNote,
25 restartContinuationNote,
26} from "./RestartBackgroundNote.ts";
27​
28const CONTINUE_PROMPT = "Continue where you left off.";
29​
30const MAX_CONTINUATION_CHAIN = 3;
31​
32function restartContinuationBlocked(
33 projection: Pick<
34 ProjectionRuntimeRecoveryState,
35 "thread" | "runtimeRequests" | "providerTurns" | "turnItems"
36 >,
37 source: OrchestrationV2Run,
38 now: DateTime.Utc,
39 settled: boolean,
40): boolean {
41 const { thread } = projection;
42 if (
43 thread.archivedAt !== null ||
44 thread.deletedAt !== null ||
45 thread.settledOverride === "settled" ||
46 (thread.snoozedUntil != null && DateTime.isGreaterThan(thread.snoozedUntil, now))
47 )
48 return true;
49 const turn = latestProviderTurnForAttempt(projection.providerTurns, source.activeAttemptId);
50 if (
51 !settled &&
52 turn !== undefined &&
53 (turn.status === "completed" || turn.status === "failed" || turn.status === "interrupted")
54 )
55 return true;
56 const waitingRequest = projection.runtimeRequests.some(
57 (request) =>
58 request.kind !== "dynamic_tool_call" &&
59 request.kind !== "auth_refresh" &&
60 request.responseCapability.type !== "message" &&
61 (request.status === "pending" ||
62 ((request.status === "expired" || request.status === "cancelled") &&
63 request.responseCapability.type === "not_resumable" &&
64 turn !== undefined &&
65 turn.id === request.providerTurnId)),
66 );
67 if (waitingRequest) return true;
68 return projection.turnItems.some(
69 (item) =>
70 item.type === "secret_request" &&
71 item.runId === source.id &&
72 (item.secretStatus === "pending" ||
73 (item.secretStatus === "cancelled" &&
74 item.completedAt !== null &&
75 source.completedAt !== null &&
76 DateTime.Equivalence(item.completedAt, source.completedAt))),
77 );
79​
80/**
81 * App-owned delegations are not counted: their own threads continue and report
82 * back.
83 */
84function hasOpenAwaitedWork(
85 projection: Pick<ProjectionRuntimeRecoveryState, "runs" | "turnItems">,
86 providerThread: ProjectionRuntimeRecoveryState["providerThreads"][number],
87): boolean {
88 const openItem = projection.turnItems.some((item) => {
89 if (item.status !== "pending" && item.status !== "running" && item.status !== "waiting")
90 return false;
91 if (item.type === "subagent" && item.origin === "app_owned" && item.childThreadId !== null)
92 return false;
93 const work = cancelledTurnItemWork(item);
94 const providerThreadId =
95 item.providerThreadId ??
96 projection.runs.find((run) => run.id === item.runId)?.providerThreadId;
97 return work !== undefined && isAwaitedWork(work) && providerThreadId === providerThread.id;
98 });
99 return (
100 openItem ||
101 (providerThread.ownerNodeId === null &&
102 (providerThread.pendingBackgroundTasks ?? []).some((task) =>
103 isAwaitedWork(cancelledRosterTaskWork(task)),
104 ))
105 );
107​
108/**
109 * A settled run needs a live session, so stale records from an older crash
110 * never wake it.
111 */
112export function restartContinuationRun(
113 projection: Pick<
114 ProjectionRuntimeRecoveryState,
115 | "thread"
116 | "runs"
117 | "providerThreads"
118 | "providerSessions"
119 | "providerTurns"
120 | "runtimeRequests"
121 | "turnItems"
122 >,
123 now: DateTime.Utc,
124): OrchestrationV2Run | undefined {
125 const run = projection.runs.reduce<OrchestrationV2Run | undefined>(
126 (latest, candidate) =>
127 candidate.status !== "queued" && (!latest || runRanAfter(candidate, latest))
128 ? candidate
129 : latest,
130 undefined,
131 );
132 if (!run) return;
133 const preparedContinuation =
134 run.status === "starting" && run.restartContinuationOfRunId !== undefined;
135 const settled = run.status === "completed" || run.status === "waiting";
136 if (run.status !== "running" && !preparedContinuation && !settled) return;
137 if (restartContinuationBlocked(projection, run, now, settled)) return;
138 const liveTurnRequired = !preparedContinuation && !settled;
139 if (projection.thread.providerInstanceId !== run.providerInstanceId) return;
140 const providerThread = projection.providerThreads.find(
141 (thread) => thread.id === run.providerThreadId,
142 );
143 if (
144 !providerThread ||
145 providerThread.appThreadId !== projection.thread.id ||
146 providerThread.ownerNodeId !== null ||
147 providerThread.providerInstanceId !== run.providerInstanceId ||
148 providerThread.nativeThreadRef?.nativeId == null ||
149 providerThread.nativeThreadRef.strength !== "strong" ||
150 providerThread.nativeThreadRef.driver !== providerThread.driver ||
151 (liveTurnRequired && providerThread.status !== "active") ||
152 providerThread.status === "closed" ||
153 providerThread.status === "archived"
154 )
155 return;
156 const session = projection.providerSessions.find(
157 (candidate) => candidate.id === providerThread.providerSessionId,
158 );
159 // Most adapters keep a live session "ready" through its turns, so only a
160 // stopped or failed session rules out a live turn.
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) => run.id !== source.id && run.status !== "queued" && runRanAfter(run, source),
215 )
216 )
217 return;
218 if (projection.thread.providerInstanceId !== source.providerInstanceId) return;
219 // A turn that keeps crashing the server would otherwise restart it forever.
220 let chainLength = 0;
221 for (
222 let run: OrchestrationV2Run | undefined = source;
223 run?.restartContinuationOfRunId !== undefined && chainLength < MAX_CONTINUATION_CHAIN;
224 run = projection.runs.find((candidate) => candidate.id === run?.restartContinuationOfRunId)
225 ) {
226 chainLength += 1;
227 }
228 if (chainLength >= MAX_CONTINUATION_CHAIN) {
229 yield* Effect.logWarning("Not continuing a run restarted too many times in a row", {
230 threadId: input.threadId,
231 sourceRunId: input.sourceRunId,
232 });
233 return;
234 }
235 const sourceRecords = yield* threads.getThreadRecords(
236 input.threadId,
237 ["messages", "turnItems"],
238 {
239 messageIds: [source.userMessageId],
240 turnItemRunIds: [source.id],
241 turnItemTypes: ["run_interrupt_request"],
242 },
243 );
244 if (
245 sourceRecords.turnItems.some(
246 (item) => item.runId === source.id && item.type === "run_interrupt_request",
247 )
248 )
249 return;
250 const sourceMessage = sourceRecords.messages.find(
251 (message) => message.id === source.userMessageId,
252 );
253 if (sourceMessage !== undefined && isNativeMaintenanceCommand(sourceMessage)) return;
254 const note = restartContinuationNote(
255 source,
256 projection.runs,
257 projection.providerTurns,
258 projection.attempts,
259 );
260 const noteText =
261 note.work.length === 0 ? undefined : restartCancelledBackgroundWorkNote(note.work);
262 const text =
263 noteText === undefined
264 ? CONTINUE_PROMPT
265 : note.settled
266 ? noteText
267 : `${noteText}\n\n${CONTINUE_PROMPT}`;
268 yield* threads
269 .dispatch({
270 type: "message.dispatch",
271 commandId: CommandId.make(`command:restart-continuation:${input.sourceRunId}`),
272 threadId: input.threadId,
273 messageId,
274 text,
275 notification: {
276 source: { kind: "system" },
277 outcome: "updated",
278 summary: note.settled
279 ? "T3 Code restarted and stopped background work"
280 : "T3 Code restarted and resumed this turn",
281 detail: text,
282 },
283 attachments: [],
284 modelSelection: source.modelSelection,
285 dispatchMode: { type: "start_immediately" },
286 createdBy: "agent",
287 creationSource: "server",
288 restartContinuationOfRunId: input.sourceRunId,
289 })
290 .pipe(
291 // The project turned this instance off since the restart. No turn
292 // resumes, and the success path below still runs so a delegated
293 // child waiting on this run is recovered immediately instead of
294 // after EffectWorker exhausts its retries on a refusal that will
295 // not change.
296 Effect.catchTags({
297 ThreadManagementProviderInstanceDisabledError: (error) =>
298 Effect.logInfo("orchestration-v2.restart-continuation.instance-disabled", {
299 threadId: input.threadId,
300 sourceRunId: input.sourceRunId,
301 projectId: error.projectId,
302 instanceId: error.instanceId,
303 }),
304 }),
305 );
306 },
307 // A delegated child this declined to continue still owes its parent a
308 // result. Once a continuation run exists this is a no-op; that run settles it.
309 (effect, input) =>
310 effect.pipe(
311 Effect.andThen(
312 Effect.gen(function* () {
313 const threads = yield* ThreadManagementService.ThreadManagementService;
314 yield* threads.recoverDelegatedTask(input.threadId, input.sourceRunId);
315 }),
316 ),
317 ),
318);