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

ProviderTurnControlService.ts

338 lines13.2 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 if (Option.isNone(loaded.session)) return;
176 yield* loaded.session.value.interruptTurn({
177 providerThread: loaded.providerThread,
178 providerTurnId: loaded.providerTurn.id,
179 requestRuntimeRestart: true,
180 });
181 }).pipe(
182 Effect.mapError((cause) =>
183 isProviderTurnControlError(cause)
184 ? cause
185 : new ProviderTurnControlError({
186 threadId: input.threadId,
187 operation: "interrupt",
188 providerTurnId: input.providerTurnId,
189 cause,
190 }),
191 ),
192 ),
193 interruptAndAwaitTerminal: (input) =>
194 Effect.gen(function* () {
195 const loaded = yield* load({ ...input, operation: "restart" });
196 if (Option.isNone(loaded.session)) {
197 // No live adapter: nothing can emit a terminal provider-turn update
198 // from interrupt. Do not poll for projection terminalization or the
199 // restart effect stalls; let detach/start proceed.
200 if (loaded.providerTurn.status === "running") {
201 yield* Effect.logWarning(
202 "Provider restart interrupt skipped; no live session for a still-projected running turn",
203 {
204 threadId: input.threadId,
205 providerSessionId: input.providerSessionId,
206 providerTurnId: input.providerTurnId,
207 },
208 );
209 }
210 return;
211 }
212​
213 yield* loaded.session.value.interruptTurn({
214 providerThread: loaded.providerThread,
215 providerTurnId: loaded.providerTurn.id,
216 });
217​
218 for (let remaining = 1_000; remaining > 0; remaining -= 1) {
219 const { providerTurn, attempt } = yield* projections.getProviderControlContext(
220 input.threadId,
221 {
222 providerThreadId: input.providerThreadId,
223 providerTurnId: input.providerTurnId,
224 attemptId: input.interruptedAttemptId,
225 },
226 );
227 if (
228 providerTurn !== undefined &&
229 providerTurn.status !== "running" &&
230 attempt !== undefined &&
231 attempt.status !== "running"
232 ) {
233 return;
234 }
235 // Provider terminal events are projected on a detached ingestion
236 // fiber. Yield through the Node event loop instead of sleeping on
237 // Effect's clock so deterministic runtimes cannot deadlock a
238 // command that is waiting for that projection.
239 yield* yieldToRuntime;
240 }
241 return yield* new ProviderTurnControlError({
242 threadId: input.threadId,
243 operation: "restart",
244 providerTurnId: input.providerTurnId,
245 cause: `Provider turn ${input.providerTurnId} did not terminalize before restart.`,
246 });
247 }).pipe(
248 Effect.mapError((cause) =>
249 isProviderTurnControlError(cause)
250 ? cause
251 : new ProviderTurnControlError({
252 threadId: input.threadId,
253 operation: "restart",
254 providerTurnId: input.providerTurnId,
255 cause,
256 }),
257 ),
258 ),
259 steer: (input) =>
260 Effect.gen(function* () {
261 const context = yield* projections.getProviderControlContext(input.threadId, input);
262 const ownership = context.message?.delegatedCompletion;
263 if (ownership !== undefined) {
264 const projection = yield* projections.getThreadProjection(input.threadId);
265 const cohort = projection.runs.find(
266 (run) => run.id === ownership.parentRunId,
267 )?.delegatedCompletion;
268 if (
269 cohort?.disposition !== "open" ||
270 cohort.delivery?.messageId !== input.messageId ||
271 cohort.delivery.generation !== ownership.generation ||
272 cohort.delivery.taskIds.length === 0
273 )
274 return;
275 }
276 const loaded = yield* load({ ...input, operation: "steer" });
277 if (Option.isNone(loaded.session)) return;
278 const { message, run } = loaded.context;
279 if (message === undefined || run === undefined) {
280 return yield* new ProviderTurnControlError({
281 threadId: input.threadId,
282 operation: "steer",
283 providerTurnId: input.providerTurnId,
284 cause: "The persisted steering message or target run is missing.",
285 });
286 }
287 yield* loaded.session.value
288 .steerTurn({
289 threadId: input.threadId,
290 runId: run.id,
291 providerThread: loaded.providerThread,
292 providerTurnId: loaded.providerTurn.id,
293 message: {
294 messageId: message.id,
295 text: projectComposerContextForProvider({
296 text: message.text,
297 records: message.context?.records ?? [],
298 }),
299 attachments: message.attachments,
300 createdBy: message.createdBy,
301 creationSource: message.creationSource,
302 ...(message.scheduledTaskId === undefined
303 ? {}
304 : { scheduledTaskId: message.scheduledTaskId }),
305 },
306 })
307 .pipe(
308 Effect.catch((cause) =>
309 Effect.gen(function* () {
310 const current = yield* projections.getProviderControlContext(
311 input.threadId,
312 input,
313 );
314 return yield* new ProviderTurnControlError({
315 threadId: input.threadId,
316 operation: "steer",
317 providerTurnId: input.providerTurnId,
318 turnCompleted: current.providerTurn?.status === "completed",
319 cause,
320 });
321 }),
322 ),
323 );
324 }).pipe(
325 Effect.mapError((cause) =>
326 isProviderTurnControlError(cause)
327 ? cause
328 : new ProviderTurnControlError({
329 threadId: input.threadId,
330 operation: "steer",
331 providerTurnId: input.providerTurnId,
332 cause,
333 }),
334 ),
335 ),
336 });
337 }),
338);