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

ProviderEventIngestor.ts

641 lines23.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 ModelSelection,
11 type RuntimeMode,
12 type ProviderInteractionMode,
13 ProviderInstanceId,
14 ProviderSessionId,
15 ProviderThreadId,
16 ProviderTurnId,
17 RawEventId,
18 RunAttemptId,
19 RunId,
20 ThreadId,
21} from "@t3tools/contracts";
22import * as Context from "effect/Context";
23import * as DateTime from "effect/DateTime";
24import * as Effect from "effect/Effect";
25import * as Layer from "effect/Layer";
26import * as Schema from "effect/Schema";
27​
28import { getModelSelectionStringOptionValue } from "@t3tools/shared/model";
29import * as AnalyticsService from "../telemetry/AnalyticsService.ts";
30import * as EventSink from "./EventSink.ts";
31import * as ProjectionStore from "./ProjectionStore.ts";
32import * as IdAllocator from "./IdAllocator.ts";
33import { ProviderAdapterV2Event } from "./ProviderAdapter.ts";
34import { makeProviderFailureTurnItem } from "./ProviderFailure.ts";
35import * as ThreadCommandExecutor from "./ThreadCommandExecutor.ts";
36​
37export class ProviderEventNormalizeError extends Schema.TaggedError<ProviderEventNormalizeError>()(
38 "ProviderEventNormalizeError",
39 {
40 providerSessionId: ProviderSessionId,
41 threadId: ThreadId,
42 providerEvent: ProviderAdapterV2Event,
43 cause: Schema.optional(Schema.Defect()),
44 },
45) {
46 override get message(): string {
47 return `Failed to normalize provider event ${this.providerEvent.type} for thread ${this.threadId}.`;
48 }
50​
51export class ProviderEventPublishError extends Schema.TaggedError<ProviderEventPublishError>()(
52 "ProviderEventPublishError",
53 {
54 providerSessionId: ProviderSessionId,
55 eventCount: Schema.Number,
56 cause: Schema.optional(Schema.Defect()),
57 },
58) {
59 override get message(): string {
60 return `Failed to publish ${this.eventCount} normalized provider event(s).`;
61 }
63​
64export const ProviderEventIngestorV2Error = Schema.Union([
65 ProviderEventNormalizeError,
66 ProviderEventPublishError,
67]);
68export type ProviderEventIngestorV2Error = typeof ProviderEventIngestorV2Error.Type;
69​
70export interface ProviderTurnAnalyticsContext {
71 readonly modelSelection: ModelSelection;
72 readonly runtimeMode?: RuntimeMode;
73 readonly interactionMode?: ProviderInteractionMode;
75​
76export class ProviderTurnAnalytics extends Context.Reference<{
77 readonly record: (properties: Readonly<Record<string, unknown>>) => Effect.Effect<void>;
78}>("t3/orchestration-v2/ProviderTurnAnalytics", {
79 defaultValue: () => ({ record: () => Effect.void }),
80}) {}
81​
82export const analyticsLive = Layer.effect(
83 ProviderTurnAnalytics,
84 Effect.gen(function* () {
85 const analytics = yield* AnalyticsService.AnalyticsService;
86 return {
87 record: (properties: Readonly<Record<string, unknown>>) =>
88 analytics.record("provider.turn.completed", properties),
89 };
90 }),
91);
92​
93function providerTurnAnalyticsProperties(input: {
94 readonly driver: ProviderAdapterV2Event["driver"];
95 readonly providerTurn: OrchestrationV2ProviderTurn;
96 readonly context?: ProviderTurnAnalyticsContext;
97}): Readonly<Record<string, unknown>> {
98 const usage = input.providerTurn.turnTokenUsage;
99 const modelSelection = input.context?.modelSelection;
100 const effort = modelSelection
101 ? (getModelSelectionStringOptionValue(modelSelection, "reasoningEffort") ??
102 getModelSelectionStringOptionValue(modelSelection, "effort"))
103 : undefined;
104 return {
105 provider: input.driver,
106 terminalStatus: input.providerTurn.status,
107 usageStatus: usage?.usageStatus ?? "unavailable",
108 usageScope: usage?.usageScope ?? "main_agent",
109 ...(usage ? { hasSubagents: usage.hasSubagents } : {}),
110 ...(usage?.inputTokens === undefined ? {} : { inputTokens: usage.inputTokens }),
111 ...(usage?.cachedInputTokens === undefined
112 ? {}
113 : { cachedInputTokens: usage.cachedInputTokens }),
114 ...(usage?.cacheCreationTokens === undefined
115 ? {}
116 : { cacheCreationTokens: usage.cacheCreationTokens }),
117 ...(usage?.outputTokens === undefined ? {} : { outputTokens: usage.outputTokens }),
118 ...(usage?.reasoningTokens === undefined ? {} : { reasoningTokens: usage.reasoningTokens }),
119 ...(modelSelection ? { model: modelSelection.model, mixedModels: false } : {}),
120 ...(effort ? { effort } : {}),
121 ...(input.context?.runtimeMode ? { runtimeMode: input.context.runtimeMode } : {}),
122 ...(input.context?.interactionMode ? { interactionMode: input.context.interactionMode } : {}),
123 ...(input.providerTurn.startedAt && input.providerTurn.completedAt
124 ? {
125 durationMs: Math.max(
126 0,
127 DateTime.toEpochMillis(input.providerTurn.completedAt) -
128 DateTime.toEpochMillis(input.providerTurn.startedAt),
129 ),
130 }
131 : {}),
132 };
134​
135type TodoListPlan = Extract<OrchestrationV2PlanArtifact, { readonly kind: "todo_list" }>;
136​
137function withPlanStepDurations(
138 plan: TodoListPlan,
139 previous: TodoListPlan | undefined,
140 occurredAt: DateTime.Utc,
141): TodoListPlan {
142 const occurredAtIso = DateTime.formatIso(occurredAt);
143 const occurredAtMs = DateTime.toEpochMillis(occurredAt);
144 const previousById = new Map(previous?.steps.map((step) => [step.id, step]));
145 // Provider step IDs may be positional. Changed text must not inherit another task's timing.
146 const previousStep = (step: TodoListPlan["steps"][number]) => {
147 const prior = previousById.get(step.id);
148 return prior?.text === step.text ? prior : undefined;
149 };
150 const hasNewCompletion = plan.steps.some((step) => {
151 const prior = previousStep(step);
152 return step.status === "completed" && prior?.status !== "completed";
153 });
154 let fallbackCompletionConsumed = false;
155​
156 return {
157 ...plan,
158 steps: plan.steps.map((step) => {
159 const prior = previousStep(step);
160 const baseStep = { id: step.id, text: step.text, status: step.status };
161 if (step.status === "completed") {
162 if (prior?.status === "completed") {
163 return {
164 ...baseStep,
165 ...(prior.durationMs === undefined ? {} : { durationMs: prior.durationMs }),
166 };
167 }
168 const durationAnchorAt =
169 prior?.status === "running" || !fallbackCompletionConsumed
170 ? prior?.durationAnchorAt
171 : occurredAtIso;
172 fallbackCompletionConsumed = true;
173 const anchorMs =
174 durationAnchorAt === undefined ? occurredAtMs : Date.parse(durationAnchorAt);
175 const durationMs = Number.isFinite(anchorMs) ? Math.max(0, occurredAtMs - anchorMs) : 0;
176 return {
177 ...baseStep,
178 ...(durationMs > 0 ? { durationMs } : {}),
179 };
180 }
181 if (step.status === "running") {
182 return {
183 ...baseStep,
184 durationAnchorAt:
185 prior?.status === "running" ? (prior.durationAnchorAt ?? occurredAtIso) : occurredAtIso,
186 };
187 }
188 return {
189 ...baseStep,
190 durationAnchorAt:
191 hasNewCompletion || prior?.status !== "pending"
192 ? occurredAtIso
193 : (prior.durationAnchorAt ?? occurredAtIso),
194 };
195 }),
196 };
198​
199export interface ProviderEventIngestInput {
200 readonly providerSessionId: ProviderSessionId;
201 readonly providerInstanceId: ProviderInstanceId;
202 readonly commandId?: CommandId;
203 readonly threadId: ThreadId;
204 readonly runId?: RunId;
205 readonly nodeId?: NodeId;
206 readonly rawEventId?: RawEventId;
207 readonly event: ProviderAdapterV2Event;
208 readonly analyticsContext?: ProviderTurnAnalyticsContext;
210​
211export interface ProviderEventIngestorV2Shape {
212 readonly normalize: (
213 input: ProviderEventIngestInput,
214 ) => Effect.Effect<ReadonlyArray<OrchestrationV2DomainEvent>, ProviderEventIngestorV2Error>;
215 readonly ingestNormalized: (
216 input: ProviderEventIngestInput & {
217 /**
218 * Atomically reject mutable provider state emitted by an attempt that
219 * lost ownership while the adapter event was in flight.
220 */
221 readonly writeIfRunCurrent?: {
222 readonly runId: RunId;
223 readonly activeAttemptId: RunAttemptId;
224 readonly expectedStatus: OrchestrationV2Run["status"];
225 };
226 /**
227 * Atomically reject provider-thread snapshots from an attempt that no
228 * longer owns the run or from a run that no longer owns the thread.
229 */
230 readonly writeIfProviderThreadOwner?: {
231 readonly providerThreadId: ProviderThreadId;
232 readonly runId: RunId;
233 readonly activeAttemptId: RunAttemptId;
234 readonly expectedLastRunOrdinal: number;
235 };
236 },
237 ) => Effect.Effect<ReadonlyArray<OrchestrationV2StoredEvent>, ProviderEventIngestorV2Error>;
239​
240export class ProviderEventIngestorV2 extends Context.Service<
241 ProviderEventIngestorV2,
242 ProviderEventIngestorV2Shape
243>()("t3/orchestration-v2/ProviderEventIngestor/ProviderEventIngestorV2") {}
244​
245function compactUndefined<T extends Record<string, unknown>>(record: T): T {
246 return Object.fromEntries(Object.entries(record).filter(([, value]) => value !== undefined)) as T;
248​
249const decodeDomainEvent = Schema.decodeUnknownEffect(OrchestrationV2DomainEvent);
250​
251export const layer: Layer.Layer<
252 ProviderEventIngestorV2,
253 never,
254 | EventSink.EventSinkV2
255 | IdAllocator.IdAllocatorV2
256 | ProjectionStore.ProjectionStoreV2
257 | ThreadCommandExecutor.ThreadCommandExecutor
258> = Layer.effect(
259 ProviderEventIngestorV2,
260 Effect.gen(function* () {
261 const eventSink = yield* EventSink.EventSinkV2;
262 const projections = yield* ProjectionStore.ProjectionStoreV2;
263 const idAllocator = yield* IdAllocator.IdAllocatorV2;
264 const threadCommands = yield* ThreadCommandExecutor.ThreadCommandExecutor;
265 const analytics = yield* ProviderTurnAnalytics;
266 const completedTurnAnalytics = new Set<string>();
267​
268 const makeDomainEvent = (
269 input: ProviderEventIngestInput,
270 payloadInput: {
271 readonly type: OrchestrationV2DomainEvent["type"];
272 readonly payload: OrchestrationV2DomainEvent["payload"];
273 readonly threadId?: ThreadId;
274 readonly runId?: RunId | null;
275 readonly nodeId?: NodeId | null;
276 readonly occurredAt?: DateTime.Utc;
277 },
278 ) =>
279 Effect.gen(function* () {
280 const threadId = payloadInput.threadId ?? input.threadId;
281 const eventId = yield* idAllocator.allocate.event({
282 threadId,
283 providerSessionId: input.providerSessionId,
284 });
285 const occurredAt = payloadInput.occurredAt ?? (yield* DateTime.now);
286 return yield* decodeDomainEvent(
287 compactUndefined({
288 id: eventId,
289 type: payloadInput.type,
290 threadId,
291 runId: payloadInput.runId ?? input.runId,
292 nodeId: payloadInput.nodeId ?? input.nodeId,
293 driver: input.event.driver,
294 providerInstanceId: input.providerInstanceId,
295 rawEventId: input.rawEventId,
296 occurredAt,
297 payload: payloadInput.payload,
298 }),
299 );
300 });
301​
302 const dismissNativeUserInputs = Effect.fn("ProviderEventIngestor.dismissNativeUserInputs")(
303 function* (
304 input: ProviderEventIngestInput,
305 providerTurnId: ProviderTurnId,
306 threadId = input.threadId,
307 ) {
308 const pending = yield* projections.getPendingNativeUserInputs(threadId, providerTurnId);
309 const now = yield* DateTime.now;
310 const events: Array<OrchestrationV2DomainEvent> = [];
311 for (const request of pending.runtimeRequests) {
312 events.push(
313 yield* makeDomainEvent(input, {
314 type: "runtime-request.updated",
315 threadId,
316 nodeId: request.nodeId,
317 payload: { ...request, status: "cancelled", resolvedAt: now },
318 }),
319 );
320 }
321 for (const node of pending.nodes) {
322 events.push(
323 yield* makeDomainEvent(input, {
324 type: "node.updated",
325 threadId,
326 nodeId: node.id,
327 runId: node.runId,
328 payload: { ...node, status: "cancelled", completedAt: now },
329 }),
330 );
331 }
332 for (const item of pending.turnItems) {
333 events.push(
334 yield* makeDomainEvent(input, {
335 type: "turn-item.updated",
336 threadId,
337 nodeId: item.nodeId,
338 runId: item.runId,
339 payload: { ...item, status: "cancelled", completedAt: now, updatedAt: now },
340 }),
341 );
342 }
343 return events;
344 },
345 );
346​
347 /**
348 * A native subagent's thread starts on the parent's model when the
349 * provider names the real one later (a Claude agent file's model arrives
350 * with the subagent's first reply). Clients read the thread's model, so
351 * move the thread to the reported one. Thread commands rewrite the whole
352 * thread row under the thread's lock, so this read and write take it too.
353 */
354 const syncSubagentThreadModel = Effect.fn("ProviderEventIngestor.syncSubagentThreadModel")(
355 function* (input: ProviderEventIngestInput, subagent: OrchestrationV2Subagent) {
356 const { childThreadId, model } = subagent;
357 if (subagent.origin !== "provider_native" || childThreadId === null || model === null) {
358 return [];
359 }
360 const staleThread = projections.getThread(childThreadId).pipe(
361 Effect.map((thread) => (thread.modelSelection.model === model ? null : thread)),
362 Effect.catchTags({ ProjectionStoreThreadNotFoundError: () => Effect.succeed(null) }),
363 );
364 // Nearly every update already matches; only a mismatch takes the lock.
365 if ((yield* staleThread) === null) return [];
366 return yield* threadCommands.withLock(
367 childThreadId,
368 Effect.gen(function* () {
369 const thread = yield* staleThread;
370 if (thread === null) return [];
371 const now = yield* DateTime.now;
372 const event = yield* makeDomainEvent(input, {
373 type: "thread.model-selection-updated",
374 threadId: thread.id,
375 // The parent's options belong to the parent's model.
376 payload: {
377 ...thread,
378 modelSelection: { instanceId: thread.modelSelection.instanceId, model },
379 updatedAt: now,
380 },
381 occurredAt: now,
382 });
383 return yield* eventSink.write({ events: [event] });
384 }),
385 );
386 },
387 );
388​
389 const normalize: ProviderEventIngestorV2Shape["normalize"] = (input) =>
390 Effect.gen(function* () {
391 switch (input.event.type) {
392 case "app_thread.created":
393 return [
394 yield* makeDomainEvent(input, {
395 type: "thread.created",
396 threadId: input.event.appThread.id,
397 payload: input.event.appThread,
398 }),
399 ];
400 case "provider_session.updated":
401 return [
402 yield* makeDomainEvent(input, {
403 type: "provider-session.updated",
404 payload: input.event.providerSession,
405 }),
406 ];
407 case "provider_thread.updated":
408 return [
409 yield* makeDomainEvent(input, {
410 type: "provider-thread.updated",
411 threadId: input.event.providerThread.appThreadId ?? input.threadId,
412 payload: input.event.providerThread,
413 }),
414 ];
415 case "provider_turn.updated":
416 return [
417 ...(["completed", "interrupted", "failed", "cancelled"].includes(
418 input.event.providerTurn.status,
419 )
420 ? yield* dismissNativeUserInputs(
421 input,
422 input.event.providerTurn.id,
423 input.event.threadId,
424 )
425 : []),
426 yield* makeDomainEvent(input, {
427 type: "provider-turn.updated",
428 ...(input.event.threadId === undefined ? {} : { threadId: input.event.threadId }),
429 payload: input.event.providerTurn,
430 nodeId: input.event.providerTurn.nodeId,
431 }),
432 ];
433 case "node.updated":
434 return [
435 yield* makeDomainEvent(input, {
436 type: "node.updated",
437 threadId: input.event.node.threadId,
438 payload: input.event.node,
439 runId: input.event.node.runId,
440 nodeId: input.event.node.id,
441 }),
442 ];
443 case "subagent.updated":
444 return [
445 yield* makeDomainEvent(input, {
446 type: "subagent.updated",
447 threadId: input.event.subagent.threadId,
448 payload: input.event.subagent,
449 runId: input.event.subagent.runId,
450 nodeId: input.event.subagent.id,
451 }),
452 ];
453 case "message.updated":
454 return [
455 yield* makeDomainEvent(input, {
456 type: "message.updated",
457 threadId: input.event.message.threadId,
458 payload: input.event.message,
459 runId: input.event.message.runId,
460 nodeId: input.event.message.nodeId,
461 }),
462 ];
463 case "turn_item.updated":
464 return [
465 yield* makeDomainEvent(input, {
466 type: "turn-item.updated",
467 threadId: input.event.turnItem.threadId,
468 payload: input.event.turnItem,
469 runId: input.event.turnItem.runId,
470 nodeId: input.event.turnItem.nodeId,
471 }),
472 ];
473 case "runtime_request.updated":
474 return [
475 yield* makeDomainEvent(input, {
476 type: "runtime-request.updated",
477 ...(input.event.threadId === undefined ? {} : { threadId: input.event.threadId }),
478 payload: input.event.runtimeRequest,
479 nodeId: input.event.runtimeRequest.nodeId,
480 }),
481 ];
482 case "plan.updated": {
483 const occurredAt = yield* DateTime.now;
484 const plan = input.event.plan;
485 const previous =
486 plan.kind === "todo_list"
487 ? yield* projections.getPlan(plan.threadId, plan.id)
488 : undefined;
489 const payload =
490 plan.kind === "todo_list"
491 ? withPlanStepDurations(
492 plan,
493 previous?.kind === "todo_list" ? previous : undefined,
494 occurredAt,
495 )
496 : plan;
497 return [
498 yield* makeDomainEvent(input, {
499 type: "plan.updated",
500 threadId: plan.threadId,
501 payload,
502 runId: plan.runId,
503 nodeId: plan.nodeId,
504 occurredAt,
505 }),
506 ];
507 }
508 case "turn.terminal":
509 const dismissed = yield* dismissNativeUserInputs(input, input.event.providerTurnId);
510 if (input.event.status !== "failed") {
511 return dismissed;
512 }
513 const occurredAt = yield* DateTime.now;
514 return [
515 ...dismissed,
516 yield* makeDomainEvent(input, {
517 type: "turn-item.updated",
518 payload: makeProviderFailureTurnItem({
519 idAllocator,
520 driver: input.event.driver,
521 threadId: input.threadId,
522 runId: input.runId ?? null,
523 nodeId: input.nodeId ?? null,
524 providerThreadId: input.event.providerThreadId,
525 providerTurnId: input.event.providerTurnId,
526 itemOrdinal: input.event.failureItemOrdinal,
527 failure: input.event.failure,
528 ...(input.event.retry === undefined ? {} : { retry: input.event.retry }),
529 ...(input.event.retryStartedAt === undefined
530 ? {}
531 : { retryStartedAt: input.event.retryStartedAt }),
532 occurredAt,
533 }),
534 }),
535 ];
536 }
537 }).pipe(
538 Effect.mapError(
539 (cause) =>
540 new ProviderEventNormalizeError({
541 providerSessionId: input.providerSessionId,
542 threadId: input.threadId,
543 providerEvent: input.event,
544 cause,
545 }),
546 ),
547 );
548​
549 return ProviderEventIngestorV2.of({
550 normalize,
551 ingestNormalized: (input) =>
552 Effect.gen(function* () {
553 const events = yield* normalize(input);
554 if (events.length === 0) {
555 return [];
556 }
557 const mapWriteError = (cause: unknown) =>
558 new ProviderEventPublishError({
559 providerSessionId: input.providerSessionId,
560 eventCount: events.length,
561 cause,
562 });
563 if (input.writeIfProviderThreadOwner !== undefined) {
564 const ownerResult = yield* eventSink
565 .writeIfProviderThreadOwner({
566 guardPendingUserInputCancellations: true,
567 ...(input.commandId === undefined ? {} : { commandId: input.commandId }),
568 ...input.writeIfProviderThreadOwner,
569 events,
570 })
571 .pipe(Effect.mapError(mapWriteError));
572 return ownerResult.storedEvents;
573 }
574 if (input.writeIfRunCurrent === undefined) {
575 return yield* eventSink
576 .write({
577 guardPendingUserInputCancellations: true,
578 ...(input.commandId === undefined ? {} : { commandId: input.commandId }),
579 events,
580 })
581 .pipe(Effect.mapError(mapWriteError));
582 }
583 const result = yield* eventSink
584 .writeIfRunCurrent({
585 guardPendingUserInputCancellations: true,
586 ...(input.commandId === undefined ? {} : { commandId: input.commandId }),
587 threadId: input.threadId,
588 ...input.writeIfRunCurrent,
589 events,
590 })
591 .pipe(Effect.mapError(mapWriteError));
592 return result.storedEvents;
593 }).pipe(
594 Effect.flatMap((storedEvents) =>
595 storedEvents.length === 0 || input.event.type !== "subagent.updated"
596 ? Effect.succeed(storedEvents)
597 : syncSubagentThreadModel(input, input.event.subagent).pipe(
598 Effect.map((synced) => [...storedEvents, ...synced]),
599 Effect.mapError(
600 (cause) =>
601 new ProviderEventPublishError({
602 providerSessionId: input.providerSessionId,
603 eventCount: 1,
604 cause,
605 }),
606 ),
607 ),
608 ),
609 Effect.tap((storedEvents) =>
610 Effect.gen(function* () {
611 if (storedEvents.length === 0 || input.event.type !== "provider_turn.updated") return;
612 const providerTurn = input.event.providerTurn;
613 if (
614 providerTurn.status !== "completed" &&
615 providerTurn.status !== "failed" &&
616 providerTurn.status !== "interrupted" &&
617 providerTurn.status !== "cancelled"
618 )
619 return;
620 const key = `${input.providerInstanceId}:${providerTurn.id}`;
621 if (completedTurnAnalytics.has(key)) return;
622 completedTurnAnalytics.add(key);
623 if (completedTurnAnalytics.size > 4096) {
624 const oldest = completedTurnAnalytics.values().next().value;
625 if (oldest !== undefined) completedTurnAnalytics.delete(oldest);
626 }
627 yield* analytics.record(
628 providerTurnAnalyticsProperties({
629 driver: input.event.driver,
630 providerTurn,
631 ...(input.analyticsContext === undefined
632 ? {}
633 : { context: input.analyticsContext }),
634 }),
635 );
636 }),
637 ),
638 ),
639 });
640 }),
641);