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