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

ProviderTurnControlService.ts

296 lines11.4 KB

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