Open History to see the last commit
1import {
2 CommandId,
3 type OrchestrationV2DomainEvent,
4 type OrchestrationV2ExecutionNode,
5 type OrchestrationV2ProviderThread,
6 type OrchestrationV2Run,
7 type OrchestrationV2RunAttempt,
8 RunId,
9 ThreadId,
10} from "@t3tools/contracts";
11import * as Context from "effect/Context";
12import * as DateTime from "effect/DateTime";
13import * as Effect from "effect/Effect";
14import * as Layer from "effect/Layer";
15import * as Schema from "effect/Schema";
16
17import { EventSinkV2 } from "./EventSink.ts";
18import {
19 ContextHandoffServiceV2,
20 providerMessageWithContextHandoffs,
21} from "./ContextHandoffService.ts";
22import { IdAllocatorV2 } from "./IdAllocator.ts";
23import { ProjectionStoreV2 } from "./ProjectionStore.ts";
24import { ProviderSessionManagerV2 } from "./ProviderSessionManager.ts";
25import { RunExecutionServiceV2 } from "./RunExecutionService.ts";
26import { RuntimePolicyV2 } from "./RuntimePolicy.ts";
27
28export class ProviderTurnStartError extends Schema.TaggedErrorClass<ProviderTurnStartError>()(
29 "ProviderTurnStartError",
30 {
31 runId: RunId,
32 cause: Schema.optional(Schema.Defect()),
33 },
34) {}
35
36const isProviderTurnStartError = Schema.is(ProviderTurnStartError);
37
38export interface ProviderTurnStartServiceV2Shape {
39 readonly start: (input: {
40 readonly threadId: ThreadId;
41 readonly runId: RunId;
42 }) => Effect.Effect<void, ProviderTurnStartError>;
43}
44
45export class ProviderTurnStartServiceV2 extends Context.Service<
46 ProviderTurnStartServiceV2,
47 ProviderTurnStartServiceV2Shape
48>()("t3/orchestration-v2/ProviderTurnStartService/ProviderTurnStartServiceV2") {}
49
50export const layer: Layer.Layer<
51 ProviderTurnStartServiceV2,
52 never,
53 | EventSinkV2
54 | ContextHandoffServiceV2
55 | IdAllocatorV2
56 | ProjectionStoreV2
57 | ProviderSessionManagerV2
58 | RunExecutionServiceV2
59 | RuntimePolicyV2
60> = Layer.effect(
61 ProviderTurnStartServiceV2,
62 Effect.gen(function* () {
63 const eventSink = yield* EventSinkV2;
64 const contextHandoffService = yield* ContextHandoffServiceV2;
65 const idAllocator = yield* IdAllocatorV2;
66 const projectionStore = yield* ProjectionStoreV2;
67 const providerSessions = yield* ProviderSessionManagerV2;
68 const runExecution = yield* RunExecutionServiceV2;
69 const runtimePolicy = yield* RuntimePolicyV2;
70
71 const start = Effect.fn("orchestrationV2.providerTurnStart.start")(function* (input: {
72 readonly threadId: ThreadId;
73 readonly runId: RunId;
74 }) {
75 const { runId } = input;
76 const projection = yield* projectionStore.getThreadProjection(input.threadId);
77 const run = projection.runs.find((candidate) => candidate.id === runId);
78 if (run === undefined) {
79 return yield* new ProviderTurnStartError({ runId, cause: `Run ${runId} was not found.` });
80 }
81 if (run.status !== "starting") {
82 // The effect is idempotent once the run has advanced or terminalized.
83 return;
84 }
85 const rootNode = projection.nodes.find((candidate) => candidate.id === run.rootNodeId);
86 const attempt = projection.attempts.find((candidate) => candidate.id === run.activeAttemptId);
87 const providerThread = projection.providerThreads.find(
88 (candidate) => candidate.id === run.providerThreadId,
89 );
90 const message = projection.messages.find((candidate) => candidate.id === run.userMessageId);
91 const checkpointScope = projection.checkpointScopes.find(
92 (candidate) => candidate.id === rootNode?.checkpointScopeId,
93 );
94 const handoffs = projection.contextHandoffs.filter(
95 (handoff) => handoff.targetRunId === run.id && handoff.status === "ready",
96 );
97 const nativeForkTransfer = projection.contextTransfers.find(
98 (transfer) =>
99 transfer.type === "fork" &&
100 transfer.targetThreadId === input.threadId &&
101 transfer.targetRunId === run.id &&
102 transfer.status === "pending" &&
103 transfer.resolution === null,
104 );
105 const existingResumeFallback = projection.contextTransfers.find(
106 (transfer) =>
107 transfer.type === "provider_handoff" &&
108 transfer.sourceThreadId === projection.thread.id &&
109 transfer.targetThreadId === projection.thread.id &&
110 transfer.targetRunId === run.id &&
111 transfer.status === "resolved_portable" &&
112 transfer.resolution?.strategy === "portable_context",
113 );
114 if (
115 rootNode === undefined ||
116 attempt === undefined ||
117 providerThread === undefined ||
118 providerThread.providerSessionId === null ||
119 message === undefined ||
120 checkpointScope === undefined
121 ) {
122 return yield* new ProviderTurnStartError({
123 runId,
124 cause: `Run ${runId} is missing its execution projection state.`,
125 });
126 }
127 const providerSessionId = providerThread.providerSessionId;
128 const isCurrentAttemptInStatus = (
129 expectedStatus: OrchestrationV2Run["status"],
130 ): Effect.Effect<boolean, never> =>
131 projectionStore.getThreadProjection(projection.thread.id).pipe(
132 Effect.map((current) => {
133 const currentRun = current.runs.find((candidate) => candidate.id === run.id);
134 return (
135 currentRun?.activeAttemptId === attempt.id && currentRun.status === expectedStatus
136 );
137 }),
138 Effect.catchCause(() => Effect.succeed(false)),
139 );
140
141 const resolvedRuntimePolicy = yield* runtimePolicy.resolve({
142 thread: projection.thread,
143 modelSelection: run.modelSelection,
144 });
145 const existingSessionProjection = projection.providerSessions.find(
146 (candidate) => candidate.id === providerSessionId,
147 );
148 const session = yield* providerSessions.open({
149 threadId: projection.thread.id,
150 providerSessionId,
151 modelSelection: run.modelSelection,
152 runtimePolicy: resolvedRuntimePolicy,
153 ...(existingSessionProjection === undefined
154 ? {}
155 : { resumeFromSession: existingSessionProjection }),
156 });
157 let effectiveHandoffs = handoffs;
158 const loadedProviderThread = yield* Effect.gen(function* () {
159 if (nativeForkTransfer !== undefined) {
160 const sourceProjection = yield* projectionStore.getThreadProjection(
161 nativeForkTransfer.sourceThreadId,
162 );
163 const sourceRun = sourceProjection.runs.find(
164 (candidate) => candidate.id === nativeForkTransfer.sourcePoint.runId,
165 );
166 const sourceProviderThread = sourceProjection.providerThreads.find(
167 (candidate) => candidate.id === sourceRun?.providerThreadId,
168 );
169 const sourceAttempt = sourceProjection.attempts.find(
170 (candidate) => candidate.id === sourceRun?.activeAttemptId,
171 );
172 const sourceProviderTurn = sourceProjection.providerTurns.find(
173 (candidate) =>
174 candidate.id === sourceAttempt?.providerTurnId ||
175 candidate.runAttemptId === sourceAttempt?.id,
176 );
177 if (sourceRun === undefined || sourceProviderThread === undefined) {
178 return yield* new ProviderTurnStartError({
179 runId,
180 cause: `Native fork transfer ${nativeForkTransfer.id} has no source provider execution.`,
181 });
182 }
183 return yield* session.forkThread({
184 sourceProviderThread,
185 sourceProviderTurns: sourceProjection.providerTurns,
186 targetThreadId: projection.thread.id,
187 modelSelection: run.modelSelection,
188 runtimePolicy: resolvedRuntimePolicy,
189 ...(sourceProviderTurn === undefined ? {} : { providerTurnId: sourceProviderTurn.id }),
190 });
191 }
192 if (providerThread.nativeThreadRef === null) {
193 return yield* session.ensureThread({
194 threadId: projection.thread.id,
195 modelSelection: run.modelSelection,
196 runtimePolicy: resolvedRuntimePolicy,
197 providerSessionId,
198 });
199 }
200 const resumed = yield* Effect.result(
201 session.resumeThread({
202 providerThread,
203 threadId: projection.thread.id,
204 modelSelection: run.modelSelection,
205 runtimePolicy: resolvedRuntimePolicy,
206 }),
207 );
208 if (resumed._tag === "Success") {
209 return resumed.success;
210 }
211
212 const replacement = yield* session.ensureThread({
213 threadId: projection.thread.id,
214 modelSelection: run.modelSelection,
215 runtimePolicy: resolvedRuntimePolicy,
216 providerSessionId,
217 });
218 if (existingResumeFallback !== undefined) {
219 return replacement;
220 }
221 const transferId = yield* idAllocator.allocate.contextTransfer({
222 sourceThreadId: projection.thread.id,
223 targetThreadId: projection.thread.id,
224 type: "provider_resume_fallback",
225 });
226 const createdAt = yield* DateTime.now;
227 const handoff = yield* contextHandoffService.prepareProviderHandoff({
228 threadId: projection.thread.id,
229 targetRunId: run.id,
230 transferId,
231 fromProviderThreadIds: [providerThread.id],
232 toProviderThreadId: providerThread.id,
233 fromProviderInstanceId: providerThread.providerInstanceId,
234 toProviderInstanceId: run.providerInstanceId,
235 coveredRunOrdinals: { from: 1, to: Math.max(1, run.ordinal - 1) },
236 strategy: "full_thread_summary",
237 items: projection.turnItems,
238 createdAt,
239 });
240 effectiveHandoffs = [...handoffs, handoff];
241 yield* eventSink.write({
242 events: [
243 {
244 id: yield* idAllocator.allocate.event({ threadId: projection.thread.id }),
245 type: "context-handoff.updated",
246 threadId: projection.thread.id,
247 runId: run.id,
248 providerInstanceId: run.providerInstanceId,
249 occurredAt: createdAt,
250 payload: handoff,
251 },
252 {
253 id: yield* idAllocator.allocate.event({ threadId: projection.thread.id }),
254 type: "context-transfer.updated",
255 threadId: projection.thread.id,
256 runId: run.id,
257 providerInstanceId: run.providerInstanceId,
258 occurredAt: createdAt,
259 payload: {
260 id: transferId,
261 type: "provider_handoff",
262 sourceThreadId: projection.thread.id,
263 targetThreadId: projection.thread.id,
264 sourcePoint: { threadId: projection.thread.id },
265 basePoint: null,
266 sourceProviderInstanceId: providerThread.providerInstanceId,
267 targetProviderInstanceId: run.providerInstanceId,
268 targetRunId: run.id,
269 status: "resolved_portable",
270 resolution: { strategy: "portable_context", contextHandoffId: handoff.id },
271 createdBy: "system",
272 error: null,
273 createdAt,
274 updatedAt: createdAt,
275 consumedAt: null,
276 },
277 },
278 ],
279 });
280 return replacement;
281 });
282 if (!(yield* isCurrentAttemptInStatus("starting"))) {
283 return;
284 }
285 const now = yield* DateTime.now;
286 const runningProviderThread: OrchestrationV2ProviderThread = {
287 ...loadedProviderThread,
288 id: providerThread.id,
289 driver: session.driver,
290 providerInstanceId: run.providerInstanceId,
291 providerSessionId,
292 appThreadId: projection.thread.id,
293 ownerNodeId: providerThread.ownerNodeId,
294 firstRunOrdinal: providerThread.firstRunOrdinal ?? run.ordinal,
295 lastRunOrdinal: run.ordinal,
296 handoffIds: providerThread.handoffIds,
297 forkedFrom: providerThread.forkedFrom,
298 status: "active",
299 createdAt: providerThread.createdAt,
300 updatedAt: now,
301 };
302 const runningRun: OrchestrationV2Run = {
303 ...run,
304 status: "running",
305 startedAt: now,
306 };
307 const runningAttempt: OrchestrationV2RunAttempt = {
308 ...attempt,
309 status: "running",
310 startedAt: now,
311 };
312 const runningRootNode: OrchestrationV2ExecutionNode = {
313 ...rootNode,
314 status: "running",
315 startedAt: now,
316 };
317 const events: Array<OrchestrationV2DomainEvent> = [
318 {
319 id: yield* idAllocator.allocate.event({
320 threadId: projection.thread.id,
321 providerSessionId,
322 }),
323 type: "provider-session.updated",
324 threadId: projection.thread.id,
325 driver: session.driver,
326 providerInstanceId: run.providerInstanceId,
327 occurredAt: now,
328 payload: session.providerSession,
329 },
330 {
331 id: yield* idAllocator.allocate.event({ threadId: projection.thread.id }),
332 type: "provider-thread.updated",
333 threadId: projection.thread.id,
334 driver: session.driver,
335 providerInstanceId: run.providerInstanceId,
336 occurredAt: now,
337 payload: runningProviderThread,
338 },
339 ...(nativeForkTransfer === undefined || runningProviderThread.nativeThreadRef === null
340 ? []
341 : [
342 {
343 id: yield* idAllocator.allocate.event({ threadId: projection.thread.id }),
344 type: "context-transfer.updated" as const,
345 threadId: projection.thread.id,
346 runId: run.id,
347 driver: session.driver,
348 providerInstanceId: run.providerInstanceId,
349 occurredAt: now,
350 payload: {
351 ...nativeForkTransfer,
352 targetProviderInstanceId: run.providerInstanceId,
353 targetRunId: run.id,
354 status: "consumed" as const,
355 resolution: {
356 strategy: "native_fork" as const,
357 providerThreadRef: runningProviderThread.nativeThreadRef,
358 },
359 error: null,
360 updatedAt: now,
361 consumedAt: now,
362 },
363 },
364 ]),
365 {
366 id: yield* idAllocator.allocate.event({ threadId: projection.thread.id }),
367 type: "run.updated",
368 threadId: projection.thread.id,
369 runId: run.id,
370 nodeId: rootNode.id,
371 providerInstanceId: run.providerInstanceId,
372 occurredAt: now,
373 payload: runningRun,
374 },
375 {
376 id: yield* idAllocator.allocate.event({ threadId: projection.thread.id }),
377 type: "run-attempt.updated",
378 threadId: projection.thread.id,
379 runId: run.id,
380 nodeId: rootNode.id,
381 providerInstanceId: run.providerInstanceId,
382 occurredAt: now,
383 payload: runningAttempt,
384 },
385 {
386 id: yield* idAllocator.allocate.event({ threadId: projection.thread.id }),
387 type: "node.updated",
388 threadId: projection.thread.id,
389 runId: run.id,
390 nodeId: rootNode.id,
391 providerInstanceId: run.providerInstanceId,
392 occurredAt: now,
393 payload: runningRootNode,
394 },
395 ];
396 const runningWrite = yield* eventSink.writeIfRunCurrent({
397 threadId: projection.thread.id,
398 runId: run.id,
399 activeAttemptId: attempt.id,
400 expectedStatus: "starting",
401 events,
402 });
403 if (!runningWrite.committed) {
404 return;
405 }
406 yield* runExecution.startRootRun({
407 commandId: CommandId.make(`command:effect:provider-turn.start:${run.id}`),
408 appThread: projection.thread,
409 providerSessionId,
410 session,
411 run: runningRun,
412 rootNode: runningRootNode,
413 checkpointScope,
414 providerThread: runningProviderThread,
415 attempt: runningAttempt,
416 attemptId: attempt.id,
417 relatedThreadIds: projection.subagents.flatMap((subagent) =>
418 subagent.childThreadId === null ? [] : [subagent.childThreadId],
419 ),
420 relatedProviderThreadIds: projection.subagents.flatMap((subagent) =>
421 subagent.providerThreadId === null ? [] : [subagent.providerThreadId],
422 ),
423 providerTurnOrdinal:
424 Math.max(
425 0,
426 ...projection.providerTurns
427 .filter((turn) => turn.providerThreadId === providerThread.id)
428 .map((turn) => turn.ordinal),
429 ) + 1,
430 shouldStartProviderTurn: () => isCurrentAttemptInStatus("running"),
431 shouldFinalizeRun: () =>
432 projectionStore.getThreadProjection(projection.thread.id).pipe(
433 Effect.map((current) => {
434 const currentRun = current.runs.find((candidate) => candidate.id === run.id);
435 return (
436 currentRun?.activeAttemptId === attempt.id &&
437 (currentRun.status === "starting" || currentRun.status === "running")
438 );
439 }),
440 Effect.catchCause(() => Effect.succeed(false)),
441 ),
442 message: {
443 messageId: message.id,
444 text:
445 effectiveHandoffs.length === 0
446 ? message.text
447 : providerMessageWithContextHandoffs({
448 handoffs: effectiveHandoffs,
449 userText: message.text,
450 }),
451 attachments: message.attachments,
452 createdBy: message.createdBy,
453 creationSource: message.creationSource,
454 },
455 modelSelection: run.modelSelection,
456 runtimePolicy: resolvedRuntimePolicy,
457 });
458 });
459
460 return ProviderTurnStartServiceV2.of({
461 start: (input) =>
462 start(input).pipe(
463 Effect.mapError((cause) =>
464 isProviderTurnStartError(cause)
465 ? cause
466 : new ProviderTurnStartError({ runId: input.runId, cause }),
467 ),
468 ),
469 });
470 }),
471);