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

ProviderTurnControlService.ts

258 lines9.7 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 }) =>
88 Effect.gen(function* () {
89 const projection = yield* projections.getThreadProjection(input.threadId);
90 const providerThread = projection.providerThreads.find(
91 (candidate) => candidate.id === input.providerThreadId,
92 );
93 const providerTurn = projection.providerTurns.find(
94 (candidate) => candidate.id === input.providerTurnId,
95 );
96 const targetsRecordedSession =
97 providerThread?.providerSessionId === input.providerSessionId;
98 const targetsCommittedReplacement =
99 input.operation === "restart" &&
100 input.replacementProviderSessionId !== undefined &&
101 providerThread?.providerSessionId === input.replacementProviderSessionId;
102 if (
103 providerThread === undefined ||
104 providerTurn === undefined ||
105 (!targetsRecordedSession && !targetsCommittedReplacement) ||
106 providerTurn.providerThreadId !== providerThread.id
107 ) {
108 return yield* new ProviderTurnControlError({
109 threadId: input.threadId,
110 operation: input.operation,
111 providerTurnId: input.providerTurnId,
112 cause: "The recorded provider execution target is no longer valid.",
113 });
114 }
115 // A restart-session command commits the replacement binding before its
116 // process-bound effect runs. The old live runtime must still receive
117 // the interrupt, but only when the projection matches the exact
118 // replacement captured by that same durable effect.
119 const interruptProviderThread = targetsRecordedSession
120 ? providerThread
121 : { ...providerThread, providerSessionId: input.providerSessionId };
122 if (providerTurn.status !== "running") {
123 return {
124 projection,
125 providerThread: interruptProviderThread,
126 providerTurn,
127 session: Option.none(),
128 };
129 }
130 const session = yield* sessions.get(input.providerSessionId);
131 if (Option.isNone(session)) {
132 return yield* new ProviderTurnControlError({
133 threadId: input.threadId,
134 operation: input.operation,
135 providerTurnId: input.providerTurnId,
136 cause: `Provider session ${input.providerSessionId} is not active.`,
137 });
138 }
139 return { projection, providerThread: interruptProviderThread, providerTurn, session };
140 });
141​
142 return ProviderTurnControlServiceV2.of({
143 interrupt: (input) =>
144 Effect.gen(function* () {
145 const loaded = yield* load({ ...input, operation: "interrupt" });
146 if (Option.isNone(loaded.session)) return;
147 yield* loaded.session.value.interruptTurn({
148 providerThread: loaded.providerThread,
149 providerTurnId: loaded.providerTurn.id,
150 });
151 }).pipe(
152 Effect.mapError((cause) =>
153 isProviderTurnControlError(cause)
154 ? cause
155 : new ProviderTurnControlError({
156 threadId: input.threadId,
157 operation: "interrupt",
158 providerTurnId: input.providerTurnId,
159 cause,
160 }),
161 ),
162 ),
163 interruptAndAwaitTerminal: (input) =>
164 Effect.gen(function* () {
165 const loaded = yield* load({ ...input, operation: "restart" });
166 if (Option.isSome(loaded.session)) {
167 yield* loaded.session.value.interruptTurn({
168 providerThread: loaded.providerThread,
169 providerTurnId: loaded.providerTurn.id,
170 });
171 }
172​
173 for (let remaining = 1_000; remaining > 0; remaining -= 1) {
174 const projection = yield* projections.getThreadProjection(input.threadId);
175 const providerTurn = projection.providerTurns.find(
176 (candidate) => candidate.id === input.providerTurnId,
177 );
178 const attempt = projection.attempts.find(
179 (candidate) => candidate.id === input.interruptedAttemptId,
180 );
181 if (
182 providerTurn !== undefined &&
183 providerTurn.status !== "running" &&
184 attempt !== undefined &&
185 attempt.status !== "running"
186 ) {
187 return;
188 }
189 // Provider terminal events are projected on a detached ingestion
190 // fiber. Yield through the Node event loop instead of sleeping on
191 // Effect's clock so deterministic runtimes cannot deadlock a
192 // command that is waiting for that projection.
193 yield* yieldToRuntime;
194 }
195 return yield* new ProviderTurnControlError({
196 threadId: input.threadId,
197 operation: "restart",
198 providerTurnId: input.providerTurnId,
199 cause: `Provider turn ${input.providerTurnId} did not terminalize before restart.`,
200 });
201 }).pipe(
202 Effect.mapError((cause) =>
203 isProviderTurnControlError(cause)
204 ? cause
205 : new ProviderTurnControlError({
206 threadId: input.threadId,
207 operation: "restart",
208 providerTurnId: input.providerTurnId,
209 cause,
210 }),
211 ),
212 ),
213 steer: (input) =>
214 Effect.gen(function* () {
215 const loaded = yield* load({ ...input, operation: "steer" });
216 if (Option.isNone(loaded.session)) return;
217 const message = loaded.projection.messages.find(
218 (candidate) => candidate.id === input.messageId,
219 );
220 const run = loaded.projection.runs.find(
221 (candidate) => candidate.activeAttemptId === loaded.providerTurn.runAttemptId,
222 );
223 if (message === undefined || run === undefined) {
224 return yield* new ProviderTurnControlError({
225 threadId: input.threadId,
226 operation: "steer",
227 providerTurnId: input.providerTurnId,
228 cause: "The persisted steering message or target run is missing.",
229 });
230 }
231 yield* loaded.session.value.steerTurn({
232 threadId: input.threadId,
233 runId: run.id,
234 providerThread: loaded.providerThread,
235 providerTurnId: loaded.providerTurn.id,
236 message: {
237 messageId: message.id,
238 text: message.text,
239 attachments: message.attachments,
240 createdBy: message.createdBy,
241 creationSource: message.creationSource,
242 },
243 });
244 }).pipe(
245 Effect.mapError((cause) =>
246 isProviderTurnControlError(cause)
247 ? cause
248 : new ProviderTurnControlError({
249 threadId: input.threadId,
250 operation: "steer",
251 providerTurnId: input.providerTurnId,
252 cause,
253 }),
254 ),
255 ),
256 });
257 }),
258);