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

ProviderEventIngestor.ts

856 lines32.7 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​
205const CONVERSATION_RUN_STATUSES = new Set<OrchestrationV2Run["status"]>([
206 "completed",
207 "interrupted",
208 "failed",
209]);
210​
211function runsOffNativeBranch(input: {
212 readonly projection: Pick<OrchestrationV2ThreadProjection, "runs" | "attempts" | "providerTurns">;
213 readonly providerThreadId: ProviderThreadId;
214 readonly retainedNativeTurnIds: ReadonlySet<string>;
215 readonly reportingRunId: RunId | undefined;
216}): ReadonlyArray<OrchestrationV2Run> {
217 const { attempts, providerTurns, runs } = input.projection;
218 const nativeTurnId = (run: OrchestrationV2Run) => {
219 const attempt = attempts.find((candidate) => candidate.id === run.activeAttemptId);
220 if (attempt === undefined) return null;
221 const ref = providerTurns.find(
222 (turn) => turn.id === attempt.providerTurnId || turn.runAttemptId === attempt.id,
223 )?.nativeTurnRef;
224 return ref?.strength === "strong" ? ref.nativeId : null;
225 };
226 const settled = runs.flatMap((run) =>
227 run.providerThreadId === input.providerThreadId &&
228 run.id !== input.reportingRunId &&
229 CONVERSATION_RUN_STATUSES.has(run.status)
230 ? [{ run, nativeTurnId: nativeTurnId(run) }]
231 : [],
232 );
233 const lastRetainedOrdinal = settled.reduce(
234 (last, { run, nativeTurnId }) =>
235 nativeTurnId !== null && input.retainedNativeTurnIds.has(nativeTurnId)
236 ? Math.max(last, run.ordinal)
237 : last,
238 0,
239 );
240 return settled
241 .filter(({ run, nativeTurnId }) =>
242 nativeTurnId === null
243 ? run.ordinal > lastRetainedOrdinal
244 : !input.retainedNativeTurnIds.has(nativeTurnId),
245 )
246 .map(({ run }) => run);
248​
249export interface ProviderEventIngestInput {
250 readonly providerSessionId: ProviderSessionId;
251 readonly providerInstanceId: ProviderInstanceId;
252 readonly commandId?: CommandId;
253 readonly threadId: ThreadId;
254 readonly runId?: RunId;
255 readonly nodeId?: NodeId;
256 readonly rawEventId?: RawEventId;
257 readonly event: ProviderAdapter.ProviderAdapterV2Event;
258 readonly analyticsContext?: ProviderTurnAnalyticsContext;
260​
261export interface ProviderEventIngestorV2Shape {
262 readonly normalize: (
263 input: ProviderEventIngestInput,
264 ) => Effect.Effect<ReadonlyArray<OrchestrationV2DomainEvent>, ProviderEventIngestorV2Error>;
265 readonly ingestNormalized: (
266 input: ProviderEventIngestInput & {
267 readonly writeIfRunCurrent?: {
268 readonly runId: RunId;
269 readonly activeAttemptId: RunAttemptId;
270 readonly expectedStatus: OrchestrationV2Run["status"];
271 };
272 readonly writeIfProviderThreadOwner?: {
273 readonly providerThreadId: ProviderThreadId;
274 readonly runId: RunId;
275 readonly activeAttemptId: RunAttemptId;
276 readonly expectedLastRunOrdinal: number;
277 };
278 },
279 ) => Effect.Effect<ReadonlyArray<OrchestrationV2StoredEvent>, ProviderEventIngestorV2Error>;
281​
282export class ProviderEventIngestorV2 extends Context.Service<
283 ProviderEventIngestorV2,
284 ProviderEventIngestorV2Shape
285>()("t3/orchestration-v2/ProviderEventIngestor/ProviderEventIngestorV2") {}
286​
287function compactUndefined<T extends Record<string, unknown>>(record: T): T {
288 return Object.fromEntries(Object.entries(record).filter(([, value]) => value !== undefined)) as T;
290​
291const decodeDomainEvent = Schema.decodeUnknownEffect(OrchestrationV2DomainEvent);
292​
293export const layer: Layer.Layer<
294 ProviderEventIngestorV2,
295 never,
296 | EventSink.EventSinkV2
297 | GitVcsDriver.GitVcsDriver
298 | IdAllocator.IdAllocatorV2
299 | ProjectionStore.ProjectionStoreV2
300 | ThreadCommandExecutor.ThreadCommandExecutor
301> = Layer.effect(
302 ProviderEventIngestorV2,
303 Effect.gen(function* () {
304 const eventSink = yield* EventSink.EventSinkV2;
305 const git = yield* GitVcsDriver.GitVcsDriver;
306 const projections = yield* ProjectionStore.ProjectionStoreV2;
307 const idAllocator = yield* IdAllocator.IdAllocatorV2;
308 const threadCommands = yield* ThreadCommandExecutor.ThreadCommandExecutor;
309 const analytics = yield* ProviderTurnAnalytics;
310 const agentScope = yield* AgentScope;
311 const completedTurnAnalytics = new Set<string>();
312​
313 const makeDomainEvent = (
314 input: ProviderEventIngestInput,
315 payloadInput: {
316 readonly type: OrchestrationV2DomainEvent["type"];
317 readonly payload: OrchestrationV2DomainEvent["payload"];
318 readonly threadId?: ThreadId;
319 readonly runId?: RunId | null;
320 readonly nodeId?: NodeId | null;
321 readonly occurredAt?: DateTime.Utc;
322 },
323 ) =>
324 Effect.gen(function* () {
325 const threadId = payloadInput.threadId ?? input.threadId;
326 const eventId = yield* idAllocator.allocate.event({
327 threadId,
328 providerSessionId: input.providerSessionId,
329 });
330 const occurredAt = payloadInput.occurredAt ?? (yield* DateTime.now);
331 return yield* decodeDomainEvent(
332 compactUndefined({
333 id: eventId,
334 type: payloadInput.type,
335 threadId,
336 runId: payloadInput.runId ?? input.runId,
337 nodeId: payloadInput.nodeId ?? input.nodeId,
338 driver: input.event.driver,
339 providerInstanceId: input.providerInstanceId,
340 rawEventId: input.rawEventId,
341 occurredAt,
342 payload: payloadInput.payload,
343 }),
344 );
345 });
346​
347 const dismissNativeUserInputs = Effect.fn("ProviderEventIngestor.dismissNativeUserInputs")(
348 function* (
349 input: ProviderEventIngestInput,
350 providerTurnId: ProviderTurnId,
351 threadId = input.threadId,
352 ) {
353 const pending = yield* projections.getPendingNativeUserInputs(threadId, providerTurnId);
354 const now = yield* DateTime.now;
355 const events: Array<OrchestrationV2DomainEvent> = [];
356 for (const request of pending.runtimeRequests) {
357 events.push(
358 yield* makeDomainEvent(input, {
359 type: "runtime-request.updated",
360 threadId,
361 nodeId: request.nodeId,
362 payload: { ...request, status: "cancelled", resolvedAt: now },
363 }),
364 );
365 }
366 for (const node of pending.nodes) {
367 events.push(
368 yield* makeDomainEvent(input, {
369 type: "node.updated",
370 threadId,
371 nodeId: node.id,
372 runId: node.runId,
373 payload: { ...node, status: "cancelled", completedAt: now },
374 }),
375 );
376 }
377 for (const item of pending.turnItems) {
378 events.push(
379 yield* makeDomainEvent(input, {
380 type: "turn-item.updated",
381 threadId,
382 nodeId: item.nodeId,
383 runId: item.runId,
384 payload: { ...item, status: "cancelled", completedAt: now, updatedAt: now },
385 }),
386 );
387 }
388 return events;
389 },
390 );
391​
392 /**
393 * A native subagent's thread starts on the parent's model when the provider
394 * names the real one later (a Claude agent file's model arrives with the
395 * subagent's first reply). Thread commands rewrite the whole thread row
396 * under the thread's lock, so this read and write take it too.
397 */
398 const syncSubagentThreadModel = Effect.fn("ProviderEventIngestor.syncSubagentThreadModel")(
399 function* (input: ProviderEventIngestInput, subagent: OrchestrationV2Subagent) {
400 const { childThreadId, model } = subagent;
401 if (
402 subagent.origin !== "provider_native" ||
403 childThreadId === null ||
404 (model === null && subagent.modelSelection === undefined)
405 ) {
406 return [];
407 }
408 const reportedSelection = ({ modelSelection }: { modelSelection: ModelSelection }) =>
409 subagent.modelSelection ??
410 (model === null || model === modelSelection.model
411 ? modelSelection
412 : { instanceId: modelSelection.instanceId, model });
413 const staleThread = projections.getThread(childThreadId).pipe(
414 Effect.map((thread) =>
415 modelSelectionsEqual(thread.modelSelection, reportedSelection(thread)) ? null : thread,
416 ),
417 Effect.catchTags({ ProjectionStoreThreadNotFoundError: () => Effect.succeed(null) }),
418 );
419 if ((yield* staleThread) === null) return [];
420 return yield* threadCommands.withLock(
421 childThreadId,
422 Effect.gen(function* () {
423 const thread = yield* staleThread;
424 if (thread === null) return [];
425 const now = yield* DateTime.now;
426 const event = yield* makeDomainEvent(input, {
427 type: "thread.model-selection-updated",
428 threadId: thread.id,
429 payload: {
430 ...thread,
431 modelSelection: reportedSelection(thread),
432 updatedAt: now,
433 },
434 occurredAt: now,
435 });
436 return yield* eventSink.write({ events: [event] });
437 }),
438 );
439 },
440 );
441​
442 /**
443 * Retire the runs that fell off its active branch with the same run,
444 * root-node, and checkpoint updates CheckpointRollbackService writes for a
445 * T3 revert. The run reporting the rewind performed it and stays, so it
446 * keeps lastRunOrdinal.
447 */
448 const rollBackRewoundRuns = Effect.fn("ProviderEventIngestor.rollBackRewoundRuns")(function* (
449 input: ProviderEventIngestInput,
450 rewind: {
451 readonly threadId: ThreadId;
452 readonly providerThreadId: ProviderThreadId;
453 readonly retainedNativeTurnIds: ReadonlySet<string>;
454 },
455 ) {
456 const projection = yield* projections.getThreadRecords(rewind.threadId, [
457 "runs",
458 "attempts",
459 "providerTurns",
460 "nodes",
461 "checkpoints",
462 ]);
463 const runs = runsOffNativeBranch({
464 projection,
465 providerThreadId: rewind.providerThreadId,
466 retainedNativeTurnIds: rewind.retainedNativeTurnIds,
467 reportingRunId: input.runId,
468 });
469 if (runs.length === 0) return [];
470 const now = yield* DateTime.now;
471 const eventId = () =>
472 idAllocator.allocate.event({
473 threadId: rewind.threadId,
474 providerSessionId: input.providerSessionId,
475 });
476 const runIds = new Set(runs.map((run) => run.id));
477 const events: Array<OrchestrationV2DomainEvent> = [];
478 for (const checkpoint of projection.checkpoints) {
479 if (checkpoint.status !== "ready" || checkpoint.runId === null) continue;
480 if (!runIds.has(checkpoint.runId)) continue;
481 events.push({
482 id: yield* eventId(),
483 type: "checkpoint.captured",
484 threadId: rewind.threadId,
485 runId: checkpoint.runId,
486 nodeId: checkpoint.nodeId,
487 providerInstanceId: input.providerInstanceId,
488 occurredAt: now,
489 payload: { ...checkpoint, status: "stale" },
490 });
491 }
492 for (const run of runs) {
493 const rootNode = projection.nodes.find((node) => node.id === run.rootNodeId);
494 events.push({
495 id: yield* eventId(),
496 type: "run.updated",
497 threadId: rewind.threadId,
498 runId: run.id,
499 ...(rootNode === undefined ? {} : { nodeId: rootNode.id }),
500 providerInstanceId: run.providerInstanceId,
501 occurredAt: now,
502 payload: { ...run, status: "rolled_back", completedAt: now },
503 });
504 if (rootNode !== undefined) {
505 events.push({
506 id: yield* eventId(),
507 type: "node.updated",
508 threadId: rewind.threadId,
509 runId: run.id,
510 nodeId: rootNode.id,
511 providerInstanceId: run.providerInstanceId,
512 occurredAt: now,
513 payload: { ...rootNode, status: "rolled_back", completedAt: now },
514 });
515 }
516 }
517 return events;
518 });
519​
520 const normalize: ProviderEventIngestorV2Shape["normalize"] = (input) =>
521 Effect.gen(function* () {
522 switch (input.event.type) {
523 case "app_thread.created": {
524 const offered = input.event.appThread;
525 const existing = yield* projections.getThread(offered.id).pipe(
526 Effect.catchTags({
527 ProjectionStoreThreadNotFoundError: () => Effect.succeed(null),
528 }),
529 );
530 if (
531 existing !== null &&
532 existing.title === offered.title &&
533 modelSelectionsEqual(existing.modelSelection, offered.modelSelection)
534 )
535 return [];
536 const now = yield* DateTime.now;
537 return [
538 yield* makeDomainEvent(input, {
539 type: existing === null ? "thread.created" : "thread.metadata-updated",
540 threadId: offered.id,
541 payload:
542 existing === null
543 ? offered
544 : {
545 ...existing,
546 title: offered.title,
547 modelSelection: offered.modelSelection,
548 updatedAt: now,
549 },
550 occurredAt: now,
551 }),
552 ];
553 }
554 case "provider_session.updated":
555 return [
556 yield* makeDomainEvent(input, {
557 type: "provider-session.updated",
558 payload: input.event.providerSession,
559 }),
560 ];
561 case "provider_thread.updated": {
562 const threadId = input.event.providerThread.appThreadId ?? input.threadId;
563 const updated = yield* makeDomainEvent(input, {
564 type: "provider-thread.updated",
565 threadId,
566 payload: input.event.providerThread,
567 });
568 return input.event.retainedNativeTurnIds === undefined
569 ? [updated]
570 : [
571 updated,
572 ...(yield* rollBackRewoundRuns(input, {
573 threadId,
574 providerThreadId: input.event.providerThread.id,
575 retainedNativeTurnIds: new Set(input.event.retainedNativeTurnIds),
576 })),
577 ];
578 }
579 case "provider_turn.updated":
580 return [
581 ...(["completed", "interrupted", "failed", "cancelled"].includes(
582 input.event.providerTurn.status,
583 )
584 ? yield* dismissNativeUserInputs(
585 input,
586 input.event.providerTurn.id,
587 input.event.threadId,
588 )
589 : []),
590 yield* makeDomainEvent(input, {
591 type: "provider-turn.updated",
592 ...(input.event.threadId === undefined ? {} : { threadId: input.event.threadId }),
593 payload: input.event.providerTurn,
594 nodeId: input.event.providerTurn.nodeId,
595 }),
596 ];
597 case "node.updated":
598 // Adapters send an unchanged node again with each text delta. Compare with the
599 // stored node, not the last one sent, because the server also writes nodes.
600 if (yield* projections.isNodeStored(input.event.node)) return [];
601 return [
602 yield* makeDomainEvent(input, {
603 type: "node.updated",
604 threadId: input.event.node.threadId,
605 payload: input.event.node,
606 runId: input.event.node.runId,
607 nodeId: input.event.node.id,
608 }),
609 ];
610 case "subagent.updated":
611 return [
612 yield* makeDomainEvent(input, {
613 type: "subagent.updated",
614 threadId: input.event.subagent.threadId,
615 payload: input.event.subagent,
616 runId: input.event.subagent.runId,
617 nodeId: input.event.subagent.id,
618 }),
619 ];
620 case "message.updated":
621 return [
622 yield* makeDomainEvent(input, {
623 type: "message.updated",
624 threadId: input.event.message.threadId,
625 payload: input.event.message,
626 runId: input.event.message.runId,
627 nodeId: input.event.message.nodeId,
628 }),
629 ];
630 case "turn_item.updated":
631 return [
632 yield* makeDomainEvent(input, {
633 type: "turn-item.updated",
634 threadId: input.event.turnItem.threadId,
635 payload: boundFileChangeForStorage(
636 stripUnservedToolOutputImageBytes(input.event.turnItem),
637 ),
638 runId: input.event.turnItem.runId,
639 nodeId: input.event.turnItem.nodeId,
640 }),
641 ];
642 case "runtime_request.updated":
643 return [
644 yield* makeDomainEvent(input, {
645 type: "runtime-request.updated",
646 ...(input.event.threadId === undefined ? {} : { threadId: input.event.threadId }),
647 payload: input.event.runtimeRequest,
648 nodeId: input.event.runtimeRequest.nodeId,
649 }),
650 ];
651 case "plan.updated": {
652 const occurredAt = yield* DateTime.now;
653 const plan = input.event.plan;
654 const previous =
655 plan.kind === "todo_list"
656 ? yield* projections.getPlan(plan.threadId, plan.id)
657 : undefined;
658 const payload =
659 plan.kind === "todo_list"
660 ? withPlanStepDurations(
661 plan,
662 previous?.kind === "todo_list" ? previous : undefined,
663 occurredAt,
664 )
665 : plan;
666 return [
667 yield* makeDomainEvent(input, {
668 type: "plan.updated",
669 threadId: plan.threadId,
670 payload,
671 runId: plan.runId,
672 nodeId: plan.nodeId,
673 occurredAt,
674 }),
675 ];
676 }
677 case "command_output.delta":
678 // Live output is routed to the command output hub before ingestion.
679 return [];
680 case "turn.terminal":
681 const dismissed = yield* dismissNativeUserInputs(input, input.event.providerTurnId);
682 if (input.event.status !== "failed") {
683 return dismissed;
684 }
685 const occurredAt = yield* DateTime.now;
686 const failure = (yield* agentScope.oomKilled(input.threadId))
687 ? { ...input.event.failure, message: "Killed: out of memory.", code: "oom_kill" }
688 : input.event.failure;
689 return [
690 ...dismissed,
691 yield* makeDomainEvent(input, {
692 type: "turn-item.updated",
693 payload: makeProviderFailureTurnItem({
694 driver: input.event.driver,
695 threadId: input.threadId,
696 runId: input.runId ?? null,
697 nodeId: input.nodeId ?? null,
698 providerThreadId: input.event.providerThreadId,
699 providerTurnId: input.event.providerTurnId,
700 itemOrdinal: input.event.failureItemOrdinal,
701 failure,
702 ...(input.event.retry === undefined ? {} : { retry: input.event.retry }),
703 ...(input.event.retryStartedAt === undefined
704 ? {}
705 : { retryStartedAt: input.event.retryStartedAt }),
706 occurredAt,
707 }),
708 }),
709 ];
710 }
711 }).pipe(
712 Effect.mapError(
713 (cause) =>
714 new ProviderEventNormalizeError({
715 providerSessionId: input.providerSessionId,
716 threadId: input.threadId,
717 providerEvent: input.event,
718 cause,
719 }),
720 ),
721 );
722​
723 return ProviderEventIngestorV2.of({
724 normalize,
725 ingestNormalized: (input) =>
726 Effect.gen(function* () {
727 const events = yield* normalize(input);
728 if (events.length === 0) {
729 return [];
730 }
731 const mapWriteError = (cause: unknown) =>
732 new ProviderEventPublishError({
733 providerSessionId: input.providerSessionId,
734 eventCount: events.length,
735 cause,
736 });
737 if (input.writeIfProviderThreadOwner !== undefined) {
738 const ownerResult = yield* eventSink
739 .writeIfProviderThreadOwner({
740 guardPendingUserInputCancellations: true,
741 ...(input.commandId === undefined ? {} : { commandId: input.commandId }),
742 ...input.writeIfProviderThreadOwner,
743 events,
744 })
745 .pipe(Effect.mapError(mapWriteError));
746 return ownerResult.storedEvents;
747 }
748 if (input.writeIfRunCurrent === undefined) {
749 return yield* eventSink
750 .write({
751 guardPendingUserInputCancellations: true,
752 ...(input.commandId === undefined ? {} : { commandId: input.commandId }),
753 events,
754 })
755 .pipe(Effect.mapError(mapWriteError));
756 }
757 const result = yield* eventSink
758 .writeIfRunCurrent({
759 guardPendingUserInputCancellations: true,
760 ...(input.commandId === undefined ? {} : { commandId: input.commandId }),
761 threadId: input.threadId,
762 ...input.writeIfRunCurrent,
763 events,
764 })
765 .pipe(Effect.mapError(mapWriteError));
766 return result.storedEvents;
767 }).pipe(
768 Effect.flatMap((storedEvents) =>
769 Effect.gen(function* () {
770 if (input.event.type !== "app_thread.created") return storedEvents;
771 const created = storedEvents.find((stored) => stored.event.type === "thread.created");
772 if (created?.event.type !== "thread.created") return storedEvents;
773 const child = created.event.payload;
774 if (
775 child.worktreePath === null ||
776 child.branch === null ||
777 !isTemporaryWorktreeBranch(child.branch)
778 )
779 return storedEvents;
780 // Git renames before scanning committed threads. If that scan missed this
781 // creation, HEAD already has the new name, even if the parent moved away.
782 const branch = yield* git.resolveBranchName(child.worktreePath, "HEAD");
783 if (branch === null || branch === child.branch) return storedEvents;
784 const now = yield* DateTime.now;
785 const event = yield* makeDomainEvent(input, {
786 type: "thread.metadata-updated",
787 threadId: child.id,
788 payload: { ...child, branch, updatedAt: now },
789 occurredAt: now,
790 });
791 const synced = yield* eventSink.write({ events: [event] });
792 return [...storedEvents, ...synced];
793 }).pipe(
794 Effect.catchCause((cause) =>
795 Effect.logWarning("Native thread worktree branch recheck failed", {
796 threadId:
797 input.event.type === "app_thread.created"
798 ? input.event.appThread.id
799 : input.threadId,
800 cause,
801 }).pipe(Effect.as(storedEvents)),
802 ),
803 ),
804 ),
805 Effect.flatMap((storedEvents) =>
806 storedEvents.length === 0 || input.event.type !== "subagent.updated"
807 ? Effect.succeed(storedEvents)
808 : syncSubagentThreadModel(input, input.event.subagent).pipe(
809 Effect.map((synced) => [...storedEvents, ...synced]),
810 Effect.mapError(
811 (cause) =>
812 new ProviderEventPublishError({
813 providerSessionId: input.providerSessionId,
814 eventCount: 1,
815 cause,
816 }),
817 ),
818 ),
819 ),
820 Effect.tap((storedEvents) =>
821 Effect.gen(function* () {
822 if (storedEvents.length === 0 || input.event.type !== "provider_turn.updated") return;
823 const providerTurn = input.event.providerTurn;
824 if (
825 providerTurn.status !== "completed" &&
826 providerTurn.status !== "failed" &&
827 providerTurn.status !== "interrupted" &&
828 providerTurn.status !== "cancelled"
829 )
830 return;
831 const key = `${input.providerInstanceId}:${providerTurn.id}`;
832 if (completedTurnAnalytics.has(key)) return;
833 completedTurnAnalytics.add(key);
834 if (completedTurnAnalytics.size > 4096) {
835 const oldest = completedTurnAnalytics.values().next().value;
836 if (oldest !== undefined) completedTurnAnalytics.delete(oldest);
837 }
838 yield* analytics.record(
839 providerTurnAnalyticsProperties({
840 driver: input.event.driver,
841 providerTurn,
842 ...(input.analyticsContext === undefined
843 ? {}
844 : { context: input.analyticsContext }),
845 }),
846 );
847 }),
848 ),
849 (effect) =>
850 input.event.type === "app_thread.created"
851 ? threadCommands.withLock(input.event.appThread.id, effect)
852 : effect,
853 ),
854 });
855 }),
856);