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

ProviderEventIngestor.ts

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