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

ProviderEventIngestor.ts

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