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

ProviderTurnStartService.ts

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