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

ProviderEventIngestor.ts

782 lines29.4 KB

1import {
2 NodeId,
3 CommandId,
4 OrchestrationV2DomainEvent,
5 OrchestrationV2StoredEvent,
6 type OrchestrationV2PlanArtifact,
7 type OrchestrationV2Run,
8 type OrchestrationV2ProviderTurn,
9 type OrchestrationV2Subagent,
10 type OrchestrationV2ThreadProjection,
11 type ModelSelection,
12 type RuntimeMode,
13 type ProviderInteractionMode,
14 ProviderInstanceId,
15 ProviderSessionId,
16 ProviderThreadId,
17 ProviderTurnId,
18 RawEventId,
19 RunAttemptId,
20 RunId,
21 ThreadId,
22} from "@t3tools/contracts";
23import * as Context from "effect/Context";
24import * as DateTime from "effect/DateTime";
25import * as Effect from "effect/Effect";
26import * as Layer from "effect/Layer";
27import * as Schema from "effect/Schema";
28​
29import { getModelSelectionStringOptionValue } from "@t3tools/shared/model";
30import * as AnalyticsService from "../telemetry/AnalyticsService.ts";
31import * as EventSink from "./EventSink.ts";
32import * as ProjectionStore from "./ProjectionStore.ts";
33import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
34import { ProviderAdapterV2Event } from "@t3tools/provider-core/server/ProviderAdapter";
35import { makeProviderFailureTurnItem } from "@t3tools/provider-core/server/failure";
36import * as ThreadCommandExecutor from "./ThreadCommandExecutor.ts";
37import { stripUnservedToolOutputImageBytes } from "./toolOutputImageBytes.ts";
38​
39export class ProviderEventNormalizeError extends Schema.TaggedError<ProviderEventNormalizeError>()(
40 "ProviderEventNormalizeError",
41 {
42 providerSessionId: ProviderSessionId,
43 threadId: ThreadId,
44 providerEvent: ProviderAdapterV2Event,
45 cause: Schema.optional(Schema.Defect()),
46 },
47) {
48 override get message(): string {
49 return `Failed to normalize provider event ${this.providerEvent.type} for thread ${this.threadId}.`;
50 }
52​
53export class ProviderEventPublishError extends Schema.TaggedError<ProviderEventPublishError>()(
54 "ProviderEventPublishError",
55 {
56 providerSessionId: ProviderSessionId,
57 eventCount: Schema.Number,
58 cause: Schema.optional(Schema.Defect()),
59 },
60) {
61 override get message(): string {
62 return `Failed to publish ${this.eventCount} normalized provider event(s).`;
63 }
65​
66export const ProviderEventIngestorV2Error = Schema.Union([
67 ProviderEventNormalizeError,
68 ProviderEventPublishError,
69]);
70export type ProviderEventIngestorV2Error = typeof ProviderEventIngestorV2Error.Type;
71​
72export interface ProviderTurnAnalyticsContext {
73 readonly modelSelection: ModelSelection;
74 readonly runtimeMode?: RuntimeMode;
75 readonly interactionMode?: ProviderInteractionMode;
77​
78export class ProviderTurnAnalytics extends Context.Reference<{
79 readonly record: (properties: Readonly<Record<string, unknown>>) => Effect.Effect<void>;
80}>("t3/orchestration-v2/ProviderTurnAnalytics", {
81 defaultValue: () => ({ record: () => Effect.void }),
82}) {}
83​
84export const layerAnalytics = Layer.effect(
85 ProviderTurnAnalytics,
86 Effect.gen(function* () {
87 const analytics = yield* AnalyticsService.AnalyticsService;
88 return {
89 record: (properties: Readonly<Record<string, unknown>>) =>
90 analytics.record("provider.turn.completed", properties),
91 };
92 }),
93);
94​
95function providerTurnAnalyticsProperties(input: {
96 readonly driver: ProviderAdapterV2Event["driver"];
97 readonly providerTurn: OrchestrationV2ProviderTurn;
98 readonly context?: ProviderTurnAnalyticsContext;
99}): Readonly<Record<string, unknown>> {
100 const usage = input.providerTurn.turnTokenUsage;
101 const modelSelection = input.context?.modelSelection;
102 const effort = modelSelection
103 ? (getModelSelectionStringOptionValue(modelSelection, "reasoningEffort") ??
104 getModelSelectionStringOptionValue(modelSelection, "effort"))
105 : undefined;
106 return {
107 provider: input.driver,
108 terminalStatus: input.providerTurn.status,
109 usageStatus: usage?.usageStatus ?? "unavailable",
110 usageScope: usage?.usageScope ?? "main_agent",
111 ...(usage ? { hasSubagents: usage.hasSubagents } : {}),
112 ...(usage?.inputTokens === undefined ? {} : { inputTokens: usage.inputTokens }),
113 ...(usage?.cachedInputTokens === undefined
114 ? {}
115 : { cachedInputTokens: usage.cachedInputTokens }),
116 ...(usage?.cacheCreationTokens === undefined
117 ? {}
118 : { cacheCreationTokens: usage.cacheCreationTokens }),
119 ...(usage?.outputTokens === undefined ? {} : { outputTokens: usage.outputTokens }),
120 ...(usage?.reasoningTokens === undefined ? {} : { reasoningTokens: usage.reasoningTokens }),
121 ...(modelSelection ? { model: modelSelection.model, mixedModels: false } : {}),
122 ...(effort ? { effort } : {}),
123 ...(input.context?.runtimeMode ? { runtimeMode: input.context.runtimeMode } : {}),
124 ...(input.context?.interactionMode ? { interactionMode: input.context.interactionMode } : {}),
125 ...(input.providerTurn.startedAt && input.providerTurn.completedAt
126 ? {
127 durationMs: Math.max(
128 0,
129 DateTime.toEpochMillis(input.providerTurn.completedAt) -
130 DateTime.toEpochMillis(input.providerTurn.startedAt),
131 ),
132 }
133 : {}),
134 };
136​
137type TodoListPlan = Extract<OrchestrationV2PlanArtifact, { readonly kind: "todo_list" }>;
138​
139function withPlanStepDurations(
140 plan: TodoListPlan,
141 previous: TodoListPlan | undefined,
142 occurredAt: DateTime.Utc,
143): TodoListPlan {
144 const occurredAtIso = DateTime.formatIso(occurredAt);
145 const occurredAtMs = DateTime.toEpochMillis(occurredAt);
146 const previousById = new Map(previous?.steps.map((step) => [step.id, step]));
147 // Provider step IDs may be positional. Changed text must not inherit another task's timing.
148 const previousStep = (step: TodoListPlan["steps"][number]) => {
149 const prior = previousById.get(step.id);
150 return prior?.text === step.text ? prior : undefined;
151 };
152 const hasNewCompletion = plan.steps.some((step) => {
153 const prior = previousStep(step);
154 return step.status === "completed" && prior?.status !== "completed";
155 });
156 let fallbackCompletionConsumed = false;
157​
158 return {
159 ...plan,
160 steps: plan.steps.map((step) => {
161 const prior = previousStep(step);
162 const baseStep = { id: step.id, text: step.text, status: step.status };
163 if (step.status === "completed") {
164 if (prior?.status === "completed") {
165 return {
166 ...baseStep,
167 ...(prior.durationMs === undefined ? {} : { durationMs: prior.durationMs }),
168 };
169 }
170 const durationAnchorAt =
171 prior?.status === "running" || !fallbackCompletionConsumed
172 ? prior?.durationAnchorAt
173 : occurredAtIso;
174 fallbackCompletionConsumed = true;
175 const anchorMs =
176 durationAnchorAt === undefined ? occurredAtMs : Date.parse(durationAnchorAt);
177 const durationMs = Number.isFinite(anchorMs) ? Math.max(0, occurredAtMs - anchorMs) : 0;
178 return {
179 ...baseStep,
180 ...(durationMs > 0 ? { durationMs } : {}),
181 };
182 }
183 if (step.status === "running") {
184 return {
185 ...baseStep,
186 durationAnchorAt:
187 prior?.status === "running" ? (prior.durationAnchorAt ?? occurredAtIso) : occurredAtIso,
188 };
189 }
190 return {
191 ...baseStep,
192 durationAnchorAt:
193 hasNewCompletion || prior?.status !== "pending"
194 ? occurredAtIso
195 : (prior.durationAnchorAt ?? occurredAtIso),
196 };
197 }),
198 };
200​
201/** Settled runs that carried conversation to the provider. */
202const CONVERSATION_RUN_STATUSES = new Set<OrchestrationV2Run["status"]>([
203 "completed",
204 "interrupted",
205 "failed",
206]);
207​
208/**
209 * Settled runs on a provider thread that a native rewind left off the active
210 * branch. A run whose provider turn has a strong native ref is judged by that
211 * ref. A run without one cannot be located, so it falls with everything after
212 * the last run still on the branch.
213 */
214function runsOffNativeBranch(input: {
215 readonly projection: Pick<OrchestrationV2ThreadProjection, "runs" | "attempts" | "providerTurns">;
216 readonly providerThreadId: ProviderThreadId;
217 readonly retainedNativeTurnIds: ReadonlySet<string>;
218 readonly reportingRunId: RunId | undefined;
219}): ReadonlyArray<OrchestrationV2Run> {
220 const { attempts, providerTurns, runs } = input.projection;
221 const nativeTurnId = (run: OrchestrationV2Run) => {
222 const attempt = attempts.find((candidate) => candidate.id === run.activeAttemptId);
223 if (attempt === undefined) return null;
224 const ref = providerTurns.find(
225 (turn) => turn.id === attempt.providerTurnId || turn.runAttemptId === attempt.id,
226 )?.nativeTurnRef;
227 return ref?.strength === "strong" ? ref.nativeId : null;
228 };
229 const settled = runs.flatMap((run) =>
230 run.providerThreadId === input.providerThreadId &&
231 run.id !== input.reportingRunId &&
232 CONVERSATION_RUN_STATUSES.has(run.status)
233 ? [{ run, nativeTurnId: nativeTurnId(run) }]
234 : [],
235 );
236 const lastRetainedOrdinal = settled.reduce(
237 (last, { run, nativeTurnId }) =>
238 nativeTurnId !== null && input.retainedNativeTurnIds.has(nativeTurnId)
239 ? Math.max(last, run.ordinal)
240 : last,
241 0,
242 );
243 return settled
244 .filter(({ run, nativeTurnId }) =>
245 nativeTurnId === null
246 ? run.ordinal > lastRetainedOrdinal
247 : !input.retainedNativeTurnIds.has(nativeTurnId),
248 )
249 .map(({ run }) => run);
251​
252export interface ProviderEventIngestInput {
253 readonly providerSessionId: ProviderSessionId;
254 readonly providerInstanceId: ProviderInstanceId;
255 readonly commandId?: CommandId;
256 readonly threadId: ThreadId;
257 readonly runId?: RunId;
258 readonly nodeId?: NodeId;
259 readonly rawEventId?: RawEventId;
260 readonly event: ProviderAdapterV2Event;
261 readonly analyticsContext?: ProviderTurnAnalyticsContext;
263​
264export interface ProviderEventIngestorV2Shape {
265 readonly normalize: (
266 input: ProviderEventIngestInput,
267 ) => Effect.Effect<ReadonlyArray<OrchestrationV2DomainEvent>, ProviderEventIngestorV2Error>;
268 readonly ingestNormalized: (
269 input: ProviderEventIngestInput & {
270 /**
271 * Atomically reject mutable provider state emitted by an attempt that
272 * lost ownership while the adapter event was in flight.
273 */
274 readonly writeIfRunCurrent?: {
275 readonly runId: RunId;
276 readonly activeAttemptId: RunAttemptId;
277 readonly expectedStatus: OrchestrationV2Run["status"];
278 };
279 /**
280 * Atomically reject provider-thread snapshots from an attempt that no
281 * longer owns the run or from a run that no longer owns the thread.
282 */
283 readonly writeIfProviderThreadOwner?: {
284 readonly providerThreadId: ProviderThreadId;
285 readonly runId: RunId;
286 readonly activeAttemptId: RunAttemptId;
287 readonly expectedLastRunOrdinal: number;
288 };
289 },
290 ) => Effect.Effect<ReadonlyArray<OrchestrationV2StoredEvent>, ProviderEventIngestorV2Error>;
292​
293export class ProviderEventIngestorV2 extends Context.Service<
294 ProviderEventIngestorV2,
295 ProviderEventIngestorV2Shape
296>()("t3/orchestration-v2/ProviderEventIngestor/ProviderEventIngestorV2") {}
297​
298function compactUndefined<T extends Record<string, unknown>>(record: T): T {
299 return Object.fromEntries(Object.entries(record).filter(([, value]) => value !== undefined)) as T;
301​
302const decodeDomainEvent = Schema.decodeUnknownEffect(OrchestrationV2DomainEvent);
303​
304export const layer: Layer.Layer<
305 ProviderEventIngestorV2,
306 never,
307 | EventSink.EventSinkV2
308 | IdAllocator.IdAllocatorV2
309 | ProjectionStore.ProjectionStoreV2
310 | ThreadCommandExecutor.ThreadCommandExecutor
311> = Layer.effect(
312 ProviderEventIngestorV2,
313 Effect.gen(function* () {
314 const eventSink = yield* EventSink.EventSinkV2;
315 const projections = yield* ProjectionStore.ProjectionStoreV2;
316 const idAllocator = yield* IdAllocator.IdAllocatorV2;
317 const threadCommands = yield* ThreadCommandExecutor.ThreadCommandExecutor;
318 const analytics = yield* ProviderTurnAnalytics;
319 const completedTurnAnalytics = new Set<string>();
320​
321 const makeDomainEvent = (
322 input: ProviderEventIngestInput,
323 payloadInput: {
324 readonly type: OrchestrationV2DomainEvent["type"];
325 readonly payload: OrchestrationV2DomainEvent["payload"];
326 readonly threadId?: ThreadId;
327 readonly runId?: RunId | null;
328 readonly nodeId?: NodeId | null;
329 readonly occurredAt?: DateTime.Utc;
330 },
331 ) =>
332 Effect.gen(function* () {
333 const threadId = payloadInput.threadId ?? input.threadId;
334 const eventId = yield* idAllocator.allocate.event({
335 threadId,
336 providerSessionId: input.providerSessionId,
337 });
338 const occurredAt = payloadInput.occurredAt ?? (yield* DateTime.now);
339 return yield* decodeDomainEvent(
340 compactUndefined({
341 id: eventId,
342 type: payloadInput.type,
343 threadId,
344 runId: payloadInput.runId ?? input.runId,
345 nodeId: payloadInput.nodeId ?? input.nodeId,
346 driver: input.event.driver,
347 providerInstanceId: input.providerInstanceId,
348 rawEventId: input.rawEventId,
349 occurredAt,
350 payload: payloadInput.payload,
351 }),
352 );
353 });
354​
355 const dismissNativeUserInputs = Effect.fn("ProviderEventIngestor.dismissNativeUserInputs")(
356 function* (
357 input: ProviderEventIngestInput,
358 providerTurnId: ProviderTurnId,
359 threadId = input.threadId,
360 ) {
361 const pending = yield* projections.getPendingNativeUserInputs(threadId, providerTurnId);
362 const now = yield* DateTime.now;
363 const events: Array<OrchestrationV2DomainEvent> = [];
364 for (const request of pending.runtimeRequests) {
365 events.push(
366 yield* makeDomainEvent(input, {
367 type: "runtime-request.updated",
368 threadId,
369 nodeId: request.nodeId,
370 payload: { ...request, status: "cancelled", resolvedAt: now },
371 }),
372 );
373 }
374 for (const node of pending.nodes) {
375 events.push(
376 yield* makeDomainEvent(input, {
377 type: "node.updated",
378 threadId,
379 nodeId: node.id,
380 runId: node.runId,
381 payload: { ...node, status: "cancelled", completedAt: now },
382 }),
383 );
384 }
385 for (const item of pending.turnItems) {
386 events.push(
387 yield* makeDomainEvent(input, {
388 type: "turn-item.updated",
389 threadId,
390 nodeId: item.nodeId,
391 runId: item.runId,
392 payload: { ...item, status: "cancelled", completedAt: now, updatedAt: now },
393 }),
394 );
395 }
396 return events;
397 },
398 );
399​
400 /**
401 * A native subagent's thread starts on the parent's model when the
402 * provider names the real one later (a Claude agent file's model arrives
403 * with the subagent's first reply). Clients read the thread's model, so
404 * move the thread to the reported one. Thread commands rewrite the whole
405 * thread row under the thread's lock, so this read and write take it too.
406 */
407 const syncSubagentThreadModel = Effect.fn("ProviderEventIngestor.syncSubagentThreadModel")(
408 function* (input: ProviderEventIngestInput, subagent: OrchestrationV2Subagent) {
409 const { childThreadId, model } = subagent;
410 if (subagent.origin !== "provider_native" || childThreadId === null || model === null) {
411 return [];
412 }
413 const staleThread = projections.getThread(childThreadId).pipe(
414 Effect.map((thread) => (thread.modelSelection.model === model ? null : thread)),
415 Effect.catchTags({ ProjectionStoreThreadNotFoundError: () => Effect.succeed(null) }),
416 );
417 // Nearly every update already matches; only a mismatch takes the lock.
418 if ((yield* staleThread) === null) return [];
419 return yield* threadCommands.withLock(
420 childThreadId,
421 Effect.gen(function* () {
422 const thread = yield* staleThread;
423 if (thread === null) return [];
424 const now = yield* DateTime.now;
425 const event = yield* makeDomainEvent(input, {
426 type: "thread.model-selection-updated",
427 threadId: thread.id,
428 // The parent's options belong to the parent's model.
429 payload: {
430 ...thread,
431 modelSelection: { instanceId: thread.modelSelection.instanceId, model },
432 updatedAt: now,
433 },
434 occurredAt: now,
435 });
436 return yield* eventSink.write({ events: [event] });
437 }),
438 );
439 },
440 );
441​
442 /**
443 * The provider rewound its conversation outside T3. Retire the runs that
444 * fell off its active branch with the same run, root-node, and checkpoint
445 * updates CheckpointRollbackService writes for a T3 revert. The run
446 * reporting the rewind performed it and stays, so it keeps lastRunOrdinal.
447 */
448 const rollBackRewoundRuns = Effect.fn("ProviderEventIngestor.rollBackRewoundRuns")(function* (
449 input: ProviderEventIngestInput,
450 rewind: {
451 readonly threadId: ThreadId;
452 readonly providerThreadId: ProviderThreadId;
453 readonly retainedNativeTurnIds: ReadonlySet<string>;
454 },
455 ) {
456 const projection = yield* projections.getThreadRecords(rewind.threadId, [
457 "runs",
458 "attempts",
459 "providerTurns",
460 "nodes",
461 "checkpoints",
462 ]);
463 const runs = runsOffNativeBranch({
464 projection,
465 providerThreadId: rewind.providerThreadId,
466 retainedNativeTurnIds: rewind.retainedNativeTurnIds,
467 reportingRunId: input.runId,
468 });
469 if (runs.length === 0) return [];
470 const now = yield* DateTime.now;
471 const eventId = () =>
472 idAllocator.allocate.event({
473 threadId: rewind.threadId,
474 providerSessionId: input.providerSessionId,
475 });
476 const runIds = new Set(runs.map((run) => run.id));
477 const events: Array<OrchestrationV2DomainEvent> = [];
478 for (const checkpoint of projection.checkpoints) {
479 if (checkpoint.status !== "ready" || checkpoint.runId === null) continue;
480 if (!runIds.has(checkpoint.runId)) continue;
481 events.push({
482 id: yield* eventId(),
483 type: "checkpoint.captured",
484 threadId: rewind.threadId,
485 runId: checkpoint.runId,
486 nodeId: checkpoint.nodeId,
487 providerInstanceId: input.providerInstanceId,
488 occurredAt: now,
489 payload: { ...checkpoint, status: "stale" },
490 });
491 }
492 for (const run of runs) {
493 const rootNode = projection.nodes.find((node) => node.id === run.rootNodeId);
494 events.push({
495 id: yield* eventId(),
496 type: "run.updated",
497 threadId: rewind.threadId,
498 runId: run.id,
499 ...(rootNode === undefined ? {} : { nodeId: rootNode.id }),
500 providerInstanceId: run.providerInstanceId,
501 occurredAt: now,
502 payload: { ...run, status: "rolled_back", completedAt: now },
503 });
504 if (rootNode !== undefined) {
505 events.push({
506 id: yield* eventId(),
507 type: "node.updated",
508 threadId: rewind.threadId,
509 runId: run.id,
510 nodeId: rootNode.id,
511 providerInstanceId: run.providerInstanceId,
512 occurredAt: now,
513 payload: { ...rootNode, status: "rolled_back", completedAt: now },
514 });
515 }
516 }
517 return events;
518 });
519​
520 const normalize: ProviderEventIngestorV2Shape["normalize"] = (input) =>
521 Effect.gen(function* () {
522 switch (input.event.type) {
523 case "app_thread.created":
524 return [
525 yield* makeDomainEvent(input, {
526 type: "thread.created",
527 threadId: input.event.appThread.id,
528 payload: input.event.appThread,
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 )
566 : []),
567 yield* makeDomainEvent(input, {
568 type: "provider-turn.updated",
569 ...(input.event.threadId === undefined ? {} : { threadId: input.event.threadId }),
570 payload: input.event.providerTurn,
571 nodeId: input.event.providerTurn.nodeId,
572 }),
573 ];
574 case "node.updated":
575 return [
576 yield* makeDomainEvent(input, {
577 type: "node.updated",
578 threadId: input.event.node.threadId,
579 payload: input.event.node,
580 runId: input.event.node.runId,
581 nodeId: input.event.node.id,
582 }),
583 ];
584 case "subagent.updated":
585 return [
586 yield* makeDomainEvent(input, {
587 type: "subagent.updated",
588 threadId: input.event.subagent.threadId,
589 payload: input.event.subagent,
590 runId: input.event.subagent.runId,
591 nodeId: input.event.subagent.id,
592 }),
593 ];
594 case "message.updated":
595 return [
596 yield* makeDomainEvent(input, {
597 type: "message.updated",
598 threadId: input.event.message.threadId,
599 payload: input.event.message,
600 runId: input.event.message.runId,
601 nodeId: input.event.message.nodeId,
602 }),
603 ];
604 case "turn_item.updated":
605 return [
606 yield* makeDomainEvent(input, {
607 type: "turn-item.updated",
608 threadId: input.event.turnItem.threadId,
609 payload: stripUnservedToolOutputImageBytes(input.event.turnItem),
610 runId: input.event.turnItem.runId,
611 nodeId: input.event.turnItem.nodeId,
612 }),
613 ];
614 case "runtime_request.updated":
615 return [
616 yield* makeDomainEvent(input, {
617 type: "runtime-request.updated",
618 ...(input.event.threadId === undefined ? {} : { threadId: input.event.threadId }),
619 payload: input.event.runtimeRequest,
620 nodeId: input.event.runtimeRequest.nodeId,
621 }),
622 ];
623 case "plan.updated": {
624 const occurredAt = yield* DateTime.now;
625 const plan = input.event.plan;
626 const previous =
627 plan.kind === "todo_list"
628 ? yield* projections.getPlan(plan.threadId, plan.id)
629 : undefined;
630 const payload =
631 plan.kind === "todo_list"
632 ? withPlanStepDurations(
633 plan,
634 previous?.kind === "todo_list" ? previous : undefined,
635 occurredAt,
636 )
637 : plan;
638 return [
639 yield* makeDomainEvent(input, {
640 type: "plan.updated",
641 threadId: plan.threadId,
642 payload,
643 runId: plan.runId,
644 nodeId: plan.nodeId,
645 occurredAt,
646 }),
647 ];
648 }
649 case "turn.terminal":
650 const dismissed = yield* dismissNativeUserInputs(input, input.event.providerTurnId);
651 if (input.event.status !== "failed") {
652 return dismissed;
653 }
654 const occurredAt = yield* DateTime.now;
655 return [
656 ...dismissed,
657 yield* makeDomainEvent(input, {
658 type: "turn-item.updated",
659 payload: makeProviderFailureTurnItem({
660 idAllocator,
661 driver: input.event.driver,
662 threadId: input.threadId,
663 runId: input.runId ?? null,
664 nodeId: input.nodeId ?? null,
665 providerThreadId: input.event.providerThreadId,
666 providerTurnId: input.event.providerTurnId,
667 itemOrdinal: input.event.failureItemOrdinal,
668 failure: input.event.failure,
669 ...(input.event.retry === undefined ? {} : { retry: input.event.retry }),
670 ...(input.event.retryStartedAt === undefined
671 ? {}
672 : { retryStartedAt: input.event.retryStartedAt }),
673 occurredAt,
674 }),
675 }),
676 ];
677 }
678 }).pipe(
679 Effect.mapError(
680 (cause) =>
681 new ProviderEventNormalizeError({
682 providerSessionId: input.providerSessionId,
683 threadId: input.threadId,
684 providerEvent: input.event,
685 cause,
686 }),
687 ),
688 );
689​
690 return ProviderEventIngestorV2.of({
691 normalize,
692 ingestNormalized: (input) =>
693 Effect.gen(function* () {
694 const events = yield* normalize(input);
695 if (events.length === 0) {
696 return [];
697 }
698 const mapWriteError = (cause: unknown) =>
699 new ProviderEventPublishError({
700 providerSessionId: input.providerSessionId,
701 eventCount: events.length,
702 cause,
703 });
704 if (input.writeIfProviderThreadOwner !== undefined) {
705 const ownerResult = yield* eventSink
706 .writeIfProviderThreadOwner({
707 guardPendingUserInputCancellations: true,
708 ...(input.commandId === undefined ? {} : { commandId: input.commandId }),
709 ...input.writeIfProviderThreadOwner,
710 events,
711 })
712 .pipe(Effect.mapError(mapWriteError));
713 return ownerResult.storedEvents;
714 }
715 if (input.writeIfRunCurrent === undefined) {
716 return yield* eventSink
717 .write({
718 guardPendingUserInputCancellations: true,
719 ...(input.commandId === undefined ? {} : { commandId: input.commandId }),
720 events,
721 })
722 .pipe(Effect.mapError(mapWriteError));
723 }
724 const result = yield* eventSink
725 .writeIfRunCurrent({
726 guardPendingUserInputCancellations: true,
727 ...(input.commandId === undefined ? {} : { commandId: input.commandId }),
728 threadId: input.threadId,
729 ...input.writeIfRunCurrent,
730 events,
731 })
732 .pipe(Effect.mapError(mapWriteError));
733 return result.storedEvents;
734 }).pipe(
735 Effect.flatMap((storedEvents) =>
736 storedEvents.length === 0 || input.event.type !== "subagent.updated"
737 ? Effect.succeed(storedEvents)
738 : syncSubagentThreadModel(input, input.event.subagent).pipe(
739 Effect.map((synced) => [...storedEvents, ...synced]),
740 Effect.mapError(
741 (cause) =>
742 new ProviderEventPublishError({
743 providerSessionId: input.providerSessionId,
744 eventCount: 1,
745 cause,
746 }),
747 ),
748 ),
749 ),
750 Effect.tap((storedEvents) =>
751 Effect.gen(function* () {
752 if (storedEvents.length === 0 || input.event.type !== "provider_turn.updated") return;
753 const providerTurn = input.event.providerTurn;
754 if (
755 providerTurn.status !== "completed" &&
756 providerTurn.status !== "failed" &&
757 providerTurn.status !== "interrupted" &&
758 providerTurn.status !== "cancelled"
759 )
760 return;
761 const key = `${input.providerInstanceId}:${providerTurn.id}`;
762 if (completedTurnAnalytics.has(key)) return;
763 completedTurnAnalytics.add(key);
764 if (completedTurnAnalytics.size > 4096) {
765 const oldest = completedTurnAnalytics.values().next().value;
766 if (oldest !== undefined) completedTurnAnalytics.delete(oldest);
767 }
768 yield* analytics.record(
769 providerTurnAnalyticsProperties({
770 driver: input.event.driver,
771 providerTurn,
772 ...(input.analyticsContext === undefined
773 ? {}
774 : { context: input.analyticsContext }),
775 }),
776 );
777 }),
778 ),
779 ),
780 });
781 }),
782);