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

ProviderEventIngestor.ts

896 lines36.0 KB

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