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

ProviderTurnStartService.ts

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