Open History to see the last commit
1import { projectComposerContextForProvider } from "@t3tools/shared/composerContextReferences";
2import {
3 MessageId,
4 ProviderSessionId,
5 ProviderThreadId,
6 ProviderTurnId,
7 RunAttemptId,
8 ThreadId,
9} from "@t3tools/contracts";
10import * as Context from "effect/Context";
11import * as Effect from "effect/Effect";
12import * as Layer from "effect/Layer";
13import * as Option from "effect/Option";
14import * as Schema from "effect/Schema";
15
16import * as ProjectionStore from "./ProjectionStore.ts";
17import * as ProviderSessionManager from "./ProviderSessionManager.ts";
18
19const yieldToRuntime = Effect.yieldNow.pipe(
20 Effect.andThen(
21 Effect.promise(
22 () =>
23 new Promise<void>((resolve) => {
24 setImmediate(resolve);
25 }),
26 ),
27 ),
28);
29
30export class ProviderTurnControlError extends Schema.TaggedError<ProviderTurnControlError>()(
31 "ProviderTurnControlError",
32 {
33 threadId: ThreadId,
34 operation: Schema.Literals(["interrupt", "restart", "steer"]),
35 providerTurnId: ProviderTurnId,
36 turnCompleted: Schema.optional(Schema.Boolean),
37 cause: Schema.optional(Schema.Defect()),
38 },
39) {}
40
41const isProviderTurnControlError = Schema.is(ProviderTurnControlError);
42
43export interface ProviderTurnControlServiceV2Shape {
44 readonly interrupt: (input: {
45 readonly threadId: ThreadId;
46 readonly providerSessionId: ProviderSessionId;
47 readonly providerThreadId: ProviderThreadId;
48 readonly providerTurnId: ProviderTurnId;
49 }) => Effect.Effect<void, ProviderTurnControlError>;
50 readonly steer: (input: {
51 readonly threadId: ThreadId;
52 readonly providerSessionId: ProviderSessionId;
53 readonly providerThreadId: ProviderThreadId;
54 readonly providerTurnId: ProviderTurnId;
55 readonly messageId: MessageId;
56 }) => Effect.Effect<void, ProviderTurnControlError>;
57 readonly interruptAndAwaitTerminal: (input: {
58 readonly threadId: ThreadId;
59 readonly providerSessionId: ProviderSessionId;
60 readonly replacementProviderSessionId?: ProviderSessionId;
61 readonly providerThreadId: ProviderThreadId;
62 readonly providerTurnId: ProviderTurnId;
63 readonly interruptedAttemptId: RunAttemptId;
64 }) => Effect.Effect<void, ProviderTurnControlError>;
65}
66
67export class ProviderTurnControlServiceV2 extends Context.Service<
68 ProviderTurnControlServiceV2,
69 ProviderTurnControlServiceV2Shape
70>()("t3/orchestration-v2/ProviderTurnControlService/ProviderTurnControlServiceV2") {}
71
72export const layer: Layer.Layer<
73 ProviderTurnControlServiceV2,
74 never,
75 ProjectionStore.ProjectionStoreV2 | ProviderSessionManager.ProviderSessionManagerV2
76> = Layer.effect(
77 ProviderTurnControlServiceV2,
78 Effect.gen(function* () {
79 const projections = yield* ProjectionStore.ProjectionStoreV2;
80 const sessions = yield* ProviderSessionManager.ProviderSessionManagerV2;
81
82 const load = (input: {
83 readonly threadId: ThreadId;
84 readonly providerSessionId: ProviderSessionId;
85 readonly replacementProviderSessionId?: ProviderSessionId;
86 readonly providerThreadId: ProviderThreadId;
87 readonly providerTurnId: ProviderTurnId;
88 readonly operation: "interrupt" | "restart" | "steer";
89 readonly messageId?: MessageId;
90 }) =>
91 Effect.gen(function* () {
92 const context = yield* projections.getProviderControlContext(input.threadId, input);
93 const { providerThread, providerTurn } = context;
94 const targetsRecordedSession =
95 providerThread?.providerSessionId === input.providerSessionId;
96 const targetsCommittedReplacement =
97 input.operation === "restart" &&
98 input.replacementProviderSessionId !== undefined &&
99 providerThread?.providerSessionId === input.replacementProviderSessionId;
100 if (
101 providerThread === undefined ||
102 providerTurn === undefined ||
103 (!targetsRecordedSession && !targetsCommittedReplacement) ||
104 providerTurn.providerThreadId !== providerThread.id
105 ) {
106 return yield* new ProviderTurnControlError({
107 threadId: input.threadId,
108 operation: input.operation,
109 providerTurnId: input.providerTurnId,
110 cause: "The recorded provider execution target is no longer valid.",
111 });
112 }
113 // A restart-session command commits the replacement binding before its
114 // process-bound effect runs. The old live runtime must still receive
115 // the interrupt, but only when the projection matches the exact
116 // replacement captured by that same durable effect.
117 const interruptProviderThread = targetsRecordedSession
118 ? providerThread
119 : { ...providerThread, providerSessionId: input.providerSessionId };
120 if (providerTurn.status !== "running") {
121 if (input.operation === "steer") {
122 return yield* new ProviderTurnControlError({
123 threadId: input.threadId,
124 operation: "steer",
125 providerTurnId: input.providerTurnId,
126 turnCompleted: providerTurn.status === "completed",
127 cause: "The provider turn ended before the steering message was delivered.",
128 });
129 }
130 return {
131 context,
132 providerThread: interruptProviderThread,
133 providerTurn,
134 session: Option.none(),
135 };
136 }
137 const session = yield* sessions.get(input.providerSessionId);
138 if (Option.isNone(session)) {
139 // Interrupt/restart against a already-released session must not fail
140 // the durable effect (and retry 5x). The turn may still look running
141 // in projection until recovery/finalization; there is no live adapter
142 // to interrupt.
143 if (input.operation === "interrupt" || input.operation === "restart") {
144 yield* Effect.logWarning(
145 "Provider interrupt/restart found no live session; treating as already stopped",
146 {
147 threadId: input.threadId,
148 operation: input.operation,
149 providerSessionId: input.providerSessionId,
150 providerTurnId: input.providerTurnId,
151 providerTurnStatus: providerTurn.status,
152 },
153 );
154 return {
155 context,
156 providerThread: interruptProviderThread,
157 providerTurn,
158 session: Option.none(),
159 };
160 }
161 return yield* new ProviderTurnControlError({
162 threadId: input.threadId,
163 operation: input.operation,
164 providerTurnId: input.providerTurnId,
165 cause: `Provider session ${input.providerSessionId} is not active.`,
166 });
167 }
168 return { context, providerThread: interruptProviderThread, providerTurn, session };
169 });
170
171 return ProviderTurnControlServiceV2.of({
172 interrupt: (input) =>
173 Effect.gen(function* () {
174 const loaded = yield* load({ ...input, operation: "interrupt" });
175 const session = Option.isSome(loaded.session)
176 ? loaded.session
177 : yield* sessions.get(input.providerSessionId);
178 if (Option.isNone(session)) return;
179 // A settled turn reaches its adapter too: only the adapter knows
180 // whether it still runs work for the thread, and each one either
181 // stops it or reports there is nothing left to stop. Background work
182 // the projection still shows is settled by the orchestrator after.
183 yield* session.value.interruptTurn({
184 providerThread: loaded.providerThread,
185 providerTurnId: loaded.providerTurn.id,
186 requestRuntimeRestart: true,
187 });
188 }).pipe(
189 Effect.mapError((cause) =>
190 isProviderTurnControlError(cause)
191 ? cause
192 : new ProviderTurnControlError({
193 threadId: input.threadId,
194 operation: "interrupt",
195 providerTurnId: input.providerTurnId,
196 cause,
197 }),
198 ),
199 ),
200 interruptAndAwaitTerminal: (input) =>
201 Effect.gen(function* () {
202 const loaded = yield* load({ ...input, operation: "restart" });
203 if (Option.isNone(loaded.session)) {
204 // No live adapter: nothing can emit a terminal provider-turn update
205 // from interrupt. Do not poll for projection terminalization or the
206 // restart effect stalls; let detach/start proceed.
207 if (loaded.providerTurn.status === "running") {
208 yield* Effect.logWarning(
209 "Provider restart interrupt skipped; no live session for a still-projected running turn",
210 {
211 threadId: input.threadId,
212 providerSessionId: input.providerSessionId,
213 providerTurnId: input.providerTurnId,
214 },
215 );
216 }
217 return;
218 }
219
220 yield* loaded.session.value.interruptTurn({
221 providerThread: loaded.providerThread,
222 providerTurnId: loaded.providerTurn.id,
223 });
224
225 for (let remaining = 1_000; remaining > 0; remaining -= 1) {
226 const { providerTurn, attempt } = yield* projections.getProviderControlContext(
227 input.threadId,
228 {
229 providerThreadId: input.providerThreadId,
230 providerTurnId: input.providerTurnId,
231 attemptId: input.interruptedAttemptId,
232 },
233 );
234 if (
235 providerTurn !== undefined &&
236 providerTurn.status !== "running" &&
237 attempt !== undefined &&
238 attempt.status !== "running"
239 ) {
240 return;
241 }
242 // Provider terminal events are projected on a detached ingestion
243 // fiber. Yield through the Node event loop instead of sleeping on
244 // Effect's clock so deterministic runtimes cannot deadlock a
245 // command that is waiting for that projection.
246 yield* yieldToRuntime;
247 }
248 return yield* new ProviderTurnControlError({
249 threadId: input.threadId,
250 operation: "restart",
251 providerTurnId: input.providerTurnId,
252 cause: `Provider turn ${input.providerTurnId} did not terminalize before restart.`,
253 });
254 }).pipe(
255 Effect.mapError((cause) =>
256 isProviderTurnControlError(cause)
257 ? cause
258 : new ProviderTurnControlError({
259 threadId: input.threadId,
260 operation: "restart",
261 providerTurnId: input.providerTurnId,
262 cause,
263 }),
264 ),
265 ),
266 steer: (input) =>
267 Effect.gen(function* () {
268 const context = yield* projections.getProviderControlContext(input.threadId, input);
269 const ownership = context.message?.delegatedCompletion;
270 if (ownership !== undefined) {
271 const projection = yield* projections.getThreadRecords(input.threadId, ["runs"], {
272 runIds: [ownership.parentRunId],
273 });
274 const cohort = projection.runs.find(
275 (run) => run.id === ownership.parentRunId,
276 )?.delegatedCompletion;
277 if (
278 cohort?.disposition !== "open" ||
279 cohort.delivery?.messageId !== input.messageId ||
280 cohort.delivery.generation !== ownership.generation ||
281 cohort.delivery.taskIds.length === 0
282 )
283 return;
284 }
285 const loaded = yield* load({ ...input, operation: "steer" });
286 if (Option.isNone(loaded.session)) return;
287 const { message, run } = loaded.context;
288 if (message === undefined || run === undefined) {
289 return yield* new ProviderTurnControlError({
290 threadId: input.threadId,
291 operation: "steer",
292 providerTurnId: input.providerTurnId,
293 cause: "The persisted steering message or target run is missing.",
294 });
295 }
296 yield* loaded.session.value
297 .steerTurn({
298 threadId: input.threadId,
299 runId: run.id,
300 providerThread: loaded.providerThread,
301 providerTurnId: loaded.providerTurn.id,
302 message: {
303 messageId: message.id,
304 text: projectComposerContextForProvider({
305 text: message.text,
306 records: message.context?.records ?? [],
307 }),
308 attachments: message.attachments,
309 createdBy: message.createdBy,
310 creationSource: message.creationSource,
311 ...(message.scheduledTaskId === undefined
312 ? {}
313 : { scheduledTaskId: message.scheduledTaskId }),
314 ...(message.senderThreadId === undefined
315 ? {}
316 : { senderThreadId: message.senderThreadId }),
317 },
318 })
319 .pipe(
320 Effect.catch((cause) =>
321 Effect.gen(function* () {
322 const current = yield* projections.getProviderControlContext(
323 input.threadId,
324 input,
325 );
326 return yield* new ProviderTurnControlError({
327 threadId: input.threadId,
328 operation: "steer",
329 providerTurnId: input.providerTurnId,
330 turnCompleted: current.providerTurn?.status === "completed",
331 cause,
332 });
333 }),
334 ),
335 );
336 }).pipe(
337 Effect.mapError((cause) =>
338 isProviderTurnControlError(cause)
339 ? cause
340 : new ProviderTurnControlError({
341 threadId: input.threadId,
342 operation: "steer",
343 providerTurnId: input.providerTurnId,
344 cause,
345 }),
346 ),
347 ),
348 });
349 }),
350);