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

ProviderTurnStartService.ts

1,294 lines52.5 KB

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