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

ProviderTurnControlService.ts

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