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

ProviderEventIngestor.ts

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