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