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