Open History to see the last commit
1import { modelSelectionsEqual } from "@t3tools/shared/model";
2import { projectComposerContextForProvider } from "@t3tools/shared/composerContextReferences";
3import {
4 CommandId,
5 latestProviderTurnForAttempt,
6 type OrchestrationV2DomainEvent,
7 type OrchestrationV2ExecutionNode,
8 type OrchestrationV2ProviderThread,
9 type OrchestrationV2Run,
10 type OrchestrationV2RunAttempt,
11 type OrchestrationV2TurnItem,
12 RunId,
13 ThreadId,
14} from "@t3tools/contracts";
15import * as Context from "effect/Context";
16import * as Cause from "effect/Cause";
17import * as DateTime from "effect/DateTime";
18import * as Effect from "effect/Effect";
19import * as FileSystem from "effect/FileSystem";
20import * as Layer from "effect/Layer";
21import * as Option from "effect/Option";
22import * as Predicate from "effect/Predicate";
23import * as Schema from "effect/Schema";
24
25import * as GitWorkflowService from "../git/GitWorkflowService.ts";
26import * as ProjectService from "../project/ProjectService.ts";
27import * as ProviderAuthService from "../provider/ProviderAuthService.ts";
28import * as EventSink from "./EventSink.ts";
29import * as ContextHandoffService from "./ContextHandoffService.ts";
30import {
31 DEFAULT_HANDOFF_TOKEN_CAP,
32 handoffTokenCapConfig,
33 handoffBudget,
34 attachmentTokenAllowance,
35 contextUsageForHandoff,
36 historicalMessage,
37 latestNativeContextUsage,
38} from "@t3tools/provider-core/server/handoffBudget";
39import { deliverContextHandoffs } from "./ContextHandoffDelivery.ts";
40import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
41import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
42import * as ProjectionStore from "./ProjectionStore.ts";
43import * as ProviderSessionManager from "./ProviderSessionManager.ts";
44import { makeProviderFailure } from "@t3tools/provider-core/server/failure";
45import * as RunExecutionService from "./RunExecutionService.ts";
46import * as RuntimePolicy from "./RuntimePolicy.ts";
47import {
48 isRestartNoteContinuation,
49 pendingRestartCancelledBackgroundWork,
50 restartCancelledBackgroundWorkNote,
51} from "./RestartBackgroundNote.ts";
52
53export class ProviderTurnStartError extends Schema.TaggedError<ProviderTurnStartError>()(
54 "ProviderTurnStartError",
55 {
56 runId: RunId,
57 cause: Schema.optional(Schema.Defect()),
58 },
59) {}
60
61const isProviderTurnStartError = Schema.is(ProviderTurnStartError);
62
63/** Claude refuses to replace a process running background work before it reads the prompt. */
64const refusedBeforePrompt = (error: unknown): boolean =>
65 Predicate.isTagged(error, "ClaudeBackgroundWorkBlocksQueryReplacementError") ||
66 (Predicate.hasProperty(error, "cause") && refusedBeforePrompt(error.cause));
67
68export interface ProviderTurnStartServiceV2Shape {
69 /**
70 * Starts the run's provider turn. When `willRetry` is true, a session open
71 * failure is returned so the caller can retry. Otherwise the run is settled
72 * as failed.
73 */
74 readonly start: (input: {
75 readonly threadId: ThreadId;
76 readonly runId: RunId;
77 readonly willRetry?: boolean;
78 }) => Effect.Effect<void, ProviderTurnStartError>;
79}
80
81export class ProviderTurnStartServiceV2 extends Context.Service<
82 ProviderTurnStartServiceV2,
83 ProviderTurnStartServiceV2Shape
84>()("t3/orchestration-v2/ProviderTurnStartService/ProviderTurnStartServiceV2") {}
85
86export const layer: Layer.Layer<
87 ProviderTurnStartServiceV2,
88 never,
89 | EventSink.EventSinkV2
90 | ContextHandoffService.ContextHandoffServiceV2
91 | IdAllocator.IdAllocatorV2
92 | FileSystem.FileSystem
93 | GitWorkflowService.GitWorkflowService
94 | ProjectService.ProjectService
95 | ProviderAuthService.ProviderAuthService
96 | ProjectionStore.ProjectionStoreV2
97 | ProviderSessionManager.ProviderSessionManagerV2
98 | RunExecutionService.RunExecutionServiceV2
99 | RuntimePolicy.RuntimePolicyV2
100> = Layer.effect(
101 ProviderTurnStartServiceV2,
102 Effect.gen(function* () {
103 const eventSink = yield* EventSink.EventSinkV2;
104 const contextHandoffService = yield* ContextHandoffService.ContextHandoffServiceV2;
105 const idAllocator = yield* IdAllocator.IdAllocatorV2;
106 const fileSystem = yield* FileSystem.FileSystem;
107 const gitWorkflow = yield* GitWorkflowService.GitWorkflowService;
108 const projects = yield* ProjectService.ProjectService;
109 const providerAuth = yield* ProviderAuthService.ProviderAuthService;
110 const projectionStore = yield* ProjectionStore.ProjectionStoreV2;
111 const providerSessions = yield* ProviderSessionManager.ProviderSessionManagerV2;
112 const runExecution = yield* RunExecutionService.RunExecutionServiceV2;
113 const runtimePolicy = yield* RuntimePolicy.RuntimePolicyV2;
114
115 // These callbacks outlive startup while a run drains background work. Build
116 // them outside start's scope so they cannot retain its full thread history.
117 const makeRunControls = (input: {
118 readonly threadId: ThreadId;
119 readonly runId: RunId;
120 readonly attemptId: OrchestrationV2RunAttempt["id"];
121 readonly providerThreadId: OrchestrationV2ProviderThread["id"];
122 readonly runOrdinal: number;
123 readonly inheritedBackgroundTurnItems: ReturnType<
124 typeof RunExecutionService.selectInheritedBackgroundTurnItems
125 >;
126 }) => {
127 // Guards and background routing need live execution state, not a fresh
128 // allocation of every completed message and tool output in the thread.
129 // `false` means the run moved on or is gone. A failed read is an error,
130 // so the caller fails the start or the run instead of skipping it.
131 const isCurrentAttemptInStatus = (expectedStatus: OrchestrationV2Run["status"]) =>
132 projectionStore.getRuntimeRecoveryProjection(input.threadId).pipe(
133 Effect.map((current) => {
134 const run = current.runs.find((candidate) => candidate.id === input.runId);
135 return run?.activeAttemptId === input.attemptId && run.status === expectedStatus;
136 }),
137 );
138 return {
139 isCurrentAttemptInStatus,
140 loadInheritedBackgroundTurnItems: () =>
141 projectionStore.getRuntimeRecoveryProjection(input.threadId).pipe(
142 Effect.map((current) =>
143 RunExecutionService.selectInheritedBackgroundTurnItems({
144 threadId: input.threadId,
145 currentProviderThreadId: input.providerThreadId,
146 currentRunOrdinal: input.runOrdinal,
147 runs: current.runs,
148 turnItems: current.turnItems,
149 }),
150 ),
151 Effect.catchCause(() => Effect.succeed(input.inheritedBackgroundTurnItems)),
152 ),
153 shouldStartProviderTurn: () => isCurrentAttemptInStatus("running"),
154 shouldFinalizeRun: () =>
155 projectionStore.getRuntimeRecoveryProjection(input.threadId).pipe(
156 Effect.map((current) => {
157 const run = current.runs.find((candidate) => candidate.id === input.runId);
158 return (
159 run?.activeAttemptId === input.attemptId &&
160 (run.status === "starting" || run.status === "running")
161 );
162 }),
163 ),
164 hasUnpairedRunInterruptRequest: () =>
165 projectionStore
166 .hasUnpairedRunInterruptRequest(
167 input.threadId,
168 idAllocator.derive.runSignalTurnItem({
169 runId: input.runId,
170 signal: "interrupt-request",
171 }),
172 idAllocator.derive.runSignalTurnItem({
173 runId: input.runId,
174 signal: "interrupt-result",
175 }),
176 )
177 .pipe(Effect.catchCause(() => Effect.succeed(false))),
178 };
179 };
180
181 const makeDeliverySession = (
182 session: ProviderAdapter.ProviderAdapterV2SessionRuntime,
183 startWithHandoffs: (
184 input: Parameters<ProviderAdapter.ProviderAdapterV2SessionRuntime["startTurn"]>[0],
185 compact?: boolean,
186 ) => ReturnType<ProviderAdapter.ProviderAdapterV2SessionRuntime["startTurn"]>,
187 ) => {
188 let deliver: typeof startWithHandoffs | undefined = startWithHandoffs;
189 const start = (
190 input: Parameters<ProviderAdapter.ProviderAdapterV2SessionRuntime["startTurn"]>[0],
191 compact = false,
192 ) =>
193 Effect.suspend(() => {
194 if (deliver !== undefined) return deliver(input, compact);
195 return compact && session.compactThread !== undefined
196 ? session.compactThread(input)
197 : session.startTurn(input);
198 }).pipe(
199 // Only startup needs the handoff history. The event worker keeps this
200 // session alive afterward, including when background work remains.
201 Effect.ensuring(
202 Effect.sync(() => {
203 deliver = undefined;
204 }),
205 ),
206 );
207 return {
208 ...session,
209 startTurn: (input: Parameters<typeof session.startTurn>[0]) => start(input),
210 ...(session.compactThread === undefined
211 ? {}
212 : {
213 compactThread: (input: Parameters<typeof session.startTurn>[0]) => start(input, true),
214 }),
215 };
216 };
217
218 const start = Effect.fn("orchestrationV2.providerTurnStart.start")(function* (input: {
219 readonly threadId: ThreadId;
220 readonly runId: RunId;
221 readonly willRetry?: boolean;
222 }) {
223 const { runId } = input;
224 const projection = yield* projectionStore.getTurnStartContext(input.threadId, runId);
225 const run = projection.runs.find((candidate) => candidate.id === runId);
226 if (run === undefined) {
227 return yield* new ProviderTurnStartError({ runId, cause: `Run ${runId} was not found.` });
228 }
229 if (run.status !== "starting") {
230 // The effect is idempotent once the run has advanced or terminalized.
231 return;
232 }
233 const rootNode = projection.nodes.find((candidate) => candidate.id === run.rootNodeId);
234 const attempt = projection.attempts.find((candidate) => candidate.id === run.activeAttemptId);
235 const providerThread = projection.providerThreads.find(
236 (candidate) => candidate.id === run.providerThreadId,
237 );
238 const message = projection.messages.find((candidate) => candidate.id === run.userMessageId);
239 const checkpointScope = projection.checkpointScopes.find(
240 (candidate) => candidate.id === rootNode?.checkpointScopeId,
241 );
242 const handoffs = projection.contextHandoffs.filter(
243 (handoff) =>
244 handoff.status === "ready" &&
245 (handoff.targetRunId === run.id ||
246 (handoff.toProviderThreadId === run.providerThreadId &&
247 projection.runs.some(
248 (source) =>
249 source.id === handoff.targetRunId &&
250 (source.status === "failed" ||
251 source.status === "interrupted" ||
252 (source.status === "completed" &&
253 handoff.delivery === undefined &&
254 projection.messages.some(
255 (message) =>
256 message.id === source.userMessageId &&
257 message.attachments.length === 0 &&
258 message.text.trim().toLowerCase() === "/compact",
259 ))),
260 ))),
261 );
262 const nativeForkTransfer = projection.contextTransfers.find(
263 (transfer) =>
264 transfer.type === "fork" &&
265 transfer.targetThreadId === input.threadId &&
266 transfer.targetRunId === run.id &&
267 transfer.status === "pending" &&
268 transfer.resolution === null,
269 );
270 if (
271 rootNode === undefined ||
272 attempt === undefined ||
273 providerThread === undefined ||
274 providerThread.providerSessionId === null ||
275 message === undefined ||
276 checkpointScope === undefined
277 ) {
278 return yield* new ProviderTurnStartError({
279 runId,
280 cause: `Run ${runId} is missing its execution projection state.`,
281 });
282 }
283 // Settles a run that never reached the provider: one signal turn item plus
284 // terminal run, attempt and root node, written only while the run is still
285 // the current starting attempt.
286 const settleRunBeforeStart = Effect.fn("orchestrationV2.providerTurnStart.settleBeforeStart")(
287 function* (input: {
288 readonly signal: string;
289 readonly status: "completed" | "failed";
290 readonly now: DateTime.Utc;
291 /** Omitted when the run never started, so `startedAt` stays as projected. */
292 readonly startedAt?: DateTime.Utc;
293 readonly providerInstanceId: OrchestrationV2Run["providerInstanceId"];
294 readonly itemProviderThreadId: OrchestrationV2ProviderThread["id"];
295 readonly item:
296 | Pick<
297 Extract<OrchestrationV2TurnItem, { type: "error" }>,
298 "type" | "title" | "failure"
299 >
300 | Pick<
301 Extract<OrchestrationV2TurnItem, { type: "command_execution" }>,
302 "type" | "title" | "input" | "output" | "exitCode"
303 >;
304 /** Emitted after the run events when the provider thread should go idle. */
305 readonly providerThreadUpdate?: OrchestrationV2ProviderThread;
306 }) {
307 const { now, status } = input;
308 const started = input.startedAt === undefined ? {} : { startedAt: input.startedAt };
309 const item: OrchestrationV2TurnItem = {
310 id: idAllocator.derive.runSignalTurnItem({ runId, signal: input.signal }),
311 threadId: projection.thread.id,
312 runId,
313 nodeId: rootNode.id,
314 providerThreadId: input.itemProviderThreadId,
315 providerTurnId: null,
316 nativeItemRef: null,
317 parentItemId: null,
318 ordinal:
319 Math.max(
320 0,
321 ...projection.turnItems
322 .filter((item) => item.runId === runId)
323 .map((item) => item.ordinal),
324 ) + 1,
325 status,
326 startedAt: now,
327 completedAt: now,
328 updatedAt: now,
329 ...input.item,
330 };
331 const eventPayloads = [
332 { type: "turn-item.updated", payload: item },
333 { type: "run.updated", payload: { ...run, status, ...started, completedAt: now } },
334 {
335 type: "run-attempt.updated",
336 payload: { ...attempt, status, ...started, completedAt: now },
337 },
338 {
339 type: "node.updated",
340 payload: { ...rootNode, status, ...started, completedAt: now },
341 },
342 ...(input.providerThreadUpdate === undefined
343 ? []
344 : [
345 {
346 type: "provider-thread.updated" as const,
347 payload: input.providerThreadUpdate,
348 },
349 ]),
350 ] as const;
351 const events = yield* Effect.forEach(eventPayloads, (event) =>
352 Effect.gen(function* () {
353 return {
354 ...event,
355 id: yield* idAllocator.allocate.event({ threadId: projection.thread.id }),
356 threadId: projection.thread.id,
357 runId,
358 nodeId: rootNode.id,
359 providerInstanceId: input.providerInstanceId,
360 occurredAt: now,
361 } satisfies OrchestrationV2DomainEvent;
362 }),
363 );
364 yield* eventSink.writeIfRunCurrent({
365 threadId: projection.thread.id,
366 runId,
367 activeAttemptId: attempt.id,
368 expectedStatus: "starting",
369 events,
370 });
371 },
372 );
373 if (message.attachments.length === 0 && message.text.trimStart().startsWith("/")) {
374 const isEmptyCompaction =
375 message.text.trim().toLowerCase() === "/compact" && !projection.hasConversation;
376 // Preparing a run may already point the thread at a newly selected
377 // provider. Account commands still belong to its last native session.
378 const nativeThreads = new Map(
379 projection.providerThreads
380 .filter(
381 (candidate) => candidate.ownerNodeId === null && candidate.nativeThreadRef !== null,
382 )
383 .map((candidate) => [candidate.id, candidate]),
384 );
385 const previousNativeRun = projection.runs.reduce<OrchestrationV2Run | undefined>(
386 (previous, candidate) =>
387 candidate.ordinal < run.ordinal &&
388 candidate.providerThreadId !== null &&
389 nativeThreads.has(candidate.providerThreadId) &&
390 (previous === undefined || candidate.ordinal > previous.ordinal)
391 ? candidate
392 : previous,
393 undefined,
394 );
395 const nativeThread = nativeThreads.get(
396 previousNativeRun?.providerThreadId ??
397 projection.thread.activeProviderThreadId ??
398 providerThread.id,
399 );
400 const authInstanceId = nativeThread?.providerInstanceId ?? run.providerInstanceId;
401 const authResult = isEmptyCompaction
402 ? null
403 : yield* Effect.result(
404 providerAuth.tryHandlePromptCommand({
405 instanceId: authInstanceId,
406 text: projectComposerContextForProvider({
407 text: message.text,
408 records: message.context?.records ?? [],
409 }),
410 hasAttachments: false,
411 }),
412 );
413 if (isEmptyCompaction || authResult?._tag === "Failure" || authResult?.success) {
414 const now = yield* DateTime.now;
415 const failure = isEmptyCompaction
416 ? makeProviderFailure({
417 class: "validation_error",
418 message: "Start a conversation before compacting this thread.",
419 })
420 : authResult?._tag === "Failure"
421 ? makeProviderFailure({
422 class: "permission_error",
423 message: authResult.failure.detail,
424 })
425 : undefined;
426 const status = failure === undefined ? "completed" : "failed";
427 yield* settleRunBeforeStart({
428 signal: isEmptyCompaction ? "empty-compaction" : "provider-sign-out",
429 status,
430 now,
431 startedAt: now,
432 providerInstanceId: authInstanceId,
433 itemProviderThreadId: nativeThread?.id ?? providerThread.id,
434 item:
435 failure !== undefined
436 ? {
437 type: "error",
438 title: isEmptyCompaction
439 ? "Cannot compact an empty thread"
440 : "Provider sign-out failed",
441 failure,
442 }
443 : {
444 type: "command_execution",
445 title: "Provider signed out",
446 input: message.text.trim(),
447 output: "Provider signed out",
448 exitCode: 0,
449 },
450 providerThreadUpdate: {
451 ...providerThread,
452 status: providerThread.nativeThreadRef === null ? "not_loaded" : "idle",
453 updatedAt: now,
454 },
455 });
456 return;
457 }
458 }
459 const { worktreePath, branch } = projection.thread;
460 if (worktreePath !== null && branch !== null) {
461 const exists = yield* fileSystem
462 .exists(worktreePath)
463 .pipe(Effect.orElseSucceed(() => true));
464 if (!exists) {
465 const project = yield* projects.getById(projection.thread.projectId).pipe(
466 Effect.map(Option.getOrUndefined),
467 Effect.orElseSucceed(() => undefined),
468 );
469 if (project !== undefined) {
470 yield* Effect.logWarning("provider turn start recreating missing worktree", {
471 threadId: projection.thread.id,
472 worktreePath,
473 branch,
474 });
475 yield* gitWorkflow.pruneWorktrees({ cwd: project.workspaceRoot }).pipe(
476 Effect.andThen(
477 gitWorkflow.createWorktree({
478 cwd: project.workspaceRoot,
479 refName: branch,
480 path: worktreePath,
481 }),
482 ),
483 Effect.catchCause((cause) =>
484 Cause.hasInterruptsOnly(cause)
485 ? Effect.failCause(cause)
486 : Effect.logWarning("provider turn start failed to recreate worktree", {
487 threadId: projection.thread.id,
488 worktreePath,
489 cause: Cause.pretty(cause),
490 }),
491 ),
492 );
493 }
494 }
495 }
496 const selectInheritedBackgroundItems = (
497 current: ProjectionStore.ProjectionRuntimeRecoveryState,
498 ): ReturnType<typeof RunExecutionService.selectInheritedBackgroundTurnItems> =>
499 RunExecutionService.selectInheritedBackgroundTurnItems({
500 threadId: current.thread.id,
501 currentProviderThreadId: providerThread.id,
502 currentRunOrdinal: run.ordinal,
503 runs: current.runs,
504 turnItems: current.turnItems,
505 });
506 const inheritedBackgroundTurnItems = yield* projectionStore
507 .getRuntimeRecoveryProjection(projection.thread.id)
508 .pipe(Effect.map(selectInheritedBackgroundItems));
509 const providerSessionId = providerThread.providerSessionId;
510 const runControls = makeRunControls({
511 threadId: projection.thread.id,
512 runId: run.id,
513 attemptId: attempt.id,
514 providerThreadId: providerThread.id,
515 runOrdinal: run.ordinal,
516 inheritedBackgroundTurnItems,
517 });
518 const { isCurrentAttemptInStatus } = runControls;
519
520 const resolvedRuntimePolicy = yield* runtimePolicy.resolve({
521 thread: projection.thread,
522 modelSelection: run.modelSelection,
523 });
524 const existingSessionProjection = projection.providerSessions.find(
525 (candidate) => candidate.id === providerSessionId,
526 );
527 const sessionResult = yield* Effect.result(
528 providerSessions.open({
529 threadId: projection.thread.id,
530 providerSessionId,
531 modelSelection: run.modelSelection,
532 runtimePolicy: resolvedRuntimePolicy,
533 ...(existingSessionProjection === undefined
534 ? {}
535 : { resumeFromSession: existingSessionProjection }),
536 ...(providerThread.nativeThreadRef?.nativeId == null
537 ? {}
538 : { initialNativeThreadId: providerThread.nativeThreadRef.nativeId }),
539 ...(providerThread.nativeMetadata?.itemIdentityVersion === undefined
540 ? {}
541 : {
542 initialProviderItemIdentityVersion:
543 providerThread.nativeMetadata.itemIdentityVersion,
544 }),
545 }),
546 );
547 // The last start attempt fails the run with the provider's own reason
548 // instead of leaving it `starting` after the effect gives up. A run that
549 // already left `starting` is not overwritten, and a failed write returns
550 // its error to the effect worker.
551 const settleStartFailure = (failed: {
552 readonly signal: string;
553 readonly title: string;
554 readonly error: Error;
555 }) =>
556 Effect.gen(function* () {
557 const nestedCause = "cause" in failed.error ? failed.error.cause : undefined;
558 yield* settleRunBeforeStart({
559 signal: failed.signal,
560 status: "failed",
561 now: yield* DateTime.now,
562 providerInstanceId: run.providerInstanceId,
563 itemProviderThreadId: providerThread.id,
564 item: {
565 type: "error",
566 title: failed.title,
567 failure: makeProviderFailure({
568 cause: failed.error,
569 message:
570 nestedCause instanceof Error
571 ? nestedCause.message
572 : typeof nestedCause === "string"
573 ? nestedCause
574 : failed.error.message,
575 class: "provider_error",
576 }),
577 },
578 });
579 });
580 if (sessionResult._tag === "Failure") {
581 if (input.willRetry === true) return yield* sessionResult.failure;
582 yield* settleStartFailure({
583 signal: "provider-session-open-failure",
584 title: "Provider session failed to open",
585 error: sessionResult.failure,
586 });
587 return;
588 }
589 const session = sessionResult.success;
590 // Only the provider's own thread load fails the run on the last attempt;
591 // store, id and handoff failures around it keep their typed errors.
592 const loadFromProvider = (
593 load: Effect.Effect<OrchestrationV2ProviderThread, ProviderAdapter.ProviderAdapterV2Error>,
594 ) =>
595 Effect.gen(function* () {
596 const loaded = yield* Effect.result(load);
597 if (loaded._tag === "Success") return loaded.success;
598 if (input.willRetry === true) return yield* loaded.failure;
599 yield* settleStartFailure({
600 signal: "provider-thread-load-failure",
601 title: "Provider turn failed to start",
602 error: loaded.failure,
603 });
604 return undefined;
605 });
606 let effectiveHandoffs = handoffs;
607 const loadedProviderThread = yield* Effect.gen(function* () {
608 if (nativeForkTransfer !== undefined) {
609 const sourceProjection = yield* projectionStore.getThreadRecords(
610 nativeForkTransfer.sourceThreadId,
611 ["runs", "providerThreads", "attempts", "providerTurns"],
612 );
613 const sourceRun = sourceProjection.runs.find(
614 (candidate) => candidate.id === nativeForkTransfer.sourcePoint.runId,
615 );
616 const sourceProviderThread = sourceProjection.providerThreads.find(
617 (candidate) => candidate.id === sourceRun?.providerThreadId,
618 );
619 const sourceAttempt = sourceProjection.attempts.find(
620 (candidate) => candidate.id === sourceRun?.activeAttemptId,
621 );
622 const sourceProviderTurn =
623 latestProviderTurnForAttempt(sourceProjection.providerTurns, sourceAttempt?.id) ??
624 sourceProjection.providerTurns.find(
625 (candidate) => candidate.id === sourceAttempt?.providerTurnId,
626 );
627 if (sourceRun === undefined || sourceProviderThread === undefined) {
628 return yield* new ProviderTurnStartError({
629 runId,
630 cause: `Native fork transfer ${nativeForkTransfer.id} has no source provider execution.`,
631 });
632 }
633 return yield* loadFromProvider(
634 session.forkThread({
635 sourceProviderThread,
636 sourceProviderTurns: sourceProjection.providerTurns,
637 targetThreadId: projection.thread.id,
638 modelSelection: run.modelSelection,
639 runtimePolicy: resolvedRuntimePolicy,
640 ...(sourceProviderTurn === undefined
641 ? {}
642 : { providerTurnId: sourceProviderTurn.id }),
643 }),
644 );
645 }
646 if (providerThread.nativeThreadRef === null) {
647 // Hand the run's provider thread to the adapter so it adopts this
648 // row's identity when attaching native state. An adapter that mints
649 // its own row instead leaves two live rows per app thread, and
650 // `activeProviderThreadId` then flaps between them on every update.
651 return yield* loadFromProvider(
652 session.ensureThread({
653 threadId: projection.thread.id,
654 title: projection.thread.title,
655 modelSelection: run.modelSelection,
656 runtimePolicy: resolvedRuntimePolicy,
657 providerSessionId,
658 existingProviderThread: providerThread,
659 }),
660 );
661 }
662 const uncertainDelivery = projection.contextHandoffs.some(
663 (handoff) =>
664 handoff.toProviderThreadId === providerThread.id &&
665 handoff.delivery?.nativeThreadId === providerThread.nativeThreadRef?.nativeId &&
666 handoff.delivery?.status === "pending",
667 );
668 const resumed = yield* Effect.result(
669 uncertainDelivery
670 ? Effect.fail(
671 new ProviderAdapter.ProviderAdapterTurnStartError({
672 driver: session.driver,
673 threadId: projection.thread.id,
674 providerThreadId: providerThread.id,
675 runId,
676 cause: "Uncertain native history injection",
677 }),
678 )
679 : session.resumeThread({
680 providerThread,
681 threadId: projection.thread.id,
682 modelSelection: run.modelSelection,
683 runtimePolicy: resolvedRuntimePolicy,
684 }),
685 );
686 if (resumed._tag === "Success") {
687 return resumed.success;
688 }
689
690 yield* Effect.logWarning("Provider resume failed; attempting a fresh native session", {
691 driver: session.driver,
692 providerThreadId: providerThread.id,
693 runId,
694 reason: uncertainDelivery ? "uncertain_history_delivery" : "resume_failed",
695 errorTag: resumed.failure._tag,
696 });
697 const replacement = yield* loadFromProvider(
698 session.ensureThread({
699 threadId: projection.thread.id,
700 title: projection.thread.title,
701 modelSelection: run.modelSelection,
702 runtimePolicy: resolvedRuntimePolicy,
703 providerSessionId,
704 // The native ref is dropped so the adapter binds a fresh native
705 // session instead of retrying the resume that just failed, while
706 // still adopting this row's identity.
707 existingProviderThread: { ...providerThread, nativeThreadRef: null },
708 }),
709 );
710 if (replacement === undefined) return undefined;
711 const transferId = yield* idAllocator.allocate.contextTransfer({
712 sourceThreadId: projection.thread.id,
713 targetThreadId: projection.thread.id,
714 type: "provider_resume_fallback",
715 });
716 const createdAt = yield* DateTime.now;
717 const handoff = yield* contextHandoffService.prepareProviderHandoff({
718 threadId: projection.thread.id,
719 targetRunId: run.id,
720 transferId,
721 fromProviderThreadIds: [providerThread.id],
722 toProviderThreadId: providerThread.id,
723 fromProviderInstanceId: providerThread.providerInstanceId,
724 toProviderInstanceId: run.providerInstanceId,
725 coveredRunOrdinals: { from: 1, to: Math.max(1, run.ordinal - 1) },
726 strategy: "full_thread_summary",
727 runs: projection.runs,
728 items: (yield* projectionStore.getTurnStartHistory(input.threadId)).filter(
729 (item) =>
730 item.runId === null ||
731 projection.runs.some(
732 (source) => source.id === item.runId && source.ordinal < run.ordinal,
733 ),
734 ),
735 createdAt,
736 });
737 effectiveHandoffs = [handoff, ...effectiveHandoffs];
738 yield* eventSink.write({
739 events: [
740 {
741 id: yield* idAllocator.allocate.event({ threadId: projection.thread.id }),
742 type: "context-handoff.updated",
743 threadId: projection.thread.id,
744 runId: run.id,
745 providerInstanceId: run.providerInstanceId,
746 occurredAt: createdAt,
747 payload: handoff,
748 },
749 {
750 id: yield* idAllocator.allocate.event({ threadId: projection.thread.id }),
751 type: "context-transfer.updated",
752 threadId: projection.thread.id,
753 runId: run.id,
754 providerInstanceId: run.providerInstanceId,
755 occurredAt: createdAt,
756 payload: {
757 id: transferId,
758 type: "provider_handoff",
759 sourceThreadId: projection.thread.id,
760 targetThreadId: projection.thread.id,
761 sourcePoint: { threadId: projection.thread.id },
762 basePoint: null,
763 sourceProviderInstanceId: providerThread.providerInstanceId,
764 targetProviderInstanceId: run.providerInstanceId,
765 targetRunId: run.id,
766 status: "resolved_portable",
767 resolution: { strategy: "portable_context", contextHandoffId: handoff.id },
768 createdBy: "system",
769 error: null,
770 createdAt,
771 updatedAt: createdAt,
772 consumedAt: null,
773 },
774 },
775 ],
776 });
777 return replacement;
778 });
779 // The last attempt already failed the run.
780 if (loadedProviderThread === undefined) return;
781 if (!(yield* isCurrentAttemptInStatus("starting"))) {
782 return;
783 }
784 const now = yield* DateTime.now;
785 // Only started runs reached the provider-thread update below. Queued runs and
786 // failures during session setup cannot establish a new telemetry selection.
787 const measuredContext = latestNativeContextUsage(projection, providerThread);
788 const previousSelection =
789 measuredContext?.modelSelection ??
790 projection.runs.findLast(
791 (source) =>
792 source.ordinal < run.ordinal &&
793 source.startedAt !== null &&
794 source.providerThreadId === providerThread.id,
795 )?.modelSelection;
796 const sameSelection =
797 previousSelection === undefined ||
798 modelSelectionsEqual(previousSelection, run.modelSelection);
799 const sameNativeThread =
800 loadedProviderThread.nativeThreadRef?.nativeId === providerThread.nativeThreadRef?.nativeId;
801 const threadUsage = loadedProviderThread.contextUsage ?? providerThread.contextUsage;
802 const previousUsage = measuredContext
803 ? { ...threadUsage, ...measuredContext.usage }
804 : threadUsage;
805 const reuseTelemetry =
806 sameSelection ||
807 (previousSelection !== undefined &&
808 session.canReuseContextUsage?.(previousSelection, run.modelSelection) === true);
809 const knownModelWindow = session.getModelContextWindow?.(
810 run.modelSelection,
811 resolvedRuntimePolicy.cwd,
812 );
813 // Persist before delivery. Keep this native transcript's measured
814 // occupancy. A different model drops compaction telemetry and uses the
815 // new window when that window is known.
816 const handoffUsage = contextUsageForHandoff({
817 sameNativeThread,
818 sameSelection,
819 reuseTelemetry,
820 previousUsage,
821 knownModelWindow,
822 });
823 const runningProviderThread: OrchestrationV2ProviderThread = {
824 ...loadedProviderThread,
825 contextUsage: handoffUsage,
826 id: providerThread.id,
827 driver: session.driver,
828 providerInstanceId: run.providerInstanceId,
829 providerSessionId,
830 appThreadId: projection.thread.id,
831 ownerNodeId: providerThread.ownerNodeId,
832 firstRunOrdinal: providerThread.firstRunOrdinal ?? run.ordinal,
833 lastRunOrdinal: run.ordinal,
834 handoffIds: providerThread.handoffIds,
835 forkedFrom: providerThread.forkedFrom,
836 status: "active",
837 createdAt: providerThread.createdAt,
838 updatedAt: now,
839 };
840 const runningRun: OrchestrationV2Run = {
841 ...run,
842 status: "running",
843 startedAt: now,
844 };
845 const runningAttempt: OrchestrationV2RunAttempt = {
846 ...attempt,
847 ...(runningProviderThread.nativeThreadRef?.nativeId == null
848 ? {}
849 : { nativeThreadId: runningProviderThread.nativeThreadRef.nativeId }),
850 status: "running",
851 startedAt: now,
852 };
853 const runningRootNode: OrchestrationV2ExecutionNode = {
854 ...rootNode,
855 status: "running",
856 startedAt: now,
857 };
858 const events: Array<OrchestrationV2DomainEvent> = [
859 {
860 id: yield* idAllocator.allocate.event({
861 threadId: projection.thread.id,
862 providerSessionId,
863 }),
864 type: "provider-session.updated",
865 threadId: projection.thread.id,
866 driver: session.driver,
867 providerInstanceId: run.providerInstanceId,
868 occurredAt: now,
869 payload: session.providerSession,
870 },
871 {
872 id: yield* idAllocator.allocate.event({ threadId: projection.thread.id }),
873 type: "provider-thread.updated",
874 threadId: projection.thread.id,
875 driver: session.driver,
876 providerInstanceId: run.providerInstanceId,
877 occurredAt: now,
878 payload: runningProviderThread,
879 },
880 ...(nativeForkTransfer === undefined || runningProviderThread.nativeThreadRef === null
881 ? []
882 : [
883 {
884 id: yield* idAllocator.allocate.event({ threadId: projection.thread.id }),
885 type: "context-transfer.updated" as const,
886 threadId: projection.thread.id,
887 runId: run.id,
888 driver: session.driver,
889 providerInstanceId: run.providerInstanceId,
890 occurredAt: now,
891 payload: {
892 ...nativeForkTransfer,
893 targetProviderInstanceId: run.providerInstanceId,
894 targetRunId: run.id,
895 status: "consumed" as const,
896 resolution: {
897 strategy: "native_fork" as const,
898 providerThreadRef: runningProviderThread.nativeThreadRef,
899 },
900 error: null,
901 updatedAt: now,
902 consumedAt: now,
903 },
904 },
905 ]),
906 {
907 id: yield* idAllocator.allocate.event({ threadId: projection.thread.id }),
908 type: "run.updated",
909 threadId: projection.thread.id,
910 runId: run.id,
911 nodeId: rootNode.id,
912 providerInstanceId: run.providerInstanceId,
913 occurredAt: now,
914 payload: runningRun,
915 },
916 {
917 id: yield* idAllocator.allocate.event({ threadId: projection.thread.id }),
918 type: "run-attempt.updated",
919 threadId: projection.thread.id,
920 runId: run.id,
921 nodeId: rootNode.id,
922 providerInstanceId: run.providerInstanceId,
923 occurredAt: now,
924 payload: runningAttempt,
925 },
926 {
927 id: yield* idAllocator.allocate.event({ threadId: projection.thread.id }),
928 type: "node.updated",
929 threadId: projection.thread.id,
930 runId: run.id,
931 nodeId: rootNode.id,
932 providerInstanceId: run.providerInstanceId,
933 occurredAt: now,
934 payload: runningRootNode,
935 },
936 ];
937 const runningWrite = yield* eventSink.writeIfRunCurrent({
938 threadId: projection.thread.id,
939 runId: run.id,
940 activeAttemptId: attempt.id,
941 expectedStatus: "starting",
942 events,
943 });
944 if (!runningWrite.committed) {
945 return;
946 }
947 const routableSubagents = projection.subagents.filter((subagent) =>
948 RunExecutionService.canRouteRelatedSubagent(subagent.status),
949 );
950 const userText = projectComposerContextForProvider({
951 text: message.text,
952 records: message.context?.records ?? [],
953 });
954 // Delivered once: this run's provider turn marks the work as told. A
955 // restart continuation is prompted by its own text or resumes natively.
956 const noteContinuation = isRestartNoteContinuation(
957 run,
958 projection.runs,
959 projection.providerTurns,
960 projection.attempts,
961 );
962 const restartCancelledWork = pendingRestartCancelledBackgroundWork({
963 runs: projection.runs,
964 providerTurns: projection.providerTurns,
965 compactionMessageIds: new Set(
966 projection.messages
967 .filter(
968 (candidate) =>
969 candidate.attachments.length === 0 &&
970 candidate.text.trim().toLowerCase() === "/compact",
971 )
972 .map((candidate) => candidate.id),
973 ),
974 run,
975 attempts: projection.attempts,
976 });
977 const restartNote =
978 restartCancelledWork.length === 0
979 ? ""
980 : restartCancelledBackgroundWorkNote(restartCancelledWork);
981 const tokenCap = yield* handoffTokenCapConfig.pipe(
982 Effect.orElseSucceed(() => DEFAULT_HANDOFF_TOKEN_CAP),
983 );
984 const settledHandoffs = projection.contextHandoffs.filter(
985 (handoff) =>
986 handoff.toProviderThreadId === providerThread.id &&
987 handoff.delivery?.nativeThreadId === runningProviderThread.nativeThreadRef?.nativeId &&
988 handoff.delivery?.status !== "pending",
989 );
990 const deliveredItemIds = new Set(
991 settledHandoffs.flatMap((handoff) => handoff.delivery?.itemIds ?? []),
992 );
993 const coveredItemIds = new Set([
994 ...deliveredItemIds,
995 ...settledHandoffs.flatMap((handoff) => handoff.delivery?.omittedItemIds ?? []),
996 ]);
997 const deliveredAttemptIds = new Set(
998 projection.providerTurns.map((turn) => turn.runAttemptId),
999 );
1000 const acceptedAttempts = projection.attempts.filter(
1001 (source) =>
1002 source.providerThreadId === providerThread.id && deliveredAttemptIds.has(source.id),
1003 );
1004 const nativeInputRunIds = new Set(
1005 acceptedAttempts
1006 .filter(
1007 (source) =>
1008 source.nativeThreadId !== undefined &&
1009 source.nativeThreadId === runningProviderThread.nativeThreadRef?.nativeId,
1010 )
1011 .map((source) => source.runId),
1012 );
1013 const legacyInputRunIds = new Set(
1014 acceptedAttempts
1015 .filter((source) => source.nativeThreadId === undefined)
1016 .map((source) => source.runId),
1017 );
1018 const legacyRecoveredRunIds = new Set(
1019 projection.runs
1020 .filter(
1021 (source) =>
1022 source.providerThreadId === providerThread.id &&
1023 settledHandoffs.some(
1024 (handoff) =>
1025 handoff.strategy === "full_thread_summary" &&
1026 handoff.fromProviderThreadIds.includes(providerThread.id) &&
1027 source.ordinal >= handoff.coveredRunOrdinals.from &&
1028 source.ordinal <= handoff.coveredRunOrdinals.to,
1029 ),
1030 )
1031 .map((source) => source.id),
1032 );
1033 // Use saved text and actual native attachments when telemetry is absent.
1034 // Legacy attempts lack native identity; exclude their explicitly recovered
1035 // history, whose attachments were not replayed into the replacement thread.
1036 const nativeContextEstimate = Effect.gen(function* () {
1037 return sameNativeThread
1038 ? (yield* projectionStore.getTurnStartHistory(input.threadId)).reduce((sum, item) => {
1039 if (
1040 item.runId === run.id ||
1041 (item.runId !== null &&
1042 missedRunIds.has(item.runId) &&
1043 !deliveredItemIds.has(item.id)) ||
1044 (item.providerThreadId !== providerThread.id && !deliveredItemIds.has(item.id))
1045 )
1046 return sum;
1047 const historical = historicalMessage(item);
1048 const nativeAttachments =
1049 item.type === "user_message" &&
1050 item.providerThreadId === providerThread.id &&
1051 item.runId !== null &&
1052 (nativeInputRunIds.has(item.runId) ||
1053 (legacyInputRunIds.has(item.runId) &&
1054 !coveredItemIds.has(item.id) &&
1055 !legacyRecoveredRunIds.has(item.runId)))
1056 ? attachmentTokenAllowance(item.attachments)
1057 : 0;
1058 return (
1059 sum +
1060 (historical === null ? 0 : Buffer.byteLength(historical.text)) +
1061 nativeAttachments
1062 );
1063 }, 0)
1064 : 0;
1065 });
1066 const modelContextWindow =
1067 knownModelWindow ??
1068 (handoffUsage !== null || reuseTelemetry ? previousUsage?.maxTokens : undefined);
1069 // Replacing a native thread clears its usage, not the selected model's capacity.
1070 const budgetProviderThread = {
1071 ...runningProviderThread,
1072 contextUsage: handoffUsage,
1073 };
1074 const missedRuns = projection.runs.filter(
1075 (source) =>
1076 source.ordinal < run.ordinal &&
1077 source.providerThreadId === providerThread.id &&
1078 (source.status === "failed" || source.status === "interrupted") &&
1079 !deliveredAttemptIds.has(source.activeAttemptId),
1080 );
1081 const missedRunIds = new Set(missedRuns.map((source) => source.id));
1082 const missedItems =
1083 missedRunIds.size === 0
1084 ? []
1085 : (yield* projectionStore.getTurnStartHistory(input.threadId, [...missedRunIds])).filter(
1086 (item) =>
1087 item.runId !== null &&
1088 missedRunIds.has(item.runId) &&
1089 !coveredItemIds.has(item.id) &&
1090 historicalMessage(item) !== null,
1091 );
1092 const startWithHandoffs = (
1093 turnInput: Parameters<typeof session.startTurn>[0],
1094 compact = false,
1095 ) =>
1096 Effect.gen(function* () {
1097 // A failed turn/start can leave the requested turn absent from
1098 // native history even when its preceding handoff was injected.
1099 const retryHandoff =
1100 missedItems.length === 0
1101 ? []
1102 : [
1103 yield* contextHandoffService.prepareProviderHandoff({
1104 threadId: projection.thread.id,
1105 targetRunId: run.id,
1106 transferId: null,
1107 fromProviderThreadIds: [providerThread.id],
1108 toProviderThreadId: providerThread.id,
1109 fromProviderInstanceId: run.providerInstanceId,
1110 toProviderInstanceId: run.providerInstanceId,
1111 coveredRunOrdinals: {
1112 from: missedRuns[0]!.ordinal,
1113 to: missedRuns.at(-1)!.ordinal,
1114 },
1115 strategy: "delta_since_target_last_seen",
1116 items: missedItems,
1117 runs: projection.runs,
1118 createdAt: yield* DateTime.now,
1119 }),
1120 ];
1121 const delivery = yield* deliverContextHandoffs({
1122 handoffs: [...effectiveHandoffs, ...retryHandoff],
1123 deferInline: compact,
1124 providerThread: runningProviderThread,
1125 budget: Effect.gen(function* () {
1126 return handoffBudget({
1127 tokenCap,
1128 modelContextWindow,
1129 // The note is sent with the user text, so it spends the same allowance.
1130 userText: restartNote === "" ? userText : `${restartNote}\n\n${userText}`,
1131 attachments: message.attachments,
1132 providerThread: budgetProviderThread,
1133 nativeContextEstimate:
1134 budgetProviderThread.contextUsage?.usedTokens === undefined
1135 ? yield* nativeContextEstimate
1136 : 0,
1137 });
1138 }),
1139 alreadyDeliveredItemIds: deliveredItemIds,
1140 ...(session.injectHistory === undefined
1141 ? {}
1142 : {
1143 inject: (history: ProviderAdapter.ProviderAdapterV2HistoricalContext) =>
1144 session.injectHistory!({
1145 providerThread: runningProviderThread,
1146 ...history,
1147 }),
1148 }),
1149 persist: (handoff) =>
1150 Effect.gen(function* () {
1151 const updatedAt = yield* DateTime.now;
1152 yield* eventSink.write({
1153 events: [
1154 {
1155 id: yield* idAllocator.allocate.event({
1156 threadId: projection.thread.id,
1157 }),
1158 type: "context-handoff.updated",
1159 threadId: projection.thread.id,
1160 runId: run.id,
1161 providerInstanceId: run.providerInstanceId,
1162 occurredAt: updatedAt,
1163 payload: { ...handoff, updatedAt },
1164 },
1165 ],
1166 });
1167 }),
1168 });
1169 if (!(yield* isCurrentAttemptInStatus("running"))) return;
1170 const start = compact ? session.compactThread! : session.startTurn;
1171 const context = [delivery.context, restartNote]
1172 .filter((part) => part !== "")
1173 .join("\n\n");
1174 // A note continuation has no turn to resume; its text is the prompt.
1175 const { restartContinuationOfRunId: _resumedRunId, ...promptedInput } = turnInput;
1176 yield* start({
1177 ...(noteContinuation ? promptedInput : turnInput),
1178 message: {
1179 ...turnInput.message,
1180 text: context === "" ? userText : `${context}\n\nUser message:\n${userText}`,
1181 },
1182 }).pipe(
1183 // A pending marker would make the next turn abandon this native
1184 // session, though the refused prompt never reached it.
1185 Effect.tapError((error) =>
1186 refusedBeforePrompt(error)
1187 ? delivery.unsent.pipe(
1188 Effect.catchCause(() =>
1189 Effect.logWarning("Failed to restore unsent context handoffs", {
1190 runId: run.id,
1191 }),
1192 ),
1193 )
1194 : Effect.void,
1195 ),
1196 );
1197 // The provider already accepted the turn. A stale pending marker
1198 // can force a fresh thread later, but must not stop live ingestion.
1199 yield* delivery.delivered.pipe(
1200 Effect.catchCause(() =>
1201 Effect.logWarning("Failed to record accepted context handoff delivery", {
1202 runId: run.id,
1203 deliveryStatus: "pending",
1204 }),
1205 ),
1206 );
1207 }).pipe(
1208 Effect.mapError((cause) =>
1209 cause._tag === "ProviderAdapterTurnStartError"
1210 ? cause
1211 : new ProviderAdapter.ProviderAdapterTurnStartError({
1212 driver: session.driver,
1213 threadId: projection.thread.id,
1214 providerThreadId: providerThread.id,
1215 runId: run.id,
1216 cause,
1217 }),
1218 ),
1219 );
1220 const deliverySession =
1221 effectiveHandoffs.length === 0 &&
1222 missedItems.length === 0 &&
1223 restartNote === "" &&
1224 !noteContinuation
1225 ? session
1226 : makeDeliverySession(session, startWithHandoffs);
1227 yield* runExecution.startRootRun({
1228 commandId: CommandId.make(`command:effect:provider-turn.start:${run.id}`),
1229 appThread: projection.thread,
1230 providerSessionId,
1231 session: deliverySession,
1232 run: runningRun,
1233 rootNode: runningRootNode,
1234 checkpointScope,
1235 providerThread: runningProviderThread,
1236 attempt: runningAttempt,
1237 attemptId: attempt.id,
1238 loadInheritedBackgroundTurnItems: runControls.loadInheritedBackgroundTurnItems,
1239 relatedThreadIds: routableSubagents.flatMap((subagent) =>
1240 subagent.childThreadId === null ? [] : [subagent.childThreadId],
1241 ),
1242 relatedProviderThreadIds: routableSubagents.flatMap((subagent) =>
1243 subagent.providerThreadId === null ? [] : [subagent.providerThreadId],
1244 ),
1245 providerTurnOrdinal:
1246 Math.max(
1247 0,
1248 ...projection.providerTurns
1249 .filter((turn) => turn.providerThreadId === providerThread.id)
1250 .map((turn) => turn.ordinal),
1251 ) + 1,
1252 // Legacy accepted attempts have no native id. They count only before
1253 // a replacement, while no accepted attempt records a native identity.
1254 nativeThreadHasTurns:
1255 nativeInputRunIds.size > 0 ||
1256 (legacyInputRunIds.size > 0 &&
1257 sameNativeThread &&
1258 !acceptedAttempts.some((source) => source.nativeThreadId !== undefined)),
1259 shouldStartProviderTurn: runControls.shouldStartProviderTurn,
1260 shouldFinalizeRun: runControls.shouldFinalizeRun,
1261 hasUnpairedRunInterruptRequest: runControls.hasUnpairedRunInterruptRequest,
1262 message: {
1263 messageId: message.id,
1264 text: userText,
1265 attachments: message.attachments,
1266 createdBy: message.createdBy,
1267 creationSource: message.creationSource,
1268 ...(message.scheduledTaskId === undefined
1269 ? {}
1270 : { scheduledTaskId: message.scheduledTaskId }),
1271 ...(message.senderThreadId === undefined
1272 ? {}
1273 : { senderThreadId: message.senderThreadId }),
1274 },
1275 modelSelection: run.modelSelection,
1276 runtimePolicy: resolvedRuntimePolicy,
1277 });
1278 });
1279
1280 return ProviderTurnStartServiceV2.of({
1281 start: (input) =>
1282 start(input).pipe(
1283 Effect.mapError((cause) =>
1284 isProviderTurnStartError(cause)
1285 ? cause
1286 : new ProviderTurnStartError({ runId: input.runId, cause }),
1287 ),
1288 ),
1289 });
1290 }),
1291);