Open History to see the last commit
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 }
55}
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 }
68}
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;
80}
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 };
139}
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 };
203}
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);
247}
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;
259}
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>;
280}
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;
289}
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 existing.title === offered.title &&
536 modelSelectionsEqual(existing.modelSelection, offered.modelSelection)
537 )
538 return [];
539 const now = yield* DateTime.now;
540 return [
541 yield* makeDomainEvent(input, {
542 type: existing === null ? "thread.created" : "thread.metadata-updated",
543 threadId: offered.id,
544 payload:
545 existing === null
546 ? offered
547 : {
548 ...existing,
549 title: offered.title,
550 modelSelection: offered.modelSelection,
551 updatedAt: now,
552 },
553 occurredAt: now,
554 }),
555 ];
556 }
557 case "provider_session.updated":
558 return [
559 yield* makeDomainEvent(input, {
560 type: "provider-session.updated",
561 payload: input.event.providerSession,
562 }),
563 ];
564 case "provider_thread.updated": {
565 const threadId = input.event.providerThread.appThreadId ?? input.threadId;
566 const updated = yield* makeDomainEvent(input, {
567 type: "provider-thread.updated",
568 threadId,
569 payload: input.event.providerThread,
570 });
571 return input.event.retainedNativeTurnIds === undefined
572 ? [updated]
573 : [
574 updated,
575 ...(yield* rollBackRewoundRuns(input, {
576 threadId,
577 providerThreadId: input.event.providerThread.id,
578 retainedNativeTurnIds: new Set(input.event.retainedNativeTurnIds),
579 })),
580 ];
581 }
582 case "provider_turn.updated":
583 return [
584 ...(["completed", "interrupted", "failed", "cancelled"].includes(
585 input.event.providerTurn.status,
586 )
587 ? yield* dismissNativeUserInputs(
588 input,
589 input.event.providerTurn.id,
590 input.event.threadId,
591 )
592 : []),
593 yield* makeDomainEvent(input, {
594 type: "provider-turn.updated",
595 ...(input.event.threadId === undefined ? {} : { threadId: input.event.threadId }),
596 payload: input.event.providerTurn,
597 nodeId: input.event.providerTurn.nodeId,
598 }),
599 ];
600 case "node.updated":
601 // Adapters send an unchanged node again with each text delta. Compare with the
602 // stored node, not the last one sent, because the server also writes nodes.
603 if (yield* projections.isNodeStored(input.event.node)) return [];
604 return [
605 yield* makeDomainEvent(input, {
606 type: "node.updated",
607 threadId: input.event.node.threadId,
608 payload: input.event.node,
609 runId: input.event.node.runId,
610 nodeId: input.event.node.id,
611 }),
612 ];
613 case "subagent.updated":
614 return [
615 yield* makeDomainEvent(input, {
616 type: "subagent.updated",
617 threadId: input.event.subagent.threadId,
618 payload: input.event.subagent,
619 runId: input.event.subagent.runId,
620 nodeId: input.event.subagent.id,
621 }),
622 ];
623 case "message.updated":
624 return [
625 yield* makeDomainEvent(input, {
626 type: "message.updated",
627 threadId: input.event.message.threadId,
628 payload: input.event.message,
629 runId: input.event.message.runId,
630 nodeId: input.event.message.nodeId,
631 }),
632 ];
633 case "turn_item.updated":
634 return [
635 yield* makeDomainEvent(input, {
636 type: "turn-item.updated",
637 threadId: input.event.turnItem.threadId,
638 payload: boundFileChangeForStorage(
639 stripUnservedToolOutputImageBytes(input.event.turnItem),
640 ),
641 runId: input.event.turnItem.runId,
642 nodeId: input.event.turnItem.nodeId,
643 }),
644 ];
645 case "runtime_request.updated":
646 return [
647 yield* makeDomainEvent(input, {
648 type: "runtime-request.updated",
649 ...(input.event.threadId === undefined ? {} : { threadId: input.event.threadId }),
650 payload: input.event.runtimeRequest,
651 nodeId: input.event.runtimeRequest.nodeId,
652 }),
653 ];
654 case "plan.updated": {
655 const occurredAt = yield* DateTime.now;
656 const plan = input.event.plan;
657 const previous =
658 plan.kind === "todo_list"
659 ? yield* projections.getPlan(plan.threadId, plan.id)
660 : undefined;
661 const payload =
662 plan.kind === "todo_list"
663 ? withPlanStepDurations(
664 plan,
665 previous?.kind === "todo_list" ? previous : undefined,
666 occurredAt,
667 )
668 : plan;
669 return [
670 yield* makeDomainEvent(input, {
671 type: "plan.updated",
672 threadId: plan.threadId,
673 payload,
674 runId: plan.runId,
675 nodeId: plan.nodeId,
676 occurredAt,
677 }),
678 ];
679 }
680 case "command_output.delta":
681 // Live output is routed to the command output hub before ingestion.
682 return [];
683 case "turn.terminal":
684 const dismissed = yield* dismissNativeUserInputs(input, input.event.providerTurnId);
685 if (input.event.status !== "failed") {
686 return dismissed;
687 }
688 const occurredAt = yield* DateTime.now;
689 const failure = (yield* agentScope.oomKilled(input.threadId))
690 ? { ...input.event.failure, message: "Killed: out of memory.", code: "oom_kill" }
691 : input.event.failure;
692 return [
693 ...dismissed,
694 yield* makeDomainEvent(input, {
695 type: "turn-item.updated",
696 payload: makeProviderFailureTurnItem({
697 driver: input.event.driver,
698 threadId: input.threadId,
699 runId: input.runId ?? null,
700 nodeId: input.nodeId ?? null,
701 providerThreadId: input.event.providerThreadId,
702 providerTurnId: input.event.providerTurnId,
703 itemOrdinal: input.event.failureItemOrdinal,
704 failure,
705 ...(input.event.retry === undefined ? {} : { retry: input.event.retry }),
706 ...(input.event.retryStartedAt === undefined
707 ? {}
708 : { retryStartedAt: input.event.retryStartedAt }),
709 occurredAt,
710 }),
711 }),
712 ];
713 }
714 },
715 (effect, input) =>
716 effect.pipe(
717 Effect.mapError(
718 (cause) =>
719 new ProviderEventNormalizeError({
720 providerSessionId: input.providerSessionId,
721 threadId: input.threadId,
722 providerEvent: input.event,
723 cause,
724 }),
725 ),
726 ),
727 );
728
729 return ProviderEventIngestorV2.of({
730 normalize,
731 ingestNormalized:
732 /* This helper runs for individual orchestration events; the enclosing operation owns the span. */
733 Effect.fnUntraced(
734 function* (input) {
735 const events = yield* normalize(input);
736 if (events.length === 0) {
737 return [];
738 }
739 const mapWriteError = (cause: unknown) =>
740 new ProviderEventPublishError({
741 providerSessionId: input.providerSessionId,
742 eventCount: events.length,
743 cause,
744 });
745 if (input.writeIfProviderThreadOwner !== undefined) {
746 const ownerResult = yield* eventSink
747 .writeIfProviderThreadOwner({
748 guardPendingUserInputCancellations: true,
749 ...(input.commandId === undefined ? {} : { commandId: input.commandId }),
750 ...input.writeIfProviderThreadOwner,
751 events,
752 })
753 .pipe(Effect.mapError(mapWriteError));
754 return ownerResult.storedEvents;
755 }
756 if (input.writeIfRunCurrent === undefined) {
757 return yield* eventSink
758 .write({
759 guardPendingUserInputCancellations: true,
760 ...(input.commandId === undefined ? {} : { commandId: input.commandId }),
761 events,
762 })
763 .pipe(Effect.mapError(mapWriteError));
764 }
765 const result = yield* eventSink
766 .writeIfRunCurrent({
767 guardPendingUserInputCancellations: true,
768 ...(input.commandId === undefined ? {} : { commandId: input.commandId }),
769 threadId: input.threadId,
770 ...input.writeIfRunCurrent,
771 events,
772 })
773 .pipe(Effect.mapError(mapWriteError));
774 return result.storedEvents;
775 },
776 (effect, input) =>
777 effect.pipe(
778 Effect.flatMap((storedEvents) =>
779 Effect.gen(function* () {
780 if (input.event.type !== "app_thread.created") return storedEvents;
781 const created = storedEvents.find(
782 (stored) => stored.event.type === "thread.created",
783 );
784 if (created?.event.type !== "thread.created") return storedEvents;
785 const child = created.event.payload;
786 if (
787 child.worktreePath === null ||
788 child.branch === null ||
789 !isTemporaryWorktreeBranch(child.branch)
790 )
791 return storedEvents;
792 // Git renames before scanning committed threads. If that scan missed this
793 // creation, HEAD already has the new name, even if the parent moved away.
794 const branch = yield* git.resolveBranchName(child.worktreePath, "HEAD");
795 if (branch === null || branch === child.branch) return storedEvents;
796 const now = yield* DateTime.now;
797 const event = yield* makeDomainEvent(input, {
798 type: "thread.metadata-updated",
799 threadId: child.id,
800 payload: { ...child, branch, updatedAt: now },
801 occurredAt: now,
802 });
803 const synced = yield* eventSink.write({ events: [event] });
804 return [...storedEvents, ...synced];
805 }).pipe(
806 Effect.catchCause((cause) =>
807 Effect.logWarning("Native thread worktree branch recheck failed", {
808 threadId:
809 input.event.type === "app_thread.created"
810 ? input.event.appThread.id
811 : input.threadId,
812 cause,
813 }).pipe(Effect.as(storedEvents)),
814 ),
815 ),
816 ),
817 Effect.flatMap((storedEvents) =>
818 storedEvents.length === 0 || input.event.type !== "subagent.updated"
819 ? Effect.succeed(storedEvents)
820 : syncSubagentThreadModel(input, input.event.subagent).pipe(
821 Effect.map((synced) => [...storedEvents, ...synced]),
822 Effect.mapError(
823 (cause) =>
824 new ProviderEventPublishError({
825 providerSessionId: input.providerSessionId,
826 eventCount: 1,
827 cause,
828 }),
829 ),
830 ),
831 ),
832 Effect.tap((storedEvents) =>
833 Effect.gen(function* () {
834 if (storedEvents.length === 0 || input.event.type !== "provider_turn.updated")
835 return;
836 const providerTurn = input.event.providerTurn;
837 if (
838 providerTurn.status !== "completed" &&
839 providerTurn.status !== "failed" &&
840 providerTurn.status !== "interrupted" &&
841 providerTurn.status !== "cancelled"
842 )
843 return;
844 const key = `${input.providerInstanceId}:${providerTurn.id}`;
845 if (completedTurnAnalytics.has(key)) return;
846 completedTurnAnalytics.add(key);
847 if (completedTurnAnalytics.size > 4096) {
848 const oldest = completedTurnAnalytics.values().next().value;
849 if (oldest !== undefined) completedTurnAnalytics.delete(oldest);
850 }
851 yield* analytics.record(
852 providerTurnAnalyticsProperties({
853 driver: input.event.driver,
854 providerTurn,
855 ...(input.analyticsContext === undefined
856 ? {}
857 : { context: input.analyticsContext }),
858 }),
859 );
860 }),
861 ),
862 (effect) =>
863 input.event.type === "app_thread.created"
864 ? threadCommands.withLock(input.event.appThread.id, effect)
865 : effect,
866 ),
867 ),
868 });
869 }),
870);