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

ProviderTurnControlService.ts

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