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