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

ProviderEventIngestor.ts

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