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

ProviderTurnStartService.ts

1,362 lines55.0 KB

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