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

ProviderEventIngestor.ts

828 lines31.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 const offered = input.event.appThread;
540 const existing = yield* projections.getThread(offered.id).pipe(
541 Effect.catchTags({
542 ProjectionStoreThreadNotFoundError: () => Effect.succeed(null),
543 }),
544 );
545 if (
546 existing !== null &&
547 existing.title === offered.title &&
548 modelSelectionsEqual(existing.modelSelection, offered.modelSelection)
549 )
550 return [];
551 const now = yield* DateTime.now;
552 return [
553 yield* makeDomainEvent(input, {
554 type: existing === null ? "thread.created" : "thread.metadata-updated",
555 threadId: offered.id,
556 payload:
557 existing === null
558 ? offered
559 : {
560 ...existing,
561 title: offered.title,
562 modelSelection: offered.modelSelection,
563 updatedAt: now,
564 },
565 occurredAt: now,
566 }),
567 ];
568 }
569 case "provider_session.updated":
570 return [
571 yield* makeDomainEvent(input, {
572 type: "provider-session.updated",
573 payload: input.event.providerSession,
574 }),
575 ];
576 case "provider_thread.updated": {
577 const threadId = input.event.providerThread.appThreadId ?? input.threadId;
578 const updated = yield* makeDomainEvent(input, {
579 type: "provider-thread.updated",
580 threadId,
581 payload: input.event.providerThread,
582 });
583 return input.event.retainedNativeTurnIds === undefined
584 ? [updated]
585 : [
586 updated,
587 ...(yield* rollBackRewoundRuns(input, {
588 threadId,
589 providerThreadId: input.event.providerThread.id,
590 retainedNativeTurnIds: new Set(input.event.retainedNativeTurnIds),
591 })),
592 ];
593 }
594 case "provider_turn.updated":
595 return [
596 ...(["completed", "interrupted", "failed", "cancelled"].includes(
597 input.event.providerTurn.status,
598 )
599 ? yield* dismissNativeUserInputs(
600 input,
601 input.event.providerTurn.id,
602 input.event.threadId,
603 )
604 : []),
605 yield* makeDomainEvent(input, {
606 type: "provider-turn.updated",
607 ...(input.event.threadId === undefined ? {} : { threadId: input.event.threadId }),
608 payload: input.event.providerTurn,
609 nodeId: input.event.providerTurn.nodeId,
610 }),
611 ];
612 case "node.updated":
613 return [
614 yield* makeDomainEvent(input, {
615 type: "node.updated",
616 threadId: input.event.node.threadId,
617 payload: input.event.node,
618 runId: input.event.node.runId,
619 nodeId: input.event.node.id,
620 }),
621 ];
622 case "subagent.updated":
623 return [
624 yield* makeDomainEvent(input, {
625 type: "subagent.updated",
626 threadId: input.event.subagent.threadId,
627 payload: input.event.subagent,
628 runId: input.event.subagent.runId,
629 nodeId: input.event.subagent.id,
630 }),
631 ];
632 case "message.updated":
633 return [
634 yield* makeDomainEvent(input, {
635 type: "message.updated",
636 threadId: input.event.message.threadId,
637 payload: input.event.message,
638 runId: input.event.message.runId,
639 nodeId: input.event.message.nodeId,
640 }),
641 ];
642 case "turn_item.updated":
643 return [
644 yield* makeDomainEvent(input, {
645 type: "turn-item.updated",
646 threadId: input.event.turnItem.threadId,
647 payload: stripUnservedToolOutputImageBytes(input.event.turnItem),
648 runId: input.event.turnItem.runId,
649 nodeId: input.event.turnItem.nodeId,
650 }),
651 ];
652 case "runtime_request.updated":
653 return [
654 yield* makeDomainEvent(input, {
655 type: "runtime-request.updated",
656 ...(input.event.threadId === undefined ? {} : { threadId: input.event.threadId }),
657 payload: input.event.runtimeRequest,
658 nodeId: input.event.runtimeRequest.nodeId,
659 }),
660 ];
661 case "plan.updated": {
662 const occurredAt = yield* DateTime.now;
663 const plan = input.event.plan;
664 const previous =
665 plan.kind === "todo_list"
666 ? yield* projections.getPlan(plan.threadId, plan.id)
667 : undefined;
668 const payload =
669 plan.kind === "todo_list"
670 ? withPlanStepDurations(
671 plan,
672 previous?.kind === "todo_list" ? previous : undefined,
673 occurredAt,
674 )
675 : plan;
676 return [
677 yield* makeDomainEvent(input, {
678 type: "plan.updated",
679 threadId: plan.threadId,
680 payload,
681 runId: plan.runId,
682 nodeId: plan.nodeId,
683 occurredAt,
684 }),
685 ];
686 }
687 case "turn.terminal":
688 const dismissed = yield* dismissNativeUserInputs(input, input.event.providerTurnId);
689 if (input.event.status !== "failed") {
690 return dismissed;
691 }
692 const occurredAt = yield* DateTime.now;
693 // A turn that failed because systemd killed the agent's scope for
694 // memory would otherwise read as a plain provider crash.
695 const failure = (yield* agentScope.oomKilled(input.threadId))
696 ? { ...input.event.failure, message: "Killed: out of memory.", code: "oom_kill" }
697 : input.event.failure;
698 return [
699 ...dismissed,
700 yield* makeDomainEvent(input, {
701 type: "turn-item.updated",
702 payload: makeProviderFailureTurnItem({
703 driver: input.event.driver,
704 threadId: input.threadId,
705 runId: input.runId ?? null,
706 nodeId: input.nodeId ?? null,
707 providerThreadId: input.event.providerThreadId,
708 providerTurnId: input.event.providerTurnId,
709 itemOrdinal: input.event.failureItemOrdinal,
710 failure,
711 ...(input.event.retry === undefined ? {} : { retry: input.event.retry }),
712 ...(input.event.retryStartedAt === undefined
713 ? {}
714 : { retryStartedAt: input.event.retryStartedAt }),
715 occurredAt,
716 }),
717 }),
718 ];
719 }
720 }).pipe(
721 Effect.mapError(
722 (cause) =>
723 new ProviderEventNormalizeError({
724 providerSessionId: input.providerSessionId,
725 threadId: input.threadId,
726 providerEvent: input.event,
727 cause,
728 }),
729 ),
730 );
731​
732 return ProviderEventIngestorV2.of({
733 normalize,
734 ingestNormalized: (input) =>
735 Effect.gen(function* () {
736 const events = yield* normalize(input);
737 if (events.length === 0) {
738 return [];
739 }
740 const mapWriteError = (cause: unknown) =>
741 new ProviderEventPublishError({
742 providerSessionId: input.providerSessionId,
743 eventCount: events.length,
744 cause,
745 });
746 if (input.writeIfProviderThreadOwner !== undefined) {
747 const ownerResult = yield* eventSink
748 .writeIfProviderThreadOwner({
749 guardPendingUserInputCancellations: true,
750 ...(input.commandId === undefined ? {} : { commandId: input.commandId }),
751 ...input.writeIfProviderThreadOwner,
752 events,
753 })
754 .pipe(Effect.mapError(mapWriteError));
755 return ownerResult.storedEvents;
756 }
757 if (input.writeIfRunCurrent === undefined) {
758 return yield* eventSink
759 .write({
760 guardPendingUserInputCancellations: true,
761 ...(input.commandId === undefined ? {} : { commandId: input.commandId }),
762 events,
763 })
764 .pipe(Effect.mapError(mapWriteError));
765 }
766 const result = yield* eventSink
767 .writeIfRunCurrent({
768 guardPendingUserInputCancellations: true,
769 ...(input.commandId === undefined ? {} : { commandId: input.commandId }),
770 threadId: input.threadId,
771 ...input.writeIfRunCurrent,
772 events,
773 })
774 .pipe(Effect.mapError(mapWriteError));
775 return result.storedEvents;
776 }).pipe(
777 Effect.flatMap((storedEvents) =>
778 storedEvents.length === 0 || input.event.type !== "subagent.updated"
779 ? Effect.succeed(storedEvents)
780 : syncSubagentThreadModel(input, input.event.subagent).pipe(
781 Effect.map((synced) => [...storedEvents, ...synced]),
782 Effect.mapError(
783 (cause) =>
784 new ProviderEventPublishError({
785 providerSessionId: input.providerSessionId,
786 eventCount: 1,
787 cause,
788 }),
789 ),
790 ),
791 ),
792 Effect.tap((storedEvents) =>
793 Effect.gen(function* () {
794 if (storedEvents.length === 0 || input.event.type !== "provider_turn.updated") return;
795 const providerTurn = input.event.providerTurn;
796 if (
797 providerTurn.status !== "completed" &&
798 providerTurn.status !== "failed" &&
799 providerTurn.status !== "interrupted" &&
800 providerTurn.status !== "cancelled"
801 )
802 return;
803 const key = `${input.providerInstanceId}:${providerTurn.id}`;
804 if (completedTurnAnalytics.has(key)) return;
805 completedTurnAnalytics.add(key);
806 if (completedTurnAnalytics.size > 4096) {
807 const oldest = completedTurnAnalytics.values().next().value;
808 if (oldest !== undefined) completedTurnAnalytics.delete(oldest);
809 }
810 yield* analytics.record(
811 providerTurnAnalyticsProperties({
812 driver: input.event.driver,
813 providerTurn,
814 ...(input.analyticsContext === undefined
815 ? {}
816 : { context: input.analyticsContext }),
817 }),
818 );
819 }),
820 ),
821 (effect) =>
822 input.event.type === "app_thread.created"
823 ? threadCommands.withLock(input.event.appThread.id, effect)
824 : effect,
825 ),
826 });
827 }),
828);