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

ProviderTurnStartService.ts

1,267 lines51.2 KB

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