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