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

ProviderTurnControlService.ts

288 lines11.0 KB

1import {
2 MessageId,
3 ProviderSessionId,
4 ProviderThreadId,
5 ProviderTurnId,
6 RunAttemptId,
7 ThreadId,
8} from "@t3tools/contracts";
9import * as Context from "effect/Context";
10import * as Effect from "effect/Effect";
11import * as Layer from "effect/Layer";
12import * as Option from "effect/Option";
13import * as Schema from "effect/Schema";
14​
15import { ProjectionStoreV2 } from "./ProjectionStore.ts";
16import { ProviderSessionManagerV2 } from "./ProviderSessionManager.ts";
17​
18const yieldToRuntime = Effect.yieldNow.pipe(
19 Effect.andThen(
20 Effect.promise(
21 () =>
22 new Promise<void>((resolve) => {
23 setImmediate(resolve);
24 }),
25 ),
26 ),
27);
28​
29export class ProviderTurnControlError extends Schema.TaggedErrorClass<ProviderTurnControlError>()(
30 "ProviderTurnControlError",
31 {
32 threadId: ThreadId,
33 operation: Schema.Literals(["interrupt", "restart", "steer"]),
34 providerTurnId: ProviderTurnId,
35 cause: Schema.optional(Schema.Defect()),
36 },
37) {}
38​
39const isProviderTurnControlError = Schema.is(ProviderTurnControlError);
40​
41export interface ProviderTurnControlServiceV2Shape {
42 readonly interrupt: (input: {
43 readonly threadId: ThreadId;
44 readonly providerSessionId: ProviderSessionId;
45 readonly providerThreadId: ProviderThreadId;
46 readonly providerTurnId: ProviderTurnId;
47 }) => Effect.Effect<void, ProviderTurnControlError>;
48 readonly steer: (input: {
49 readonly threadId: ThreadId;
50 readonly providerSessionId: ProviderSessionId;
51 readonly providerThreadId: ProviderThreadId;
52 readonly providerTurnId: ProviderTurnId;
53 readonly messageId: MessageId;
54 }) => Effect.Effect<void, ProviderTurnControlError>;
55 readonly interruptAndAwaitTerminal: (input: {
56 readonly threadId: ThreadId;
57 readonly providerSessionId: ProviderSessionId;
58 readonly replacementProviderSessionId?: ProviderSessionId;
59 readonly providerThreadId: ProviderThreadId;
60 readonly providerTurnId: ProviderTurnId;
61 readonly interruptedAttemptId: RunAttemptId;
62 }) => Effect.Effect<void, ProviderTurnControlError>;
64​
65export class ProviderTurnControlServiceV2 extends Context.Service<
66 ProviderTurnControlServiceV2,
67 ProviderTurnControlServiceV2Shape
68>()("t3/orchestration-v2/ProviderTurnControlService/ProviderTurnControlServiceV2") {}
69​
70export const layer: Layer.Layer<
71 ProviderTurnControlServiceV2,
72 never,
73 ProjectionStoreV2 | ProviderSessionManagerV2
74> = Layer.effect(
75 ProviderTurnControlServiceV2,
76 Effect.gen(function* () {
77 const projections = yield* ProjectionStoreV2;
78 const sessions = yield* ProviderSessionManagerV2;
79​
80 const load = (input: {
81 readonly threadId: ThreadId;
82 readonly providerSessionId: ProviderSessionId;
83 readonly replacementProviderSessionId?: ProviderSessionId;
84 readonly providerThreadId: ProviderThreadId;
85 readonly providerTurnId: ProviderTurnId;
86 readonly operation: "interrupt" | "restart" | "steer";
87 readonly messageId?: MessageId;
88 }) =>
89 Effect.gen(function* () {
90 const context = yield* projections.getProviderControlContext(input.threadId, input);
91 const { providerThread, providerTurn } = context;
92 const targetsRecordedSession =
93 providerThread?.providerSessionId === input.providerSessionId;
94 const targetsCommittedReplacement =
95 input.operation === "restart" &&
96 input.replacementProviderSessionId !== undefined &&
97 providerThread?.providerSessionId === input.replacementProviderSessionId;
98 if (
99 providerThread === undefined ||
100 providerTurn === undefined ||
101 (!targetsRecordedSession && !targetsCommittedReplacement) ||
102 providerTurn.providerThreadId !== providerThread.id
103 ) {
104 return yield* new ProviderTurnControlError({
105 threadId: input.threadId,
106 operation: input.operation,
107 providerTurnId: input.providerTurnId,
108 cause: "The recorded provider execution target is no longer valid.",
109 });
110 }
111 // A restart-session command commits the replacement binding before its
112 // process-bound effect runs. The old live runtime must still receive
113 // the interrupt, but only when the projection matches the exact
114 // replacement captured by that same durable effect.
115 const interruptProviderThread = targetsRecordedSession
116 ? providerThread
117 : { ...providerThread, providerSessionId: input.providerSessionId };
118 if (providerTurn.status !== "running") {
119 return {
120 context,
121 providerThread: interruptProviderThread,
122 providerTurn,
123 session: Option.none(),
124 };
125 }
126 const session = yield* sessions.get(input.providerSessionId);
127 if (Option.isNone(session)) {
128 // Interrupt/restart against a already-released session must not fail
129 // the durable effect (and retry 5x). The turn may still look running
130 // in projection until recovery/finalization; there is no live adapter
131 // to interrupt.
132 if (input.operation === "interrupt" || input.operation === "restart") {
133 yield* Effect.logWarning(
134 "Provider interrupt/restart found no live session; treating as already stopped",
135 {
136 threadId: input.threadId,
137 operation: input.operation,
138 providerSessionId: input.providerSessionId,
139 providerTurnId: input.providerTurnId,
140 providerTurnStatus: providerTurn.status,
141 },
142 );
143 return {
144 context,
145 providerThread: interruptProviderThread,
146 providerTurn,
147 session: Option.none(),
148 };
149 }
150 return yield* new ProviderTurnControlError({
151 threadId: input.threadId,
152 operation: input.operation,
153 providerTurnId: input.providerTurnId,
154 cause: `Provider session ${input.providerSessionId} is not active.`,
155 });
156 }
157 return { context, providerThread: interruptProviderThread, providerTurn, session };
158 });
159​
160 return ProviderTurnControlServiceV2.of({
161 interrupt: (input) =>
162 Effect.gen(function* () {
163 const loaded = yield* load({ ...input, operation: "interrupt" });
164 if (Option.isNone(loaded.session)) return;
165 yield* loaded.session.value.interruptTurn({
166 providerThread: loaded.providerThread,
167 providerTurnId: loaded.providerTurn.id,
168 requestRuntimeRestart: true,
169 });
170 }).pipe(
171 Effect.mapError((cause) =>
172 isProviderTurnControlError(cause)
173 ? cause
174 : new ProviderTurnControlError({
175 threadId: input.threadId,
176 operation: "interrupt",
177 providerTurnId: input.providerTurnId,
178 cause,
179 }),
180 ),
181 ),
182 interruptAndAwaitTerminal: (input) =>
183 Effect.gen(function* () {
184 const loaded = yield* load({ ...input, operation: "restart" });
185 if (Option.isNone(loaded.session)) {
186 // No live adapter: nothing can emit a terminal provider-turn update
187 // from interrupt. Do not poll for projection terminalization or the
188 // restart effect stalls; let detach/start proceed.
189 if (loaded.providerTurn.status === "running") {
190 yield* Effect.logWarning(
191 "Provider restart interrupt skipped; no live session for a still-projected running turn",
192 {
193 threadId: input.threadId,
194 providerSessionId: input.providerSessionId,
195 providerTurnId: input.providerTurnId,
196 },
197 );
198 }
199 return;
200 }
201​
202 yield* loaded.session.value.interruptTurn({
203 providerThread: loaded.providerThread,
204 providerTurnId: loaded.providerTurn.id,
205 });
206​
207 for (let remaining = 1_000; remaining > 0; remaining -= 1) {
208 const { providerTurn, attempt } = yield* projections.getProviderControlContext(
209 input.threadId,
210 {
211 providerThreadId: input.providerThreadId,
212 providerTurnId: input.providerTurnId,
213 attemptId: input.interruptedAttemptId,
214 },
215 );
216 if (
217 providerTurn !== undefined &&
218 providerTurn.status !== "running" &&
219 attempt !== undefined &&
220 attempt.status !== "running"
221 ) {
222 return;
223 }
224 // Provider terminal events are projected on a detached ingestion
225 // fiber. Yield through the Node event loop instead of sleeping on
226 // Effect's clock so deterministic runtimes cannot deadlock a
227 // command that is waiting for that projection.
228 yield* yieldToRuntime;
229 }
230 return yield* new ProviderTurnControlError({
231 threadId: input.threadId,
232 operation: "restart",
233 providerTurnId: input.providerTurnId,
234 cause: `Provider turn ${input.providerTurnId} did not terminalize before restart.`,
235 });
236 }).pipe(
237 Effect.mapError((cause) =>
238 isProviderTurnControlError(cause)
239 ? cause
240 : new ProviderTurnControlError({
241 threadId: input.threadId,
242 operation: "restart",
243 providerTurnId: input.providerTurnId,
244 cause,
245 }),
246 ),
247 ),
248 steer: (input) =>
249 Effect.gen(function* () {
250 const loaded = yield* load({ ...input, operation: "steer" });
251 if (Option.isNone(loaded.session)) return;
252 const { message, run } = loaded.context;
253 if (message === undefined || run === undefined) {
254 return yield* new ProviderTurnControlError({
255 threadId: input.threadId,
256 operation: "steer",
257 providerTurnId: input.providerTurnId,
258 cause: "The persisted steering message or target run is missing.",
259 });
260 }
261 yield* loaded.session.value.steerTurn({
262 threadId: input.threadId,
263 runId: run.id,
264 providerThread: loaded.providerThread,
265 providerTurnId: loaded.providerTurn.id,
266 message: {
267 messageId: message.id,
268 text: message.text,
269 attachments: message.attachments,
270 createdBy: message.createdBy,
271 creationSource: message.creationSource,
272 },
273 });
274 }).pipe(
275 Effect.mapError((cause) =>
276 isProviderTurnControlError(cause)
277 ? cause
278 : new ProviderTurnControlError({
279 threadId: input.threadId,
280 operation: "steer",
281 providerTurnId: input.providerTurnId,
282 cause,
283 }),
284 ),
285 ),
286 });
287 }),
288);