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