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

ProviderTurnControlService.ts

405 lines15.9 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 // Settled turns still reach adapters, which alone know whether background work remains.
217 yield* session.value.interruptTurn({
218 providerThread: loaded.providerThread,
219 providerTurnId: loaded.providerTurn.id,
220 requestRuntimeRestart: true,
221 });
222 // Use real time; ingestion fibers do not advance TestClock and would leave Stop blocked.
223 yield* Effect.gen(function* () {
224 const deadline = (yield* Clock.currentTimeMillis) + 2_000;
225 while (
226 loaded.providerTurn.status === "running" &&
227 (yield* Clock.currentTimeMillis) < deadline
228 ) {
229 const current = yield* projections.getProviderControlContext(input.threadId, input);
230 if (
231 current.providerTurn?.status !== "running" &&
232 current.attempt?.status !== "running"
233 ) {
234 return;
235 }
236 yield* Effect.sleep("10 millis");
237 }
238 }).pipe(Effect.provideService(Clock.Clock, Clock.Clock.defaultValue()));
239 },
240 (effect, input) =>
241 effect.pipe(
242 Effect.mapError((cause) =>
243 isProviderTurnControlError(cause)
244 ? cause
245 : new ProviderTurnControlError({
246 threadId: input.threadId,
247 operation: "interrupt",
248 providerTurnId: input.providerTurnId,
249 cause,
250 }),
251 ),
252 ),
253 ),
254 interruptAndAwaitTerminal: Effect.fn("ProviderTurnControlService.interruptAndAwaitTerminal")(
255 function* (input) {
256 const loaded = yield* load({ ...input, operation: "restart" });
257 if (Option.isNone(loaded.session)) {
258 // Without a live adapter, no terminal event can arrive; proceed to detach/start without polling.
259 if (loaded.providerTurn.status === "running") {
260 yield* Effect.logWarning(
261 "Provider restart interrupt skipped; no live session for a still-projected running turn",
262 {
263 threadId: input.threadId,
264 providerSessionId: input.providerSessionId,
265 providerTurnId: input.providerTurnId,
266 },
267 );
268 }
269 return;
270 }
271​
272 yield* loaded.session.value.interruptTurn({
273 providerThread: loaded.providerThread,
274 providerTurnId: loaded.providerTurn.id,
275 });
276​
277 for (let remaining = 1_000; remaining > 0; remaining -= 1) {
278 const { providerTurn, attempt } = yield* projections.getProviderControlContext(
279 input.threadId,
280 {
281 providerThreadId: input.providerThreadId,
282 providerTurnId: input.providerTurnId,
283 attemptId: input.interruptedAttemptId,
284 },
285 );
286 if (
287 providerTurn !== undefined &&
288 providerTurn.status !== "running" &&
289 attempt !== undefined &&
290 attempt.status !== "running"
291 ) {
292 return;
293 }
294 // Yield through Node's event loop; detached ingestion cannot advance a deterministic Effect clock.
295 yield* yieldToRuntime;
296 }
297 return yield* new ProviderTurnControlError({
298 threadId: input.threadId,
299 operation: "restart",
300 providerTurnId: input.providerTurnId,
301 cause: `Provider turn ${input.providerTurnId} did not terminalize before restart.`,
302 });
303 },
304 (effect, input) =>
305 effect.pipe(
306 Effect.mapError((cause) =>
307 isProviderTurnControlError(cause)
308 ? cause
309 : new ProviderTurnControlError({
310 threadId: input.threadId,
311 operation: "restart",
312 providerTurnId: input.providerTurnId,
313 cause,
314 }),
315 ),
316 ),
317 ),
318 steer: Effect.fn("ProviderTurnControlService.steer")(
319 function* (input) {
320 const context = yield* projections.getProviderControlContext(input.threadId, input);
321 const ownership = context.message?.delegatedCompletion;
322 if (ownership !== undefined) {
323 const projection = yield* projections.getThreadRecords(input.threadId, ["runs"], {
324 runIds: [ownership.parentRunId],
325 });
326 const cohort = projection.runs.find(
327 (run) => run.id === ownership.parentRunId,
328 )?.delegatedCompletion;
329 if (
330 cohort?.disposition !== "open" ||
331 cohort.delivery?.messageId !== input.messageId ||
332 cohort.delivery.generation !== ownership.generation ||
333 cohort.delivery.taskIds.length === 0
334 )
335 return;
336 }
337 const loaded = yield* load({ ...input, operation: "steer" });
338 if (Option.isNone(loaded.session)) return;
339 const { message, run } = loaded.context;
340 if (message === undefined || run === undefined) {
341 return yield* new ProviderTurnControlError({
342 threadId: input.threadId,
343 operation: "steer",
344 providerTurnId: input.providerTurnId,
345 cause: "The persisted steering message or target run is missing.",
346 });
347 }
348 yield* loaded.session.value
349 .steerTurn({
350 threadId: input.threadId,
351 runId: run.id,
352 providerThread: loaded.providerThread,
353 providerTurnId: loaded.providerTurn.id,
354 message: {
355 messageId: message.id,
356 text: projectComposerContextForProvider({
357 text: message.text,
358 records: message.context?.records ?? [],
359 }),
360 attachments: message.attachments,
361 createdBy: message.createdBy,
362 creationSource: message.creationSource,
363 ...(message.scheduledTaskId === undefined
364 ? {}
365 : { scheduledTaskId: message.scheduledTaskId }),
366 ...(message.senderThreadId === undefined
367 ? {}
368 : { senderThreadId: message.senderThreadId }),
369 },
370 })
371 .pipe(
372 Effect.catch((cause) =>
373 Effect.gen(function* () {
374 const current = yield* projections.getProviderControlContext(
375 input.threadId,
376 input,
377 );
378 return yield* new ProviderTurnControlError({
379 threadId: input.threadId,
380 operation: "steer",
381 providerTurnId: input.providerTurnId,
382 turnCompleted: current.providerTurn?.status === "completed",
383 cause,
384 });
385 }),
386 ),
387 );
388 },
389 (effect, input) =>
390 effect.pipe(
391 Effect.mapError((cause) =>
392 isProviderTurnControlError(cause)
393 ? cause
394 : new ProviderTurnControlError({
395 threadId: input.threadId,
396 operation: "steer",
397 providerTurnId: input.providerTurnId,
398 cause,
399 }),
400 ),
401 ),
402 ),
403 });
404 }),
405);