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