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