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

ProviderEventIngestor.ts

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