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

ProviderEventIngestor.ts

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