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

ProviderEventIngestor.ts

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