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

ProviderEventIngestor.ts

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