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

ProviderTurnControlService.ts

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