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