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