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

ProviderTurnControlService.ts

409 lines16.1 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 const continuingRun =
131 input.operation === "steer" &&
132 context.run?.status === "running" &&
133 context.run.activeAttemptId === providerTurn.runAttemptId;
134 if (providerTurn.status !== "running" && !continuingRun) {
135 if (input.operation === "steer") {
136 return yield* new ProviderTurnControlError({
137 threadId: input.threadId,
138 operation: "steer",
139 providerTurnId: input.providerTurnId,
140 turnCompleted: providerTurn.status === "completed",
141 cause: "The provider turn ended before the steering message was delivered.",
142 });
143 }
144 return {
145 context,
146 providerThread: interruptProviderThread,
147 providerTurn,
148 session: Option.none(),
149 };
150 }
151 const session = yield* sessions.get(input.providerSessionId);
152 if (Option.isNone(session)) {
153 // Interrupt/restart against a already-released session must not fail
154 // the durable effect (and retry 5x). The turn may still look running
155 // in projection until recovery/finalization; there is no live adapter
156 // to interrupt.
157 if (input.operation === "interrupt" || input.operation === "restart") {
158 yield* Effect.logWarning(
159 "Provider interrupt/restart found no live session; treating as already stopped",
160 {
161 threadId: input.threadId,
162 operation: input.operation,
163 providerSessionId: input.providerSessionId,
164 providerTurnId: input.providerTurnId,
165 providerTurnStatus: providerTurn.status,
166 },
167 );
168 return {
169 context,
170 providerThread: interruptProviderThread,
171 providerTurn,
172 session: Option.none(),
173 };
174 }
175 return yield* new ProviderTurnControlError({
176 threadId: input.threadId,
177 operation: input.operation,
178 providerTurnId: input.providerTurnId,
179 cause: `Provider session ${input.providerSessionId} is not active.`,
180 });
181 }
182 return { context, providerThread: interruptProviderThread, providerTurn, session };
183 });
184​
185 return ProviderTurnControlServiceV2.of({
186 interrupt: Effect.fn("ProviderTurnControlService.interrupt")(
187 function* (input) {
188 const loaded = yield* load({ ...input, operation: "interrupt" });
189 const session = Option.isSome(loaded.session)
190 ? loaded.session
191 : yield* sessions.get(input.providerSessionId);
192 if (Option.isNone(session)) {
193 if (input.subagent !== undefined) {
194 return yield* new ProviderTurnControlError({
195 threadId: input.threadId,
196 operation: "interrupt",
197 providerTurnId: input.providerTurnId,
198 cause: "No live provider session can confirm this subagent's outcome.",
199 });
200 }
201 return;
202 }
203 if (input.subagent !== undefined) {
204 if (session.value.stopSubagent === undefined) {
205 return yield* new ProviderTurnControlError({
206 threadId: input.threadId,
207 operation: "interrupt",
208 providerTurnId: input.providerTurnId,
209 cause: "The provider does not support stopping a native subagent.",
210 });
211 }
212 return yield* session.value.stopSubagent({
213 providerThread: loaded.providerThread,
214 nativeTaskId: input.subagent.nativeTaskId,
215 ...(input.subagent.requestedAt === undefined
216 ? {}
217 : { requestedAt: input.subagent.requestedAt }),
218 });
219 }
220 // Settled turns still reach adapters, which alone know whether background work remains.
221 yield* session.value.interruptTurn({
222 providerThread: loaded.providerThread,
223 providerTurnId: loaded.providerTurn.id,
224 requestRuntimeRestart: true,
225 });
226 // Use real time; ingestion fibers do not advance TestClock and would leave Stop blocked.
227 yield* Effect.gen(function* () {
228 const deadline = (yield* Clock.currentTimeMillis) + 2_000;
229 while (
230 loaded.providerTurn.status === "running" &&
231 (yield* Clock.currentTimeMillis) < deadline
232 ) {
233 const current = yield* projections.getProviderControlContext(input.threadId, input);
234 if (
235 current.providerTurn?.status !== "running" &&
236 current.attempt?.status !== "running"
237 ) {
238 return;
239 }
240 yield* Effect.sleep("10 millis");
241 }
242 }).pipe(Effect.provideService(Clock.Clock, Clock.Clock.defaultValue()));
243 },
244 (effect, input) =>
245 effect.pipe(
246 Effect.mapError((cause) =>
247 isProviderTurnControlError(cause)
248 ? cause
249 : new ProviderTurnControlError({
250 threadId: input.threadId,
251 operation: "interrupt",
252 providerTurnId: input.providerTurnId,
253 cause,
254 }),
255 ),
256 ),
257 ),
258 interruptAndAwaitTerminal: Effect.fn("ProviderTurnControlService.interruptAndAwaitTerminal")(
259 function* (input) {
260 const loaded = yield* load({ ...input, operation: "restart" });
261 if (Option.isNone(loaded.session)) {
262 // Without a live adapter, no terminal event can arrive; proceed to detach/start without polling.
263 if (loaded.providerTurn.status === "running") {
264 yield* Effect.logWarning(
265 "Provider restart interrupt skipped; no live session for a still-projected running turn",
266 {
267 threadId: input.threadId,
268 providerSessionId: input.providerSessionId,
269 providerTurnId: input.providerTurnId,
270 },
271 );
272 }
273 return;
274 }
275​
276 yield* loaded.session.value.interruptTurn({
277 providerThread: loaded.providerThread,
278 providerTurnId: loaded.providerTurn.id,
279 });
280​
281 for (let remaining = 1_000; remaining > 0; remaining -= 1) {
282 const { providerTurn, attempt } = yield* projections.getProviderControlContext(
283 input.threadId,
284 {
285 providerThreadId: input.providerThreadId,
286 providerTurnId: input.providerTurnId,
287 attemptId: input.interruptedAttemptId,
288 },
289 );
290 if (
291 providerTurn !== undefined &&
292 providerTurn.status !== "running" &&
293 attempt !== undefined &&
294 attempt.status !== "running"
295 ) {
296 return;
297 }
298 // Yield through Node's event loop; detached ingestion cannot advance a deterministic Effect clock.
299 yield* yieldToRuntime;
300 }
301 return yield* new ProviderTurnControlError({
302 threadId: input.threadId,
303 operation: "restart",
304 providerTurnId: input.providerTurnId,
305 cause: `Provider turn ${input.providerTurnId} did not terminalize before restart.`,
306 });
307 },
308 (effect, input) =>
309 effect.pipe(
310 Effect.mapError((cause) =>
311 isProviderTurnControlError(cause)
312 ? cause
313 : new ProviderTurnControlError({
314 threadId: input.threadId,
315 operation: "restart",
316 providerTurnId: input.providerTurnId,
317 cause,
318 }),
319 ),
320 ),
321 ),
322 steer: Effect.fn("ProviderTurnControlService.steer")(
323 function* (input) {
324 const context = yield* projections.getProviderControlContext(input.threadId, input);
325 const ownership = context.message?.delegatedCompletion;
326 if (ownership !== undefined) {
327 const projection = yield* projections.getThreadRecords(input.threadId, ["runs"], {
328 runIds: [ownership.parentRunId],
329 });
330 const cohort = projection.runs.find(
331 (run) => run.id === ownership.parentRunId,
332 )?.delegatedCompletion;
333 if (
334 cohort?.disposition !== "open" ||
335 cohort.delivery?.messageId !== input.messageId ||
336 cohort.delivery.generation !== ownership.generation ||
337 cohort.delivery.taskIds.length === 0
338 )
339 return;
340 }
341 const loaded = yield* load({ ...input, operation: "steer" });
342 if (Option.isNone(loaded.session)) return;
343 const { message, run } = loaded.context;
344 if (message === undefined || run === undefined) {
345 return yield* new ProviderTurnControlError({
346 threadId: input.threadId,
347 operation: "steer",
348 providerTurnId: input.providerTurnId,
349 cause: "The persisted steering message or target run is missing.",
350 });
351 }
352 yield* loaded.session.value
353 .steerTurn({
354 threadId: input.threadId,
355 runId: run.id,
356 providerThread: loaded.providerThread,
357 providerTurnId: loaded.providerTurn.id,
358 message: {
359 messageId: message.id,
360 text: projectComposerContextForProvider({
361 text: message.text,
362 records: message.context?.records ?? [],
363 }),
364 attachments: message.attachments,
365 createdBy: message.createdBy,
366 creationSource: message.creationSource,
367 ...(message.scheduledTaskId === undefined
368 ? {}
369 : { scheduledTaskId: message.scheduledTaskId }),
370 ...(message.senderThreadId === undefined
371 ? {}
372 : { senderThreadId: message.senderThreadId }),
373 },
374 })
375 .pipe(
376 Effect.catch((cause) =>
377 Effect.gen(function* () {
378 const current = yield* projections.getProviderControlContext(
379 input.threadId,
380 input,
381 );
382 return yield* new ProviderTurnControlError({
383 threadId: input.threadId,
384 operation: "steer",
385 providerTurnId: input.providerTurnId,
386 turnCompleted: current.providerTurn?.status === "completed",
387 cause,
388 });
389 }),
390 ),
391 );
392 },
393 (effect, input) =>
394 effect.pipe(
395 Effect.mapError((cause) =>
396 isProviderTurnControlError(cause)
397 ? cause
398 : new ProviderTurnControlError({
399 threadId: input.threadId,
400 operation: "steer",
401 providerTurnId: input.providerTurnId,
402 cause,
403 }),
404 ),
405 ),
406 ),
407 });
408 }),
409);