Open History to see the last commit
1import {
2 NodeId,
3 CommandId,
4 OrchestrationV2DomainEvent,
5 OrchestrationV2StoredEvent,
6 type OrchestrationV2PlanArtifact,
7 type OrchestrationV2Run,
8 type OrchestrationV2Subagent,
9 type OrchestrationV2ThreadProjection,
10 type ModelSelection,
11 ProviderInstanceId,
12 ProviderSessionId,
13 ProviderThreadId,
14 ProviderTurnId,
15 RawEventId,
16 RunAttemptId,
17 RunId,
18 type RuntimeRequestId,
19 ThreadId,
20} from "@t3tools/contracts";
21import * as Context from "effect/Context";
22import * as DateTime from "effect/DateTime";
23import * as Effect from "effect/Effect";
24import * as Layer from "effect/Layer";
25import * as Schema from "effect/Schema";
26import * as SqlError from "effect/sql/SqlError";
27
28import { AgentScope } from "@t3tools/shared/AgentScope";
29import { modelSelectionsEqual } from "@t3tools/shared/model";
30import {
31 ProviderTurnAnalytics,
32 type ProviderTurnAnalyticsContext,
33} from "../telemetry/ProviderUsageAnalytics.ts";
34import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
35import * as ProviderInstanceRegistry from "../provider/ProviderInstanceRegistry.ts";
36import { UsageLimitResetFallback } from "../usage/UsageLimitSources.ts";
37import * as EventSink from "./EventSink.ts";
38import * as ProjectionStore from "./ProjectionStore.ts";
39import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
40import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
41import { makeProviderFailureTurnItem } from "@t3tools/provider-core/server/failure";
42import * as ThreadCommandExecutor from "./ThreadCommandExecutor.ts";
43import { stripUnservedToolOutputImageBytes } from "./toolOutputImageBytes.ts";
44import { boundFileChangeForStorage } from "./WireProjection.ts";
45
46export class ProviderEventNormalizeError extends Schema.TaggedError<ProviderEventNormalizeError>()(
47 "ProviderEventNormalizeError",
48 {
49 providerSessionId: ProviderSessionId,
50 threadId: ThreadId,
51 // The rejected payload cannot be validated again while reporting its normalization failure.
52 eventType: Schema.String,
53 cause: Schema.optional(Schema.Defect()),
54 },
55) {
56 override get message(): string {
57 return `Failed to normalize provider event ${this.eventType} for thread ${this.threadId}.`;
58 }
59}
60
61export class ProviderEventPublishError extends Schema.TaggedError<ProviderEventPublishError>()(
62 "ProviderEventPublishError",
63 {
64 providerSessionId: ProviderSessionId,
65 eventCount: Schema.Number,
66 cause: Schema.optional(Schema.Defect()),
67 },
68) {
69 override get message(): string {
70 return `Failed to publish ${this.eventCount} normalized provider event(s).`;
71 }
72}
73
74// A write that outlasts busy_timeout at BEGIN IMMEDIATE fails before anything
75// commits, and the sink publishes only after a commit, so repeating the whole
76// write is safe. Failing it would fail the run over a brief lock.
77const isLockTimeout = (error: EventSink.EventSinkV2Error) =>
78 SqlError.isSqlError(error.cause) && error.cause.reason._tag === "LockTimeoutError";
79const retryLockTimeout = <A, R>(write: Effect.Effect<A, EventSink.EventSinkV2Error, R>) =>
80 Effect.retry(write, { while: isLockTimeout, times: 2 });
81
82export const ProviderEventIngestorV2Error = Schema.Union([
83 ProviderEventNormalizeError,
84 ProviderEventPublishError,
85]);
86export type ProviderEventIngestorV2Error = typeof ProviderEventIngestorV2Error.Type;
87
88type TodoListPlan = Extract<OrchestrationV2PlanArtifact, { readonly kind: "todo_list" }>;
89
90function withPlanStepDurations(
91 plan: TodoListPlan,
92 previous: TodoListPlan | undefined,
93 occurredAt: DateTime.Utc,
94): TodoListPlan {
95 const occurredAtIso = DateTime.formatIso(occurredAt);
96 const occurredAtMs = DateTime.toEpochMillis(occurredAt);
97 const previousById = new Map(previous?.steps.map((step) => [step.id, step]));
98 // Provider step IDs may be positional. Changed text must not inherit another task's timing.
99 const previousStep = (step: TodoListPlan["steps"][number]) => {
100 const prior = previousById.get(step.id);
101 return prior?.text === step.text ? prior : undefined;
102 };
103 const hasNewCompletion = plan.steps.some((step) => {
104 const prior = previousStep(step);
105 return step.status === "completed" && prior?.status !== "completed";
106 });
107 let fallbackCompletionConsumed = false;
108
109 return {
110 ...plan,
111 steps: plan.steps.map((step) => {
112 const prior = previousStep(step);
113 const baseStep = { id: step.id, text: step.text, status: step.status };
114 if (step.status === "completed") {
115 if (prior?.status === "completed") {
116 return {
117 ...baseStep,
118 ...(prior.durationMs === undefined ? {} : { durationMs: prior.durationMs }),
119 };
120 }
121 const durationAnchorAt =
122 prior?.status === "running" || !fallbackCompletionConsumed
123 ? prior?.durationAnchorAt
124 : occurredAtIso;
125 fallbackCompletionConsumed = true;
126 const anchorMs =
127 durationAnchorAt === undefined ? occurredAtMs : Date.parse(durationAnchorAt);
128 const durationMs = Number.isFinite(anchorMs) ? Math.max(0, occurredAtMs - anchorMs) : 0;
129 return {
130 ...baseStep,
131 ...(durationMs > 0 ? { durationMs } : {}),
132 };
133 }
134 if (step.status === "running") {
135 return {
136 ...baseStep,
137 durationAnchorAt:
138 prior?.status === "running" ? (prior.durationAnchorAt ?? occurredAtIso) : occurredAtIso,
139 };
140 }
141 return {
142 ...baseStep,
143 durationAnchorAt:
144 hasNewCompletion || prior?.status !== "pending"
145 ? occurredAtIso
146 : (prior.durationAnchorAt ?? occurredAtIso),
147 };
148 }),
149 };
150}
151
152const CONVERSATION_RUN_STATUSES = new Set<OrchestrationV2Run["status"]>([
153 "completed",
154 "interrupted",
155 "failed",
156]);
157
158function runsOffNativeBranch(input: {
159 readonly projection: Pick<OrchestrationV2ThreadProjection, "runs" | "attempts" | "providerTurns">;
160 readonly providerThreadId: ProviderThreadId;
161 readonly retainedNativeTurnIds: ReadonlySet<string>;
162 readonly reportingRunId: RunId | undefined;
163}): ReadonlyArray<OrchestrationV2Run> {
164 const { attempts, providerTurns, runs } = input.projection;
165 const nativeTurnId = (run: OrchestrationV2Run) => {
166 const attempt = attempts.find((candidate) => candidate.id === run.activeAttemptId);
167 if (attempt === undefined) return null;
168 const ref = providerTurns.find(
169 (turn) => turn.id === attempt.providerTurnId || turn.runAttemptId === attempt.id,
170 )?.nativeTurnRef;
171 return ref?.strength === "strong" ? ref.nativeId : null;
172 };
173 const settled = runs.flatMap((run) =>
174 run.providerThreadId === input.providerThreadId &&
175 run.id !== input.reportingRunId &&
176 CONVERSATION_RUN_STATUSES.has(run.status)
177 ? [{ run, nativeTurnId: nativeTurnId(run) }]
178 : [],
179 );
180 const lastRetainedOrdinal = settled.reduce(
181 (last, { run, nativeTurnId }) =>
182 nativeTurnId !== null && input.retainedNativeTurnIds.has(nativeTurnId)
183 ? Math.max(last, run.ordinal)
184 : last,
185 0,
186 );
187 return settled
188 .filter(({ run, nativeTurnId }) =>
189 nativeTurnId === null
190 ? run.ordinal > lastRetainedOrdinal
191 : !input.retainedNativeTurnIds.has(nativeTurnId),
192 )
193 .map(({ run }) => run);
194}
195
196export interface ProviderEventIngestInput {
197 readonly providerSessionId: ProviderSessionId;
198 readonly providerInstanceId: ProviderInstanceId;
199 readonly commandId?: CommandId;
200 readonly threadId: ThreadId;
201 readonly runId?: RunId;
202 readonly nodeId?: NodeId;
203 readonly rawEventId?: RawEventId;
204 readonly event: ProviderAdapter.ProviderAdapterV2Event;
205 readonly analyticsContext?: ProviderTurnAnalyticsContext;
206}
207
208export interface ProviderEventIngestorV2Shape {
209 readonly normalize: (
210 input: ProviderEventIngestInput,
211 ) => Effect.Effect<ReadonlyArray<OrchestrationV2DomainEvent>, ProviderEventIngestorV2Error>;
212 readonly ingestNormalized: (
213 input: ProviderEventIngestInput & {
214 readonly writeIfRunCurrent?: {
215 readonly runId: RunId;
216 readonly activeAttemptId: RunAttemptId;
217 readonly expectedStatus: OrchestrationV2Run["status"];
218 };
219 readonly writeIfProviderThreadOwner?: {
220 readonly providerThreadId: ProviderThreadId;
221 readonly runId: RunId;
222 readonly activeAttemptId: RunAttemptId;
223 readonly expectedLastRunOrdinal: number;
224 };
225 },
226 ) => Effect.Effect<ReadonlyArray<OrchestrationV2StoredEvent>, ProviderEventIngestorV2Error>;
227}
228
229export class ProviderEventIngestorV2 extends Context.Service<
230 ProviderEventIngestorV2,
231 ProviderEventIngestorV2Shape
232>()("t3/orchestration-v2/ProviderEventIngestor/ProviderEventIngestorV2") {}
233
234function compactUndefined<T extends Record<string, unknown>>(record: T): T {
235 return Object.fromEntries(Object.entries(record).filter(([, value]) => value !== undefined)) as T;
236}
237
238const decodeDomainEvent = Schema.decodeUnknownEffect(OrchestrationV2DomainEvent);
239
240export const layer: Layer.Layer<
241 ProviderEventIngestorV2,
242 never,
243 | EventSink.EventSinkV2
244 | GitVcsDriver.GitVcsDriver
245 | IdAllocator.IdAllocatorV2
246 | ProjectionStore.ProjectionStoreV2
247 | ThreadCommandExecutor.ThreadCommandExecutor
248 | ProviderInstanceRegistry.ProviderInstanceRegistry
249> = Layer.effect(
250 ProviderEventIngestorV2,
251 Effect.gen(function* () {
252 const eventSink = yield* EventSink.EventSinkV2;
253 const git = yield* GitVcsDriver.GitVcsDriver;
254 const projections = yield* ProjectionStore.ProjectionStoreV2;
255 const idAllocator = yield* IdAllocator.IdAllocatorV2;
256 const threadCommands = yield* ThreadCommandExecutor.ThreadCommandExecutor;
257 const analytics = yield* ProviderTurnAnalytics;
258 const agentScope = yield* AgentScope;
259 const instances = yield* ProviderInstanceRegistry.ProviderInstanceRegistry;
260 const usageLimitResets = yield* UsageLimitResetFallback;
261 const scope = yield* Effect.scope;
262 const completedTurnAnalytics = new Set<string>();
263
264 const makeDomainEvent =
265 /* This helper runs for individual orchestration events; the enclosing operation owns the span. */
266 Effect.fnUntraced(function* (
267 input: ProviderEventIngestInput,
268 payloadInput: {
269 readonly type: OrchestrationV2DomainEvent["type"];
270 readonly payload: OrchestrationV2DomainEvent["payload"];
271 readonly threadId?: ThreadId;
272 readonly runId?: RunId | null;
273 readonly nodeId?: NodeId | null;
274 readonly occurredAt?: DateTime.Utc;
275 },
276 ) {
277 const threadId = payloadInput.threadId ?? input.threadId;
278 const eventId = yield* idAllocator.allocate.event({
279 threadId,
280 providerSessionId: input.providerSessionId,
281 });
282 const occurredAt = payloadInput.occurredAt ?? (yield* DateTime.now);
283 return yield* decodeDomainEvent(
284 compactUndefined({
285 id: eventId,
286 type: payloadInput.type,
287 threadId,
288 runId: payloadInput.runId ?? input.runId,
289 nodeId: payloadInput.nodeId ?? input.nodeId,
290 driver: input.event.driver,
291 providerInstanceId: input.providerInstanceId,
292 rawEventId: input.rawEventId,
293 occurredAt,
294 payload: payloadInput.payload,
295 }),
296 );
297 });
298
299 const dismissNativeUserInputs = Effect.fn("ProviderEventIngestor.dismissNativeUserInputs")(
300 function* (
301 input: ProviderEventIngestInput,
302 providerTurnId: ProviderTurnId,
303 threadId = input.threadId,
304 retained: ReadonlyArray<RuntimeRequestId> = [],
305 ) {
306 const pending = yield* projections.getPendingNativeUserInputs(threadId, providerTurnId);
307 const now = yield* DateTime.now;
308 const events: Array<OrchestrationV2DomainEvent> = [];
309 const kept = new Set(retained);
310 for (const request of pending.runtimeRequests) {
311 if (kept.has(request.id)) continue;
312 events.push(
313 yield* makeDomainEvent(input, {
314 type: "runtime-request.updated",
315 threadId,
316 nodeId: request.nodeId,
317 payload: { ...request, status: "cancelled", resolvedAt: now },
318 }),
319 );
320 }
321 for (const node of pending.nodes) {
322 if (node.runtimeRequestId !== null && kept.has(node.runtimeRequestId)) continue;
323 events.push(
324 yield* makeDomainEvent(input, {
325 type: "node.updated",
326 threadId,
327 nodeId: node.id,
328 runId: node.runId,
329 payload: { ...node, status: "cancelled", completedAt: now },
330 }),
331 );
332 }
333 for (const item of pending.turnItems) {
334 if (item.type === "user_input_request" && kept.has(item.requestId)) continue;
335 events.push(
336 yield* makeDomainEvent(input, {
337 type: "turn-item.updated",
338 threadId,
339 nodeId: item.nodeId,
340 runId: item.runId,
341 payload: { ...item, status: "cancelled", completedAt: now, updatedAt: now },
342 }),
343 );
344 }
345 return events;
346 },
347 );
348
349 /** Providers may reveal native subagent models late; lock full-row updates against concurrent thread commands. */
350 const syncSubagentThreadModel = Effect.fn("ProviderEventIngestor.syncSubagentThreadModel")(
351 function* (input: ProviderEventIngestInput, subagent: OrchestrationV2Subagent) {
352 const { childThreadId, model } = subagent;
353 if (
354 subagent.origin !== "provider_native" ||
355 childThreadId === null ||
356 (model === null && subagent.modelSelection === undefined)
357 ) {
358 return [];
359 }
360 const reportedSelection = ({ modelSelection }: { modelSelection: ModelSelection }) =>
361 subagent.modelSelection ??
362 (model === null || model === modelSelection.model
363 ? modelSelection
364 : { instanceId: modelSelection.instanceId, model });
365 const staleThread = projections.getThread(childThreadId).pipe(
366 Effect.map((thread) =>
367 modelSelectionsEqual(thread.modelSelection, reportedSelection(thread)) ? null : thread,
368 ),
369 Effect.catchTags({ ProjectionStoreThreadNotFoundError: () => Effect.succeed(null) }),
370 );
371 if ((yield* staleThread) === null) return [];
372 return yield* threadCommands.withLock(
373 childThreadId,
374 Effect.gen(function* () {
375 const thread = yield* staleThread;
376 if (thread === null) return [];
377 const now = yield* DateTime.now;
378 const event = yield* makeDomainEvent(input, {
379 type: "thread.model-selection-updated",
380 threadId: thread.id,
381 payload: {
382 ...thread,
383 modelSelection: reportedSelection(thread),
384 updatedAt: now,
385 },
386 occurredAt: now,
387 });
388 return yield* eventSink.write({ events: [event] }).pipe(retryLockTimeout);
389 }),
390 );
391 },
392 );
393
394 /** Retire rewound runs like CheckpointRollbackService; retain the reporting run and its lastRunOrdinal. */
395 const rollBackRewoundRuns = Effect.fn("ProviderEventIngestor.rollBackRewoundRuns")(function* (
396 input: ProviderEventIngestInput,
397 rewind: {
398 readonly threadId: ThreadId;
399 readonly providerThreadId: ProviderThreadId;
400 readonly retainedNativeTurnIds: ReadonlySet<string>;
401 },
402 ) {
403 const projection = yield* projections.getThreadRecords(rewind.threadId, [
404 "runs",
405 "attempts",
406 "providerTurns",
407 "nodes",
408 "checkpoints",
409 ]);
410 const runs = runsOffNativeBranch({
411 projection,
412 providerThreadId: rewind.providerThreadId,
413 retainedNativeTurnIds: rewind.retainedNativeTurnIds,
414 reportingRunId: input.runId,
415 });
416 if (runs.length === 0) return [];
417 const now = yield* DateTime.now;
418 const eventId = () =>
419 idAllocator.allocate.event({
420 threadId: rewind.threadId,
421 providerSessionId: input.providerSessionId,
422 });
423 const runIds = new Set(runs.map((run) => run.id));
424 const events: Array<OrchestrationV2DomainEvent> = [];
425 for (const checkpoint of projection.checkpoints) {
426 if (checkpoint.status !== "ready" || checkpoint.runId === null) continue;
427 if (!runIds.has(checkpoint.runId)) continue;
428 events.push({
429 id: yield* eventId(),
430 type: "checkpoint.captured",
431 threadId: rewind.threadId,
432 runId: checkpoint.runId,
433 nodeId: checkpoint.nodeId,
434 providerInstanceId: input.providerInstanceId,
435 occurredAt: now,
436 payload: { ...checkpoint, status: "stale" },
437 });
438 }
439 for (const run of runs) {
440 const rootNode = projection.nodes.find((node) => node.id === run.rootNodeId);
441 events.push({
442 id: yield* eventId(),
443 type: "run.updated",
444 threadId: rewind.threadId,
445 runId: run.id,
446 ...(rootNode === undefined ? {} : { nodeId: rootNode.id }),
447 providerInstanceId: run.providerInstanceId,
448 occurredAt: now,
449 payload: { ...run, status: "rolled_back", completedAt: now },
450 });
451 if (rootNode !== undefined) {
452 events.push({
453 id: yield* eventId(),
454 type: "node.updated",
455 threadId: rewind.threadId,
456 runId: run.id,
457 nodeId: rootNode.id,
458 providerInstanceId: run.providerInstanceId,
459 occurredAt: now,
460 payload: { ...rootNode, status: "rolled_back", completedAt: now },
461 });
462 }
463 }
464 return events;
465 });
466
467 const normalize: ProviderEventIngestorV2Shape["normalize"] =
468 /* This helper runs for individual orchestration events; the enclosing operation owns the span. */
469 Effect.fnUntraced(
470 function* (input) {
471 switch (input.event.type) {
472 case "app_thread.created": {
473 const offered = input.event.appThread;
474 const existing = yield* projections.findThread(offered.id);
475 if (
476 existing !== null &&
477 (input.event.createOnly === true ||
478 (existing.title === offered.title &&
479 modelSelectionsEqual(existing.modelSelection, offered.modelSelection)))
480 )
481 return [];
482 const now = yield* DateTime.now;
483 return [
484 yield* makeDomainEvent(input, {
485 type: existing === null ? "thread.created" : "thread.metadata-updated",
486 threadId: offered.id,
487 payload:
488 existing === null
489 ? offered
490 : {
491 ...existing,
492 title: offered.title,
493 modelSelection: offered.modelSelection,
494 updatedAt: now,
495 },
496 occurredAt: now,
497 }),
498 ];
499 }
500 case "thread_model_selection.updated": {
501 const { instanceId, changes } = input.event;
502 const thread = yield* projections.getThread(input.event.threadId).pipe(
503 Effect.catchTags({
504 ProjectionStoreThreadNotFoundError: () => Effect.succeed(null),
505 }),
506 );
507 const current = thread?.modelSelection;
508 if (thread === null || current?.instanceId !== instanceId || !current.options) {
509 return [];
510 }
511 let changed = false;
512 const options = current.options.map((option) => {
513 const change = changes.find(
514 (candidate) => candidate.id === option.id && candidate.from === option.value,
515 );
516 if (change === undefined) return option;
517 changed = true;
518 return { ...option, value: change.to };
519 });
520 if (!changed) return [];
521 const now = yield* DateTime.now;
522 return [
523 yield* makeDomainEvent(input, {
524 type: "thread.model-selection-updated",
525 threadId: thread.id,
526 payload: { ...thread, modelSelection: { ...current, options }, updatedAt: now },
527 occurredAt: now,
528 }),
529 ];
530 }
531 case "provider_session.updated":
532 return [
533 yield* makeDomainEvent(input, {
534 type: "provider-session.updated",
535 payload: input.event.providerSession,
536 }),
537 ];
538 case "provider_thread.updated": {
539 const threadId = input.event.providerThread.appThreadId ?? input.threadId;
540 const updated = yield* makeDomainEvent(input, {
541 type: "provider-thread.updated",
542 threadId,
543 payload: input.event.providerThread,
544 });
545 return input.event.retainedNativeTurnIds === undefined
546 ? [updated]
547 : [
548 updated,
549 ...(yield* rollBackRewoundRuns(input, {
550 threadId,
551 providerThreadId: input.event.providerThread.id,
552 retainedNativeTurnIds: new Set(input.event.retainedNativeTurnIds),
553 })),
554 ];
555 }
556 case "provider_turn.updated":
557 return [
558 ...(["completed", "interrupted", "failed", "cancelled"].includes(
559 input.event.providerTurn.status,
560 )
561 ? yield* dismissNativeUserInputs(
562 input,
563 input.event.providerTurn.id,
564 input.event.threadId,
565 input.event.retainedRuntimeRequestIds,
566 )
567 : []),
568 yield* makeDomainEvent(input, {
569 type: "provider-turn.updated",
570 ...(input.event.threadId === undefined ? {} : { threadId: input.event.threadId }),
571 payload: input.event.providerTurn,
572 nodeId: input.event.providerTurn.nodeId,
573 }),
574 ];
575 case "node.updated":
576 // Adapters send an unchanged node again with each text delta. Compare with the
577 // stored node, not the last one sent, because the server also writes nodes.
578 if (yield* projections.isNodeStored(input.event.node)) return [];
579 return [
580 yield* makeDomainEvent(input, {
581 type: "node.updated",
582 threadId: input.event.node.threadId,
583 payload: input.event.node,
584 runId: input.event.node.runId,
585 nodeId: input.event.node.id,
586 }),
587 ];
588 case "subagent.updated":
589 return [
590 yield* makeDomainEvent(input, {
591 type: "subagent.updated",
592 threadId: input.event.subagent.threadId,
593 payload: input.event.subagent,
594 runId: input.event.subagent.runId,
595 nodeId: input.event.subagent.id,
596 }),
597 ];
598 case "message.updated":
599 return [
600 yield* makeDomainEvent(input, {
601 type: "message.updated",
602 threadId: input.event.message.threadId,
603 payload: input.event.message,
604 runId: input.event.message.runId,
605 nodeId: input.event.message.nodeId,
606 }),
607 ];
608 case "turn_item.updated":
609 return [
610 yield* makeDomainEvent(input, {
611 type: "turn-item.updated",
612 threadId: input.event.turnItem.threadId,
613 payload: boundFileChangeForStorage(
614 stripUnservedToolOutputImageBytes(input.event.turnItem),
615 ),
616 runId: input.event.turnItem.runId,
617 nodeId: input.event.turnItem.nodeId,
618 }),
619 ];
620 case "runtime_request.updated":
621 return [
622 yield* makeDomainEvent(input, {
623 type: "runtime-request.updated",
624 ...(input.event.threadId === undefined ? {} : { threadId: input.event.threadId }),
625 payload: input.event.runtimeRequest,
626 nodeId: input.event.runtimeRequest.nodeId,
627 }),
628 ];
629 case "plan.updated": {
630 const occurredAt = yield* DateTime.now;
631 const plan = input.event.plan;
632 const previous =
633 plan.kind === "todo_list"
634 ? yield* projections.getPlan(plan.threadId, plan.id)
635 : undefined;
636 const payload =
637 plan.kind === "todo_list"
638 ? withPlanStepDurations(
639 plan,
640 previous?.kind === "todo_list" ? previous : undefined,
641 occurredAt,
642 )
643 : plan;
644 return [
645 yield* makeDomainEvent(input, {
646 type: "plan.updated",
647 threadId: plan.threadId,
648 payload,
649 runId: plan.runId,
650 nodeId: plan.nodeId,
651 occurredAt,
652 }),
653 ];
654 }
655 case "steer.updated": {
656 const item = yield* projections.getTurnItem({
657 threadId: input.event.threadId,
658 itemId: idAllocator.derive.userTurnItem({ messageId: input.event.messageId }),
659 });
660 if (
661 item?.type !== "user_message" ||
662 item.status === input.event.status ||
663 (item.status !== "pending" && item.status !== "completed")
664 ) {
665 return [];
666 }
667 const occurredAt = yield* DateTime.now;
668 return [
669 yield* makeDomainEvent(input, {
670 type: "turn-item.updated",
671 threadId: item.threadId,
672 payload: {
673 ...item,
674 status: input.event.status,
675 completedAt: input.event.status === "pending" ? null : occurredAt,
676 updatedAt: occurredAt,
677 },
678 runId: item.runId,
679 nodeId: item.nodeId,
680 occurredAt,
681 }),
682 ];
683 }
684 case "background_work.updated":
685 return [];
686 case "background_work.lost":
687 case "command_output.delta":
688 case "prompt_suggestion.updated":
689 // The session manager handles these before ingestion.
690 return [];
691 case "turn.terminal":
692 const dismissed = yield* dismissNativeUserInputs(
693 input,
694 input.event.providerTurnId,
695 undefined,
696 input.event.retainedRuntimeRequestIds,
697 );
698 if (input.event.status !== "failed") {
699 return dismissed;
700 }
701 const occurredAt = yield* DateTime.now;
702 const reported = (yield* agentScope.oomKilled(input.threadId))
703 ? { ...input.event.failure, message: "Killed: out of memory.", code: "oom_kill" }
704 : input.event.failure;
705 // A proxied CLI can drop the reset time; the hub still knows when its pool refills.
706 const endpoint =
707 reported.class === "usage_limit" && reported.resetAt == null
708 ? (yield* Effect.flatMap(
709 instances.getInstance(input.providerInstanceId),
710 (instance) => instance?.snapshot.getSnapshot ?? Effect.undefined,
711 ))?.auth.endpoint
712 : undefined;
713 const hubResetAt =
714 endpoint === undefined
715 ? null
716 : yield* Effect.gen(function* () {
717 // The failing run's model, which may differ from a selection changed mid-turn.
718 const { runs } =
719 input.runId === undefined
720 ? { runs: [] }
721 : yield* projections.getThreadRecords(input.threadId, ["runs"], {
722 runIds: [input.runId],
723 });
724 return (
725 runs[0]?.modelSelection ??
726 (yield* projections.getThread(input.threadId)).modelSelection
727 ).model;
728 }).pipe(
729 Effect.orElseSucceed(() => null),
730 Effect.flatMap((model) =>
731 usageLimitResets.resetAt(input.event.driver, endpoint, model),
732 ),
733 );
734 const failure = hubResetAt === null ? reported : { ...reported, resetAt: hubResetAt };
735 return [
736 ...dismissed,
737 yield* makeDomainEvent(input, {
738 type: "turn-item.updated",
739 payload: makeProviderFailureTurnItem({
740 ...(input.event.failureItemId === undefined
741 ? {}
742 : { id: input.event.failureItemId }),
743 driver: input.event.driver,
744 threadId: input.threadId,
745 runId: input.runId ?? null,
746 nodeId: input.nodeId ?? null,
747 providerThreadId: input.event.providerThreadId,
748 providerTurnId: input.event.providerTurnId,
749 itemOrdinal: input.event.failureItemOrdinal,
750 failure,
751 ...(input.event.retry === undefined ? {} : { retry: input.event.retry }),
752 ...(input.event.retryStartedAt === undefined
753 ? {}
754 : { retryStartedAt: input.event.retryStartedAt }),
755 occurredAt,
756 }),
757 }),
758 ];
759 }
760 },
761 (effect, input) =>
762 effect.pipe(
763 Effect.mapError(
764 (cause) =>
765 new ProviderEventNormalizeError({
766 providerSessionId: input.providerSessionId,
767 threadId: input.threadId,
768 eventType: input.event.type,
769 cause,
770 }),
771 ),
772 ),
773 );
774
775 return ProviderEventIngestorV2.of({
776 normalize,
777 ingestNormalized:
778 /* This helper runs for individual orchestration events; the enclosing operation owns the span. */
779 Effect.fnUntraced(
780 function* (input) {
781 const events = yield* normalize(input);
782 if (events.length === 0) {
783 return [];
784 }
785 const mapWriteError = (cause: unknown) =>
786 new ProviderEventPublishError({
787 providerSessionId: input.providerSessionId,
788 eventCount: events.length,
789 cause,
790 });
791 if (input.writeIfProviderThreadOwner !== undefined) {
792 const ownerResult = yield* eventSink
793 .writeIfProviderThreadOwner({
794 guardPendingUserInputCancellations: true,
795 ...(input.commandId === undefined ? {} : { commandId: input.commandId }),
796 ...input.writeIfProviderThreadOwner,
797 events,
798 })
799 .pipe(retryLockTimeout, Effect.mapError(mapWriteError));
800 return ownerResult.storedEvents;
801 }
802 if (input.writeIfRunCurrent === undefined) {
803 return yield* eventSink
804 .write({
805 guardPendingUserInputCancellations: true,
806 ...(input.commandId === undefined ? {} : { commandId: input.commandId }),
807 events,
808 })
809 .pipe(retryLockTimeout, Effect.mapError(mapWriteError));
810 }
811 const result = yield* eventSink
812 .writeIfRunCurrent({
813 guardPendingUserInputCancellations: true,
814 ...(input.commandId === undefined ? {} : { commandId: input.commandId }),
815 threadId: input.threadId,
816 ...input.writeIfRunCurrent,
817 events,
818 })
819 .pipe(retryLockTimeout, Effect.mapError(mapWriteError));
820 return result.storedEvents;
821 },
822 (effect, input) =>
823 effect.pipe(
824 Effect.tap((storedEvents) =>
825 Effect.gen(function* () {
826 if (
827 storedEvents.length === 0 ||
828 input.event.type !== "turn.terminal" ||
829 input.event.status !== "failed" ||
830 input.event.failure.class !== "usage_limit"
831 )
832 return;
833 const instance = yield* instances.getInstance(input.providerInstanceId);
834 if (!instance?.snapshot.refreshUsage) return;
835 yield* instance.snapshot.refreshUsage.pipe(
836 Effect.ignoreCause({ log: true }),
837 Effect.forkIn(scope, { startImmediately: true }),
838 );
839 }),
840 ),
841 Effect.flatMap((storedEvents) =>
842 Effect.gen(function* () {
843 if (input.event.type !== "app_thread.created") return storedEvents;
844 const created = storedEvents.find(
845 (stored) => stored.event.type === "thread.created",
846 );
847 if (created?.event.type !== "thread.created") return storedEvents;
848 const child = created.event.payload;
849 if (child.worktreePath === null || child.branch === null) return storedEvents;
850 // Git renames before scanning committed threads. If that scan missed this
851 // creation, HEAD already has the new name, even if the parent moved away.
852 const branch = yield* git.resolveBranchName(child.worktreePath, "HEAD");
853 if (branch === null || branch === child.branch) return storedEvents;
854 const now = yield* DateTime.now;
855 const event = yield* makeDomainEvent(input, {
856 type: "thread.metadata-updated",
857 threadId: child.id,
858 payload: { ...child, branch, updatedAt: now },
859 occurredAt: now,
860 });
861 const synced = yield* eventSink.write({ events: [event] });
862 return [...storedEvents, ...synced];
863 }).pipe(
864 Effect.catchCause((cause) =>
865 Effect.logWarning("Native thread worktree branch recheck failed", {
866 threadId:
867 input.event.type === "app_thread.created"
868 ? input.event.appThread.id
869 : input.threadId,
870 cause,
871 }).pipe(Effect.as(storedEvents)),
872 ),
873 ),
874 ),
875 // @effect-diagnostics-next-line flatMapConditionalToFilterOrFail:off - The predicate narrows the captured event for the subagent update.
876 Effect.flatMap((storedEvents) =>
877 storedEvents.length === 0 || input.event.type !== "subagent.updated"
878 ? Effect.succeed(storedEvents)
879 : syncSubagentThreadModel(input, input.event.subagent).pipe(
880 Effect.map((synced) => [...storedEvents, ...synced]),
881 Effect.mapError(
882 (cause) =>
883 new ProviderEventPublishError({
884 providerSessionId: input.providerSessionId,
885 eventCount: 1,
886 cause,
887 }),
888 ),
889 ),
890 ),
891 Effect.tap((storedEvents) =>
892 Effect.gen(function* () {
893 if (storedEvents.length === 0 || input.event.type !== "provider_turn.updated")
894 return;
895 const providerTurn = input.event.providerTurn;
896 if (
897 providerTurn.status !== "completed" &&
898 providerTurn.status !== "failed" &&
899 providerTurn.status !== "interrupted" &&
900 providerTurn.status !== "cancelled"
901 )
902 return;
903 const key = `${input.providerInstanceId}:${providerTurn.id}`;
904 if (completedTurnAnalytics.has(key)) return;
905 completedTurnAnalytics.add(key);
906 if (completedTurnAnalytics.size > 4096) {
907 const oldest = completedTurnAnalytics.values().next().value;
908 if (oldest !== undefined) completedTurnAnalytics.delete(oldest);
909 }
910 yield* analytics.turnCompleted({
911 driver: input.event.driver,
912 providerTurn,
913 ...(input.analyticsContext === undefined
914 ? {}
915 : { context: input.analyticsContext }),
916 });
917 }),
918 ),
919 (effect) =>
920 input.event.type === "app_thread.created"
921 ? threadCommands.withLock(input.event.appThread.id, effect)
922 : input.event.type === "thread_model_selection.updated"
923 ? threadCommands.withLock(input.event.threadId, effect)
924 : effect,
925 ),
926 ),
927 });
928 }),
929);