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

RestartContinuation.ts

295 lines11.1 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 "./Orchestrator.ts";
17import * as ThreadManagementService from "./ThreadManagementService.ts";
18import {
19 isRestartNoteSource,
20 restartCancelledBackgroundWorkNote,
21 restartContinuationNote,
22} from "./RestartBackgroundNote.ts";
23​
24const CONTINUE_PROMPT = "Continue where you left off.";
25​
26/** Consecutive automatic continuations allowed before a person has to step in. */
27const MAX_CONTINUATION_CHAIN = 3;
28​
29/**
30 * Whether a restart must leave this run for the user: the thread is put away,
31 * the provider turn already ended, or the user owes an answer. Checked when
32 * intent is recorded and again when the continuation is delivered.
33 */
34function restartContinuationBlocked(
35 projection: Pick<
36 ProjectionRuntimeRecoveryState,
37 "thread" | "runtimeRequests" | "providerTurns" | "turnItems"
38 >,
39 source: OrchestrationV2Run,
40 now: DateTime.Utc,
41): boolean {
42 const { thread } = projection;
43 if (
44 thread.archivedAt !== null ||
45 thread.deletedAt !== null ||
46 thread.settledOverride === "settled" ||
47 (thread.snoozedUntil != null && DateTime.isGreaterThan(thread.snoozedUntil, now))
48 )
49 return true;
50 const turn = latestProviderTurnForAttempt(projection.providerTurns, source.activeAttemptId);
51 if (
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 // Tool calls and auth refreshes do not wait on a person, and a
59 // message-capable question stays answerable after the restart.
60 request.kind !== "dynamic_tool_call" &&
61 request.kind !== "auth_refresh" &&
62 request.responseCapability.type !== "message" &&
63 (request.status === "pending" ||
64 // Recovery closes live callbacks on the cut turn; it does not answer them.
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 // Recovery cancels an open secret card and its run at the same instant.
77 (item.secretStatus === "cancelled" &&
78 item.completedAt !== null &&
79 source.completedAt !== null &&
80 DateTime.Equivalence(item.completedAt, source.completedAt))),
81 );
83​
84/**
85 * Resume only an unfinished root turn. Leftover background work is cleaned up
86 * separately and reported on the next user turn; it must not wake a settled run.
87 */
88export function restartContinuationRun(
89 projection: Pick<
90 ProjectionRuntimeRecoveryState,
91 | "thread"
92 | "runs"
93 | "providerThreads"
94 | "providerSessions"
95 | "providerTurns"
96 | "runtimeRequests"
97 | "turnItems"
98 >,
99 now: DateTime.Utc,
100): OrchestrationV2Run | undefined {
101 // Queued runs never started; recovery holds them behind the cut run.
102 const run = projection.runs.reduce<OrchestrationV2Run | undefined>(
103 (latest, candidate) =>
104 candidate.status !== "queued" && (!latest || runRanAfter(candidate, latest))
105 ? candidate
106 : latest,
107 undefined,
108 );
109 if (!run) return;
110 const preparedContinuation =
111 run.status === "starting" && run.restartContinuationOfRunId !== undefined;
112 if (run.status !== "running" && !preparedContinuation) return;
113 if (restartContinuationBlocked(projection, run, now)) return;
114 const liveTurnRequired = !preparedContinuation;
115 if (projection.thread.providerInstanceId !== run.providerInstanceId) return;
116 const providerThread = projection.providerThreads.find(
117 (thread) => thread.id === run.providerThreadId,
118 );
119 if (
120 !providerThread ||
121 providerThread.appThreadId !== projection.thread.id ||
122 providerThread.ownerNodeId !== null ||
123 providerThread.providerInstanceId !== run.providerInstanceId ||
124 providerThread.nativeThreadRef?.nativeId == null ||
125 providerThread.nativeThreadRef.strength !== "strong" ||
126 providerThread.nativeThreadRef.driver !== providerThread.driver ||
127 (liveTurnRequired && providerThread.status !== "active") ||
128 providerThread.status === "closed" ||
129 providerThread.status === "archived"
130 )
131 return;
132 const session = projection.providerSessions.find(
133 (candidate) => candidate.id === providerThread.providerSessionId,
134 );
135 // Most adapters keep a live session "ready" through its turns, so only a
136 // stopped or failed session rules out a live turn.
137 if (
138 session === undefined ||
139 session.providerInstanceId !== run.providerInstanceId ||
140 session.driver !== providerThread.driver ||
141 (liveTurnRequired && (session.status === "stopped" || session.status === "error"))
142 )
143 return;
144 if (
145 liveTurnRequired &&
146 !projection.providerTurns.some(
147 (turn) =>
148 turn.providerThreadId === providerThread.id &&
149 turn.runAttemptId === run.activeAttemptId &&
150 turn.status === "running",
151 )
152 )
153 return;
154 return run;
156​
157export const continueRestartedRun = Effect.fn("RestartContinuation.continueRestartedRun")(
158 function* (input: { readonly threadId: ThreadId; readonly sourceRunId: RunId }) {
159 const settings = yield* ServerSettings.ServerSettingsService;
160 const enabled = yield* settings.getSettings.pipe(Effect.orElseSucceed(() => null));
161 if (!enabled) return;
162 const threads = yield* ThreadManagementService.ThreadManagementService;
163 const messageId = MessageId.make(`message:restart-continuation:${input.sourceRunId}`);
164 const projection = yield* threads.getThreadRecords(
165 input.threadId,
166 ["messages", "runs", "providerTurns", "attempts", "runtimeRequests", "turnItems"],
167 { messageIds: [messageId], turnItemTypes: ["secret_request"] },
168 );
169 if (
170 !resolveProjectSettings(enabled, projection.thread.projectId).settings
171 .continueThreadsAfterServerUpdate
172 )
173 return;
174 if (projection.messages.some((message) => message.id === messageId)) return;
175 const source = projection.runs.find((run) => run.id === input.sourceRunId);
176 // Pending effects from older versions may target settled background work,
177 // including waiting runs that reconciliation subsequently cancelled.
178 if (
179 !source ||
180 source.status !== "cancelled" ||
181 isRestartNoteSource(source, projection.providerTurns) ||
182 restartContinuationBlocked(projection, source, yield* DateTime.now)
183 )
184 return;
185 // A user submission after reconciliation takes precedence over an automatic
186 // prompt. Queued runs never started and stay held behind this one.
187 if (
188 projection.runs.some(
189 (run) => run.id !== source.id && run.status !== "queued" && runRanAfter(run, source),
190 )
191 )
192 return;
193 if (projection.thread.providerInstanceId !== source.providerInstanceId) return;
194 // A turn that keeps crashing the server would otherwise restart it forever.
195 let chainLength = 0;
196 for (
197 let run: OrchestrationV2Run | undefined = source;
198 run?.restartContinuationOfRunId !== undefined && chainLength < MAX_CONTINUATION_CHAIN;
199 run = projection.runs.find((candidate) => candidate.id === run?.restartContinuationOfRunId)
200 ) {
201 chainLength += 1;
202 }
203 if (chainLength >= MAX_CONTINUATION_CHAIN) {
204 yield* Effect.logWarning("Not continuing a run restarted too many times in a row", {
205 threadId: input.threadId,
206 sourceRunId: input.sourceRunId,
207 });
208 return;
209 }
210 const sourceRecords = yield* threads.getThreadRecords(
211 input.threadId,
212 ["messages", "turnItems"],
213 {
214 messageIds: [source.userMessageId],
215 turnItemRunIds: [source.id],
216 turnItemTypes: ["run_interrupt_request"],
217 },
218 );
219 // The user asked this run to stop before the restart cut it.
220 if (
221 sourceRecords.turnItems.some(
222 (item) => item.runId === source.id && item.type === "run_interrupt_request",
223 )
224 )
225 return;
226 const sourceMessage = sourceRecords.messages.find(
227 (message) => message.id === source.userMessageId,
228 );
229 if (sourceMessage !== undefined && isNativeMaintenanceCommand(sourceMessage)) return;
230 const note = restartContinuationNote(
231 source,
232 projection.runs,
233 projection.providerTurns,
234 projection.attempts,
235 );
236 const noteText =
237 note.work.length === 0 ? undefined : restartCancelledBackgroundWorkNote(note.work);
238 const text =
239 noteText === undefined
240 ? CONTINUE_PROMPT
241 : note.settled
242 ? noteText
243 : `${noteText}\n\n${CONTINUE_PROMPT}`;
244 yield* threads
245 .dispatch({
246 type: "message.dispatch",
247 commandId: CommandId.make(`command:restart-continuation:${input.sourceRunId}`),
248 threadId: input.threadId,
249 messageId,
250 text,
251 // Shown as a work log row; the prompt the agent got is its detail.
252 notification: {
253 source: { kind: "system" },
254 outcome: "updated",
255 summary: note.settled
256 ? "T3 Code restarted and stopped background work"
257 : "T3 Code restarted and resumed this turn",
258 detail: text,
259 },
260 attachments: [],
261 modelSelection: source.modelSelection,
262 dispatchMode: { type: "start_immediately" },
263 createdBy: "agent",
264 creationSource: "server",
265 restartContinuationOfRunId: input.sourceRunId,
266 })
267 .pipe(
268 // The project turned this instance off since the restart. No turn
269 // resumes, and the success path below still runs so a delegated
270 // child waiting on this run is recovered immediately instead of
271 // after EffectWorker exhausts its retries on a refusal that will
272 // not change.
273 Effect.catchTags({
274 ThreadManagementProviderInstanceDisabledError: (error) =>
275 Effect.logInfo("orchestration-v2.restart-continuation.instance-disabled", {
276 threadId: input.threadId,
277 sourceRunId: input.sourceRunId,
278 projectId: error.projectId,
279 instanceId: error.instanceId,
280 }),
281 }),
282 );
283 },
284 // A delegated child this declined to continue still owes its parent a
285 // result. Once a continuation run exists this is a no-op; that run settles it.
286 (effect, input) =>
287 effect.pipe(
288 Effect.andThen(
289 Effect.gen(function* () {
290 const threads = yield* ThreadManagementService.ThreadManagementService;
291 yield* threads.recoverDelegatedTask(input.threadId, input.sourceRunId);
292 }),
293 ),
294 ),
295);