Open History to see the last commit
1import { projectComposerContextForProvider } from "@t3tools/shared/composerContextReferences";
2import {
3 MessageId,
4 type ModelSelection,
5 type NodeId,
6 ProviderSessionId,
7 ProviderThreadId,
8 ProviderTurnId,
9 RunAttemptId,
10 ThreadId,
11} from "@t3tools/contracts";
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";
18import * as Stream from "effect/Stream";
19
20import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
21import * as EventSink from "./EventSink.ts";
22import * as ProjectionStore from "./ProjectionStore.ts";
23import * as ProviderSessionManager from "./ProviderSessionManager.ts";
24
25const yieldToRuntime = Effect.yieldNow.pipe(
26 Effect.andThen(
27 Effect.promise(
28 () =>
29 new Promise<void>((resolve) => {
30 setImmediate(resolve);
31 }),
32 ),
33 ),
34);
35
36export class ProviderTurnControlError extends Schema.TaggedError<ProviderTurnControlError>()(
37 "ProviderTurnControlError",
38 {
39 threadId: ThreadId,
40 operation: Schema.Literals(["interrupt", "restart", "steer"]),
41 providerTurnId: ProviderTurnId,
42 turnCompleted: Schema.optional(Schema.Boolean),
43 steerDeclined: Schema.optional(Schema.Boolean),
44 /** The provider never confirmed the stop; Force stop is the way out. */
45 unresponsive: Schema.optional(Schema.Boolean),
46 cause: Schema.optional(Schema.Defect()),
47 },
48) {}
49
50const isProviderTurnControlError = Schema.is(ProviderTurnControlError);
51
52export interface ProviderTurnControlServiceV2Shape {
53 readonly interrupt: (input: {
54 readonly subagent?: {
55 readonly id: NodeId;
56 readonly nativeTaskId: string;
57 readonly requestedAt?: DateTime.Utc;
58 };
59 readonly threadId: ThreadId;
60 readonly providerSessionId: ProviderSessionId;
61 readonly providerThreadId: ProviderThreadId;
62 readonly providerTurnId: ProviderTurnId;
63 }) => Effect.Effect<
64 void | ProviderAdapter.ProviderAdapterV2SubagentOutcome,
65 ProviderTurnControlError
66 >;
67 readonly steer: (input: {
68 readonly threadId: ThreadId;
69 readonly providerSessionId: ProviderSessionId;
70 readonly providerThreadId: ProviderThreadId;
71 readonly providerTurnId: ProviderTurnId;
72 readonly messageId: MessageId;
73 readonly modelSelection?: ModelSelection;
74 }) => Effect.Effect<void, ProviderTurnControlError>;
75 /** Best effort: a turn that ended or moved sessions picks the selection up when it next starts. */
76 readonly applyModelSelection: (input: {
77 readonly threadId: ThreadId;
78 readonly providerSessionId: ProviderSessionId;
79 readonly providerThreadId: ProviderThreadId;
80 readonly modelSelection: ModelSelection;
81 }) => Effect.Effect<
82 void,
83 | ProjectionStore.ProjectionStoreV2Error
84 | ProviderSessionManager.ProviderSessionManagerV2Error
85 | ProviderAdapter.ProviderAdapterV2Error
86 >;
87 /** Best effort: a provider thread that is no longer live picks the title up when its next turn starts. */
88 readonly applyThreadTitle: (input: {
89 readonly threadId: ThreadId;
90 readonly title: string;
91 }) => Effect.Effect<
92 void,
93 | ProjectionStore.ProjectionStoreV2Error
94 | ProviderSessionManager.ProviderSessionManagerV2Error
95 | ProviderAdapter.ProviderAdapterV2Error
96 >;
97 readonly interruptAndAwaitTerminal: (input: {
98 readonly threadId: ThreadId;
99 readonly providerSessionId: ProviderSessionId;
100 readonly replacementProviderSessionId?: ProviderSessionId;
101 readonly providerThreadId: ProviderThreadId;
102 readonly providerTurnId: ProviderTurnId;
103 readonly interruptedAttemptId: RunAttemptId;
104 }) => Effect.Effect<void, ProviderTurnControlError>;
105}
106
107export class ProviderTurnControlServiceV2 extends Context.Service<
108 ProviderTurnControlServiceV2,
109 ProviderTurnControlServiceV2Shape
110>()("t3/orchestration-v2/ProviderTurnControlService/ProviderTurnControlServiceV2") {}
111
112export const layer: Layer.Layer<
113 ProviderTurnControlServiceV2,
114 never,
115 | EventSink.EventSinkV2
116 | ProjectionStore.ProjectionStoreV2
117 | ProviderSessionManager.ProviderSessionManagerV2
118> = Layer.effect(
119 ProviderTurnControlServiceV2,
120 Effect.gen(function* () {
121 const eventSink = yield* EventSink.EventSinkV2;
122 const projections = yield* ProjectionStore.ProjectionStoreV2;
123 const sessions = yield* ProviderSessionManager.ProviderSessionManagerV2;
124
125 const load = Effect.fn("ProviderTurnControlService.load")(function* (input: {
126 readonly threadId: ThreadId;
127 readonly providerSessionId: ProviderSessionId;
128 readonly replacementProviderSessionId?: ProviderSessionId;
129 readonly providerThreadId: ProviderThreadId;
130 readonly providerTurnId: ProviderTurnId;
131 readonly operation: "interrupt" | "restart" | "steer";
132 readonly messageId?: MessageId;
133 }) {
134 const context = yield* projections.getProviderControlContext(input.threadId, input);
135 const { providerThread, providerTurn } = context;
136 const targetsRecordedSession = providerThread?.providerSessionId === input.providerSessionId;
137 const targetsCommittedReplacement =
138 input.operation === "restart" &&
139 input.replacementProviderSessionId !== undefined &&
140 providerThread?.providerSessionId === input.replacementProviderSessionId;
141 if (
142 providerThread === undefined ||
143 providerTurn === undefined ||
144 (!targetsRecordedSession && !targetsCommittedReplacement) ||
145 providerTurn.providerThreadId !== providerThread.id
146 ) {
147 return yield* new ProviderTurnControlError({
148 threadId: input.threadId,
149 operation: input.operation,
150 providerTurnId: input.providerTurnId,
151 cause: "The recorded provider execution target is no longer valid.",
152 });
153 }
154 // A restart-session command commits the replacement binding before its
155 // process-bound effect runs. The old live runtime must still receive
156 // the interrupt, but only when the projection matches the exact
157 // replacement captured by that same durable effect.
158 const interruptProviderThread = targetsRecordedSession
159 ? providerThread
160 : { ...providerThread, providerSessionId: input.providerSessionId };
161 const continuingRun =
162 input.operation === "steer" &&
163 context.run?.status === "running" &&
164 context.run.activeAttemptId === providerTurn.runAttemptId;
165 if (providerTurn.status !== "running" && !continuingRun) {
166 if (input.operation === "steer") {
167 return yield* new ProviderTurnControlError({
168 threadId: input.threadId,
169 operation: "steer",
170 providerTurnId: input.providerTurnId,
171 turnCompleted: providerTurn.status === "completed",
172 cause: "The provider turn ended before the steering message was delivered.",
173 });
174 }
175 return {
176 context,
177 providerThread: interruptProviderThread,
178 providerTurn,
179 session: Option.none(),
180 };
181 }
182 const session = yield* sessions.get(input.providerSessionId);
183 if (Option.isNone(session)) {
184 // Interrupt/restart against a already-released session must not fail
185 // the durable effect (and retry 5x). The turn may still look running
186 // in projection until recovery/finalization; there is no live adapter
187 // to interrupt.
188 if (input.operation === "interrupt" || input.operation === "restart") {
189 yield* Effect.logWarning(
190 "Provider interrupt/restart found no live session; treating as already stopped",
191 {
192 threadId: input.threadId,
193 operation: input.operation,
194 providerSessionId: input.providerSessionId,
195 providerTurnId: input.providerTurnId,
196 providerTurnStatus: providerTurn.status,
197 },
198 );
199 return {
200 context,
201 providerThread: interruptProviderThread,
202 providerTurn,
203 session: Option.none(),
204 };
205 }
206 return yield* new ProviderTurnControlError({
207 threadId: input.threadId,
208 operation: input.operation,
209 providerTurnId: input.providerTurnId,
210 cause: `Provider session ${input.providerSessionId} is not active.`,
211 });
212 }
213 return { context, providerThread: interruptProviderThread, providerTurn, session };
214 });
215
216 const awaitSettled = Effect.fn("ProviderTurnControlService.awaitSettled")(function* (
217 threadId: ThreadId,
218 target: ProjectionStore.ProjectionProviderControlTarget,
219 ) {
220 const isSettled = projections
221 .getProviderControlContext(threadId, target)
222 .pipe(
223 Effect.map(
224 ({ providerTurn, attempt }) =>
225 providerTurn?.status !== "running" && attempt?.status !== "running",
226 ),
227 );
228 const afterSequence = yield* eventSink.latestSequence({ threadId });
229 if (yield* isSettled) return;
230 yield* eventSink.stream({ threadId, afterSequence }).pipe(
231 Stream.filter(
232 ({ event }) =>
233 event.type === "provider-turn.updated" || event.type === "run-attempt.updated",
234 ),
235 Stream.mapEffect(() => isSettled),
236 Stream.takeUntil((settled) => settled),
237 Stream.runDrain,
238 );
239 });
240
241 return ProviderTurnControlServiceV2.of({
242 applyModelSelection: Effect.fn("ProviderTurnControlService.applyModelSelection")(
243 function* (input) {
244 const { providerThread, providerTurn } = yield* projections.getRunningTurnContext(
245 input.threadId,
246 );
247 if (
248 providerThread?.id !== input.providerThreadId ||
249 providerThread.providerSessionId !== input.providerSessionId ||
250 providerTurn === undefined
251 ) {
252 return;
253 }
254 const session = yield* sessions.get(input.providerSessionId);
255 if (Option.isNone(session) || session.value.applyModelSelection === undefined) return;
256 yield* session.value.applyModelSelection({
257 providerThread,
258 modelSelection: input.modelSelection,
259 });
260 },
261 ),
262 applyThreadTitle: Effect.fn("ProviderTurnControlService.applyThreadTitle")(function* (input) {
263 const { thread, providerThreads } = yield* projections.getThreadRecords(input.threadId, [
264 "providerThreads",
265 ]);
266 const providerThread = providerThreads.find(
267 (candidate) => candidate.id === thread.activeProviderThreadId,
268 );
269 if (!providerThread?.providerSessionId) return;
270 const session = yield* sessions.get(providerThread.providerSessionId);
271 if (Option.isNone(session) || session.value.applyThreadTitle === undefined) return;
272 yield* session.value.applyThreadTitle({ providerThread, title: input.title });
273 }),
274 interrupt: Effect.fn("ProviderTurnControlService.interrupt")(
275 function* (input) {
276 const loaded = yield* load({ ...input, operation: "interrupt" });
277 const session = Option.isSome(loaded.session)
278 ? loaded.session
279 : yield* sessions.get(input.providerSessionId);
280 if (Option.isNone(session)) {
281 if (input.subagent !== undefined) {
282 return yield* new ProviderTurnControlError({
283 threadId: input.threadId,
284 operation: "interrupt",
285 providerTurnId: input.providerTurnId,
286 cause: "No live provider session can confirm this subagent's outcome.",
287 });
288 }
289 return;
290 }
291 if (input.subagent !== undefined) {
292 if (session.value.stopSubagent === undefined) {
293 return yield* new ProviderTurnControlError({
294 threadId: input.threadId,
295 operation: "interrupt",
296 providerTurnId: input.providerTurnId,
297 cause: "The provider does not support stopping a native subagent.",
298 });
299 }
300 return yield* session.value.stopSubagent({
301 providerThread: loaded.providerThread,
302 nativeTaskId: input.subagent.nativeTaskId,
303 ...(input.subagent.requestedAt === undefined
304 ? {}
305 : { requestedAt: input.subagent.requestedAt }),
306 });
307 }
308 // Settled turns still reach adapters, which alone know whether background work remains.
309 yield* session.value
310 .interruptTurn({
311 providerThread: loaded.providerThread,
312 providerTurnId: loaded.providerTurn.id,
313 requestRuntimeRestart: true,
314 })
315 .pipe(
316 Effect.catchTags({
317 ProviderAdapterInterruptTimeoutError: (cause) =>
318 Effect.fail(
319 new ProviderTurnControlError({
320 threadId: input.threadId,
321 operation: "interrupt",
322 providerTurnId: input.providerTurnId,
323 unresponsive: true,
324 cause,
325 }),
326 ),
327 }),
328 );
329 if (loaded.providerTurn.status === "running") {
330 // Let native terminal ingestion finalize the attempt before the Stop follow-up repairs it.
331 const { runAttemptId } = loaded.providerTurn;
332 yield* awaitSettled(input.threadId, {
333 providerThreadId: input.providerThreadId,
334 providerTurnId: input.providerTurnId,
335 ...(runAttemptId === null ? {} : { attemptId: runAttemptId }),
336 }).pipe(Effect.timeoutOption("2 seconds"));
337 }
338 },
339 (effect, input) =>
340 effect.pipe(
341 Effect.mapError((cause) =>
342 isProviderTurnControlError(cause)
343 ? cause
344 : new ProviderTurnControlError({
345 threadId: input.threadId,
346 operation: "interrupt",
347 providerTurnId: input.providerTurnId,
348 cause,
349 }),
350 ),
351 ),
352 ),
353 interruptAndAwaitTerminal: Effect.fn("ProviderTurnControlService.interruptAndAwaitTerminal")(
354 function* (input) {
355 const loaded = yield* load({ ...input, operation: "restart" });
356 if (Option.isNone(loaded.session)) {
357 // Without a live adapter, no terminal event can arrive; proceed to detach/start without polling.
358 if (loaded.providerTurn.status === "running") {
359 yield* Effect.logWarning(
360 "Provider restart interrupt skipped; no live session for a still-projected running turn",
361 {
362 threadId: input.threadId,
363 providerSessionId: input.providerSessionId,
364 providerTurnId: input.providerTurnId,
365 },
366 );
367 }
368 return;
369 }
370
371 yield* loaded.session.value.interruptTurn({
372 providerThread: loaded.providerThread,
373 providerTurnId: loaded.providerTurn.id,
374 });
375
376 for (let remaining = 1_000; remaining > 0; remaining -= 1) {
377 const { providerTurn, attempt } = yield* projections.getProviderControlContext(
378 input.threadId,
379 {
380 providerThreadId: input.providerThreadId,
381 providerTurnId: input.providerTurnId,
382 attemptId: input.interruptedAttemptId,
383 },
384 );
385 if (
386 providerTurn !== undefined &&
387 providerTurn.status !== "running" &&
388 attempt !== undefined &&
389 attempt.status !== "running"
390 ) {
391 return;
392 }
393 // Yield through Node's event loop; detached ingestion cannot advance a deterministic Effect clock.
394 yield* yieldToRuntime;
395 }
396 return yield* new ProviderTurnControlError({
397 threadId: input.threadId,
398 operation: "restart",
399 providerTurnId: input.providerTurnId,
400 cause: `Provider turn ${input.providerTurnId} did not terminalize before restart.`,
401 });
402 },
403 (effect, input) =>
404 effect.pipe(
405 Effect.mapError((cause) =>
406 isProviderTurnControlError(cause)
407 ? cause
408 : new ProviderTurnControlError({
409 threadId: input.threadId,
410 operation: "restart",
411 providerTurnId: input.providerTurnId,
412 cause,
413 }),
414 ),
415 ),
416 ),
417 steer: Effect.fn("ProviderTurnControlService.steer")(
418 function* (input) {
419 const context = yield* projections.getProviderControlContext(input.threadId, input);
420 const ownership = context.message?.delegatedCompletion;
421 if (ownership !== undefined) {
422 const projection = yield* projections.getThreadRecords(input.threadId, ["runs"], {
423 runIds: [ownership.parentRunId],
424 });
425 const cohort = projection.runs.find(
426 (run) => run.id === ownership.parentRunId,
427 )?.delegatedCompletion;
428 if (
429 cohort?.disposition !== "open" ||
430 cohort.delivery?.messageId !== input.messageId ||
431 cohort.delivery.generation !== ownership.generation ||
432 cohort.delivery.taskIds.length === 0
433 )
434 return;
435 }
436 const loaded = yield* load({ ...input, operation: "steer" });
437 if (Option.isNone(loaded.session)) return;
438 const { message, run } = loaded.context;
439 if (message === undefined || run === undefined) {
440 return yield* new ProviderTurnControlError({
441 threadId: input.threadId,
442 operation: "steer",
443 providerTurnId: input.providerTurnId,
444 cause: "The persisted steering message or target run is missing.",
445 });
446 }
447 yield* loaded.session.value
448 .steerTurn({
449 threadId: input.threadId,
450 runId: run.id,
451 providerThread: loaded.providerThread,
452 providerTurnId: loaded.providerTurn.id,
453 ...(input.modelSelection === undefined
454 ? {}
455 : { modelSelection: input.modelSelection }),
456 message: {
457 messageId: message.id,
458 text: projectComposerContextForProvider({
459 text: message.text,
460 records: message.context?.records ?? [],
461 }),
462 attachments: message.attachments,
463 createdBy: message.createdBy,
464 creationSource: message.creationSource,
465 ...(message.scheduledTaskId === undefined
466 ? {}
467 : { scheduledTaskId: message.scheduledTaskId }),
468 ...(message.senderThreadId === undefined
469 ? {}
470 : { senderThreadId: message.senderThreadId }),
471 },
472 })
473 .pipe(
474 Effect.catchTags({
475 ProviderAdapterSteerDeclinedError: (cause) =>
476 Effect.fail(
477 new ProviderTurnControlError({
478 threadId: input.threadId,
479 operation: "steer",
480 providerTurnId: input.providerTurnId,
481 steerDeclined: true,
482 cause,
483 }),
484 ),
485 }),
486 Effect.catch((cause) =>
487 Effect.gen(function* () {
488 if (isProviderTurnControlError(cause)) return yield* cause;
489 const current = yield* projections.getProviderControlContext(
490 input.threadId,
491 input,
492 );
493 const status = current.providerTurn?.status;
494 return yield* new ProviderTurnControlError({
495 threadId: input.threadId,
496 operation: "steer",
497 providerTurnId: input.providerTurnId,
498 turnCompleted: status === "completed",
499 cause,
500 });
501 }),
502 ),
503 );
504 },
505 (effect, input) =>
506 effect.pipe(
507 Effect.mapError((cause) =>
508 isProviderTurnControlError(cause)
509 ? cause
510 : new ProviderTurnControlError({
511 threadId: input.threadId,
512 operation: "steer",
513 providerTurnId: input.providerTurnId,
514 cause,
515 }),
516 ),
517 ),
518 ),
519 });
520 }),
521);