Open History to see the last commit
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>;
77}
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 = (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 Effect.gen(function* () {
104 const context = yield* projections.getProviderControlContext(input.threadId, input);
105 const { providerThread, providerTurn } = context;
106 const targetsRecordedSession =
107 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 if (providerTurn.status !== "running") {
133 if (input.operation === "steer") {
134 return yield* new ProviderTurnControlError({
135 threadId: input.threadId,
136 operation: "steer",
137 providerTurnId: input.providerTurnId,
138 turnCompleted: providerTurn.status === "completed",
139 cause: "The provider turn ended before the steering message was delivered.",
140 });
141 }
142 return {
143 context,
144 providerThread: interruptProviderThread,
145 providerTurn,
146 session: Option.none(),
147 };
148 }
149 const session = yield* sessions.get(input.providerSessionId);
150 if (Option.isNone(session)) {
151 // Interrupt/restart against a already-released session must not fail
152 // the durable effect (and retry 5x). The turn may still look running
153 // in projection until recovery/finalization; there is no live adapter
154 // to interrupt.
155 if (input.operation === "interrupt" || input.operation === "restart") {
156 yield* Effect.logWarning(
157 "Provider interrupt/restart found no live session; treating as already stopped",
158 {
159 threadId: input.threadId,
160 operation: input.operation,
161 providerSessionId: input.providerSessionId,
162 providerTurnId: input.providerTurnId,
163 providerTurnStatus: providerTurn.status,
164 },
165 );
166 return {
167 context,
168 providerThread: interruptProviderThread,
169 providerTurn,
170 session: Option.none(),
171 };
172 }
173 return yield* new ProviderTurnControlError({
174 threadId: input.threadId,
175 operation: input.operation,
176 providerTurnId: input.providerTurnId,
177 cause: `Provider session ${input.providerSessionId} is not active.`,
178 });
179 }
180 return { context, providerThread: interruptProviderThread, providerTurn, session };
181 });
182
183 return ProviderTurnControlServiceV2.of({
184 interrupt: (input) =>
185 Effect.gen(function* () {
186 const loaded = yield* load({ ...input, operation: "interrupt" });
187 const session = Option.isSome(loaded.session)
188 ? loaded.session
189 : yield* sessions.get(input.providerSessionId);
190 if (Option.isNone(session)) {
191 if (input.subagent !== undefined) {
192 return yield* new ProviderTurnControlError({
193 threadId: input.threadId,
194 operation: "interrupt",
195 providerTurnId: input.providerTurnId,
196 cause: "No live provider session can confirm this subagent's outcome.",
197 });
198 }
199 return;
200 }
201 if (input.subagent !== undefined) {
202 if (session.value.stopSubagent === undefined) {
203 return yield* new ProviderTurnControlError({
204 threadId: input.threadId,
205 operation: "interrupt",
206 providerTurnId: input.providerTurnId,
207 cause: "The provider does not support stopping a native subagent.",
208 });
209 }
210 return yield* session.value.stopSubagent({
211 providerThread: loaded.providerThread,
212 nativeTaskId: input.subagent.nativeTaskId,
213 ...(input.subagent.requestedAt === undefined
214 ? {}
215 : { requestedAt: input.subagent.requestedAt }),
216 });
217 }
218 // A settled turn reaches its adapter too: only the adapter knows
219 // whether it still runs work for the thread, and each one either
220 // stops it or reports there is nothing left to stop.
221 yield* session.value.interruptTurn({
222 providerThread: loaded.providerThread,
223 providerTurnId: loaded.providerTurn.id,
224 requestRuntimeRestart: true,
225 });
226 // The wait is real time: ingestion runs on other fibers and never
227 // advances a test clock, so a test clock would hold Stop forever.
228 yield* Effect.gen(function* () {
229 const deadline = (yield* Clock.currentTimeMillis) + 2_000;
230 while (
231 loaded.providerTurn.status === "running" &&
232 (yield* Clock.currentTimeMillis) < deadline
233 ) {
234 const current = yield* projections.getProviderControlContext(input.threadId, input);
235 if (
236 current.providerTurn?.status !== "running" &&
237 current.attempt?.status !== "running"
238 ) {
239 return;
240 }
241 yield* Effect.sleep("10 millis");
242 }
243 }).pipe(Effect.provideService(Clock.Clock, Clock.Clock.defaultValue()));
244 }).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 interruptAndAwaitTerminal: (input) =>
257 Effect.gen(function* () {
258 const loaded = yield* load({ ...input, operation: "restart" });
259 if (Option.isNone(loaded.session)) {
260 // No live adapter: nothing can emit a terminal provider-turn update
261 // from interrupt. Do not poll for projection terminalization or the
262 // restart effect stalls; let detach/start proceed.
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 // Provider terminal events are projected on a detached ingestion
299 // fiber. Yield through the Node event loop instead of sleeping on
300 // Effect's clock so deterministic runtimes cannot deadlock a
301 // command that is waiting for that projection.
302 yield* yieldToRuntime;
303 }
304 return yield* new ProviderTurnControlError({
305 threadId: input.threadId,
306 operation: "restart",
307 providerTurnId: input.providerTurnId,
308 cause: `Provider turn ${input.providerTurnId} did not terminalize before restart.`,
309 });
310 }).pipe(
311 Effect.mapError((cause) =>
312 isProviderTurnControlError(cause)
313 ? cause
314 : new ProviderTurnControlError({
315 threadId: input.threadId,
316 operation: "restart",
317 providerTurnId: input.providerTurnId,
318 cause,
319 }),
320 ),
321 ),
322 steer: (input) =>
323 Effect.gen(function* () {
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 }).pipe(
393 Effect.mapError((cause) =>
394 isProviderTurnControlError(cause)
395 ? cause
396 : new ProviderTurnControlError({
397 threadId: input.threadId,
398 operation: "steer",
399 providerTurnId: input.providerTurnId,
400 cause,
401 }),
402 ),
403 ),
404 });
405 }),
406);