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

ProviderTurnControlService.ts

347 lines13.6 KB

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 { ProjectionStoreV2 } from "./ProjectionStore.ts";
17import { ProviderSessionManagerV2 } 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>;
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 ProjectionStoreV2 | ProviderSessionManagerV2
76> = Layer.effect(
77 ProviderTurnControlServiceV2,
78 Effect.gen(function* () {
79 const projections = yield* ProjectionStoreV2;
80 const sessions = yield* 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 if (
180 loaded.providerTurn.status !== "running" &&
181 (session.value.hasPendingBackgroundWorkForThread === undefined ||
182 !(yield* session.value.hasPendingBackgroundWorkForThread(loaded.providerThread)))
183 )
184 return;
185 yield* session.value.interruptTurn({
186 providerThread: loaded.providerThread,
187 providerTurnId: loaded.providerTurn.id,
188 requestRuntimeRestart: true,
189 });
190 }).pipe(
191 Effect.mapError((cause) =>
192 isProviderTurnControlError(cause)
193 ? cause
194 : new ProviderTurnControlError({
195 threadId: input.threadId,
196 operation: "interrupt",
197 providerTurnId: input.providerTurnId,
198 cause,
199 }),
200 ),
201 ),
202 interruptAndAwaitTerminal: (input) =>
203 Effect.gen(function* () {
204 const loaded = yield* load({ ...input, operation: "restart" });
205 if (Option.isNone(loaded.session)) {
206 // No live adapter: nothing can emit a terminal provider-turn update
207 // from interrupt. Do not poll for projection terminalization or the
208 // restart effect stalls; let detach/start proceed.
209 if (loaded.providerTurn.status === "running") {
210 yield* Effect.logWarning(
211 "Provider restart interrupt skipped; no live session for a still-projected running turn",
212 {
213 threadId: input.threadId,
214 providerSessionId: input.providerSessionId,
215 providerTurnId: input.providerTurnId,
216 },
217 );
218 }
219 return;
220 }
221​
222 yield* loaded.session.value.interruptTurn({
223 providerThread: loaded.providerThread,
224 providerTurnId: loaded.providerTurn.id,
225 });
226​
227 for (let remaining = 1_000; remaining > 0; remaining -= 1) {
228 const { providerTurn, attempt } = yield* projections.getProviderControlContext(
229 input.threadId,
230 {
231 providerThreadId: input.providerThreadId,
232 providerTurnId: input.providerTurnId,
233 attemptId: input.interruptedAttemptId,
234 },
235 );
236 if (
237 providerTurn !== undefined &&
238 providerTurn.status !== "running" &&
239 attempt !== undefined &&
240 attempt.status !== "running"
241 ) {
242 return;
243 }
244 // Provider terminal events are projected on a detached ingestion
245 // fiber. Yield through the Node event loop instead of sleeping on
246 // Effect's clock so deterministic runtimes cannot deadlock a
247 // command that is waiting for that projection.
248 yield* yieldToRuntime;
249 }
250 return yield* new ProviderTurnControlError({
251 threadId: input.threadId,
252 operation: "restart",
253 providerTurnId: input.providerTurnId,
254 cause: `Provider turn ${input.providerTurnId} did not terminalize before restart.`,
255 });
256 }).pipe(
257 Effect.mapError((cause) =>
258 isProviderTurnControlError(cause)
259 ? cause
260 : new ProviderTurnControlError({
261 threadId: input.threadId,
262 operation: "restart",
263 providerTurnId: input.providerTurnId,
264 cause,
265 }),
266 ),
267 ),
268 steer: (input) =>
269 Effect.gen(function* () {
270 const context = yield* projections.getProviderControlContext(input.threadId, input);
271 const ownership = context.message?.delegatedCompletion;
272 if (ownership !== undefined) {
273 const projection = yield* projections.getThreadProjection(input.threadId);
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 },
315 })
316 .pipe(
317 Effect.catch((cause) =>
318 Effect.gen(function* () {
319 const current = yield* projections.getProviderControlContext(
320 input.threadId,
321 input,
322 );
323 return yield* new ProviderTurnControlError({
324 threadId: input.threadId,
325 operation: "steer",
326 providerTurnId: input.providerTurnId,
327 turnCompleted: current.providerTurn?.status === "completed",
328 cause,
329 });
330 }),
331 ),
332 );
333 }).pipe(
334 Effect.mapError((cause) =>
335 isProviderTurnControlError(cause)
336 ? cause
337 : new ProviderTurnControlError({
338 threadId: input.threadId,
339 operation: "steer",
340 providerTurnId: input.providerTurnId,
341 cause,
342 }),
343 ),
344 ),
345 });
346 }),
347);