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

ProviderTurnControlService.ts

413 lines16.3 KB

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