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