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