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

ProviderTurnStartService.ts

1,274 lines51.6 KB

1import { modelSelectionsEqual } from "@t3tools/shared/model";
2import { projectComposerContextForProvider } from "@t3tools/shared/composerContextReferences";
3import {
4 CommandId,
5 latestProviderTurnForAttempt,
6 type OrchestrationV2DomainEvent,
7 type OrchestrationV2ExecutionNode,
8 type OrchestrationV2ProviderThread,
9 type OrchestrationV2Run,
10 type OrchestrationV2RunAttempt,
11 type OrchestrationV2TurnItem,
12 RunId,
13 ThreadId,
14} from "@t3tools/contracts";
15import * as Context from "effect/Context";
16import * as Cause from "effect/Cause";
17import * as DateTime from "effect/DateTime";
18import * as Effect from "effect/Effect";
19import * as FileSystem from "effect/FileSystem";
20import * as Layer from "effect/Layer";
21import * as Option from "effect/Option";
22import * as Schema from "effect/Schema";
23​
24import * as GitWorkflowService from "../git/GitWorkflowService.ts";
25import * as ProjectService from "../project/ProjectService.ts";
26import * as ProviderAuthService from "../provider/ProviderAuthService.ts";
27import * as EventSink from "./EventSink.ts";
28import * as ContextHandoffService from "./ContextHandoffService.ts";
29import {
30 DEFAULT_HANDOFF_TOKEN_CAP,
31 handoffTokenCapConfig,
32 handoffBudget,
33 attachmentTokenAllowance,
34 contextUsageForHandoff,
35 historicalMessage,
36 latestNativeContextUsage,
37} from "./ContextHandoffBudget.ts";
38import { deliverContextHandoffs } from "./ContextHandoffDelivery.ts";
39import {
40 ProviderAdapterTurnStartError,
41 type ProviderAdapterV2Error,
42 type ProviderAdapterV2HistoricalContext,
43 type ProviderAdapterV2SessionRuntime,
44} from "./ProviderAdapter.ts";
45import * as IdAllocator from "./IdAllocator.ts";
46import * as ProjectionStore from "./ProjectionStore.ts";
47import * as ProviderSessionManager from "./ProviderSessionManager.ts";
48import { makeProviderFailure } from "./ProviderFailure.ts";
49import * as RunExecutionService from "./RunExecutionService.ts";
50import * as RuntimePolicy from "./RuntimePolicy.ts";
51import {
52 isRestartNoteContinuation,
53 pendingRestartCancelledBackgroundWork,
54 restartCancelledBackgroundWorkNote,
55} from "./RestartBackgroundNote.ts";
56​
57export class ProviderTurnStartError extends Schema.TaggedError<ProviderTurnStartError>()(
58 "ProviderTurnStartError",
59 {
60 runId: RunId,
61 cause: Schema.optional(Schema.Defect()),
62 },
63) {}
64​
65const isProviderTurnStartError = Schema.is(ProviderTurnStartError);
66​
67export interface ProviderTurnStartServiceV2Shape {
68 /**
69 * Starts the run's provider turn. When `willRetry` is true, a session open
70 * failure is returned so the caller can retry. Otherwise the run is settled
71 * as failed.
72 */
73 readonly start: (input: {
74 readonly threadId: ThreadId;
75 readonly runId: RunId;
76 readonly willRetry?: boolean;
77 }) => Effect.Effect<void, ProviderTurnStartError>;
79​
80export class ProviderTurnStartServiceV2 extends Context.Service<
81 ProviderTurnStartServiceV2,
82 ProviderTurnStartServiceV2Shape
83>()("t3/orchestration-v2/ProviderTurnStartService/ProviderTurnStartServiceV2") {}
84​
85export const layer: Layer.Layer<
86 ProviderTurnStartServiceV2,
87 never,
88 | EventSink.EventSinkV2
89 | ContextHandoffService.ContextHandoffServiceV2
90 | IdAllocator.IdAllocatorV2
91 | FileSystem.FileSystem
92 | GitWorkflowService.GitWorkflowService
93 | ProjectService.ProjectService
94 | ProviderAuthService.ProviderAuthService
95 | ProjectionStore.ProjectionStoreV2
96 | ProviderSessionManager.ProviderSessionManagerV2
97 | RunExecutionService.RunExecutionServiceV2
98 | RuntimePolicy.RuntimePolicyV2
99> = Layer.effect(
100 ProviderTurnStartServiceV2,
101 Effect.gen(function* () {
102 const eventSink = yield* EventSink.EventSinkV2;
103 const contextHandoffService = yield* ContextHandoffService.ContextHandoffServiceV2;
104 const idAllocator = yield* IdAllocator.IdAllocatorV2;
105 const fileSystem = yield* FileSystem.FileSystem;
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 // Guards and background routing need live execution state, not a fresh
127 // allocation of every completed message and tool output in the thread.
128 // `false` means the run moved on or is gone. A failed read is an error,
129 // so the caller fails the start or the run instead of skipping it.
130 const isCurrentAttemptInStatus = (expectedStatus: OrchestrationV2Run["status"]) =>
131 projectionStore.getRuntimeRecoveryProjection(input.threadId).pipe(
132 Effect.map((current) => {
133 const run = current.runs.find((candidate) => candidate.id === input.runId);
134 return run?.activeAttemptId === input.attemptId && run.status === expectedStatus;
135 }),
136 );
137 return {
138 isCurrentAttemptInStatus,
139 loadInheritedBackgroundTurnItems: () =>
140 projectionStore.getRuntimeRecoveryProjection(input.threadId).pipe(
141 Effect.map((current) =>
142 RunExecutionService.selectInheritedBackgroundTurnItems({
143 threadId: input.threadId,
144 currentProviderThreadId: input.providerThreadId,
145 currentRunOrdinal: input.runOrdinal,
146 runs: current.runs,
147 turnItems: current.turnItems,
148 }),
149 ),
150 Effect.catchCause(() => Effect.succeed(input.inheritedBackgroundTurnItems)),
151 ),
152 shouldStartProviderTurn: () => isCurrentAttemptInStatus("running"),
153 shouldFinalizeRun: () =>
154 projectionStore.getRuntimeRecoveryProjection(input.threadId).pipe(
155 Effect.map((current) => {
156 const run = current.runs.find((candidate) => candidate.id === input.runId);
157 return (
158 run?.activeAttemptId === input.attemptId &&
159 (run.status === "starting" || run.status === "running")
160 );
161 }),
162 ),
163 hasUnpairedRunInterruptRequest: () =>
164 projectionStore
165 .hasUnpairedRunInterruptRequest(
166 input.threadId,
167 idAllocator.derive.runSignalTurnItem({
168 runId: input.runId,
169 signal: "interrupt-request",
170 }),
171 idAllocator.derive.runSignalTurnItem({
172 runId: input.runId,
173 signal: "interrupt-result",
174 }),
175 )
176 .pipe(Effect.catchCause(() => Effect.succeed(false))),
177 };
178 };
179​
180 const makeDeliverySession = (
181 session: ProviderAdapterV2SessionRuntime,
182 startWithHandoffs: (
183 input: Parameters<ProviderAdapterV2SessionRuntime["startTurn"]>[0],
184 compact?: boolean,
185 ) => ReturnType<ProviderAdapterV2SessionRuntime["startTurn"]>,
186 ) => {
187 let deliver: typeof startWithHandoffs | undefined = startWithHandoffs;
188 const start = (
189 input: Parameters<ProviderAdapterV2SessionRuntime["startTurn"]>[0],
190 compact = false,
191 ) =>
192 Effect.suspend(() => {
193 if (deliver !== undefined) return deliver(input, compact);
194 return compact && session.compactThread !== undefined
195 ? session.compactThread(input)
196 : session.startTurn(input);
197 }).pipe(
198 // Only startup needs the handoff history. The event worker keeps this
199 // session alive afterward, including when background work remains.
200 Effect.ensuring(
201 Effect.sync(() => {
202 deliver = undefined;
203 }),
204 ),
205 );
206 return {
207 ...session,
208 startTurn: (input: Parameters<typeof session.startTurn>[0]) => start(input),
209 ...(session.compactThread === undefined
210 ? {}
211 : {
212 compactThread: (input: Parameters<typeof session.startTurn>[0]) => start(input, true),
213 }),
214 };
215 };
216​
217 const start = Effect.fn("orchestrationV2.providerTurnStart.start")(function* (input: {
218 readonly threadId: ThreadId;
219 readonly runId: RunId;
220 readonly willRetry?: boolean;
221 }) {
222 const { runId } = input;
223 const projection = yield* projectionStore.getTurnStartContext(input.threadId, runId);
224 const run = projection.runs.find((candidate) => candidate.id === runId);
225 if (run === undefined) {
226 return yield* new ProviderTurnStartError({ runId, cause: `Run ${runId} was not found.` });
227 }
228 if (run.status !== "starting") {
229 // The effect is idempotent once the run has advanced or terminalized.
230 return;
231 }
232 const rootNode = projection.nodes.find((candidate) => candidate.id === run.rootNodeId);
233 const attempt = projection.attempts.find((candidate) => candidate.id === run.activeAttemptId);
234 const providerThread = projection.providerThreads.find(
235 (candidate) => candidate.id === run.providerThreadId,
236 );
237 const message = projection.messages.find((candidate) => candidate.id === run.userMessageId);
238 const checkpointScope = projection.checkpointScopes.find(
239 (candidate) => candidate.id === rootNode?.checkpointScopeId,
240 );
241 const handoffs = projection.contextHandoffs.filter(
242 (handoff) =>
243 handoff.status === "ready" &&
244 (handoff.targetRunId === run.id ||
245 (handoff.toProviderThreadId === run.providerThreadId &&
246 projection.runs.some(
247 (source) =>
248 source.id === handoff.targetRunId &&
249 (source.status === "failed" ||
250 source.status === "interrupted" ||
251 (source.status === "completed" &&
252 handoff.delivery === undefined &&
253 projection.messages.some(
254 (message) =>
255 message.id === source.userMessageId &&
256 message.attachments.length === 0 &&
257 message.text.trim().toLowerCase() === "/compact",
258 ))),
259 ))),
260 );
261 const nativeForkTransfer = projection.contextTransfers.find(
262 (transfer) =>
263 transfer.type === "fork" &&
264 transfer.targetThreadId === input.threadId &&
265 transfer.targetRunId === run.id &&
266 transfer.status === "pending" &&
267 transfer.resolution === null,
268 );
269 if (
270 rootNode === undefined ||
271 attempt === undefined ||
272 providerThread === undefined ||
273 providerThread.providerSessionId === null ||
274 message === undefined ||
275 checkpointScope === undefined
276 ) {
277 return yield* new ProviderTurnStartError({
278 runId,
279 cause: `Run ${runId} is missing its execution projection state.`,
280 });
281 }
282 // Settles a run that never reached the provider: one signal turn item plus
283 // terminal run, attempt and root node, written only while the run is still
284 // the current starting attempt.
285 const settleRunBeforeStart = Effect.fn("orchestrationV2.providerTurnStart.settleBeforeStart")(
286 function* (input: {
287 readonly signal: string;
288 readonly status: "completed" | "failed";
289 readonly now: DateTime.Utc;
290 /** Omitted when the run never started, so `startedAt` stays as projected. */
291 readonly startedAt?: DateTime.Utc;
292 readonly providerInstanceId: OrchestrationV2Run["providerInstanceId"];
293 readonly itemProviderThreadId: OrchestrationV2ProviderThread["id"];
294 readonly item:
295 | Pick<
296 Extract<OrchestrationV2TurnItem, { type: "error" }>,
297 "type" | "title" | "failure"
298 >
299 | Pick<
300 Extract<OrchestrationV2TurnItem, { type: "command_execution" }>,
301 "type" | "title" | "input" | "output" | "exitCode"
302 >;
303 /** Emitted after the run events when the provider thread should go idle. */
304 readonly providerThreadUpdate?: OrchestrationV2ProviderThread;
305 }) {
306 const { now, status } = input;
307 const started = input.startedAt === undefined ? {} : { startedAt: input.startedAt };
308 const item: OrchestrationV2TurnItem = {
309 id: idAllocator.derive.runSignalTurnItem({ runId, signal: input.signal }),
310 threadId: projection.thread.id,
311 runId,
312 nodeId: rootNode.id,
313 providerThreadId: input.itemProviderThreadId,
314 providerTurnId: null,
315 nativeItemRef: null,
316 parentItemId: null,
317 ordinal:
318 Math.max(
319 0,
320 ...projection.turnItems
321 .filter((item) => item.runId === runId)
322 .map((item) => item.ordinal),
323 ) + 1,
324 status,
325 startedAt: now,
326 completedAt: now,
327 updatedAt: now,
328 ...input.item,
329 };
330 const eventPayloads = [
331 { type: "turn-item.updated", payload: item },
332 { type: "run.updated", payload: { ...run, status, ...started, completedAt: now } },
333 {
334 type: "run-attempt.updated",
335 payload: { ...attempt, status, ...started, completedAt: now },
336 },
337 {
338 type: "node.updated",
339 payload: { ...rootNode, status, ...started, completedAt: now },
340 },
341 ...(input.providerThreadUpdate === undefined
342 ? []
343 : [
344 {
345 type: "provider-thread.updated" as const,
346 payload: input.providerThreadUpdate,
347 },
348 ]),
349 ] as const;
350 const events = yield* Effect.forEach(eventPayloads, (event) =>
351 Effect.gen(function* () {
352 return {
353 ...event,
354 id: yield* idAllocator.allocate.event({ threadId: projection.thread.id }),
355 threadId: projection.thread.id,
356 runId,
357 nodeId: rootNode.id,
358 providerInstanceId: input.providerInstanceId,
359 occurredAt: now,
360 } satisfies OrchestrationV2DomainEvent;
361 }),
362 );
363 yield* eventSink.writeIfRunCurrent({
364 threadId: projection.thread.id,
365 runId,
366 activeAttemptId: attempt.id,
367 expectedStatus: "starting",
368 events,
369 });
370 },
371 );
372 if (message.attachments.length === 0 && message.text.trimStart().startsWith("/")) {
373 const isEmptyCompaction =
374 message.text.trim().toLowerCase() === "/compact" && !projection.hasConversation;
375 // Preparing a run may already point the thread at a newly selected
376 // provider. Account commands still belong to its last native session.
377 const nativeThreads = new Map(
378 projection.providerThreads
379 .filter(
380 (candidate) => candidate.ownerNodeId === null && candidate.nativeThreadRef !== null,
381 )
382 .map((candidate) => [candidate.id, candidate]),
383 );
384 const previousNativeRun = projection.runs.reduce<OrchestrationV2Run | undefined>(
385 (previous, candidate) =>
386 candidate.ordinal < run.ordinal &&
387 candidate.providerThreadId !== null &&
388 nativeThreads.has(candidate.providerThreadId) &&
389 (previous === undefined || candidate.ordinal > previous.ordinal)
390 ? candidate
391 : previous,
392 undefined,
393 );
394 const nativeThread = nativeThreads.get(
395 previousNativeRun?.providerThreadId ??
396 projection.thread.activeProviderThreadId ??
397 providerThread.id,
398 );
399 const authInstanceId = nativeThread?.providerInstanceId ?? run.providerInstanceId;
400 const authResult = isEmptyCompaction
401 ? null
402 : yield* Effect.result(
403 providerAuth.tryHandlePromptCommand({
404 instanceId: authInstanceId,
405 text: projectComposerContextForProvider({
406 text: message.text,
407 records: message.context?.records ?? [],
408 }),
409 hasAttachments: false,
410 }),
411 );
412 if (isEmptyCompaction || authResult?._tag === "Failure" || authResult?.success) {
413 const now = yield* DateTime.now;
414 const failure = isEmptyCompaction
415 ? makeProviderFailure({
416 class: "validation_error",
417 message: "Start a conversation before compacting this thread.",
418 })
419 : authResult?._tag === "Failure"
420 ? makeProviderFailure({
421 class: "permission_error",
422 message: authResult.failure.detail,
423 })
424 : undefined;
425 const status = failure === undefined ? "completed" : "failed";
426 yield* settleRunBeforeStart({
427 signal: isEmptyCompaction ? "empty-compaction" : "provider-sign-out",
428 status,
429 now,
430 startedAt: now,
431 providerInstanceId: authInstanceId,
432 itemProviderThreadId: nativeThread?.id ?? providerThread.id,
433 item:
434 failure !== undefined
435 ? {
436 type: "error",
437 title: isEmptyCompaction
438 ? "Cannot compact an empty thread"
439 : "Provider sign-out failed",
440 failure,
441 }
442 : {
443 type: "command_execution",
444 title: "Provider signed out",
445 input: message.text.trim(),
446 output: "Provider signed out",
447 exitCode: 0,
448 },
449 providerThreadUpdate: {
450 ...providerThread,
451 status: providerThread.nativeThreadRef === null ? "not_loaded" : "idle",
452 updatedAt: now,
453 },
454 });
455 return;
456 }
457 }
458 const { worktreePath, branch } = projection.thread;
459 if (worktreePath !== null && branch !== null) {
460 const exists = yield* fileSystem
461 .exists(worktreePath)
462 .pipe(Effect.orElseSucceed(() => true));
463 if (!exists) {
464 const project = yield* projects.getById(projection.thread.projectId).pipe(
465 Effect.map(Option.getOrUndefined),
466 Effect.orElseSucceed(() => undefined),
467 );
468 if (project !== undefined) {
469 yield* Effect.logWarning("provider turn start recreating missing worktree", {
470 threadId: projection.thread.id,
471 worktreePath,
472 branch,
473 });
474 yield* gitWorkflow.pruneWorktrees({ cwd: project.workspaceRoot }).pipe(
475 Effect.andThen(
476 gitWorkflow.createWorktree({
477 cwd: project.workspaceRoot,
478 refName: branch,
479 path: worktreePath,
480 }),
481 ),
482 Effect.catchCause((cause) =>
483 Cause.hasInterruptsOnly(cause)
484 ? Effect.failCause(cause)
485 : Effect.logWarning("provider turn start failed to recreate worktree", {
486 threadId: projection.thread.id,
487 worktreePath,
488 cause: Cause.pretty(cause),
489 }),
490 ),
491 );
492 }
493 }
494 }
495 const selectInheritedBackgroundItems = (
496 current: ProjectionStore.ProjectionRuntimeRecoveryState,
497 ): ReturnType<typeof RunExecutionService.selectInheritedBackgroundTurnItems> =>
498 RunExecutionService.selectInheritedBackgroundTurnItems({
499 threadId: current.thread.id,
500 currentProviderThreadId: providerThread.id,
501 currentRunOrdinal: run.ordinal,
502 runs: current.runs,
503 turnItems: current.turnItems,
504 });
505 const inheritedBackgroundTurnItems = yield* projectionStore
506 .getRuntimeRecoveryProjection(projection.thread.id)
507 .pipe(Effect.map(selectInheritedBackgroundItems));
508 const providerSessionId = providerThread.providerSessionId;
509 const runControls = makeRunControls({
510 threadId: projection.thread.id,
511 runId: run.id,
512 attemptId: attempt.id,
513 providerThreadId: providerThread.id,
514 runOrdinal: run.ordinal,
515 inheritedBackgroundTurnItems,
516 });
517 const { isCurrentAttemptInStatus } = runControls;
518​
519 const resolvedRuntimePolicy = yield* runtimePolicy.resolve({
520 thread: projection.thread,
521 modelSelection: run.modelSelection,
522 });
523 const existingSessionProjection = projection.providerSessions.find(
524 (candidate) => candidate.id === providerSessionId,
525 );
526 const sessionResult = yield* Effect.result(
527 providerSessions.open({
528 threadId: projection.thread.id,
529 providerSessionId,
530 modelSelection: run.modelSelection,
531 runtimePolicy: resolvedRuntimePolicy,
532 ...(existingSessionProjection === undefined
533 ? {}
534 : { resumeFromSession: existingSessionProjection }),
535 ...(providerThread.nativeThreadRef?.nativeId == null
536 ? {}
537 : { initialNativeThreadId: providerThread.nativeThreadRef.nativeId }),
538 ...(providerThread.nativeMetadata?.itemIdentityVersion === undefined
539 ? {}
540 : {
541 initialProviderItemIdentityVersion:
542 providerThread.nativeMetadata.itemIdentityVersion,
543 }),
544 }),
545 );
546 // The last start attempt fails the run with the provider's own reason
547 // instead of leaving it `starting` after the effect gives up. A run that
548 // already left `starting` is not overwritten, and a failed write returns
549 // its error to the effect worker.
550 const settleStartFailure = (failed: {
551 readonly signal: string;
552 readonly title: string;
553 readonly error: Error;
554 }) =>
555 Effect.gen(function* () {
556 const nestedCause = "cause" in failed.error ? failed.error.cause : undefined;
557 yield* settleRunBeforeStart({
558 signal: failed.signal,
559 status: "failed",
560 now: yield* DateTime.now,
561 providerInstanceId: run.providerInstanceId,
562 itemProviderThreadId: providerThread.id,
563 item: {
564 type: "error",
565 title: failed.title,
566 failure: makeProviderFailure({
567 cause: failed.error,
568 message:
569 nestedCause instanceof Error
570 ? nestedCause.message
571 : typeof nestedCause === "string"
572 ? nestedCause
573 : failed.error.message,
574 class: "provider_error",
575 }),
576 },
577 });
578 });
579 if (sessionResult._tag === "Failure") {
580 if (input.willRetry === true) return yield* sessionResult.failure;
581 yield* settleStartFailure({
582 signal: "provider-session-open-failure",
583 title: "Provider session failed to open",
584 error: sessionResult.failure,
585 });
586 return;
587 }
588 const session = sessionResult.success;
589 // Only the provider's own thread load fails the run on the last attempt;
590 // store, id and handoff failures around it keep their typed errors.
591 const loadFromProvider = (
592 load: Effect.Effect<OrchestrationV2ProviderThread, ProviderAdapterV2Error>,
593 ) =>
594 Effect.gen(function* () {
595 const loaded = yield* Effect.result(load);
596 if (loaded._tag === "Success") return loaded.success;
597 if (input.willRetry === true) return yield* loaded.failure;
598 yield* settleStartFailure({
599 signal: "provider-thread-load-failure",
600 title: "Provider turn failed to start",
601 error: loaded.failure,
602 });
603 return undefined;
604 });
605 let effectiveHandoffs = handoffs;
606 const loadedProviderThread = yield* Effect.gen(function* () {
607 if (nativeForkTransfer !== undefined) {
608 const sourceProjection = yield* projectionStore.getThreadRecords(
609 nativeForkTransfer.sourceThreadId,
610 ["runs", "providerThreads", "attempts", "providerTurns"],
611 );
612 const sourceRun = sourceProjection.runs.find(
613 (candidate) => candidate.id === nativeForkTransfer.sourcePoint.runId,
614 );
615 const sourceProviderThread = sourceProjection.providerThreads.find(
616 (candidate) => candidate.id === sourceRun?.providerThreadId,
617 );
618 const sourceAttempt = sourceProjection.attempts.find(
619 (candidate) => candidate.id === sourceRun?.activeAttemptId,
620 );
621 const sourceProviderTurn =
622 latestProviderTurnForAttempt(sourceProjection.providerTurns, sourceAttempt?.id) ??
623 sourceProjection.providerTurns.find(
624 (candidate) => candidate.id === sourceAttempt?.providerTurnId,
625 );
626 if (sourceRun === undefined || sourceProviderThread === undefined) {
627 return yield* new ProviderTurnStartError({
628 runId,
629 cause: `Native fork transfer ${nativeForkTransfer.id} has no source provider execution.`,
630 });
631 }
632 return yield* loadFromProvider(
633 session.forkThread({
634 sourceProviderThread,
635 sourceProviderTurns: sourceProjection.providerTurns,
636 targetThreadId: projection.thread.id,
637 modelSelection: run.modelSelection,
638 runtimePolicy: resolvedRuntimePolicy,
639 ...(sourceProviderTurn === undefined
640 ? {}
641 : { providerTurnId: sourceProviderTurn.id }),
642 }),
643 );
644 }
645 if (providerThread.nativeThreadRef === null) {
646 // Hand the run's provider thread to the adapter so it adopts this
647 // row's identity when attaching native state. An adapter that mints
648 // its own row instead leaves two live rows per app thread, and
649 // `activeProviderThreadId` then flaps between them on every update.
650 return yield* loadFromProvider(
651 session.ensureThread({
652 threadId: projection.thread.id,
653 modelSelection: run.modelSelection,
654 runtimePolicy: resolvedRuntimePolicy,
655 providerSessionId,
656 existingProviderThread: providerThread,
657 }),
658 );
659 }
660 const uncertainDelivery = projection.contextHandoffs.some(
661 (handoff) =>
662 handoff.toProviderThreadId === providerThread.id &&
663 handoff.delivery?.nativeThreadId === providerThread.nativeThreadRef?.nativeId &&
664 handoff.delivery?.status === "pending",
665 );
666 const resumed = yield* Effect.result(
667 uncertainDelivery
668 ? Effect.fail(
669 new ProviderAdapterTurnStartError({
670 driver: session.driver,
671 threadId: projection.thread.id,
672 providerThreadId: providerThread.id,
673 runId,
674 cause: "Uncertain native history injection",
675 }),
676 )
677 : session.resumeThread({
678 providerThread,
679 threadId: projection.thread.id,
680 modelSelection: run.modelSelection,
681 runtimePolicy: resolvedRuntimePolicy,
682 }),
683 );
684 if (resumed._tag === "Success") {
685 return resumed.success;
686 }
687​
688 yield* Effect.logWarning("Provider resume failed; attempting a fresh native session", {
689 driver: session.driver,
690 providerThreadId: providerThread.id,
691 runId,
692 reason: uncertainDelivery ? "uncertain_history_delivery" : "resume_failed",
693 errorTag: resumed.failure._tag,
694 });
695 const replacement = yield* loadFromProvider(
696 session.ensureThread({
697 threadId: projection.thread.id,
698 modelSelection: run.modelSelection,
699 runtimePolicy: resolvedRuntimePolicy,
700 providerSessionId,
701 // The native ref is dropped so the adapter binds a fresh native
702 // session instead of retrying the resume that just failed, while
703 // still adopting this row's identity.
704 existingProviderThread: { ...providerThread, nativeThreadRef: null },
705 }),
706 );
707 if (replacement === undefined) return undefined;
708 const transferId = yield* idAllocator.allocate.contextTransfer({
709 sourceThreadId: projection.thread.id,
710 targetThreadId: projection.thread.id,
711 type: "provider_resume_fallback",
712 });
713 const createdAt = yield* DateTime.now;
714 const handoff = yield* contextHandoffService.prepareProviderHandoff({
715 threadId: projection.thread.id,
716 targetRunId: run.id,
717 transferId,
718 fromProviderThreadIds: [providerThread.id],
719 toProviderThreadId: providerThread.id,
720 fromProviderInstanceId: providerThread.providerInstanceId,
721 toProviderInstanceId: run.providerInstanceId,
722 coveredRunOrdinals: { from: 1, to: Math.max(1, run.ordinal - 1) },
723 strategy: "full_thread_summary",
724 runs: projection.runs,
725 items: (yield* projectionStore.getTurnStartHistory(input.threadId)).filter(
726 (item) =>
727 item.runId === null ||
728 projection.runs.some(
729 (source) => source.id === item.runId && source.ordinal < run.ordinal,
730 ),
731 ),
732 createdAt,
733 });
734 effectiveHandoffs = [handoff, ...effectiveHandoffs];
735 yield* eventSink.write({
736 events: [
737 {
738 id: yield* idAllocator.allocate.event({ threadId: projection.thread.id }),
739 type: "context-handoff.updated",
740 threadId: projection.thread.id,
741 runId: run.id,
742 providerInstanceId: run.providerInstanceId,
743 occurredAt: createdAt,
744 payload: handoff,
745 },
746 {
747 id: yield* idAllocator.allocate.event({ threadId: projection.thread.id }),
748 type: "context-transfer.updated",
749 threadId: projection.thread.id,
750 runId: run.id,
751 providerInstanceId: run.providerInstanceId,
752 occurredAt: createdAt,
753 payload: {
754 id: transferId,
755 type: "provider_handoff",
756 sourceThreadId: projection.thread.id,
757 targetThreadId: projection.thread.id,
758 sourcePoint: { threadId: projection.thread.id },
759 basePoint: null,
760 sourceProviderInstanceId: providerThread.providerInstanceId,
761 targetProviderInstanceId: run.providerInstanceId,
762 targetRunId: run.id,
763 status: "resolved_portable",
764 resolution: { strategy: "portable_context", contextHandoffId: handoff.id },
765 createdBy: "system",
766 error: null,
767 createdAt,
768 updatedAt: createdAt,
769 consumedAt: null,
770 },
771 },
772 ],
773 });
774 return replacement;
775 });
776 // The last attempt already failed the run.
777 if (loadedProviderThread === undefined) return;
778 if (!(yield* isCurrentAttemptInStatus("starting"))) {
779 return;
780 }
781 const now = yield* DateTime.now;
782 // Only started runs reached the provider-thread update below. Queued runs and
783 // failures during session setup cannot establish a new telemetry selection.
784 const measuredContext = latestNativeContextUsage(projection, providerThread);
785 const previousSelection =
786 measuredContext?.modelSelection ??
787 projection.runs.findLast(
788 (source) =>
789 source.ordinal < run.ordinal &&
790 source.startedAt !== null &&
791 source.providerThreadId === providerThread.id,
792 )?.modelSelection;
793 const sameSelection =
794 previousSelection === undefined ||
795 modelSelectionsEqual(previousSelection, run.modelSelection);
796 const sameNativeThread =
797 loadedProviderThread.nativeThreadRef?.nativeId === providerThread.nativeThreadRef?.nativeId;
798 const threadUsage = loadedProviderThread.contextUsage ?? providerThread.contextUsage;
799 const previousUsage = measuredContext
800 ? { ...threadUsage, ...measuredContext.usage }
801 : threadUsage;
802 const reuseTelemetry =
803 sameSelection ||
804 (previousSelection !== undefined &&
805 session.canReuseContextUsage?.(previousSelection, run.modelSelection) === true);
806 const knownModelWindow = session.getModelContextWindow?.(
807 run.modelSelection,
808 resolvedRuntimePolicy.cwd,
809 );
810 // Persist before delivery. Keep this native transcript's measured
811 // occupancy. A different model drops compaction telemetry and uses the
812 // new window when that window is known.
813 const handoffUsage = contextUsageForHandoff({
814 sameNativeThread,
815 sameSelection,
816 reuseTelemetry,
817 previousUsage,
818 knownModelWindow,
819 });
820 const runningProviderThread: OrchestrationV2ProviderThread = {
821 ...loadedProviderThread,
822 contextUsage: handoffUsage,
823 id: providerThread.id,
824 driver: session.driver,
825 providerInstanceId: run.providerInstanceId,
826 providerSessionId,
827 appThreadId: projection.thread.id,
828 ownerNodeId: providerThread.ownerNodeId,
829 firstRunOrdinal: providerThread.firstRunOrdinal ?? run.ordinal,
830 lastRunOrdinal: run.ordinal,
831 handoffIds: providerThread.handoffIds,
832 forkedFrom: providerThread.forkedFrom,
833 status: "active",
834 createdAt: providerThread.createdAt,
835 updatedAt: now,
836 };
837 const runningRun: OrchestrationV2Run = {
838 ...run,
839 status: "running",
840 startedAt: now,
841 };
842 const runningAttempt: OrchestrationV2RunAttempt = {
843 ...attempt,
844 ...(runningProviderThread.nativeThreadRef?.nativeId == null
845 ? {}
846 : { nativeThreadId: runningProviderThread.nativeThreadRef.nativeId }),
847 status: "running",
848 startedAt: now,
849 };
850 const runningRootNode: OrchestrationV2ExecutionNode = {
851 ...rootNode,
852 status: "running",
853 startedAt: now,
854 };
855 const events: Array<OrchestrationV2DomainEvent> = [
856 {
857 id: yield* idAllocator.allocate.event({
858 threadId: projection.thread.id,
859 providerSessionId,
860 }),
861 type: "provider-session.updated",
862 threadId: projection.thread.id,
863 driver: session.driver,
864 providerInstanceId: run.providerInstanceId,
865 occurredAt: now,
866 payload: session.providerSession,
867 },
868 {
869 id: yield* idAllocator.allocate.event({ threadId: projection.thread.id }),
870 type: "provider-thread.updated",
871 threadId: projection.thread.id,
872 driver: session.driver,
873 providerInstanceId: run.providerInstanceId,
874 occurredAt: now,
875 payload: runningProviderThread,
876 },
877 ...(nativeForkTransfer === undefined || runningProviderThread.nativeThreadRef === null
878 ? []
879 : [
880 {
881 id: yield* idAllocator.allocate.event({ threadId: projection.thread.id }),
882 type: "context-transfer.updated" as const,
883 threadId: projection.thread.id,
884 runId: run.id,
885 driver: session.driver,
886 providerInstanceId: run.providerInstanceId,
887 occurredAt: now,
888 payload: {
889 ...nativeForkTransfer,
890 targetProviderInstanceId: run.providerInstanceId,
891 targetRunId: run.id,
892 status: "consumed" as const,
893 resolution: {
894 strategy: "native_fork" as const,
895 providerThreadRef: runningProviderThread.nativeThreadRef,
896 },
897 error: null,
898 updatedAt: now,
899 consumedAt: now,
900 },
901 },
902 ]),
903 {
904 id: yield* idAllocator.allocate.event({ threadId: projection.thread.id }),
905 type: "run.updated",
906 threadId: projection.thread.id,
907 runId: run.id,
908 nodeId: rootNode.id,
909 providerInstanceId: run.providerInstanceId,
910 occurredAt: now,
911 payload: runningRun,
912 },
913 {
914 id: yield* idAllocator.allocate.event({ threadId: projection.thread.id }),
915 type: "run-attempt.updated",
916 threadId: projection.thread.id,
917 runId: run.id,
918 nodeId: rootNode.id,
919 providerInstanceId: run.providerInstanceId,
920 occurredAt: now,
921 payload: runningAttempt,
922 },
923 {
924 id: yield* idAllocator.allocate.event({ threadId: projection.thread.id }),
925 type: "node.updated",
926 threadId: projection.thread.id,
927 runId: run.id,
928 nodeId: rootNode.id,
929 providerInstanceId: run.providerInstanceId,
930 occurredAt: now,
931 payload: runningRootNode,
932 },
933 ];
934 const runningWrite = yield* eventSink.writeIfRunCurrent({
935 threadId: projection.thread.id,
936 runId: run.id,
937 activeAttemptId: attempt.id,
938 expectedStatus: "starting",
939 events,
940 });
941 if (!runningWrite.committed) {
942 return;
943 }
944 const routableSubagents = projection.subagents.filter((subagent) =>
945 RunExecutionService.canRouteRelatedSubagent(subagent.status),
946 );
947 const userText = projectComposerContextForProvider({
948 text: message.text,
949 records: message.context?.records ?? [],
950 });
951 // Delivered once: this run's provider turn marks the work as told. A
952 // restart continuation is prompted by its own text or resumes natively.
953 const noteContinuation = isRestartNoteContinuation(
954 run,
955 projection.runs,
956 projection.providerTurns,
957 projection.attempts,
958 );
959 const restartCancelledWork = pendingRestartCancelledBackgroundWork({
960 runs: projection.runs,
961 providerTurns: projection.providerTurns,
962 compactionMessageIds: new Set(
963 projection.messages
964 .filter(
965 (candidate) =>
966 candidate.attachments.length === 0 &&
967 candidate.text.trim().toLowerCase() === "/compact",
968 )
969 .map((candidate) => candidate.id),
970 ),
971 run,
972 attempts: projection.attempts,
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 // Legacy accepted attempts have no native id. They count only before
1236 // a replacement, while no accepted attempt records a native identity.
1237 nativeThreadHasTurns:
1238 nativeInputRunIds.size > 0 ||
1239 (legacyInputRunIds.size > 0 &&
1240 sameNativeThread &&
1241 !acceptedAttempts.some((source) => source.nativeThreadId !== undefined)),
1242 shouldStartProviderTurn: runControls.shouldStartProviderTurn,
1243 shouldFinalizeRun: runControls.shouldFinalizeRun,
1244 hasUnpairedRunInterruptRequest: runControls.hasUnpairedRunInterruptRequest,
1245 message: {
1246 messageId: message.id,
1247 text: userText,
1248 attachments: message.attachments,
1249 createdBy: message.createdBy,
1250 creationSource: message.creationSource,
1251 ...(message.scheduledTaskId === undefined
1252 ? {}
1253 : { scheduledTaskId: message.scheduledTaskId }),
1254 ...(message.senderThreadId === undefined
1255 ? {}
1256 : { senderThreadId: message.senderThreadId }),
1257 },
1258 modelSelection: run.modelSelection,
1259 runtimePolicy: resolvedRuntimePolicy,
1260 });
1261 });
1262​
1263 return ProviderTurnStartServiceV2.of({
1264 start: (input) =>
1265 start(input).pipe(
1266 Effect.mapError((cause) =>
1267 isProviderTurnStartError(cause)
1268 ? cause
1269 : new ProviderTurnStartError({ runId: input.runId, cause }),
1270 ),
1271 ),
1272 });
1273 }),