metrics.ts 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230
  1. /**
  2. * pi-turn-runner metrics (MR1) — emit the `pi_*` metric family for the
  3. * agent-core inner loop through the optionally injected `MetricsClient`.
  4. *
  5. * Design constraints:
  6. * - Noop-safe: no client → the internal client is a noop and assembly
  7. * fingerprinting stays disabled.
  8. * - Zero behavior change: every observation point is wrapped so that a
  9. * throwing client or a bug in the recorder can never break the turn.
  10. * - Bare metric names (no `local_runtime_` prefix — the reporting layer
  11. * rejects prefixed names since MR0); labels are low-cardinality only.
  12. */
  13. import type { Agent, AgentEvent, AgentMessage, StreamFn } from '@earendil-works/pi-agent-core';
  14. import type {
  15. AssistantMessage,
  16. AssistantMessageEvent,
  17. AssistantMessageEventStream,
  18. Context,
  19. } from '@earendil-works/pi-ai';
  20. import type { MetricLabels, MetricsClient } from '@mavis/shared/metrics-proxy';
  21. import {
  22. normalizeLLMError,
  23. toLLMMetricErrorKind,
  24. type LLMMetricErrorKind,
  25. type NormalizedLLMError,
  26. } from '@mavis/shared/llm-error-classifier';
  27. import type { TurnTerminationReason } from '../event-bridge/types.js';
  28. import type { RuntimeTool, ToolOperationClassifier } from '../tools/index.js';
  29. import type { LLMCallSettledEvent, LLMRetryEvent } from './llm-retry.js';
  30. import {
  31. normalizeAbortSource,
  32. type LLMModelConfig,
  33. type RunTurnCaller,
  34. type PiTurnRunnerLogger,
  35. } from './types.js';
  36. import {
  37. createToolContextHistogramBucketsByName,
  38. measureToolArguments,
  39. measureToolContext,
  40. measureToolResult,
  41. type MeasuredToolValue,
  42. type ToolContextSizeEstimator,
  43. } from './tool-context-size.js';
  44. import { fingerprintAssembly, type AssemblyFingerprint } from './assembly-fingerprint.js';
  45. const LARGE_TOOL_IO_TOKEN_THRESHOLD = 8_000;
  46. const MAX_ASSEMBLY_FINGERPRINT_BASELINES = 2_048;
  47. const MAX_LLM_REQUEST_GAP_BASELINES = 2_048;
  48. const LLM_TOKENS_PER_SECOND_BUCKETS = [0.1, 0.5, 1, 2, 5, 10, 20, 50, 100, 200];
  49. const LLM_GAP_MS_BUCKETS = [
  50. 100, 250, 500, 1000, 2500, 5000, 10_000, 30_000, 60_000, 120_000, 300_000, 600_000, 900_000,
  51. 1_800_000, 3_600_000,
  52. ];
  53. const MAX_TOOL_OPERATION_VALUES = 128;
  54. const MAX_TOOL_OPERATION_VALUE_LENGTH = 64;
  55. export type PiLLMCacheOutcome = 'read' | 'no_read' | 'telemetry_unknown';
  56. export interface PiLLMRequestStartedInfo {
  57. readonly sessionId: string;
  58. readonly turnId: string;
  59. readonly startedAtMs: number;
  60. readonly provider: string;
  61. readonly model: string;
  62. readonly caller: string;
  63. }
  64. export interface PiLLMRequestSettledInfo {
  65. readonly endedAtMs: number;
  66. readonly cacheOutcome: PiLLMCacheOutcome;
  67. }
  68. /** Fail-open host observer for one physical provider request lifecycle. */
  69. export type PiLLMRequestSettlementObserver = (info: PiLLMRequestSettledInfo) => void;
  70. /**
  71. * Called when a physical provider request starts. The optional returned closure
  72. * is called exactly once when that request settles and may capture host state
  73. * without asking agent-core to own product-specific correlation.
  74. */
  75. export type PiLLMRequestObserver = (
  76. info: PiLLMRequestStartedInfo,
  77. ) => PiLLMRequestSettlementObserver | undefined | void;
  78. interface TurnMetricsDiagnostics {
  79. sessionId: string;
  80. turnId: string;
  81. estimator?: ToolContextSizeEstimator;
  82. logger: PiTurnRunnerLogger;
  83. }
  84. interface RegisteredToolOperationClassifier {
  85. readonly allowedValues: ReadonlySet<string>;
  86. /**
  87. * How many declared values were dropped by the cardinality/length caps.
  88. * Non-zero means some real operations will report as `unknown`.
  89. */
  90. readonly rejectedValueCount: number;
  91. classify(args: unknown): string | undefined;
  92. }
  93. export type TurnErrorSource =
  94. | 'llm'
  95. | 'before_llm_hook'
  96. | 'tool'
  97. | 'history'
  98. | 'event_bridge'
  99. | 'message_identity'
  100. | 'event_writer'
  101. | 'turn_end_hook'
  102. | 'runner'
  103. | 'unknown';
  104. export type NonLLMTurnErrorKind =
  105. | 'hook_error'
  106. | 'persistence'
  107. | 'translation'
  108. | 'identity'
  109. | 'delivery'
  110. | 'runtime_error'
  111. | 'unknown';
  112. export interface LLMFailureObservation {
  113. normalized: NormalizedLLMError;
  114. metricKind: LLMMetricErrorKind;
  115. }
  116. /**
  117. * Data passed to the host-injected {@link PiLLMRequestFailureHook} after a physical provider
  118. * request fails.
  119. *
  120. * agent-core is host-independent: it only classifies failures and forwards raw error data. The host
  121. * (local-runtime) generates reportable error logs and handles formatting, encryption, and
  122. * transport, keeping the reporting pipeline out of agent-core.
  123. */
  124. export interface PiLLMRequestFailureInfo {
  125. /**
  126. * The value thrown directly by the physical request, such as a custom streamFn, transport error,
  127. * or timeout. `undefined` if the failure is carried by a completed assistant message.
  128. */
  129. error?: unknown;
  130. /** Raw exception captured by the provider before formatting the final error text. */
  131. providerError?: unknown;
  132. /**
  133. * Final error text carried by a completed assistant message (`stopReason === 'error'`); present
  134. * when {@link error} is `undefined`.
  135. */
  136. errorMessage?: string;
  137. /**
  138. * The framework's fixed-cardinality failure classification. User cancellation (`'abort'`) is
  139. * filtered before invoking the hook, so hook implementations never receive abort.
  140. */
  141. metricKind: LLMMetricErrorKind;
  142. /** The model and call source actually used for this physical request. */
  143. request: {
  144. api: string;
  145. baseUrl: string;
  146. caller: string;
  147. model: string;
  148. provider: string;
  149. };
  150. /** Unix timestamp in milliseconds when the failure was observed. */
  151. occurredAtMs: number;
  152. }
  153. /**
  154. * Optional host callback invoked once per confirmed physical provider request failure by {@link
  155. * TurnMetricsRecorder.wrapStreamFn}, rather than the logical request wrapper. Each retry attempt's
  156. * physical failure triggers it, but user cancellation does not.
  157. *
  158. * The hook may only produce out-of-band side effects and must not throw from the caller's
  159. * perspective. agent-core always protects the call with `swallow`, ensuring hook errors cannot
  160. * affect LLM requests, retries, or turn results.
  161. */
  162. export type PiLLMRequestFailureHook = (info: PiLLMRequestFailureInfo) => void;
  163. export interface TurnFailureProvenance {
  164. errorSource: TurnErrorSource;
  165. errorKind: LLMMetricErrorKind | NonLLMTurnErrorKind;
  166. }
  167. const FIRST_TOKEN_EVENT_TYPES: ReadonlySet<AssistantMessageEvent['type']> = new Set([
  168. 'text_start',
  169. 'text_delta',
  170. 'thinking_start',
  171. 'thinking_delta',
  172. 'toolcall_start',
  173. 'toolcall_delta',
  174. ]);
  175. const noopMetricsClient = {
  176. counter() {},
  177. gauge() {},
  178. histogram() {},
  179. } as unknown as MetricsClient;
  180. export function newPiTurnMetrics(
  181. client: MetricsClient | undefined,
  182. nowMs: () => number,
  183. onLLMRequestFailure?: PiLLMRequestFailureHook,
  184. observeLLMRequest?: PiLLMRequestObserver,
  185. ): PiTurnMetrics {
  186. return new PiTurnMetrics(
  187. client ?? noopMetricsClient,
  188. nowMs,
  189. client !== undefined,
  190. onLLMRequestFailure,
  191. observeLLMRequest,
  192. );
  193. }
  194. export function createPiTurnHistogramBucketsByName(): Record<string, number[]> {
  195. return {
  196. pi_llm_tokens_per_second: [...LLM_TOKENS_PER_SECOND_BUCKETS],
  197. pi_llm_inter_request_gap_ms: [...LLM_GAP_MS_BUCKETS],
  198. ...createToolContextHistogramBucketsByName(),
  199. };
  200. }
  201. /**
  202. * Record the final outcome of one logical LLM call without conflating it with
  203. * its physical retry attempts. All labels are fixed-cardinality framework
  204. * classifications.
  205. */
  206. export function recordPiLLMCallMetrics(
  207. client: Pick<MetricsClient, 'counter'> | undefined,
  208. caller: string,
  209. event: LLMCallSettledEvent,
  210. ): void {
  211. if (!client) return;
  212. const baseLabels = {
  213. provider: event.provider,
  214. model: event.model,
  215. caller,
  216. scope: event.scope,
  217. };
  218. swallow(() =>
  219. client.counter('pi_llm_logical_call_total', 1, {
  220. ...baseLabels,
  221. outcome: event.final.outcome,
  222. errorKind: event.final.errorKind,
  223. retryTriggered: String(event.retryTriggered),
  224. }),
  225. );
  226. const reason = event.retryReason;
  227. if (!event.retryTriggered || !reason) return;
  228. const outcome =
  229. event.final.outcome === 'success'
  230. ? 'recovered'
  231. : event.final.outcome === 'abort'
  232. ? 'cancelled'
  233. : 'failed';
  234. swallow(() =>
  235. client.counter('pi_llm_retry_episode_total', 1, {
  236. ...baseLabels,
  237. reason,
  238. outcome,
  239. }),
  240. );
  241. }
  242. /**
  243. * Per-`PiTurnRunner` metrics host. Owns the concurrent-turn gauge state and
  244. * hands out one {@link TurnMetricsRecorder} per `runTurn` call.
  245. */
  246. export class PiTurnMetrics {
  247. readonly client: MetricsClient;
  248. readonly nowMs: () => number;
  249. private readonly enabled: boolean;
  250. /**
  251. * Host-injected receiver for physical LLM request failures, used for error-log reporting.
  252. * Independent of {@link enabled} and `client`: error reporting and metrics are separate
  253. * pipelines, so it stays connected even without a MetricsClient.
  254. */
  255. readonly onLLMRequestFailure?: PiLLMRequestFailureHook;
  256. readonly observeLLMRequest?: PiLLMRequestObserver;
  257. // ponytail: gauge scope is per-runner instance — the local product path
  258. // constructs a single PiTurnRunner per process, which is what the gauge is
  259. // meant to describe. Move to a shared registry if multiple runners ever
  260. // share one MetricsClient.
  261. private readonly activeTurns = new Map<string, number>();
  262. private readonly assemblyFingerprints = new Map<
  263. string,
  264. AssemblyFingerprint & { turnId: string }
  265. >();
  266. private readonly lastLLMRequestSettledAtBySession = new Map<string, number>();
  267. constructor(
  268. client: MetricsClient,
  269. nowMs: () => number,
  270. enabled = true,
  271. onLLMRequestFailure?: PiLLMRequestFailureHook,
  272. observeLLMRequest?: PiLLMRequestObserver,
  273. ) {
  274. this.client = client;
  275. this.nowMs = nowMs;
  276. this.enabled = enabled;
  277. this.onLLMRequestFailure = onLLMRequestFailure;
  278. this.observeLLMRequest = observeLLMRequest;
  279. }
  280. beginTurn(
  281. caller: RunTurnCaller | undefined,
  282. model: LLMModelConfig['model'],
  283. diagnostics: TurnMetricsDiagnostics,
  284. ): TurnMetricsRecorder {
  285. return new TurnMetricsRecorder(this, caller ?? 'unknown', model, diagnostics);
  286. }
  287. bumpActiveTurns(caller: string, delta: number): void {
  288. const next = Math.max(0, (this.activeTurns.get(caller) ?? 0) + delta);
  289. if (next === 0) {
  290. this.activeTurns.delete(caller);
  291. } else {
  292. this.activeTurns.set(caller, next);
  293. }
  294. this.client.gauge('pi_active_turns', next, { caller });
  295. }
  296. observeLLMRequestStarted(sessionId: string, startedAt: number): number | undefined {
  297. const previous = this.lastLLMRequestSettledAtBySession.get(sessionId);
  298. if (previous === undefined) return undefined;
  299. return Math.max(0, startedAt - previous);
  300. }
  301. observeLLMRequestSettled(sessionId: string, settledAt: number): void {
  302. this.lastLLMRequestSettledAtBySession.delete(sessionId);
  303. this.lastLLMRequestSettledAtBySession.set(sessionId, settledAt);
  304. if (this.lastLLMRequestSettledAtBySession.size <= MAX_LLM_REQUEST_GAP_BASELINES) return;
  305. const oldest = this.lastLLMRequestSettledAtBySession.keys().next().value;
  306. if (oldest !== undefined) this.lastLLMRequestSettledAtBySession.delete(oldest);
  307. }
  308. observeAssembly(
  309. caller: string,
  310. model: LLMModelConfig['model'],
  311. diagnostics: TurnMetricsDiagnostics,
  312. context: Context,
  313. ): void {
  314. if (!this.enabled) return;
  315. const current = fingerprintAssembly(context);
  316. const key = JSON.stringify([diagnostics.sessionId, String(model.provider), String(model.id)]);
  317. const previous = this.assemblyFingerprints.get(key);
  318. // Refresh insertion order so this map is a bounded process-local LRU.
  319. this.assemblyFingerprints.delete(key);
  320. this.assemblyFingerprints.set(key, { ...current, turnId: diagnostics.turnId });
  321. if (this.assemblyFingerprints.size > MAX_ASSEMBLY_FINGERPRINT_BASELINES) {
  322. const oldest = this.assemblyFingerprints.keys().next().value;
  323. if (oldest !== undefined) this.assemblyFingerprints.delete(oldest);
  324. }
  325. if (!previous) return;
  326. const scope = previous.turnId === diagnostics.turnId ? 'within_turn' : 'across_turn';
  327. const labels = {
  328. provider: String(model.provider),
  329. model: String(model.id),
  330. caller,
  331. scope,
  332. };
  333. this.observeAssemblyPart(
  334. diagnostics,
  335. labels,
  336. 'system_prompt',
  337. previous.systemPrompt,
  338. current.systemPrompt,
  339. );
  340. this.observeAssemblyPart(diagnostics, labels, 'tools', previous.tools, current.tools);
  341. }
  342. private observeAssemblyPart(
  343. diagnostics: TurnMetricsDiagnostics,
  344. labels: MetricLabels,
  345. part: 'system_prompt' | 'tools',
  346. previousFingerprint: string,
  347. currentFingerprint: string,
  348. ): void {
  349. const result = previousFingerprint === currentFingerprint ? 'stable' : 'changed';
  350. this.client.counter('pi_llm_assembly_stability_total', 1, { ...labels, part, result });
  351. if (result !== 'changed') return;
  352. swallow(() =>
  353. diagnostics.logger.info?.(
  354. {
  355. session_id: diagnostics.sessionId,
  356. turn_id: diagnostics.turnId,
  357. part,
  358. scope: labels.scope,
  359. provider: labels.provider,
  360. model: labels.model,
  361. caller: labels.caller,
  362. previous_fingerprint: previousFingerprint,
  363. current_fingerprint: currentFingerprint,
  364. },
  365. 'pi_llm_assembly_fingerprint_changed',
  366. ),
  367. );
  368. }
  369. }
  370. /**
  371. * Per-turn recorder. `PiTurnRunner.runTurn` creates one before any work and
  372. * always calls {@link finish} in a `finally`, so turn totals/gauges stay
  373. * balanced on every exit path (completed / failed / aborted / thrown).
  374. */
  375. export class TurnMetricsRecorder {
  376. private readonly owner: PiTurnMetrics;
  377. private readonly caller: string;
  378. private readonly turnLabels: MetricLabels;
  379. private readonly turnStartedAt: number;
  380. private readonly diagnostics: TurnMetricsDiagnostics;
  381. private loopSteps = 0;
  382. private batchStartedAt: number | undefined;
  383. private readonly toolStartedAt = new Map<string, number>();
  384. private readonly toolIOStarted = new Map<
  385. string,
  386. { toolName: string; operation?: string; arguments: MeasuredToolValue }
  387. >();
  388. private readonly registeredToolNames = new Set<string>();
  389. private readonly toolOperationClassifiers = new Map<string, RegisteredToolOperationClassifier>();
  390. private finished = false;
  391. private llmFailure?: LLMFailureObservation;
  392. private terminalFailure?: TurnFailureProvenance;
  393. // Caller abort can record llm/abort before the Turn settles as cancelled.
  394. // Retain a real cleanup failure without changing first-wins semantics.
  395. private firstNonLlmTerminalFailure?: TurnFailureProvenance;
  396. private readonly pendingSettlements: Promise<unknown>[] = [];
  397. private readonly degradationErrors = new WeakSet<object>();
  398. // The provider result object is also carried by pi's message_end event. Keep the
  399. // physical request duration beside that identity until EventBridge materialises usage.
  400. private readonly requestDurationsMs = new WeakMap<object, number>();
  401. constructor(
  402. owner: PiTurnMetrics,
  403. caller: string,
  404. model: LLMModelConfig['model'],
  405. diagnostics: TurnMetricsDiagnostics,
  406. ) {
  407. this.owner = owner;
  408. this.caller = caller;
  409. this.turnLabels = {
  410. provider: String(model.provider),
  411. model: String(model.id),
  412. caller,
  413. };
  414. this.turnStartedAt = owner.nowMs();
  415. this.diagnostics = diagnostics;
  416. swallow(() => owner.bumpActiveTurns(caller, +1));
  417. }
  418. /**
  419. * Wrap the fully composed streamFn so one LLM request maps to exactly one
  420. * `pi_llm_request_total` observation. Request start = wrapper invocation.
  421. */
  422. wrapStreamFn(inner: StreamFn, settings: { recordTerminalFailure?: boolean } = {}): StreamFn {
  423. const recordTerminalFailure = settings.recordTerminalFailure ?? true;
  424. return (async (model, context, streamOptions) => {
  425. const labels: MetricLabels = {
  426. provider: String(model.provider),
  427. model: String(model.id),
  428. caller: this.caller,
  429. };
  430. const requestStartedAt = this.owner.nowMs();
  431. const interRequestGapMs = this.owner.observeLLMRequestStarted(
  432. this.diagnostics.sessionId,
  433. requestStartedAt,
  434. );
  435. const settlementObserver = swallowValue(() =>
  436. this.owner.observeLLMRequest?.({
  437. sessionId: this.diagnostics.sessionId,
  438. turnId: this.diagnostics.turnId,
  439. startedAtMs: requestStartedAt,
  440. provider: String(model.provider),
  441. model: String(model.id),
  442. caller: this.caller,
  443. }),
  444. );
  445. if (interRequestGapMs !== undefined) {
  446. swallow(() =>
  447. this.owner.client.histogram('pi_llm_inter_request_gap_ms', interRequestGapMs, labels),
  448. );
  449. }
  450. let providerError: unknown;
  451. let hasProviderError = false;
  452. const callerOnProviderError = streamOptions?.onProviderError;
  453. const observedStreamOptions = {
  454. ...streamOptions,
  455. onProviderError(error: unknown, observedModel: typeof model): void {
  456. providerError = error;
  457. hasProviderError = true;
  458. swallow(() => callerOnProviderError?.(error, observedModel));
  459. },
  460. };
  461. swallow(() => this.owner.observeAssembly(this.caller, model, this.diagnostics, context));
  462. swallow(() => this.recordToolContextResidency(model, context.messages as AgentMessage[]));
  463. swallow(() => this.owner.client.counter('pi_llm_request_total', 1, labels));
  464. let stream: AssistantMessageEventStream;
  465. try {
  466. stream = await inner(model, context, observedStreamOptions);
  467. } catch (err) {
  468. // StreamFn contract says failures should be encoded in the stream,
  469. // but custom streamFns may still throw — count it, then rethrow.
  470. swallow(() =>
  471. this.recordLLMSettled(
  472. labels,
  473. requestStartedAt,
  474. model,
  475. undefined,
  476. err,
  477. hasProviderError ? providerError : undefined,
  478. recordTerminalFailure,
  479. interRequestGapMs,
  480. settlementObserver,
  481. ),
  482. );
  483. throw err;
  484. }
  485. // A custom stream may throw from iteration without ever resolving its
  486. // result promise. Fold that failure into settlement so observability
  487. // cannot keep runTurn's finally block pending forever.
  488. const iteratorFailure = newIteratorFailure();
  489. const observedResult = Promise.race([
  490. Promise.resolve().then(() => stream.result()),
  491. iteratorFailure.promise,
  492. ]).then(
  493. (final) => {
  494. swallow(() =>
  495. this.recordLLMSettled(
  496. labels,
  497. requestStartedAt,
  498. model,
  499. final,
  500. undefined,
  501. hasProviderError ? providerError : undefined,
  502. recordTerminalFailure,
  503. interRequestGapMs,
  504. settlementObserver,
  505. ),
  506. );
  507. return final;
  508. },
  509. (err) => {
  510. swallow(() =>
  511. this.recordLLMSettled(
  512. labels,
  513. requestStartedAt,
  514. model,
  515. undefined,
  516. err,
  517. hasProviderError ? providerError : undefined,
  518. recordTerminalFailure,
  519. interRequestGapMs,
  520. settlementObserver,
  521. ),
  522. );
  523. throw err;
  524. },
  525. );
  526. this.pendingSettlements.push(observedResult.catch(() => undefined));
  527. return observeFirstToken(
  528. stream,
  529. observedResult,
  530. () => {
  531. const observedAt = this.owner.nowMs();
  532. swallow(() =>
  533. this.owner.client.histogram(
  534. 'pi_llm_first_token_ms',
  535. observedAt - requestStartedAt,
  536. labels,
  537. ),
  538. );
  539. },
  540. iteratorFailure.reject,
  541. );
  542. }) as StreamFn;
  543. }
  544. requestDurationMsFor(message: unknown): number | undefined {
  545. return message !== null && typeof message === 'object'
  546. ? this.requestDurationsMs.get(message)
  547. : undefined;
  548. }
  549. /** Observe only the final logical call outcome, without recounting provider requests. */
  550. wrapLogicalStreamFn(
  551. inner: StreamFn,
  552. settings: { recordTerminalFailure?: boolean } = {},
  553. ): StreamFn {
  554. const recordTerminalFailure = settings.recordTerminalFailure ?? true;
  555. return (async (model, context, options) => {
  556. let stream: AssistantMessageEventStream;
  557. try {
  558. stream = await inner(model, context, options);
  559. } catch (error) {
  560. if (recordTerminalFailure) {
  561. swallow(() => this.recordLogicalLLMFailure(undefined, error));
  562. }
  563. throw error;
  564. }
  565. const iteratorFailure = newIteratorFailure();
  566. const observedResult = Promise.race([
  567. Promise.resolve().then(() => stream.result()),
  568. iteratorFailure.promise,
  569. ]).then(
  570. (final) => {
  571. if (recordTerminalFailure) {
  572. swallow(() => this.recordLogicalLLMFailure(final));
  573. }
  574. return final;
  575. },
  576. (error) => {
  577. if (recordTerminalFailure) {
  578. swallow(() => this.recordLogicalLLMFailure(undefined, error));
  579. }
  580. throw error;
  581. },
  582. );
  583. this.pendingSettlements.push(observedResult.catch(() => undefined));
  584. return observeFirstToken(stream, observedResult, () => {}, iteratorFailure.reject);
  585. }) as StreamFn;
  586. }
  587. observeRetry(event: LLMRetryEvent): void {
  588. const reason = event.error?.reason;
  589. if (!reason) return;
  590. const labels = { ...this.turnLabels, reason, scope: event.scope };
  591. if (event.status === 'waiting') {
  592. swallow(() => this.owner.client.counter('pi_llm_retry_total', 1, labels));
  593. const { delayMs } = event;
  594. if (delayMs !== undefined) {
  595. swallow(() => this.owner.client.histogram('pi_llm_retry_delay_ms', delayMs, labels));
  596. }
  597. } else if (event.status === 'exhausted') {
  598. swallow(() => this.owner.client.counter('pi_llm_retry_exhausted_total', 1, labels));
  599. }
  600. }
  601. observeLLMCall(event: LLMCallSettledEvent): void {
  602. recordPiLLMCallMetrics(this.owner.client, this.caller, event);
  603. }
  604. /** Second lightweight subscription — tool/loop/batch observations. */
  605. observeAgent(agent: Agent, runtimeTools?: readonly RuntimeTool[]): void {
  606. agent.state.tools.forEach((tool) => this.registeredToolNames.add(tool.name));
  607. for (const tool of runtimeTools ?? []) {
  608. swallow(() => {
  609. const classifier = tool.def.operationClassifier;
  610. if (!classifier || !this.registeredToolNames.has(tool.def.name)) return;
  611. const registered = registerToolOperationClassifier(classifier);
  612. if (registered.rejectedValueCount > 0) {
  613. // Rejected entries silently collapse into the `unknown` bucket at
  614. // query time, which looks like a product problem rather than a
  615. // vocabulary problem. Name it once at registration instead.
  616. this.diagnostics.logger.warn?.(
  617. {
  618. session_id: this.diagnostics.sessionId,
  619. turn_id: this.diagnostics.turnId,
  620. tool_name: tool.def.name,
  621. accepted_operations: registered.allowedValues.size,
  622. rejected_operations: registered.rejectedValueCount,
  623. max_operations: MAX_TOOL_OPERATION_VALUES,
  624. max_operation_length: MAX_TOOL_OPERATION_VALUE_LENGTH,
  625. },
  626. 'pi_tool_operation_vocabulary_truncated',
  627. );
  628. }
  629. this.toolOperationClassifiers.set(tool.def.name, registered);
  630. });
  631. }
  632. agent.subscribe((event) => {
  633. swallow(() => this.onAgentEvent(event));
  634. });
  635. }
  636. getLLMFailureObservation(): LLMFailureObservation | undefined {
  637. return this.llmFailure;
  638. }
  639. tryRecordTerminalFailure(provenance: TurnFailureProvenance): boolean {
  640. if (provenance.errorSource !== 'llm') {
  641. this.firstNonLlmTerminalFailure ??= provenance;
  642. }
  643. if (this.terminalFailure) return false;
  644. this.terminalFailure = provenance;
  645. return true;
  646. }
  647. recordDegradation(
  648. errorSource: TurnErrorSource,
  649. errorKind: NonLLMTurnErrorKind,
  650. err?: unknown,
  651. ): void {
  652. if (err && typeof err === 'object') {
  653. if (this.degradationErrors.has(err)) return;
  654. this.degradationErrors.add(err);
  655. }
  656. swallow(() =>
  657. this.owner.client.counter('pi_turn_degradation_total', 1, {
  658. caller: this.caller,
  659. errorSource,
  660. errorKind,
  661. }),
  662. );
  663. }
  664. async settle(): Promise<void> {
  665. await Promise.all(this.pendingSettlements);
  666. }
  667. finish(termination: TurnTerminationReason | undefined, abortReason?: unknown): void {
  668. swallow(() => {
  669. if (this.finished) return;
  670. this.finished = true;
  671. this.toolIOStarted.clear();
  672. const { client } = this.owner;
  673. const caller = this.caller;
  674. const labels = this.turnLabels;
  675. this.owner.bumpActiveTurns(caller, -1);
  676. // Prometheus freezes a metric family's label keys. Keep the legacy
  677. // family schema stable and put model dimensions under a new name.
  678. client.counter('pi_turn_total', 1, { caller });
  679. client.counter('pi_turn_model_total', 1, labels);
  680. const isCancellation = termination?.kind === 'aborted';
  681. let failure = this.terminalFailure;
  682. if (isCancellation && failure?.errorSource === 'llm') {
  683. failure = this.firstNonLlmTerminalFailure;
  684. }
  685. if (!failure && termination?.kind === 'failed' && this.llmFailure) {
  686. failure = { errorSource: 'llm', errorKind: this.llmFailure.metricKind };
  687. } else if (!failure && termination === undefined) {
  688. failure = { errorSource: 'runner', errorKind: 'runtime_error' };
  689. } else if (!failure && termination?.kind === 'failed') {
  690. failure = { errorSource: 'unknown', errorKind: 'unknown' };
  691. }
  692. if (failure) {
  693. // `pi_turn_error_total` shipped as {caller,errorKind}; errorSource
  694. // belongs to a distinct family so older app versions remain accepted.
  695. client.counter('pi_turn_error_total', 1, {
  696. caller,
  697. errorKind: failure.errorKind,
  698. });
  699. client.counter('pi_turn_failure_total', 1, { caller, ...failure });
  700. }
  701. if (isCancellation) {
  702. // Preserve the legacy error family while keeping cancellations out of
  703. // the failure family. A real terminal failure still takes precedence.
  704. if (!failure) {
  705. client.counter('pi_turn_error_total', 1, { caller, errorKind: 'abort' });
  706. }
  707. client.counter('pi_turn_abort_total', 1, {
  708. ...labels,
  709. abortSource: normalizeAbortSource(abortReason),
  710. });
  711. }
  712. client.histogram('pi_turn_duration_ms', this.owner.nowMs() - this.turnStartedAt, { caller });
  713. client.histogram('pi_loop_steps', this.loopSteps, { caller });
  714. });
  715. }
  716. private onAgentEvent(event: AgentEvent): void {
  717. const { client } = this.owner;
  718. const caller = this.caller;
  719. switch (event.type) {
  720. case 'turn_start':
  721. // One pi turn == one inner loop step (assistant response + tool batch).
  722. this.loopSteps += 1;
  723. client.counter('pi_loop_step_total', 1, this.turnLabels);
  724. this.batchStartedAt = undefined;
  725. break;
  726. case 'tool_execution_start': {
  727. const now = this.owner.nowMs();
  728. const toolName = this.metricToolName(event.toolName);
  729. this.toolStartedAt.set(event.toolCallId, now);
  730. this.batchStartedAt ??= now;
  731. client.counter('pi_tool_call_total', 1, { toolName, caller });
  732. const operation = this.metricToolOperation(toolName, event.args);
  733. this.toolIOStarted.set(event.toolCallId, {
  734. toolName,
  735. ...(operation !== undefined ? { operation } : {}),
  736. arguments: measureToolArguments(event.args, this.diagnostics.estimator),
  737. });
  738. break;
  739. }
  740. case 'tool_execution_end': {
  741. const now = this.owner.nowMs();
  742. const toolName = this.metricToolName(event.toolName);
  743. const startedAt = this.toolStartedAt.get(event.toolCallId);
  744. this.toolStartedAt.delete(event.toolCallId);
  745. if (startedAt !== undefined) {
  746. client.histogram('pi_tool_call_duration_ms', now - startedAt, {
  747. toolName,
  748. caller,
  749. });
  750. }
  751. if (event.isError) {
  752. client.counter('pi_tool_call_error_total', 1, {
  753. toolName,
  754. caller,
  755. errorKind: toolErrorKind(event.result),
  756. });
  757. }
  758. const toolIO = this.toolIOStarted.get(event.toolCallId);
  759. this.toolIOStarted.delete(event.toolCallId);
  760. if (toolIO) {
  761. this.recordToolIO(
  762. event.toolCallId,
  763. toolIO.toolName,
  764. toolIO.operation,
  765. 'arguments',
  766. toolIO.arguments,
  767. );
  768. this.recordToolIO(
  769. event.toolCallId,
  770. toolIO.toolName,
  771. toolIO.operation,
  772. 'result',
  773. measureToolResult(event.result, this.diagnostics.estimator),
  774. );
  775. }
  776. break;
  777. }
  778. case 'turn_end':
  779. if (this.batchStartedAt !== undefined) {
  780. client.histogram('pi_tool_batch_duration_ms', this.owner.nowMs() - this.batchStartedAt, {
  781. caller,
  782. });
  783. this.batchStartedAt = undefined;
  784. }
  785. this.toolIOStarted.clear();
  786. break;
  787. default:
  788. break;
  789. }
  790. }
  791. private metricToolName(toolName: string): string {
  792. return this.registeredToolNames.has(toolName) ? toolName : 'unknown';
  793. }
  794. private metricToolOperation(toolName: string, args: unknown): string | undefined {
  795. const classifier = this.toolOperationClassifiers.get(toolName);
  796. if (!classifier) return undefined;
  797. try {
  798. const operation = classifier.classify(args);
  799. return operation !== undefined && classifier.allowedValues.has(operation)
  800. ? operation
  801. : 'unknown';
  802. } catch {
  803. return 'unknown';
  804. }
  805. }
  806. private recordToolIO(
  807. toolCallId: string,
  808. toolName: string,
  809. operation: string | undefined,
  810. direction: 'arguments' | 'result',
  811. measured: MeasuredToolValue,
  812. ): void {
  813. const labels = { direction, toolName, caller: this.caller };
  814. const client = this.owner.client;
  815. client.histogram('pi_tool_io_bytes', measured.bytes, labels);
  816. const tokens = measured.tokens;
  817. if (tokens !== undefined) {
  818. client.histogram('pi_tool_io_tokens', tokens, labels);
  819. if (tokens >= LARGE_TOOL_IO_TOKEN_THRESHOLD) {
  820. this.diagnostics.logger.info?.(
  821. {
  822. session_id: this.diagnostics.sessionId,
  823. turn_id: this.diagnostics.turnId,
  824. tool_call_id: toolCallId,
  825. tool_name: toolName,
  826. direction,
  827. bytes: measured.bytes,
  828. estimated_tokens: tokens,
  829. caller: this.caller,
  830. ...(operation !== undefined ? { tool_operation: operation } : {}),
  831. },
  832. 'pi_tool_context_large_io_observed',
  833. );
  834. }
  835. }
  836. if (operation === undefined || direction !== 'result') return;
  837. const operationLabels = { toolName, operation, caller: this.caller };
  838. swallow(() =>
  839. client.histogram('pi_tool_operation_result_bytes', measured.bytes, operationLabels),
  840. );
  841. if (tokens !== undefined) {
  842. swallow(() => client.histogram('pi_tool_operation_result_tokens', tokens, operationLabels));
  843. }
  844. }
  845. private recordToolContextResidency(
  846. model: LLMModelConfig['model'],
  847. messages: readonly AgentMessage[],
  848. ): void {
  849. const breakdown = measureToolContext(messages, this.diagnostics.estimator, (toolName) =>
  850. this.metricToolName(toolName),
  851. );
  852. const labels = {
  853. provider: String(model.provider),
  854. model: String(model.id),
  855. caller: this.caller,
  856. };
  857. this.owner.client.histogram('pi_tool_context_resident_bytes', breakdown.argumentBytes, {
  858. kind: 'arguments',
  859. ...labels,
  860. });
  861. this.owner.client.histogram('pi_tool_context_resident_bytes', breakdown.resultBytes, {
  862. kind: 'result',
  863. ...labels,
  864. });
  865. if (breakdown.argumentTokens !== undefined) {
  866. this.owner.client.histogram('pi_tool_context_resident_tokens', breakdown.argumentTokens, {
  867. kind: 'arguments',
  868. ...labels,
  869. });
  870. }
  871. if (breakdown.resultTokens !== undefined) {
  872. this.owner.client.histogram('pi_tool_context_resident_tokens', breakdown.resultTokens, {
  873. kind: 'result',
  874. ...labels,
  875. });
  876. }
  877. for (const [toolName, contribution] of breakdown.byTool) {
  878. this.recordResidentContribution(toolName, 'arguments', {
  879. bytes: contribution.argumentBytes,
  880. ...(contribution.argumentTokens !== undefined
  881. ? { tokens: contribution.argumentTokens }
  882. : {}),
  883. });
  884. this.recordResidentContribution(toolName, 'result', {
  885. bytes: contribution.resultBytes,
  886. ...(contribution.resultTokens !== undefined ? { tokens: contribution.resultTokens } : {}),
  887. });
  888. }
  889. }
  890. private recordResidentContribution(
  891. toolName: string,
  892. kind: 'arguments' | 'result',
  893. measured: MeasuredToolValue,
  894. ): void {
  895. const labels = { kind, toolName, caller: this.caller };
  896. if (measured.bytes > 0) {
  897. this.owner.client.counter('pi_tool_context_resident_bytes_total', measured.bytes, labels);
  898. }
  899. if (measured.tokens !== undefined && measured.tokens > 0) {
  900. this.owner.client.counter('pi_tool_context_resident_tokens_total', measured.tokens, labels);
  901. }
  902. }
  903. private recordLLMSettled(
  904. labels: MetricLabels,
  905. requestStartedAt: number,
  906. model: LLMModelConfig['model'],
  907. final: AssistantMessage | undefined,
  908. thrown?: unknown,
  909. providerError?: unknown,
  910. recordTerminalFailure = true,
  911. interRequestGapMs?: number,
  912. settlementObserver?: PiLLMRequestSettlementObserver | void,
  913. ): void {
  914. const { client } = this.owner;
  915. const responseCompletedAt = this.owner.nowMs();
  916. swallow(() =>
  917. this.owner.observeLLMRequestSettled(this.diagnostics.sessionId, responseCompletedAt),
  918. );
  919. const requestDurationMs = responseCompletedAt - requestStartedAt;
  920. const cacheOutcome: PiLLMCacheOutcome =
  921. typeof final?.usage?.cacheRead === 'number'
  922. ? final.usage.cacheRead > 0
  923. ? 'read'
  924. : 'no_read'
  925. : 'telemetry_unknown';
  926. if (settlementObserver) {
  927. swallow(() => settlementObserver({ endedAtMs: responseCompletedAt, cacheOutcome }));
  928. }
  929. client.histogram('pi_llm_response_ms', requestDurationMs, labels);
  930. if (final && Number.isFinite(requestDurationMs) && requestDurationMs > 0) {
  931. this.requestDurationsMs.set(final, requestDurationMs);
  932. }
  933. const observation = observeLLMFailure(final, thrown);
  934. const gapClass = classifyLLMGap(interRequestGapMs);
  935. swallow(() =>
  936. client.counter('pi_llm_cache_outcome_total', 1, {
  937. ...labels,
  938. gapClass,
  939. outcome: cacheOutcome,
  940. }),
  941. );
  942. if (final?.usage) {
  943. emitTokens(client, labels, 'input', final.usage.input);
  944. emitTokens(
  945. client,
  946. labels,
  947. 'cache',
  948. (final.usage.cacheRead ?? 0) + (final.usage.cacheWrite ?? 0),
  949. );
  950. emitCacheTokens(client, labels, 'read', final.usage.cacheRead);
  951. emitCacheTokens(client, labels, 'write', final.usage.cacheWrite);
  952. emitTokens(client, labels, 'output', final.usage.output);
  953. if (!observation) {
  954. emitOutputTokensPerSecond(
  955. client,
  956. labels,
  957. final.usage.output,
  958. requestStartedAt,
  959. responseCompletedAt,
  960. );
  961. }
  962. }
  963. if (observation) {
  964. if (recordTerminalFailure) {
  965. this.llmFailure ??= observation;
  966. this.tryRecordTerminalFailure({ errorSource: 'llm', errorKind: observation.metricKind });
  967. }
  968. client.counter('pi_llm_request_error_total', 1, {
  969. ...labels,
  970. errorKind: observation.metricKind,
  971. });
  972. // Host-injected error-log reporting hook, initially used for LLM provider failures.
  973. // Fires for every physical request failure, including each retry attempt. Placed at physical request completion,
  974. // rather than the logical request wrapper, to avoid collapsing retries into one log. `'abort'` is not a real
  975. // provider failure, and the design excludes user cancellations from reporting by default.
  976. // Protect the call with `swallow` so hook errors cannot disrupt requests, retries, or turns.
  977. if (observation.metricKind !== 'abort' && this.owner.onLLMRequestFailure) {
  978. const hook = this.owner.onLLMRequestFailure;
  979. swallow(() =>
  980. hook({
  981. ...(thrown !== undefined ? { error: thrown } : {}),
  982. ...(providerError !== undefined ? { providerError } : {}),
  983. ...(final?.errorMessage ? { errorMessage: final.errorMessage } : {}),
  984. metricKind: observation.metricKind,
  985. request: {
  986. api: String(model.api),
  987. baseUrl: String(model.baseUrl),
  988. caller: this.caller,
  989. model: String(model.id),
  990. provider: String(model.provider),
  991. },
  992. occurredAtMs: responseCompletedAt,
  993. }),
  994. );
  995. }
  996. }
  997. }
  998. private recordLogicalLLMFailure(final: AssistantMessage | undefined, thrown?: unknown): void {
  999. const observation = observeLLMFailure(final, thrown);
  1000. if (!observation) return;
  1001. this.llmFailure ??= observation;
  1002. this.tryRecordTerminalFailure({ errorSource: 'llm', errorKind: observation.metricKind });
  1003. }
  1004. }
  1005. function classifyLLMGap(gapMs: number | undefined): 'first_request' | 'lt_5m' | 'gte_5m' {
  1006. if (gapMs === undefined) return 'first_request';
  1007. return gapMs < 300_000 ? 'lt_5m' : 'gte_5m';
  1008. }
  1009. function observeLLMFailure(
  1010. final: AssistantMessage | undefined,
  1011. thrown?: unknown,
  1012. ): LLMFailureObservation | undefined {
  1013. if (thrown === undefined && final?.stopReason !== 'error' && final?.stopReason !== 'aborted') {
  1014. return undefined;
  1015. }
  1016. const normalized = normalizeLLMError({
  1017. ...(thrown !== undefined ? { raw: thrown } : {}),
  1018. finishReason: final?.stopReason,
  1019. errorMessage: final?.errorMessage,
  1020. explicitAbort: final?.stopReason === 'aborted',
  1021. });
  1022. return { normalized, metricKind: toLLMMetricErrorKind(normalized.facts) };
  1023. }
  1024. function emitTokens(
  1025. client: MetricsClient,
  1026. labels: MetricLabels,
  1027. kind: 'input' | 'cache' | 'output',
  1028. count: number | undefined,
  1029. ): void {
  1030. if (typeof count !== 'number' || !Number.isFinite(count) || count <= 0) return;
  1031. client.counter('pi_llm_tokens_total', count, { ...labels, kind });
  1032. }
  1033. function emitOutputTokensPerSecond(
  1034. client: MetricsClient,
  1035. labels: MetricLabels,
  1036. outputTokens: number | undefined,
  1037. requestStartedAt: number,
  1038. responseCompletedAt: number,
  1039. ): void {
  1040. if (typeof outputTokens !== 'number' || !Number.isFinite(outputTokens) || outputTokens <= 0) {
  1041. return;
  1042. }
  1043. const requestDurationMs = responseCompletedAt - requestStartedAt;
  1044. if (!Number.isFinite(requestDurationMs) || requestDurationMs <= 0) return;
  1045. const tokensPerSecond = outputTokens / (requestDurationMs / 1_000);
  1046. if (!Number.isFinite(tokensPerSecond) || tokensPerSecond <= 0) return;
  1047. client.histogram('pi_llm_tokens_per_second', tokensPerSecond, labels);
  1048. }
  1049. function emitCacheTokens(
  1050. client: MetricsClient,
  1051. labels: MetricLabels,
  1052. operation: 'read' | 'write',
  1053. count: number | undefined,
  1054. ): void {
  1055. if (typeof count !== 'number' || !Number.isFinite(count) || count <= 0) return;
  1056. client.counter('pi_llm_cache_tokens_total', count, { ...labels, operation });
  1057. }
  1058. function registerToolOperationClassifier(
  1059. classifier: ToolOperationClassifier,
  1060. ): RegisteredToolOperationClassifier {
  1061. const allowedValues = new Set<string>();
  1062. let rejectedValueCount = 0;
  1063. for (const value of classifier.allowedValues) {
  1064. if (
  1065. allowedValues.size >= MAX_TOOL_OPERATION_VALUES ||
  1066. typeof value !== 'string' ||
  1067. value.length === 0 ||
  1068. value.length > MAX_TOOL_OPERATION_VALUE_LENGTH
  1069. ) {
  1070. rejectedValueCount += 1;
  1071. continue;
  1072. }
  1073. allowedValues.add(value);
  1074. }
  1075. return {
  1076. allowedValues,
  1077. rejectedValueCount,
  1078. classify: (args) => classifier.classify(args),
  1079. };
  1080. }
  1081. /**
  1082. * errorKind for tool failures. Tool errors at this layer are already
  1083. * collapsed into a text result, so keep the bucket set tiny and bounded.
  1084. */
  1085. function toolErrorKind(result: unknown): 'abort' | 'timeout' | 'error' {
  1086. const content = (result as { content?: Array<{ type?: string; text?: string }> })?.content;
  1087. const text = Array.isArray(content)
  1088. ? (content.find((block) => block?.type === 'text')?.text ?? '')
  1089. : '';
  1090. if (/\babort/i.test(text)) return 'abort';
  1091. if (/\btimed?\s*out\b/i.test(text)) return 'timeout';
  1092. return 'error';
  1093. }
  1094. /**
  1095. * Duck-type stream wrapper: forwards iteration/result untouched and fires
  1096. * `onFirstToken` once on the first content-bearing event. The agent loop only
  1097. * consumes `[Symbol.asyncIterator]()` and `result()`.
  1098. */
  1099. function observeFirstToken(
  1100. stream: AssistantMessageEventStream,
  1101. result: Promise<AssistantMessage>,
  1102. onFirstToken: () => void,
  1103. onIteratorError: (error: unknown) => void,
  1104. ): AssistantMessageEventStream {
  1105. let seen = false;
  1106. const wrapped = {
  1107. [Symbol.asyncIterator](): AsyncIterator<AssistantMessageEvent> {
  1108. const inner = createObservedIterator(stream, onIteratorError);
  1109. const iterator: AsyncIterator<AssistantMessageEvent> = {
  1110. next: async (...args) => {
  1111. try {
  1112. const step = await inner.next(...args);
  1113. if (!seen && !step.done && step.value && FIRST_TOKEN_EVENT_TYPES.has(step.value.type)) {
  1114. seen = true;
  1115. onFirstToken();
  1116. }
  1117. return step;
  1118. } catch (error) {
  1119. onIteratorError(error);
  1120. throw error;
  1121. }
  1122. },
  1123. };
  1124. if (inner.return) iterator.return = inner.return.bind(inner);
  1125. if (inner.throw) iterator.throw = inner.throw.bind(inner);
  1126. return iterator;
  1127. },
  1128. result: () => result,
  1129. };
  1130. return wrapped as unknown as AssistantMessageEventStream;
  1131. }
  1132. function createObservedIterator(
  1133. stream: AssistantMessageEventStream,
  1134. onIteratorError: (error: unknown) => void,
  1135. ): AsyncIterator<AssistantMessageEvent> {
  1136. try {
  1137. return stream[Symbol.asyncIterator]();
  1138. } catch (error) {
  1139. onIteratorError(error);
  1140. throw error;
  1141. }
  1142. }
  1143. function newIteratorFailure(): { promise: Promise<never>; reject: (error: unknown) => void } {
  1144. let rejectPromise: (error: unknown) => void = () => {};
  1145. const promise = new Promise<never>((_, reject) => {
  1146. rejectPromise = reject;
  1147. });
  1148. return { promise, reject: rejectPromise };
  1149. }
  1150. /** Metrics must never break the product path — not even on client bugs. */
  1151. function swallow(fn: () => void): void {
  1152. try {
  1153. fn();
  1154. } catch {
  1155. // intentionally silent
  1156. }
  1157. }
  1158. function swallowValue<T>(fn: () => T): T | undefined {
  1159. try {
  1160. return fn();
  1161. } catch {
  1162. return undefined;
  1163. }
  1164. }