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

ProviderEventIngestor.ts

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