Open History to see the last commit
1import { projectComposerContextForProvider } from "@t3tools/shared/composerContextReferences";
2import {
3 CommandId,
4 type OrchestrationV2DomainEvent,
5 type OrchestrationV2ExecutionNode,
6 type OrchestrationV2ProviderThread,
7 type OrchestrationV2Run,
8 type OrchestrationV2RunAttempt,
9 type OrchestrationV2TurnItem,
10 RunId,
11 ThreadId,
12} from "@t3tools/contracts";
13import * as Context from "effect/Context";
14import * as Cause from "effect/Cause";
15import * as DateTime from "effect/DateTime";
16import * as Effect from "effect/Effect";
17import * as FileSystem from "effect/FileSystem";
18import * as Layer from "effect/Layer";
19import * as Option from "effect/Option";
20import * as Schema from "effect/Schema";
21
22import { GitWorkflowService } from "../git/GitWorkflowService.ts";
23import { ProjectService } from "../project/ProjectService.ts";
24import { ProviderAuthService } from "../provider/Services/ProviderAuthService.ts";
25import { EventSinkV2 } from "./EventSink.ts";
26import {
27 ContextHandoffServiceV2,
28 providerMessageWithContextHandoffs,
29} from "./ContextHandoffService.ts";
30import { IdAllocatorV2 } from "./IdAllocator.ts";
31import { ProjectionStoreV2 } from "./ProjectionStore.ts";
32import { ProviderSessionManagerV2 } from "./ProviderSessionManager.ts";
33import { makeProviderFailure } from "./ProviderFailure.ts";
34import {
35 canRouteRelatedSubagent,
36 RunExecutionServiceV2,
37 selectInheritedBackgroundTurnItems,
38} from "./RunExecutionService.ts";
39import { RuntimePolicyV2 } from "./RuntimePolicy.ts";
40
41export class ProviderTurnStartError extends Schema.TaggedError<ProviderTurnStartError>()(
42 "ProviderTurnStartError",
43 {
44 runId: RunId,
45 cause: Schema.optional(Schema.Defect()),
46 },
47) {}
48
49const isProviderTurnStartError = Schema.is(ProviderTurnStartError);
50
51export interface ProviderTurnStartServiceV2Shape {
52 readonly start: (input: {
53 readonly threadId: ThreadId;
54 readonly runId: RunId;
55 }) => Effect.Effect<void, ProviderTurnStartError>;
56}
57
58export class ProviderTurnStartServiceV2 extends Context.Service<
59 ProviderTurnStartServiceV2,
60 ProviderTurnStartServiceV2Shape
61>()("t3/orchestration-v2/ProviderTurnStartService/ProviderTurnStartServiceV2") {}
62
63export const layer: Layer.Layer<
64 ProviderTurnStartServiceV2,
65 never,
66 | EventSinkV2
67 | ContextHandoffServiceV2
68 | IdAllocatorV2
69 | FileSystem.FileSystem
70 | GitWorkflowService
71 | ProjectService
72 | ProviderAuthService
73 | ProjectionStoreV2
74 | ProviderSessionManagerV2
75 | RunExecutionServiceV2
76 | RuntimePolicyV2
77> = Layer.effect(
78 ProviderTurnStartServiceV2,
79 Effect.gen(function* () {
80 const eventSink = yield* EventSinkV2;
81 const contextHandoffService = yield* ContextHandoffServiceV2;
82 const idAllocator = yield* IdAllocatorV2;
83 const fileSystem = yield* FileSystem.FileSystem;
84 const gitWorkflow = yield* GitWorkflowService;
85 const projects = yield* ProjectService;
86 const providerAuth = yield* ProviderAuthService;
87 const projectionStore = yield* ProjectionStoreV2;
88 const providerSessions = yield* ProviderSessionManagerV2;
89 const runExecution = yield* RunExecutionServiceV2;
90 const runtimePolicy = yield* RuntimePolicyV2;
91
92 const start = Effect.fn("orchestrationV2.providerTurnStart.start")(function* (input: {
93 readonly threadId: ThreadId;
94 readonly runId: RunId;
95 }) {
96 const { runId } = input;
97 const projection = yield* projectionStore.getThreadProjection(input.threadId);
98 const run = projection.runs.find((candidate) => candidate.id === runId);
99 if (run === undefined) {
100 return yield* new ProviderTurnStartError({ runId, cause: `Run ${runId} was not found.` });
101 }
102 if (run.status !== "starting") {
103 // The effect is idempotent once the run has advanced or terminalized.
104 return;
105 }
106 const rootNode = projection.nodes.find((candidate) => candidate.id === run.rootNodeId);
107 const attempt = projection.attempts.find((candidate) => candidate.id === run.activeAttemptId);
108 const providerThread = projection.providerThreads.find(
109 (candidate) => candidate.id === run.providerThreadId,
110 );
111 const message = projection.messages.find((candidate) => candidate.id === run.userMessageId);
112 const checkpointScope = projection.checkpointScopes.find(
113 (candidate) => candidate.id === rootNode?.checkpointScopeId,
114 );
115 const handoffs = projection.contextHandoffs.filter(
116 (handoff) => handoff.targetRunId === run.id && handoff.status === "ready",
117 );
118 const nativeForkTransfer = projection.contextTransfers.find(
119 (transfer) =>
120 transfer.type === "fork" &&
121 transfer.targetThreadId === input.threadId &&
122 transfer.targetRunId === run.id &&
123 transfer.status === "pending" &&
124 transfer.resolution === null,
125 );
126 const existingResumeFallback = projection.contextTransfers.find(
127 (transfer) =>
128 transfer.type === "provider_handoff" &&
129 transfer.sourceThreadId === projection.thread.id &&
130 transfer.targetThreadId === projection.thread.id &&
131 transfer.targetRunId === run.id &&
132 transfer.status === "resolved_portable" &&
133 transfer.resolution?.strategy === "portable_context",
134 );
135 if (
136 rootNode === undefined ||
137 attempt === undefined ||
138 providerThread === undefined ||
139 providerThread.providerSessionId === null ||
140 message === undefined ||
141 checkpointScope === undefined
142 ) {
143 return yield* new ProviderTurnStartError({
144 runId,
145 cause: `Run ${runId} is missing its execution projection state.`,
146 });
147 }
148 if (message.attachments.length === 0 && message.text.trimStart().startsWith("/")) {
149 const isEmptyCompaction =
150 message.text.trim().toLowerCase() === "/compact" &&
151 !projection.messages.some(
152 (candidate) =>
153 candidate.role === "user" &&
154 (candidate.text.trim().toLowerCase() !== "/compact" ||
155 candidate.attachments.length > 0),
156 );
157 // Preparing a run may already point the thread at a newly selected
158 // provider. Account commands still belong to its last native session.
159 const nativeThreads = new Map(
160 projection.providerThreads
161 .filter(
162 (candidate) => candidate.ownerNodeId === null && candidate.nativeThreadRef !== null,
163 )
164 .map((candidate) => [candidate.id, candidate]),
165 );
166 const previousNativeRun = projection.runs.reduce<OrchestrationV2Run | undefined>(
167 (previous, candidate) =>
168 candidate.ordinal < run.ordinal &&
169 candidate.providerThreadId !== null &&
170 nativeThreads.has(candidate.providerThreadId) &&
171 (previous === undefined || candidate.ordinal > previous.ordinal)
172 ? candidate
173 : previous,
174 undefined,
175 );
176 const nativeThread = nativeThreads.get(
177 previousNativeRun?.providerThreadId ??
178 projection.thread.activeProviderThreadId ??
179 providerThread.id,
180 );
181 const authInstanceId = nativeThread?.providerInstanceId ?? run.providerInstanceId;
182 const authResult = isEmptyCompaction
183 ? null
184 : yield* Effect.result(
185 providerAuth.tryHandlePromptCommand({
186 instanceId: authInstanceId,
187 text: projectComposerContextForProvider({
188 text: message.text,
189 records: message.context?.records ?? [],
190 }),
191 hasAttachments: false,
192 }),
193 );
194 if (isEmptyCompaction || authResult?._tag === "Failure" || authResult?.success) {
195 const now = yield* DateTime.now;
196 const failure = isEmptyCompaction
197 ? makeProviderFailure({
198 class: "validation_error",
199 message: "Start a conversation before compacting this thread.",
200 })
201 : authResult?._tag === "Failure"
202 ? makeProviderFailure({
203 class: "permission_error",
204 message: authResult.failure.detail,
205 })
206 : undefined;
207 const status = failure === undefined ? "completed" : "failed";
208 const itemBase = {
209 id: idAllocator.derive.runSignalTurnItem({
210 runId,
211 signal: isEmptyCompaction ? "empty-compaction" : "provider-sign-out",
212 }),
213 threadId: projection.thread.id,
214 runId,
215 nodeId: rootNode.id,
216 providerThreadId: nativeThread?.id ?? providerThread.id,
217 providerTurnId: null,
218 nativeItemRef: null,
219 parentItemId: null,
220 ordinal:
221 Math.max(
222 0,
223 ...projection.turnItems
224 .filter((item) => item.runId === runId)
225 .map((item) => item.ordinal),
226 ) + 1,
227 status,
228 startedAt: now,
229 completedAt: now,
230 updatedAt: now,
231 } as const;
232 const item: OrchestrationV2TurnItem =
233 failure !== undefined
234 ? {
235 ...itemBase,
236 type: "error",
237 title: isEmptyCompaction
238 ? "Cannot compact an empty thread"
239 : "Provider sign-out failed",
240 failure,
241 }
242 : {
243 ...itemBase,
244 type: "command_execution",
245 title: "Provider signed out",
246 input: message.text.trim(),
247 output: "Provider signed out",
248 exitCode: 0,
249 };
250 const eventPayloads = [
251 { type: "turn-item.updated", payload: item },
252 { type: "run.updated", payload: { ...run, status, startedAt: now, completedAt: now } },
253 {
254 type: "run-attempt.updated",
255 payload: { ...attempt, status, startedAt: now, completedAt: now },
256 },
257 {
258 type: "node.updated",
259 payload: { ...rootNode, status, startedAt: now, completedAt: now },
260 },
261 {
262 type: "provider-thread.updated",
263 payload: {
264 ...providerThread,
265 status: providerThread.nativeThreadRef === null ? "not_loaded" : "idle",
266 updatedAt: now,
267 },
268 },
269 ] as const;
270 const events = yield* Effect.forEach(eventPayloads, (event) =>
271 Effect.gen(function* () {
272 return {
273 ...event,
274 id: yield* idAllocator.allocate.event({ threadId: projection.thread.id }),
275 threadId: projection.thread.id,
276 runId,
277 nodeId: rootNode.id,
278 providerInstanceId: authInstanceId,
279 occurredAt: now,
280 } satisfies OrchestrationV2DomainEvent;
281 }),
282 );
283 yield* eventSink.writeIfRunCurrent({
284 threadId: projection.thread.id,
285 runId,
286 activeAttemptId: attempt.id,
287 expectedStatus: "starting",
288 events,
289 });
290 return;
291 }
292 }
293 const { worktreePath, branch } = projection.thread;
294 if (worktreePath !== null && branch !== null) {
295 const exists = yield* fileSystem
296 .exists(worktreePath)
297 .pipe(Effect.orElseSucceed(() => true));
298 if (!exists) {
299 const project = yield* projects.getById(projection.thread.projectId).pipe(
300 Effect.map(Option.getOrUndefined),
301 Effect.orElseSucceed(() => undefined),
302 );
303 if (project !== undefined) {
304 yield* Effect.logWarning("provider turn start recreating missing worktree", {
305 threadId: projection.thread.id,
306 worktreePath,
307 branch,
308 });
309 yield* gitWorkflow.pruneWorktrees({ cwd: project.workspaceRoot }).pipe(
310 Effect.andThen(
311 gitWorkflow.createWorktree({
312 cwd: project.workspaceRoot,
313 refName: branch,
314 path: worktreePath,
315 }),
316 ),
317 Effect.catchCause((cause) =>
318 Cause.hasInterruptsOnly(cause)
319 ? Effect.failCause(cause)
320 : Effect.logWarning("provider turn start failed to recreate worktree", {
321 threadId: projection.thread.id,
322 worktreePath,
323 cause: Cause.pretty(cause),
324 }),
325 ),
326 );
327 }
328 }
329 }
330 const selectInheritedBackgroundItems = (
331 current: typeof projection,
332 ): ReturnType<typeof selectInheritedBackgroundTurnItems> =>
333 selectInheritedBackgroundTurnItems({
334 threadId: current.thread.id,
335 currentProviderThreadId: providerThread.id,
336 currentRunOrdinal: run.ordinal,
337 runs: current.runs,
338 turnItems: current.turnItems,
339 });
340 const inheritedBackgroundTurnItems = yield* projectionStore
341 .getThreadProjection(projection.thread.id)
342 .pipe(Effect.map(selectInheritedBackgroundItems));
343 const providerSessionId = providerThread.providerSessionId;
344 const isCurrentAttemptInStatus = (
345 expectedStatus: OrchestrationV2Run["status"],
346 ): Effect.Effect<boolean, never> =>
347 projectionStore.getThreadProjection(projection.thread.id).pipe(
348 Effect.map((current) => {
349 const currentRun = current.runs.find((candidate) => candidate.id === run.id);
350 return (
351 currentRun?.activeAttemptId === attempt.id && currentRun.status === expectedStatus
352 );
353 }),
354 Effect.catchCause(() => Effect.succeed(false)),
355 );
356
357 const resolvedRuntimePolicy = yield* runtimePolicy.resolve({
358 thread: projection.thread,
359 modelSelection: run.modelSelection,
360 });
361 const existingSessionProjection = projection.providerSessions.find(
362 (candidate) => candidate.id === providerSessionId,
363 );
364 const session = yield* providerSessions.open({
365 threadId: projection.thread.id,
366 providerSessionId,
367 modelSelection: run.modelSelection,
368 runtimePolicy: resolvedRuntimePolicy,
369 ...(existingSessionProjection === undefined
370 ? {}
371 : { resumeFromSession: existingSessionProjection }),
372 ...(providerThread.nativeThreadRef?.nativeId == null
373 ? {}
374 : { initialNativeThreadId: providerThread.nativeThreadRef.nativeId }),
375 ...(providerThread.nativeMetadata?.itemIdentityVersion === undefined
376 ? {}
377 : {
378 initialProviderItemIdentityVersion: providerThread.nativeMetadata.itemIdentityVersion,
379 }),
380 });
381 let effectiveHandoffs = handoffs;
382 const loadedProviderThread = yield* Effect.gen(function* () {
383 if (nativeForkTransfer !== undefined) {
384 const sourceProjection = yield* projectionStore.getThreadProjection(
385 nativeForkTransfer.sourceThreadId,
386 );
387 const sourceRun = sourceProjection.runs.find(
388 (candidate) => candidate.id === nativeForkTransfer.sourcePoint.runId,
389 );
390 const sourceProviderThread = sourceProjection.providerThreads.find(
391 (candidate) => candidate.id === sourceRun?.providerThreadId,
392 );
393 const sourceAttempt = sourceProjection.attempts.find(
394 (candidate) => candidate.id === sourceRun?.activeAttemptId,
395 );
396 const sourceProviderTurn = sourceProjection.providerTurns.find(
397 (candidate) =>
398 candidate.id === sourceAttempt?.providerTurnId ||
399 candidate.runAttemptId === sourceAttempt?.id,
400 );
401 if (sourceRun === undefined || sourceProviderThread === undefined) {
402 return yield* new ProviderTurnStartError({
403 runId,
404 cause: `Native fork transfer ${nativeForkTransfer.id} has no source provider execution.`,
405 });
406 }
407 return yield* session.forkThread({
408 sourceProviderThread,
409 sourceProviderTurns: sourceProjection.providerTurns,
410 targetThreadId: projection.thread.id,
411 modelSelection: run.modelSelection,
412 runtimePolicy: resolvedRuntimePolicy,
413 ...(sourceProviderTurn === undefined ? {} : { providerTurnId: sourceProviderTurn.id }),
414 });
415 }
416 if (providerThread.nativeThreadRef === null) {
417 // Hand the run's provider thread to the adapter so it adopts this
418 // row's identity when attaching native state. An adapter that mints
419 // its own row instead leaves two live rows per app thread, and
420 // `activeProviderThreadId` then flaps between them on every update.
421 return yield* session.ensureThread({
422 threadId: projection.thread.id,
423 modelSelection: run.modelSelection,
424 runtimePolicy: resolvedRuntimePolicy,
425 providerSessionId,
426 existingProviderThread: providerThread,
427 });
428 }
429 const resumed = yield* Effect.result(
430 session.resumeThread({
431 providerThread,
432 threadId: projection.thread.id,
433 modelSelection: run.modelSelection,
434 runtimePolicy: resolvedRuntimePolicy,
435 }),
436 );
437 if (resumed._tag === "Success") {
438 return resumed.success;
439 }
440
441 const replacement = yield* session.ensureThread({
442 threadId: projection.thread.id,
443 modelSelection: run.modelSelection,
444 runtimePolicy: resolvedRuntimePolicy,
445 providerSessionId,
446 // The native ref is dropped so the adapter binds a fresh native
447 // session instead of retrying the resume that just failed, while
448 // still adopting this row's identity.
449 existingProviderThread: { ...providerThread, nativeThreadRef: null },
450 });
451 if (existingResumeFallback !== undefined) {
452 return replacement;
453 }
454 const transferId = yield* idAllocator.allocate.contextTransfer({
455 sourceThreadId: projection.thread.id,
456 targetThreadId: projection.thread.id,
457 type: "provider_resume_fallback",
458 });
459 const createdAt = yield* DateTime.now;
460 const handoff = yield* contextHandoffService.prepareProviderHandoff({
461 threadId: projection.thread.id,
462 targetRunId: run.id,
463 transferId,
464 fromProviderThreadIds: [providerThread.id],
465 toProviderThreadId: providerThread.id,
466 fromProviderInstanceId: providerThread.providerInstanceId,
467 toProviderInstanceId: run.providerInstanceId,
468 coveredRunOrdinals: { from: 1, to: Math.max(1, run.ordinal - 1) },
469 strategy: "full_thread_summary",
470 items: projection.turnItems,
471 createdAt,
472 });
473 effectiveHandoffs = [...handoffs, handoff];
474 yield* eventSink.write({
475 events: [
476 {
477 id: yield* idAllocator.allocate.event({ threadId: projection.thread.id }),
478 type: "context-handoff.updated",
479 threadId: projection.thread.id,
480 runId: run.id,
481 providerInstanceId: run.providerInstanceId,
482 occurredAt: createdAt,
483 payload: handoff,
484 },
485 {
486 id: yield* idAllocator.allocate.event({ threadId: projection.thread.id }),
487 type: "context-transfer.updated",
488 threadId: projection.thread.id,
489 runId: run.id,
490 providerInstanceId: run.providerInstanceId,
491 occurredAt: createdAt,
492 payload: {
493 id: transferId,
494 type: "provider_handoff",
495 sourceThreadId: projection.thread.id,
496 targetThreadId: projection.thread.id,
497 sourcePoint: { threadId: projection.thread.id },
498 basePoint: null,
499 sourceProviderInstanceId: providerThread.providerInstanceId,
500 targetProviderInstanceId: run.providerInstanceId,
501 targetRunId: run.id,
502 status: "resolved_portable",
503 resolution: { strategy: "portable_context", contextHandoffId: handoff.id },
504 createdBy: "system",
505 error: null,
506 createdAt,
507 updatedAt: createdAt,
508 consumedAt: null,
509 },
510 },
511 ],
512 });
513 return replacement;
514 });
515 if (!(yield* isCurrentAttemptInStatus("starting"))) {
516 return;
517 }
518 const now = yield* DateTime.now;
519 const runningProviderThread: OrchestrationV2ProviderThread = {
520 ...loadedProviderThread,
521 id: providerThread.id,
522 driver: session.driver,
523 providerInstanceId: run.providerInstanceId,
524 providerSessionId,
525 appThreadId: projection.thread.id,
526 ownerNodeId: providerThread.ownerNodeId,
527 firstRunOrdinal: providerThread.firstRunOrdinal ?? run.ordinal,
528 lastRunOrdinal: run.ordinal,
529 handoffIds: providerThread.handoffIds,
530 forkedFrom: providerThread.forkedFrom,
531 status: "active",
532 createdAt: providerThread.createdAt,
533 updatedAt: now,
534 };
535 const runningRun: OrchestrationV2Run = {
536 ...run,
537 status: "running",
538 startedAt: now,
539 };
540 const runningAttempt: OrchestrationV2RunAttempt = {
541 ...attempt,
542 status: "running",
543 startedAt: now,
544 };
545 const runningRootNode: OrchestrationV2ExecutionNode = {
546 ...rootNode,
547 status: "running",
548 startedAt: now,
549 };
550 const events: Array<OrchestrationV2DomainEvent> = [
551 {
552 id: yield* idAllocator.allocate.event({
553 threadId: projection.thread.id,
554 providerSessionId,
555 }),
556 type: "provider-session.updated",
557 threadId: projection.thread.id,
558 driver: session.driver,
559 providerInstanceId: run.providerInstanceId,
560 occurredAt: now,
561 payload: session.providerSession,
562 },
563 {
564 id: yield* idAllocator.allocate.event({ threadId: projection.thread.id }),
565 type: "provider-thread.updated",
566 threadId: projection.thread.id,
567 driver: session.driver,
568 providerInstanceId: run.providerInstanceId,
569 occurredAt: now,
570 payload: runningProviderThread,
571 },
572 ...(nativeForkTransfer === undefined || runningProviderThread.nativeThreadRef === null
573 ? []
574 : [
575 {
576 id: yield* idAllocator.allocate.event({ threadId: projection.thread.id }),
577 type: "context-transfer.updated" as const,
578 threadId: projection.thread.id,
579 runId: run.id,
580 driver: session.driver,
581 providerInstanceId: run.providerInstanceId,
582 occurredAt: now,
583 payload: {
584 ...nativeForkTransfer,
585 targetProviderInstanceId: run.providerInstanceId,
586 targetRunId: run.id,
587 status: "consumed" as const,
588 resolution: {
589 strategy: "native_fork" as const,
590 providerThreadRef: runningProviderThread.nativeThreadRef,
591 },
592 error: null,
593 updatedAt: now,
594 consumedAt: now,
595 },
596 },
597 ]),
598 {
599 id: yield* idAllocator.allocate.event({ threadId: projection.thread.id }),
600 type: "run.updated",
601 threadId: projection.thread.id,
602 runId: run.id,
603 nodeId: rootNode.id,
604 providerInstanceId: run.providerInstanceId,
605 occurredAt: now,
606 payload: runningRun,
607 },
608 {
609 id: yield* idAllocator.allocate.event({ threadId: projection.thread.id }),
610 type: "run-attempt.updated",
611 threadId: projection.thread.id,
612 runId: run.id,
613 nodeId: rootNode.id,
614 providerInstanceId: run.providerInstanceId,
615 occurredAt: now,
616 payload: runningAttempt,
617 },
618 {
619 id: yield* idAllocator.allocate.event({ threadId: projection.thread.id }),
620 type: "node.updated",
621 threadId: projection.thread.id,
622 runId: run.id,
623 nodeId: rootNode.id,
624 providerInstanceId: run.providerInstanceId,
625 occurredAt: now,
626 payload: runningRootNode,
627 },
628 ];
629 const runningWrite = yield* eventSink.writeIfRunCurrent({
630 threadId: projection.thread.id,
631 runId: run.id,
632 activeAttemptId: attempt.id,
633 expectedStatus: "starting",
634 events,
635 });
636 if (!runningWrite.committed) {
637 return;
638 }
639 const routableSubagents = projection.subagents.filter((subagent) =>
640 canRouteRelatedSubagent(subagent.status),
641 );
642 yield* runExecution.startRootRun({
643 commandId: CommandId.make(`command:effect:provider-turn.start:${run.id}`),
644 appThread: projection.thread,
645 providerSessionId,
646 session,
647 run: runningRun,
648 rootNode: runningRootNode,
649 checkpointScope,
650 providerThread: runningProviderThread,
651 attempt: runningAttempt,
652 attemptId: attempt.id,
653 loadInheritedBackgroundTurnItems: () =>
654 projectionStore.getThreadProjection(projection.thread.id).pipe(
655 Effect.map(selectInheritedBackgroundItems),
656 Effect.catchCause(() => Effect.succeed(inheritedBackgroundTurnItems)),
657 ),
658 relatedThreadIds: routableSubagents.flatMap((subagent) =>
659 subagent.childThreadId === null ? [] : [subagent.childThreadId],
660 ),
661 relatedProviderThreadIds: routableSubagents.flatMap((subagent) =>
662 subagent.providerThreadId === null ? [] : [subagent.providerThreadId],
663 ),
664 providerTurnOrdinal:
665 Math.max(
666 0,
667 ...projection.providerTurns
668 .filter((turn) => turn.providerThreadId === providerThread.id)
669 .map((turn) => turn.ordinal),
670 ) + 1,
671 shouldStartProviderTurn: () => isCurrentAttemptInStatus("running"),
672 shouldFinalizeRun: () =>
673 projectionStore.getThreadProjection(projection.thread.id).pipe(
674 Effect.map((current) => {
675 const currentRun = current.runs.find((candidate) => candidate.id === run.id);
676 return (
677 currentRun?.activeAttemptId === attempt.id &&
678 (currentRun.status === "starting" || currentRun.status === "running")
679 );
680 }),
681 Effect.catchCause(() => Effect.succeed(false)),
682 ),
683 hasUnpairedRunInterruptRequest: () =>
684 projectionStore.getThreadProjection(projection.thread.id).pipe(
685 Effect.map((current) => {
686 const requestId = idAllocator.derive.runSignalTurnItem({
687 runId: run.id,
688 signal: "interrupt-request",
689 });
690 const resultId = idAllocator.derive.runSignalTurnItem({
691 runId: run.id,
692 signal: "interrupt-result",
693 });
694 const hasRequest = current.turnItems.some((item) => item.id === requestId);
695 const hasResult = current.turnItems.some((item) => item.id === resultId);
696 return hasRequest && !hasResult;
697 }),
698 Effect.catchCause(() => Effect.succeed(false)),
699 ),
700 message: {
701 messageId: message.id,
702 text:
703 effectiveHandoffs.length === 0
704 ? projectComposerContextForProvider({
705 text: message.text,
706 records: message.context?.records ?? [],
707 })
708 : providerMessageWithContextHandoffs({
709 handoffs: effectiveHandoffs,
710 userText: projectComposerContextForProvider({
711 text: message.text,
712 records: message.context?.records ?? [],
713 }),
714 }),
715 attachments: message.attachments,
716 createdBy: message.createdBy,
717 creationSource: message.creationSource,
718 ...(message.scheduledTaskId === undefined
719 ? {}
720 : { scheduledTaskId: message.scheduledTaskId }),
721 },
722 modelSelection: run.modelSelection,
723 runtimePolicy: resolvedRuntimePolicy,
724 });
725 });
726
727 return ProviderTurnStartServiceV2.of({
728 start: (input) =>
729 start(input).pipe(
730 Effect.mapError((cause) =>
731 isProviderTurnStartError(cause)
732 ? cause
733 : new ProviderTurnStartError({ runId: input.runId, cause }),
734 ),
735 ),
736 });
737 }),
738);