Open History to see the last commit
1import { runRanAfter } from "@t3tools/shared/orchestrationV2ThreadError";
2import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
3import {
4 CommandId,
5 MessageId,
6 type OrchestrationV2Run,
7 type RunId,
8 type ThreadId,
9} from "@t3tools/contracts";
10import * as Effect from "effect/Effect";
11import type { ProjectionRuntimeRecoveryState } from "./ProjectionStore.ts";
12
13import * as ServerSettings from "../serverSettings.ts";
14import { isNativeMaintenanceCommand } from "./Orchestrator.ts";
15import * as ThreadManagementService from "./ThreadManagementService.ts";
16import {
17 isRestartNoteSource,
18 restartCancelledBackgroundWorkNote,
19 restartContinuationNote,
20} from "./RestartBackgroundNote.ts";
21
22const CONTINUE_PROMPT = "Continue where you left off.";
23
24/**
25 * Resume only an unfinished root turn. Leftover background work is cleaned up
26 * separately and reported on the next user turn; it must not wake a settled run.
27 */
28export function restartContinuationRun(
29 projection: Pick<
30 ProjectionRuntimeRecoveryState,
31 "thread" | "runs" | "providerThreads" | "providerSessions" | "providerTurns"
32 >,
33): OrchestrationV2Run | undefined {
34 if (projection.thread.archivedAt !== null || projection.thread.deletedAt !== null) return;
35 // Queued runs never started; recovery holds them behind the cut run.
36 const run = projection.runs.reduce<OrchestrationV2Run | undefined>(
37 (latest, candidate) =>
38 candidate.status !== "queued" && (!latest || runRanAfter(candidate, latest))
39 ? candidate
40 : latest,
41 undefined,
42 );
43 if (!run) return;
44 const preparedContinuation =
45 run.status === "starting" && run.restartContinuationOfRunId !== undefined;
46 if (run.status !== "running" && !preparedContinuation) return;
47 const liveTurnRequired = !preparedContinuation;
48 if (projection.thread.providerInstanceId !== run.providerInstanceId) return;
49 const providerThread = projection.providerThreads.find(
50 (thread) => thread.id === run.providerThreadId,
51 );
52 if (
53 !providerThread ||
54 providerThread.appThreadId !== projection.thread.id ||
55 providerThread.ownerNodeId !== null ||
56 providerThread.providerInstanceId !== run.providerInstanceId ||
57 providerThread.nativeThreadRef?.nativeId == null ||
58 providerThread.nativeThreadRef.strength !== "strong" ||
59 providerThread.nativeThreadRef.driver !== providerThread.driver ||
60 (liveTurnRequired && providerThread.status !== "active") ||
61 providerThread.status === "closed" ||
62 providerThread.status === "archived"
63 )
64 return;
65 const session = projection.providerSessions.find(
66 (candidate) => candidate.id === providerThread.providerSessionId,
67 );
68 // Most adapters keep a live session "ready" through its turns, so only a
69 // stopped or failed session rules out a live turn.
70 if (
71 session === undefined ||
72 session.providerInstanceId !== run.providerInstanceId ||
73 session.driver !== providerThread.driver ||
74 (liveTurnRequired && (session.status === "stopped" || session.status === "error"))
75 )
76 return;
77 if (
78 liveTurnRequired &&
79 !projection.providerTurns.some(
80 (turn) =>
81 turn.providerThreadId === providerThread.id &&
82 turn.runAttemptId === run.activeAttemptId &&
83 turn.status === "running",
84 )
85 )
86 return;
87 return run;
88}
89
90export const continueRestartedRun = Effect.fn("RestartContinuation.continueRestartedRun")(
91 function* (input: { readonly threadId: ThreadId; readonly sourceRunId: RunId }) {
92 const settings = yield* ServerSettings.ServerSettingsService;
93 const enabled = yield* settings.getSettings.pipe(Effect.orElseSucceed(() => null));
94 if (!enabled) return;
95 const threads = yield* ThreadManagementService.ThreadManagementService;
96 const messageId = MessageId.make(`message:restart-continuation:${input.sourceRunId}`);
97 const projection = yield* threads.getThreadRecords(
98 input.threadId,
99 ["messages", "runs", "providerTurns", "attempts"],
100 { messageIds: [messageId] },
101 );
102 if (
103 !resolveProjectSettings(enabled, projection.thread.projectId).settings
104 .continueThreadsAfterServerUpdate
105 )
106 return;
107 if (projection.thread.archivedAt !== null || projection.thread.deletedAt !== null) return;
108
109 if (projection.messages.some((message) => message.id === messageId)) return;
110 const source = projection.runs.find((run) => run.id === input.sourceRunId);
111 // Pending effects from older versions may target settled background work,
112 // including waiting runs that reconciliation subsequently cancelled.
113 if (
114 !source ||
115 source.status !== "cancelled" ||
116 isRestartNoteSource(source, projection.providerTurns)
117 )
118 return;
119 // A user submission after reconciliation takes precedence over an automatic
120 // prompt. Queued runs never started and stay held behind this one.
121 if (
122 projection.runs.some(
123 (run) => run.id !== source.id && run.status !== "queued" && runRanAfter(run, source),
124 )
125 )
126 return;
127 if (projection.thread.providerInstanceId !== source.providerInstanceId) return;
128 const sourceRecords = yield* threads.getThreadRecords(
129 input.threadId,
130 ["messages", "turnItems"],
131 {
132 messageIds: [source.userMessageId],
133 turnItemRunIds: [source.id],
134 turnItemTypes: ["run_interrupt_request"],
135 },
136 );
137 // The user asked this run to stop before the restart cut it.
138 if (
139 sourceRecords.turnItems.some(
140 (item) => item.runId === source.id && item.type === "run_interrupt_request",
141 )
142 )
143 return;
144 const sourceMessage = sourceRecords.messages.find(
145 (message) => message.id === source.userMessageId,
146 );
147 if (sourceMessage !== undefined && isNativeMaintenanceCommand(sourceMessage)) return;
148 const note = restartContinuationNote(
149 source,
150 projection.runs,
151 projection.providerTurns,
152 projection.attempts,
153 );
154 const noteText =
155 note.work.length === 0 ? undefined : restartCancelledBackgroundWorkNote(note.work);
156 const text =
157 noteText === undefined
158 ? CONTINUE_PROMPT
159 : note.settled
160 ? noteText
161 : `${noteText}\n\n${CONTINUE_PROMPT}`;
162 yield* threads.dispatch({
163 type: "message.dispatch",
164 commandId: CommandId.make(`command:restart-continuation:${input.sourceRunId}`),
165 threadId: input.threadId,
166 messageId,
167 text,
168 // Shown as a work log row; the prompt the agent got is its detail.
169 notification: {
170 source: { kind: "system" },
171 outcome: "updated",
172 summary: note.settled
173 ? "T3 Code restarted and stopped background work"
174 : "T3 Code restarted and resumed this turn",
175 detail: text,
176 },
177 attachments: [],
178 modelSelection: source.modelSelection,
179 dispatchMode: { type: "start_immediately" },
180 createdBy: "agent",
181 creationSource: "server",
182 restartContinuationOfRunId: input.sourceRunId,
183 });
184 },
185 // A delegated child this declined to continue still owes its parent a
186 // result. Once a continuation run exists this is a no-op; that run settles it.
187 (effect, input) =>
188 effect.pipe(
189 Effect.andThen(
190 Effect.gen(function* () {
191 const threads = yield* ThreadManagementService.ThreadManagementService;
192 yield* threads.recoverDelegatedTask(input.threadId, input.sourceRunId);
193 }),
194 ),
195 ),
196);