Open History to see the last commit
1import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
2import {
3 CommandId,
4 MessageId,
5 type OrchestrationV2Run,
6 type ProviderThreadId,
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 * as ThreadManagementService from "./ThreadManagementService.ts";
15import {
16 isRestartNoteSource,
17 restartCancelledBackgroundWorkNote,
18} from "./RestartBackgroundNote.ts";
19
20/**
21 * The run a restart continuation resumes, if any: an unfinished root run, or a
22 * settled one whose own provider thread lost background work in the restart
23 * (`cancelledWorkProviderThreadIds`, which recovery records on that thread).
24 */
25export function restartContinuationRun(
26 projection: Pick<
27 ProjectionRuntimeRecoveryState,
28 "thread" | "runs" | "providerThreads" | "providerSessions" | "providerTurns"
29 >,
30 cancelledWorkProviderThreadIds: ReadonlySet<ProviderThreadId> = new Set(),
31): OrchestrationV2Run | undefined {
32 if (projection.thread.archivedAt !== null || projection.thread.deletedAt !== null) return;
33 const run = projection.runs.reduce<OrchestrationV2Run | undefined>(
34 (latest, candidate) => (!latest || candidate.ordinal > latest.ordinal ? candidate : latest),
35 undefined,
36 );
37 if (!run) return;
38 const preparedContinuation =
39 run.status === "starting" && run.restartContinuationOfRunId !== undefined;
40 // Background work outlived this settled turn; the provider has no live turn.
41 const settledWithCancelledWork =
42 (run.status === "completed" || run.status === "waiting") &&
43 run.providerThreadId !== null &&
44 cancelledWorkProviderThreadIds.has(run.providerThreadId);
45 if (run.status !== "running" && !preparedContinuation && !settledWithCancelledWork) return;
46 const liveTurnRequired = !preparedContinuation && !settledWithCancelledWork;
47 if (projection.thread.providerInstanceId !== run.providerInstanceId) return;
48 const providerThread = projection.providerThreads.find(
49 (thread) => thread.id === run.providerThreadId,
50 );
51 if (
52 !providerThread ||
53 providerThread.appThreadId !== projection.thread.id ||
54 providerThread.ownerNodeId !== null ||
55 providerThread.providerInstanceId !== run.providerInstanceId ||
56 providerThread.nativeThreadRef?.nativeId == null ||
57 providerThread.nativeThreadRef.strength !== "strong" ||
58 providerThread.nativeThreadRef.driver !== providerThread.driver ||
59 (liveTurnRequired && providerThread.status !== "active") ||
60 providerThread.status === "closed" ||
61 providerThread.status === "archived"
62 )
63 return;
64 const session = projection.providerSessions.find(
65 (candidate) => candidate.id === providerThread.providerSessionId,
66 );
67 // A settled thread's session may already be stopped and out of the recovery
68 // read; the continuation reopens it from the provider thread's native ref.
69 // Most adapters keep a live session "ready" through its turns, so only a
70 // stopped or failed session rules out a live turn.
71 if (
72 session === undefined
73 ? !settledWithCancelledWork
74 : session.providerInstanceId !== run.providerInstanceId ||
75 session.driver !== providerThread.driver ||
76 (liveTurnRequired && (session.status === "stopped" || session.status === "error"))
77 )
78 return;
79 if (
80 liveTurnRequired &&
81 !projection.providerTurns.some(
82 (turn) =>
83 turn.providerThreadId === providerThread.id &&
84 turn.runAttemptId === run.activeAttemptId &&
85 turn.status === "running",
86 )
87 )
88 return;
89 return run;
90}
91
92export const continueRestartedRun = Effect.fn("RestartContinuation.continueRestartedRun")(
93 function* (input: { readonly threadId: ThreadId; readonly sourceRunId: RunId }) {
94 const settings = yield* ServerSettings.ServerSettingsService;
95 const enabled = yield* settings.getSettings.pipe(Effect.orElseSucceed(() => null));
96 if (!enabled) return;
97 const threads = yield* ThreadManagementService.ThreadManagementService;
98 const messageId = MessageId.make(`message:restart-continuation:${input.sourceRunId}`);
99 const projection = yield* threads.getThreadRecords(
100 input.threadId,
101 ["messages", "runs", "providerTurns"],
102 { messageIds: [messageId] },
103 );
104 if (
105 !resolveProjectSettings(enabled, projection.thread.projectId).settings
106 .continueThreadsAfterServerUpdate
107 )
108 return;
109 if (projection.thread.archivedAt !== null || projection.thread.deletedAt !== null) return;
110
111 if (projection.messages.some((message) => message.id === messageId)) return;
112 const source = projection.runs.find((run) => run.id === input.sourceRunId);
113 // A settled source prompts with the note of the background work it lost.
114 const noteSource =
115 source !== undefined && isRestartNoteSource(source, projection.providerTurns);
116 if (!source || (source.status !== "cancelled" && !noteSource)) return;
117 // A user submission after reconciliation takes precedence over an automatic prompt.
118 if (projection.runs.some((run) => run.ordinal > source.ordinal)) return;
119 if (projection.thread.providerInstanceId !== source.providerInstanceId) return;
120 yield* threads.dispatch({
121 type: "message.dispatch",
122 commandId: CommandId.make(`command:restart-continuation:${input.sourceRunId}`),
123 threadId: input.threadId,
124 messageId,
125 text: noteSource
126 ? restartCancelledBackgroundWorkNote(source.restartCancelledBackgroundWork ?? [])
127 : "Continue where you left off.",
128 attachments: [],
129 modelSelection: source.modelSelection,
130 dispatchMode: { type: "start_immediately" },
131 createdBy: "agent",
132 creationSource: "server",
133 restartContinuationOfRunId: input.sourceRunId,
134 });
135 },
136);