@osfactory/otel-hook 0.13.0 → 0.13.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/README.md +51 -3
  2. package/dist/cli.js +907 -164
  3. package/dist/cli.js.map +1 -1
  4. package/dist/config.d.ts +5 -3
  5. package/dist/config.js +39 -5
  6. package/dist/config.js.map +1 -1
  7. package/dist/{destinations-DvqsPulb.d.ts → destinations-C4sSKjDO.d.ts} +1 -1
  8. package/dist/{export-destinations-Bey2djRk.d.ts → export-destinations-BjRXDots.d.ts} +37 -5
  9. package/dist/{hook-D5imE0Qc.d.ts → hook-CKLpgrYP.d.ts} +2 -2
  10. package/dist/index.d.ts +9 -9
  11. package/dist/index.js +921 -182
  12. package/dist/index.js.map +1 -1
  13. package/dist/install.d.ts +1 -1
  14. package/dist/install.js +5 -1
  15. package/dist/install.js.map +1 -1
  16. package/dist/integration.d.ts +15 -8
  17. package/dist/integration.js +998 -160
  18. package/dist/integration.js.map +1 -1
  19. package/dist/lifecycle.d.ts +8 -1
  20. package/dist/lifecycle.js +10 -3
  21. package/dist/lifecycle.js.map +1 -1
  22. package/dist/{metric-model-CFIeUwqd.d.ts → metric-model-B4lIuk6i.d.ts} +8 -0
  23. package/dist/{payload-CdDKeRpH.d.ts → payload-DLK7QaBB.d.ts} +17 -1
  24. package/dist/providers.d.ts +91 -6
  25. package/dist/providers.js +311 -4
  26. package/dist/providers.js.map +1 -1
  27. package/dist/{registry-BKQhhIO3.d.ts → registry-DM-4YvIA.d.ts} +1 -1
  28. package/dist/runtime.d.ts +3 -3
  29. package/dist/runtime.js +23 -3
  30. package/dist/runtime.js.map +1 -1
  31. package/dist/{schema-SpFM6YQY.d.ts → schema-CD61uW99.d.ts} +32 -3
  32. package/dist/state.js +20 -6
  33. package/dist/state.js.map +1 -1
  34. package/dist/telemetry.d.ts +4 -4
  35. package/dist/telemetry.js +865 -472
  36. package/dist/telemetry.js.map +1 -1
  37. package/dist/testing.d.ts +3 -3
  38. package/dist/testing.js +61 -21
  39. package/dist/testing.js.map +1 -1
  40. package/package.json +2 -1
@@ -92,6 +92,14 @@ type SpanCorrelation = {
92
92
  * discriminator keeps them from claiming the same span id.
93
93
  */
94
94
  readonly spanIdDiscriminator?: string;
95
+ /**
96
+ * Set for a later *run* of a scope whose first run was already exported (a
97
+ * resumed session): mixed into the span id of this run's record, on the
98
+ * deferred start as well as on the end, so both edges agree and the id differs
99
+ * from the first run's. A resumed session span hangs under the first run's
100
+ * session span, so the trace stays one tree.
101
+ */
102
+ readonly runSpanIdDiscriminator?: string;
95
103
  /** Start recovered from state; authoritative over the batch's own start edge. */
96
104
  readonly startMillis?: number;
97
105
  /** End recovered from state; authoritative so a redelivered end re-exports an identical span. */
@@ -135,6 +135,22 @@ declare const CODEX_PROVIDER_ID: ProviderId;
135
135
  /** Adapter package version, independent of the Codex CLI's own version. */
136
136
  declare const CODEX_ADAPTER_VERSION = "0.1.0";
137
137
 
138
+ /**
139
+ * Mirrors the rollout/exec `total_token_usage` / `last_token_usage` shape.
140
+ *
141
+ * Codex copies the Responses API counters verbatim: `input_tokens` is the whole
142
+ * prompt, and `cached_input_tokens` (cache reads) and `cache_write_input_tokens`
143
+ * (cache writes, Codex 0.163+) are subsets of it. See docs/usage-semantics.md.
144
+ */
145
+ declare const codexUsageSchema: z.ZodObject<{
146
+ input_tokens: z.ZodOptional<z.ZodNumber>;
147
+ cached_input_tokens: z.ZodOptional<z.ZodNumber>;
148
+ cache_write_input_tokens: z.ZodOptional<z.ZodNumber>;
149
+ output_tokens: z.ZodOptional<z.ZodNumber>;
150
+ reasoning_output_tokens: z.ZodOptional<z.ZodNumber>;
151
+ total_tokens: z.ZodOptional<z.ZodNumber>;
152
+ }, z.core.$strip>;
153
+ type CodexUsage = z.infer<typeof codexUsageSchema>;
138
154
  declare const CODEX_HOOK_EVENT_NAMES: readonly ["SessionStart", "UserPromptSubmit", "PreToolUse", "PermissionRequest", "PostToolUse", "PreCompact", "PostCompact", "SubagentStart", "SubagentStop", "Stop"];
139
155
  type CodexHookEventName = (typeof CODEX_HOOK_EVENT_NAMES)[number];
140
156
 
@@ -237,4 +253,4 @@ declare const createAntigravityAdapter: (options?: AntigravityAdapterOptions) =>
237
253
  declare const ANTIGRAVITY_HOOK_EVENT_NAMES: readonly ["PreInvocation", "PostInvocation", "PreToolUse", "PostToolUse", "Stop"];
238
254
  type AntigravityHookEventName = (typeof ANTIGRAVITY_HOOK_EVENT_NAMES)[number];
239
255
 
240
- export { ANTIGRAVITY_CAPABILITIES as A, CLAUDE_CODE_PROVIDER_ID as C, DEFAULT_GEMINI_CAPABILITIES as D, GEMINI_ADAPTER_VERSION as G, ANTIGRAVITY_HOOK_EVENT_NAMES as a, ANTIGRAVITY_PROVIDER_ID as b, type AntigravityAdapterOptions as c, type AntigravityHookEventName as d, CLAUDE_HOOK_EVENT_NAMES as e, CODEX_ADAPTER_VERSION as f, CODEX_HOOK_EVENT_NAMES as g, CODEX_PROVIDER_ID as h, CURSOR_DECISION_EVENTS as i, CURSOR_HOOK_EVENT_NAMES as j, CURSOR_PROVIDER_ID as k, CURSOR_UNMODELLED_HOOK_EVENT_NAMES as l, type ClaudeHookEventName as m, type CodexHookEventName as n, type CursorHookEventName as o, GEMINI_HOOK_EVENT_NAMES as p, GEMINI_PROVIDER_ID as q, type GeminiAdapterOptions as r, type GeminiHookEventName as s, createAntigravityAdapter as t, createGeminiCliAdapter as u, type ClaudeUsage as v };
256
+ export { ANTIGRAVITY_CAPABILITIES as A, CLAUDE_CODE_PROVIDER_ID as C, DEFAULT_GEMINI_CAPABILITIES as D, GEMINI_ADAPTER_VERSION as G, ANTIGRAVITY_HOOK_EVENT_NAMES as a, ANTIGRAVITY_PROVIDER_ID as b, type AntigravityAdapterOptions as c, type AntigravityHookEventName as d, CLAUDE_HOOK_EVENT_NAMES as e, CODEX_ADAPTER_VERSION as f, CODEX_HOOK_EVENT_NAMES as g, CODEX_PROVIDER_ID as h, CURSOR_DECISION_EVENTS as i, CURSOR_HOOK_EVENT_NAMES as j, CURSOR_PROVIDER_ID as k, CURSOR_UNMODELLED_HOOK_EVENT_NAMES as l, type ClaudeHookEventName as m, type CodexHookEventName as n, type CursorHookEventName as o, GEMINI_HOOK_EVENT_NAMES as p, GEMINI_PROVIDER_ID as q, type GeminiAdapterOptions as r, type GeminiHookEventName as s, createAntigravityAdapter as t, createGeminiCliAdapter as u, type ClaudeUsage as v, type CodexUsage as w };
@@ -3,10 +3,10 @@ export { D as DELIVERY_COMPONENT_PATTERN, a as DELIVERY_GAP_REASON_PATTERN, M as
3
3
  import { b as CanonicalEvent, u as TargetHint, q as SessionStartEvent, p as SessionEndEvent, P as PromptSubmittedEvent, l as GenerationStartEvent, G as GenerationEndEvent, A as ToolStartEvent, y as ToolEndEvent, t as SubagentStartEvent, r as SubagentEndEvent, g as CompactionPerformedEvent, i as ErrorRaisedEvent } from './events-fcomX6d5.js';
4
4
  import { d as InvocationIdentity } from './identity-BrVBs901.js';
5
5
  import { d as EventId } from './primitives-CJ8-rn-f.js';
6
- import { P as ProviderRegistry } from './registry-BKQhhIO3.js';
7
- export { B as BUILT_IN_PROVIDERS, D as DetectionCandidate, R as RegistryDetectionResult, c as createProviderRegistry } from './registry-BKQhhIO3.js';
8
- import { v as ClaudeUsage } from './payload-CdDKeRpH.js';
9
- export { A as ANTIGRAVITY_CAPABILITIES, a as ANTIGRAVITY_HOOK_EVENT_NAMES, b as ANTIGRAVITY_PROVIDER_ID, c as AntigravityAdapterOptions, d as AntigravityHookEventName, C as CLAUDE_CODE_PROVIDER_ID, e as CLAUDE_HOOK_EVENT_NAMES, f as CODEX_ADAPTER_VERSION, g as CODEX_HOOK_EVENT_NAMES, h as CODEX_PROVIDER_ID, i as CURSOR_DECISION_EVENTS, j as CURSOR_HOOK_EVENT_NAMES, k as CURSOR_PROVIDER_ID, l as CURSOR_UNMODELLED_HOOK_EVENT_NAMES, m as ClaudeHookEventName, n as CodexHookEventName, o as CursorHookEventName, D as DEFAULT_GEMINI_CAPABILITIES, G as GEMINI_ADAPTER_VERSION, p as GEMINI_HOOK_EVENT_NAMES, q as GEMINI_PROVIDER_ID, r as GeminiAdapterOptions, s as GeminiHookEventName, t as createAntigravityAdapter, u as createGeminiCliAdapter } from './payload-CdDKeRpH.js';
6
+ import { P as ProviderRegistry } from './registry-DM-4YvIA.js';
7
+ export { B as BUILT_IN_PROVIDERS, D as DetectionCandidate, R as RegistryDetectionResult, c as createProviderRegistry } from './registry-DM-4YvIA.js';
8
+ import { v as ClaudeUsage, w as CodexUsage } from './payload-DLK7QaBB.js';
9
+ export { A as ANTIGRAVITY_CAPABILITIES, a as ANTIGRAVITY_HOOK_EVENT_NAMES, b as ANTIGRAVITY_PROVIDER_ID, c as AntigravityAdapterOptions, d as AntigravityHookEventName, C as CLAUDE_CODE_PROVIDER_ID, e as CLAUDE_HOOK_EVENT_NAMES, f as CODEX_ADAPTER_VERSION, g as CODEX_HOOK_EVENT_NAMES, h as CODEX_PROVIDER_ID, i as CURSOR_DECISION_EVENTS, j as CURSOR_HOOK_EVENT_NAMES, k as CURSOR_PROVIDER_ID, l as CURSOR_UNMODELLED_HOOK_EVENT_NAMES, m as ClaudeHookEventName, n as CodexHookEventName, o as CursorHookEventName, D as DEFAULT_GEMINI_CAPABILITIES, G as GEMINI_ADAPTER_VERSION, p as GEMINI_HOOK_EVENT_NAMES, q as GEMINI_PROVIDER_ID, r as GeminiAdapterOptions, s as GeminiHookEventName, t as createAntigravityAdapter, u as createGeminiCliAdapter } from './payload-DLK7QaBB.js';
10
10
  import { P as PayloadEnricher } from './ports-DhpSDIkp.js';
11
11
  import 'zod';
12
12
  import './errors.js';
@@ -14,7 +14,7 @@ import './taxonomy-DwhTtuWd.js';
14
14
  import './policy-CimmCfRp.js';
15
15
  import './content-M9xIKG7h.js';
16
16
  import './service-CbI9CObT.js';
17
- import './schema-SpFM6YQY.js';
17
+ import './schema-CD61uW99.js';
18
18
 
19
19
  /** Fields the factory supplies; an adapter never sets them itself. */
20
20
  type ManagedFields = "schemaVersion" | "eventId" | "invocationId" | "sessionId" | "sequence" | "provenance" | "workspace" | "extensions" | "subagentId" | "contextAttributes" | "target" | "occurredAt";
@@ -293,6 +293,91 @@ declare const createCursorAdapter: (options?: CursorAdapterOptions) => ProviderA
293
293
  declare const CODEX_CAPABILITIES: ProviderCapabilities;
294
294
  declare const createCodexAdapter: () => ProviderAdapter;
295
295
 
296
+ /**
297
+ * The hook-runtime side of `providers.codex.readRolloutUsage`: attach the
298
+ * session's token usage, read from Codex's own rollout file, to a Codex `Stop`.
299
+ *
300
+ * Why: Codex (observed on 0.163) puts no `usage` on any hook payload. The
301
+ * counters exist only in the rollout JSONL Codex writes for every thread
302
+ * (`$CODEX_HOME/sessions/YYYY/MM/DD/rollout-<time>-<session-id>.jsonl`), on
303
+ * `event_msg` records of `payload.type === "token_count"`:
304
+ *
305
+ * ```text
306
+ * { "type": "event_msg", "payload": { "type": "token_count", "info": {
307
+ * "total_token_usage": { input_tokens, cached_input_tokens,
308
+ * cache_write_input_tokens, output_tokens, reasoning_output_tokens, total_tokens },
309
+ * "last_token_usage": { ...same keys, the last request only } } } }
310
+ * ```
311
+ *
312
+ * and, from 0.163, on `token_usage_record` records (`payload.thread_token_usage`,
313
+ * the same running total). `total_token_usage` is the thread's running total:
314
+ * exactly what the Codex adapter already takes `Stop.usage` to be (cumulative,
315
+ * one series per session, diffed against the previous snapshot downstream). So
316
+ * the enricher attaches the **last** snapshot, never a sum, which makes every
317
+ * read exact on its own: a late read counts late, a missed read is caught up by
318
+ * the next `Stop`, and nothing can be counted twice. That is also why no
319
+ * `usage_partial` exists here.
320
+ *
321
+ * Not part of the Codex adapter, which gets no filesystem handle (ADR 0003). The
322
+ * runtime keeps a byte cursor per session (`read-cursor` state value):
323
+ *
324
+ * - `SessionStart` records where the rollout ends now (0 when it does not exist
325
+ * yet), unless a cursor for the same file is stored already.
326
+ * - `Stop` reads from the cursor to the end (bounded in bytes and time) and
327
+ * attaches the last snapshot found there; the cursor moves to the end. With no
328
+ * new snapshot since the cursor (no model request this turn, or Codex has not
329
+ * flushed it yet) it waits once, briefly, then attaches nothing: the next
330
+ * `Stop` carries the running total that includes it.
331
+ * - No usable cursor, a range over the cap, or a file that shrank: the last
332
+ * snapshot in the bounded tail is attached instead (still exact, see above).
333
+ * - A timeout or an unreadable file attaches nothing and keeps the cursor.
334
+ *
335
+ * The rollout is the one named by the payload's `transcript_path`. Only when a
336
+ * payload names none, and the host gave a sessions root, is it looked up by
337
+ * session id — in at most {@link ROLLOUT_LOOKUP_DAYS} date directories, by an
338
+ * exact file-name match, never recursively.
339
+ *
340
+ * Nothing but numeric counters and a model id leaves this module.
341
+ */
342
+ declare const CODEX_ROLLOUT_USAGE_ENRICHER_ID = "codex-rollout-usage";
343
+ declare const DEFAULT_CODEX_ROLLOUT_RANGE_BYTES = 8388608;
344
+ declare const DEFAULT_CODEX_ROLLOUT_TAIL_BYTES = 1048576;
345
+ declare const DEFAULT_CODEX_ROLLOUT_TIMEOUT_MILLIS = 500;
346
+ /** How long a `Stop` waits once for a snapshot Codex has not flushed yet. */
347
+ declare const DEFAULT_CODEX_ROLLOUT_SETTLE_MILLIS = 150;
348
+ type CodexRolloutUsageEnricherOptions = {
349
+ /** Most bytes one `Stop` reads from its cursor. Default 8 MiB, clamped to 64 KiB..64 MiB. */
350
+ readonly maxRangeBytes?: number;
351
+ /** Bytes read from the end when no cursor applies. Default 1 MiB, clamped to 64 KiB..16 MiB. */
352
+ readonly maxTailBytes?: number;
353
+ /** Budget for one enrichment, lookup and settle wait included. Default 500 ms, clamped to 10 ms..5 s. */
354
+ readonly timeoutMillis?: number;
355
+ /** Wait before the one re-read when no snapshot is found yet. Default 150 ms, 0 disables. */
356
+ readonly settleMillis?: number;
357
+ /**
358
+ * `$CODEX_HOME/sessions`, for payloads that name no `transcript_path`. Absent,
359
+ * such payloads are left alone. Supplied by the host, never read from the
360
+ * environment here.
361
+ */
362
+ readonly sessionsRoot?: string;
363
+ /** Clock for the date directories of the session-id lookup. */
364
+ readonly now?: () => Date;
365
+ };
366
+ /** One running-total snapshot, with the model in force when it was written. */
367
+ type CodexRolloutSnapshot = {
368
+ readonly usage: CodexUsage;
369
+ readonly model?: string;
370
+ };
371
+ declare const createCodexRolloutUsageEnricher: (options?: CodexRolloutUsageEnricherOptions) => PayloadEnricher;
372
+ /**
373
+ * The last running-total snapshot in a Codex rollout, for a wrapping harness
374
+ * that wants to attach `usage` itself. Bounded to the last `maxTailBytes`.
375
+ * Never throws.
376
+ */
377
+ declare const readCodexRolloutUsage: (rolloutPath: string, options?: {
378
+ readonly maxTailBytes?: number;
379
+ }) => Promise<CodexRolloutSnapshot | undefined>;
380
+
296
381
  /**
297
382
  * Maturity of the Antigravity provider adapter.
298
383
  *
@@ -423,4 +508,4 @@ declare const DELIVERY_IDENTIFIER_SUMMARY: Readonly<Record<DeliveryIdentifierSup
423
508
  */
424
509
  declare const describeProviderCatalog: (options?: DefaultRegistryOptions) => readonly ProviderCatalogEntry[];
425
510
 
426
- export { ANTIGRAVITY_PROMOTION_GATES, ANTIGRAVITY_PROVIDER_MATURITY, AdapterDescription, type AntigravityProviderMaturity, CLAUDE_CODE_CAPABILITIES, CLAUDE_TRANSCRIPT_USAGE_ENRICHER_ID, CODEX_CAPABILITIES, CURSOR_ADAPTER_VERSION, CURSOR_CAPABILITIES, type CanonicalEventDraft, type ClaudeCodeAdapterOptions, type ClaudeTranscriptRange, type ClaudeTranscriptTurn, type ClaudeTranscriptUsageEnricherOptions, type CursorAdapterOptions, DEFAULT_CLAUDE_TRANSCRIPT_RANGE_BYTES, DEFAULT_CLAUDE_TRANSCRIPT_RANGE_TIMEOUT_MILLIS, DEFAULT_CLAUDE_TRANSCRIPT_TAIL_BYTES, DEFAULT_CLAUDE_TRANSCRIPT_TIMEOUT_MILLIS, DELIVERY_IDENTIFIER_SUMMARY, type DefaultRegistryOptions, DeliveryIdentifierSupport, EXPERIMENTAL_PROVIDER_IDS, type EventFactory, type EventFactoryInput, PROVIDER_DESCRIPTORS, ProviderAdapter, ProviderCapabilities, type ProviderCatalogEntry, ProviderContext, type ProviderDescriptor, type ProviderMaturity, ProviderRegistry, type ReadClaudeTranscriptRangeOptions, type ReadClaudeTranscriptTurnOptions, attachClaudeTranscriptTurn, createClaudeCodeAdapter, createClaudeTranscriptUsageEnricher, createCodexAdapter, createCursorAdapter, createDefaultProviderRegistry, createEventFactory, describeProviderCatalog, findProviderDescriptor, isExperimentalProvider, readClaudeTranscriptRange, readClaudeTranscriptTurn };
511
+ export { ANTIGRAVITY_PROMOTION_GATES, ANTIGRAVITY_PROVIDER_MATURITY, AdapterDescription, type AntigravityProviderMaturity, CLAUDE_CODE_CAPABILITIES, CLAUDE_TRANSCRIPT_USAGE_ENRICHER_ID, CODEX_CAPABILITIES, CODEX_ROLLOUT_USAGE_ENRICHER_ID, CURSOR_ADAPTER_VERSION, CURSOR_CAPABILITIES, type CanonicalEventDraft, type ClaudeCodeAdapterOptions, type ClaudeTranscriptRange, type ClaudeTranscriptTurn, type ClaudeTranscriptUsageEnricherOptions, type CodexRolloutSnapshot, type CodexRolloutUsageEnricherOptions, type CursorAdapterOptions, DEFAULT_CLAUDE_TRANSCRIPT_RANGE_BYTES, DEFAULT_CLAUDE_TRANSCRIPT_RANGE_TIMEOUT_MILLIS, DEFAULT_CLAUDE_TRANSCRIPT_TAIL_BYTES, DEFAULT_CLAUDE_TRANSCRIPT_TIMEOUT_MILLIS, DEFAULT_CODEX_ROLLOUT_RANGE_BYTES, DEFAULT_CODEX_ROLLOUT_SETTLE_MILLIS, DEFAULT_CODEX_ROLLOUT_TAIL_BYTES, DEFAULT_CODEX_ROLLOUT_TIMEOUT_MILLIS, DELIVERY_IDENTIFIER_SUMMARY, type DefaultRegistryOptions, DeliveryIdentifierSupport, EXPERIMENTAL_PROVIDER_IDS, type EventFactory, type EventFactoryInput, PROVIDER_DESCRIPTORS, ProviderAdapter, ProviderCapabilities, type ProviderCatalogEntry, ProviderContext, type ProviderDescriptor, type ProviderMaturity, ProviderRegistry, type ReadClaudeTranscriptRangeOptions, type ReadClaudeTranscriptTurnOptions, attachClaudeTranscriptTurn, createClaudeCodeAdapter, createClaudeTranscriptUsageEnricher, createCodexAdapter, createCodexRolloutUsageEnricher, createCursorAdapter, createDefaultProviderRegistry, createEventFactory, describeProviderCatalog, findProviderDescriptor, isExperimentalProvider, readClaudeTranscriptRange, readClaudeTranscriptTurn, readCodexRolloutUsage };
package/dist/providers.js CHANGED
@@ -1299,7 +1299,10 @@ var postToolUseFailurePayloadSchema = z12.object({
1299
1299
  hook_event_name: z12.literal("PostToolUseFailure"),
1300
1300
  tool_name: z12.string().min(1),
1301
1301
  tool_input: z12.unknown().optional(),
1302
- tool_error: z12.unknown(),
1302
+ // Optional: a failure that names no message still ends its tool call. The
1303
+ // `error` spelling Claude Code 2.1.x sends is folded onto it by
1304
+ // `normalizeClaudeHookPayload`.
1305
+ tool_error: z12.unknown().optional(),
1303
1306
  tool_use_id: z12.string().min(1)
1304
1307
  });
1305
1308
  var permissionRequestPayloadSchema = z12.object({
@@ -1668,7 +1671,13 @@ var normalizeClaudeHookPayload = (payload) => {
1668
1671
  if (record === void 0) {
1669
1672
  return payload;
1670
1673
  }
1671
- return applyUsageShape(applyPrintResultShape(applyFieldAliases(record)));
1674
+ return applyUsageShape(applyToolFailureShape(applyPrintResultShape(applyFieldAliases(record))));
1675
+ };
1676
+ var applyToolFailureShape = (record) => {
1677
+ if (record.hook_event_name !== "PostToolUseFailure" || record.tool_error !== void 0 || record.error === void 0) {
1678
+ return record;
1679
+ }
1680
+ return { ...record, tool_error: record.error };
1672
1681
  };
1673
1682
  var applyUsageShape = (record) => {
1674
1683
  const usage = coerceClaudeUsage(record.usage) ?? coerceClaudeUsage(record.token_usage) ?? coerceClaudeUsage(record.tokenUsage);
@@ -3632,6 +3641,7 @@ var permissionModeSchema = z14.enum([
3632
3641
  var codexUsageSchema = z14.object({
3633
3642
  input_tokens: z14.number().int().min(0).optional(),
3634
3643
  cached_input_tokens: z14.number().int().min(0).optional(),
3644
+ cache_write_input_tokens: z14.number().int().min(0).optional(),
3635
3645
  output_tokens: z14.number().int().min(0).optional(),
3636
3646
  reasoning_output_tokens: z14.number().int().min(0).optional(),
3637
3647
  total_tokens: z14.number().int().min(0).optional()
@@ -3887,6 +3897,10 @@ var codexUsageToReport = (usage, temporality) => ({
3887
3897
  temporality,
3888
3898
  ...usage.input_tokens === void 0 ? {} : { inputTokens: usage.input_tokens },
3889
3899
  ...usage.cached_input_tokens === void 0 ? {} : { cachedInputTokens: usage.cached_input_tokens },
3900
+ ...usage.cache_write_input_tokens === void 0 ? {} : {
3901
+ cacheCreationInputTokens: usage.cache_write_input_tokens,
3902
+ cacheCreationAccounting: "included-in-input"
3903
+ },
3890
3904
  ...usage.output_tokens === void 0 ? {} : { outputTokens: usage.output_tokens },
3891
3905
  ...usage.reasoning_output_tokens === void 0 ? {} : { reasoningOutputTokens: usage.reasoning_output_tokens },
3892
3906
  ...usage.total_tokens === void 0 ? {} : { providerTotalTokens: usage.total_tokens }
@@ -3915,8 +3929,9 @@ var CODEX_CAPABILITIES = Object.freeze({
3915
3929
  // turn; see docs/usage-semantics.md.
3916
3930
  cumulativeUsageSeries: "session-lifetime",
3917
3931
  reportsCachedInput: true,
3918
- reportsCacheCreation: false,
3919
- cacheCreationAccounting: "not-reported",
3932
+ // Codex 0.163+ reports `cache_write_input_tokens`, a subset of `input_tokens`.
3933
+ reportsCacheCreation: true,
3934
+ cacheCreationAccounting: "included-in-input",
3920
3935
  reportsReasoningOutput: true,
3921
3936
  reportsProviderTotal: true,
3922
3937
  reportsCost: false,
@@ -4275,6 +4290,291 @@ var createCodexAdapter = () => ({
4275
4290
  hookResponse
4276
4291
  });
4277
4292
 
4293
+ // src/providers/codex/rollout-usage.ts
4294
+ import { createHash as createHash2 } from "crypto";
4295
+ import { open as open2, readdir, stat as stat2 } from "fs/promises";
4296
+ import path2 from "path";
4297
+ var CODEX_ROLLOUT_USAGE_ENRICHER_ID = "codex-rollout-usage";
4298
+ var DEFAULT_CODEX_ROLLOUT_RANGE_BYTES = 8388608;
4299
+ var DEFAULT_CODEX_ROLLOUT_TAIL_BYTES = 1048576;
4300
+ var DEFAULT_CODEX_ROLLOUT_TIMEOUT_MILLIS = 500;
4301
+ var DEFAULT_CODEX_ROLLOUT_SETTLE_MILLIS = 150;
4302
+ var ROLLOUT_LOOKUP_DAYS = 7;
4303
+ var MIN_BYTES = 65536;
4304
+ var MAX_RANGE_BYTES2 = 67108864;
4305
+ var MAX_TAIL_BYTES2 = 16777216;
4306
+ var MIN_TIMEOUT_MILLIS2 = 10;
4307
+ var MAX_TIMEOUT_MILLIS2 = 5e3;
4308
+ var MAX_SETTLE_MILLIS = 1e3;
4309
+ var MAX_MODEL_ID_LENGTH2 = 256;
4310
+ var MAX_LOOKUP_DIR_ENTRIES = 2e4;
4311
+ var SESSION_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_-]{7,127}$/;
4312
+ var clamp2 = (value, fallback, min, max) => {
4313
+ if (value === void 0 || !Number.isFinite(value)) {
4314
+ return fallback;
4315
+ }
4316
+ return Math.min(max, Math.max(min, Math.floor(value)));
4317
+ };
4318
+ var asRecord8 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
4319
+ var isRolloutPath = (value) => typeof value === "string" && value.length > 0 && value.length <= 4096 && !value.includes("\0") && path2.isAbsolute(value) && path2.extname(value) === ".jsonl";
4320
+ var sourceDigest2 = (rolloutPath) => createHash2("sha256").update(rolloutPath, "utf8").digest("hex").slice(0, 32);
4321
+ var parseUsage = (value) => {
4322
+ const parsed = codexUsageSchema.safeParse(value);
4323
+ if (!parsed.success) {
4324
+ return void 0;
4325
+ }
4326
+ const usage = parsed.data;
4327
+ return usage.input_tokens === void 0 || usage.output_tokens === void 0 ? void 0 : usage;
4328
+ };
4329
+ var modelOf = (value) => typeof value === "string" && value.length > 0 && value.length <= MAX_MODEL_ID_LENGTH2 ? value : void 0;
4330
+ var factsOf = (line) => {
4331
+ const usageLine = line.includes('"token_count"') || line.includes('"token_usage_record"');
4332
+ const contextLine = line.includes('"turn_context"');
4333
+ if (!usageLine && !contextLine) {
4334
+ return void 0;
4335
+ }
4336
+ let parsed;
4337
+ try {
4338
+ parsed = JSON.parse(line);
4339
+ } catch {
4340
+ return void 0;
4341
+ }
4342
+ const record = asRecord8(parsed);
4343
+ const payload = asRecord8(record?.payload);
4344
+ if (record === void 0 || payload === void 0) {
4345
+ return void 0;
4346
+ }
4347
+ if (record.type === "turn_context") {
4348
+ const model = modelOf(payload.model);
4349
+ return model === void 0 ? void 0 : { model };
4350
+ }
4351
+ if (record.type === "event_msg" && payload.type === "token_count") {
4352
+ const info = asRecord8(payload.info) ?? payload;
4353
+ const usage = parseUsage(info.total_token_usage);
4354
+ return usage === void 0 ? void 0 : { usage };
4355
+ }
4356
+ if (record.type === "token_usage_record") {
4357
+ const usage = parseUsage(payload.thread_token_usage);
4358
+ return usage === void 0 ? void 0 : { usage };
4359
+ }
4360
+ return void 0;
4361
+ };
4362
+ var lastSnapshotIn = (lines) => {
4363
+ let usage;
4364
+ let model;
4365
+ for (const line of lines) {
4366
+ const facts = factsOf(line.trim());
4367
+ if (facts === void 0) {
4368
+ continue;
4369
+ }
4370
+ if (facts.model !== void 0) {
4371
+ model = facts.model;
4372
+ }
4373
+ if (facts.usage !== void 0) {
4374
+ usage = facts.usage;
4375
+ }
4376
+ }
4377
+ return usage === void 0 ? void 0 : { usage, ...model === void 0 ? {} : { model } };
4378
+ };
4379
+ var readBytes2 = async (handle, start, length) => {
4380
+ const buffer = Buffer.alloc(length);
4381
+ let filled = 0;
4382
+ while (filled < length) {
4383
+ const { bytesRead } = await handle.read(buffer, filled, length - filled, start + filled);
4384
+ if (bytesRead === 0) {
4385
+ break;
4386
+ }
4387
+ filled += bytesRead;
4388
+ }
4389
+ return buffer.subarray(0, filled);
4390
+ };
4391
+ var readRollout = async (rolloutPath, fromOffset, maxRangeBytes, tailBytes) => {
4392
+ let handle;
4393
+ try {
4394
+ const info = await stat2(rolloutPath);
4395
+ if (!info.isFile()) {
4396
+ return { status: "unavailable", reason: "not-a-file" };
4397
+ }
4398
+ handle = await open2(rolloutPath, "r");
4399
+ } catch {
4400
+ return { status: "unavailable", reason: "unreadable" };
4401
+ }
4402
+ try {
4403
+ const { size } = await handle.stat();
4404
+ let start;
4405
+ if (fromOffset === void 0) {
4406
+ start = Math.max(0, size - tailBytes);
4407
+ } else if (size < fromOffset) {
4408
+ return { status: "unavailable", reason: "truncated" };
4409
+ } else if (size - fromOffset > maxRangeBytes) {
4410
+ return { status: "unavailable", reason: "over-cap" };
4411
+ } else {
4412
+ start = fromOffset;
4413
+ }
4414
+ const bytes = await readBytes2(handle, start, size - start);
4415
+ const lastNewline = bytes.lastIndexOf(10);
4416
+ const endOffset = lastNewline < 0 ? start : start + lastNewline + 1;
4417
+ const lines = bytes.subarray(0, endOffset - start).toString("utf8").split("\n");
4418
+ if (fromOffset === void 0 && start > 0) {
4419
+ lines.shift();
4420
+ }
4421
+ const snapshot = lastSnapshotIn(lines);
4422
+ return { status: "found", ...snapshot === void 0 ? {} : { snapshot }, endOffset };
4423
+ } catch {
4424
+ return { status: "unavailable", reason: "unreadable" };
4425
+ } finally {
4426
+ await handle.close().catch(() => void 0);
4427
+ }
4428
+ };
4429
+ var pad = (value) => String(value).padStart(2, "0");
4430
+ var findRolloutBySessionId = async (sessionsRoot, sessionId, now) => {
4431
+ if (!SESSION_ID_PATTERN.test(sessionId) || !path2.isAbsolute(sessionsRoot)) {
4432
+ return void 0;
4433
+ }
4434
+ const suffix = `-${sessionId}.jsonl`;
4435
+ for (let back = 0; back < ROLLOUT_LOOKUP_DAYS; back += 1) {
4436
+ const day = new Date(now.getFullYear(), now.getMonth(), now.getDate() - back);
4437
+ const dir = path2.join(sessionsRoot, String(day.getFullYear()), pad(day.getMonth() + 1), pad(day.getDate()));
4438
+ let names;
4439
+ try {
4440
+ names = await readdir(dir);
4441
+ } catch {
4442
+ continue;
4443
+ }
4444
+ if (names.length > MAX_LOOKUP_DIR_ENTRIES) {
4445
+ continue;
4446
+ }
4447
+ const match = names.find((name) => name.startsWith("rollout-") && name.endsWith(suffix));
4448
+ if (match !== void 0) {
4449
+ return path2.join(dir, match);
4450
+ }
4451
+ }
4452
+ return void 0;
4453
+ };
4454
+ var TIMED_OUT2 = /* @__PURE__ */ Symbol("timed-out");
4455
+ var withTimeout2 = async (work, timeoutMillis) => {
4456
+ let timer;
4457
+ const timeout = new Promise((resolve) => {
4458
+ timer = setTimeout(() => {
4459
+ resolve(TIMED_OUT2);
4460
+ }, timeoutMillis);
4461
+ timer.unref();
4462
+ });
4463
+ try {
4464
+ return await Promise.race([work, timeout]);
4465
+ } finally {
4466
+ clearTimeout(timer);
4467
+ }
4468
+ };
4469
+ var sleep = (millis) => new Promise((resolve) => {
4470
+ setTimeout(resolve, millis).unref();
4471
+ });
4472
+ var hasUsage2 = (record) => record.usage !== void 0;
4473
+ var createCodexRolloutUsageEnricher = (options = {}) => {
4474
+ const maxRangeBytes = clamp2(options.maxRangeBytes, DEFAULT_CODEX_ROLLOUT_RANGE_BYTES, MIN_BYTES, MAX_RANGE_BYTES2);
4475
+ const maxTailBytes = clamp2(options.maxTailBytes, DEFAULT_CODEX_ROLLOUT_TAIL_BYTES, MIN_BYTES, MAX_TAIL_BYTES2);
4476
+ const timeoutMillis = clamp2(
4477
+ options.timeoutMillis,
4478
+ DEFAULT_CODEX_ROLLOUT_TIMEOUT_MILLIS,
4479
+ MIN_TIMEOUT_MILLIS2,
4480
+ MAX_TIMEOUT_MILLIS2
4481
+ );
4482
+ const settleMillis = clamp2(options.settleMillis, DEFAULT_CODEX_ROLLOUT_SETTLE_MILLIS, 0, MAX_SETTLE_MILLIS);
4483
+ const now = options.now ?? (() => /* @__PURE__ */ new Date());
4484
+ const fileSize = async (rolloutPath) => {
4485
+ try {
4486
+ const info = await stat2(rolloutPath);
4487
+ return info.isFile() ? info.size : void 0;
4488
+ } catch (thrown) {
4489
+ return thrown?.code === "ENOENT" ? "absent" : void 0;
4490
+ }
4491
+ };
4492
+ const resolveRollout = async (record) => {
4493
+ const named = record.transcript_path;
4494
+ if (named !== void 0 && named !== null) {
4495
+ return isRolloutPath(named) ? named : void 0;
4496
+ }
4497
+ const sessionId = record.session_id;
4498
+ if (options.sessionsRoot === void 0 || typeof sessionId !== "string") {
4499
+ return void 0;
4500
+ }
4501
+ return findRolloutBySessionId(options.sessionsRoot, sessionId, now());
4502
+ };
4503
+ const enrichWithin = async (input) => {
4504
+ const unchanged = { payload: input.payload };
4505
+ const record = asRecord8(input.payload);
4506
+ const eventName = record?.hook_event_name;
4507
+ if (record === void 0 || eventName !== "SessionStart" && eventName !== "Stop") {
4508
+ return unchanged;
4509
+ }
4510
+ const rolloutPath = await resolveRollout(record);
4511
+ if (rolloutPath === void 0) {
4512
+ return { ...unchanged, notes: ["no rollout named or found for this session"] };
4513
+ }
4514
+ const source = sourceDigest2(rolloutPath);
4515
+ const cursor = input.cursor?.source === source ? input.cursor : void 0;
4516
+ if (eventName === "SessionStart") {
4517
+ if (cursor !== void 0) {
4518
+ return unchanged;
4519
+ }
4520
+ const size = await fileSize(rolloutPath);
4521
+ if (size === void 0) {
4522
+ return { ...unchanged, notes: ["rollout is not a readable regular file; no cursor recorded"] };
4523
+ }
4524
+ return { payload: input.payload, cursor: { source, offset: size === "absent" ? 0 : size } };
4525
+ }
4526
+ if (hasUsage2(record)) {
4527
+ const size = await fileSize(rolloutPath);
4528
+ return typeof size === "number" ? { payload: input.payload, cursor: { source, offset: size } } : unchanged;
4529
+ }
4530
+ const attach = (snapshot) => ({
4531
+ ...record,
4532
+ ...record.model === void 0 && snapshot.model !== void 0 ? { model: snapshot.model } : {},
4533
+ usage: snapshot.usage
4534
+ });
4535
+ let read = await readRollout(rolloutPath, cursor?.offset, maxRangeBytes, maxTailBytes);
4536
+ if (read.status === "found" && read.snapshot === void 0 && cursor !== void 0 && settleMillis > 0) {
4537
+ await sleep(settleMillis);
4538
+ read = await readRollout(rolloutPath, cursor.offset, maxRangeBytes, maxTailBytes);
4539
+ }
4540
+ if (read.status === "unavailable") {
4541
+ if (read.reason !== "truncated" && read.reason !== "over-cap") {
4542
+ return { ...unchanged, notes: [`rollout not read (${read.reason}); cursor kept`] };
4543
+ }
4544
+ read = await readRollout(rolloutPath, void 0, maxRangeBytes, maxTailBytes);
4545
+ if (read.status === "unavailable") {
4546
+ return { ...unchanged, notes: [`rollout tail not read (${read.reason})`] };
4547
+ }
4548
+ }
4549
+ const next = { source, offset: read.endOffset };
4550
+ if (read.snapshot === void 0) {
4551
+ return { payload: input.payload, cursor: next, notes: ["no token_count since the last stop"] };
4552
+ }
4553
+ return {
4554
+ payload: attach(read.snapshot),
4555
+ cursor: next,
4556
+ notes: [cursor === void 0 ? "no cursor; attached the last running total in the tail" : "attached the running total"]
4557
+ };
4558
+ };
4559
+ const enrich = async (input) => {
4560
+ try {
4561
+ const result = await withTimeout2(enrichWithin(input), timeoutMillis);
4562
+ return result === TIMED_OUT2 ? { payload: input.payload, notes: ["rollout read timed out; cursor kept"] } : result;
4563
+ } catch {
4564
+ return { payload: input.payload, notes: ["rollout read failed; cursor kept"] };
4565
+ }
4566
+ };
4567
+ return Object.freeze({ id: CODEX_ROLLOUT_USAGE_ENRICHER_ID, providerId: CODEX_PROVIDER_ID, enrich });
4568
+ };
4569
+ var readCodexRolloutUsage = async (rolloutPath, options = {}) => {
4570
+ if (!isRolloutPath(rolloutPath)) {
4571
+ return void 0;
4572
+ }
4573
+ const tail = clamp2(options.maxTailBytes, DEFAULT_CODEX_ROLLOUT_TAIL_BYTES, MIN_BYTES, MAX_TAIL_BYTES2);
4574
+ const read = await readRollout(rolloutPath, void 0, DEFAULT_CODEX_ROLLOUT_RANGE_BYTES, tail).catch(() => void 0);
4575
+ return read?.status === "found" ? read.snapshot : void 0;
4576
+ };
4577
+
4278
4578
  // src/providers/gemini/delivery.ts
4279
4579
  var GEMINI_UNIDENTIFIABLE_CALLBACKS = Object.freeze({
4280
4580
  SessionStart: "fires again within the same session_id on resume and clear (payload `source`), so session_id names a class of firings rather than one",
@@ -5307,6 +5607,7 @@ export {
5307
5607
  CODEX_CAPABILITIES,
5308
5608
  CODEX_HOOK_EVENT_NAMES,
5309
5609
  CODEX_PROVIDER_ID,
5610
+ CODEX_ROLLOUT_USAGE_ENRICHER_ID,
5310
5611
  CURSOR_ADAPTER_VERSION,
5311
5612
  CURSOR_CAPABILITIES,
5312
5613
  CURSOR_DECISION_EVENTS,
@@ -5317,6 +5618,10 @@ export {
5317
5618
  DEFAULT_CLAUDE_TRANSCRIPT_RANGE_TIMEOUT_MILLIS,
5318
5619
  DEFAULT_CLAUDE_TRANSCRIPT_TAIL_BYTES,
5319
5620
  DEFAULT_CLAUDE_TRANSCRIPT_TIMEOUT_MILLIS,
5621
+ DEFAULT_CODEX_ROLLOUT_RANGE_BYTES,
5622
+ DEFAULT_CODEX_ROLLOUT_SETTLE_MILLIS,
5623
+ DEFAULT_CODEX_ROLLOUT_TAIL_BYTES,
5624
+ DEFAULT_CODEX_ROLLOUT_TIMEOUT_MILLIS,
5320
5625
  DEFAULT_GEMINI_CAPABILITIES,
5321
5626
  DELIVERY_COMPONENT_PATTERN,
5322
5627
  DELIVERY_GAP_REASON_PATTERN,
@@ -5336,6 +5641,7 @@ export {
5336
5641
  createClaudeCodeAdapter,
5337
5642
  createClaudeTranscriptUsageEnricher,
5338
5643
  createCodexAdapter,
5644
+ createCodexRolloutUsageEnricher,
5339
5645
  createCursorAdapter,
5340
5646
  createDefaultProviderRegistry,
5341
5647
  createEventFactory,
@@ -5355,6 +5661,7 @@ export {
5355
5661
  providerHookResponseSchema,
5356
5662
  readClaudeTranscriptRange,
5357
5663
  readClaudeTranscriptTurn,
5664
+ readCodexRolloutUsage,
5358
5665
  readDeliveryClaim,
5359
5666
  readDeliveryGap,
5360
5667
  unknownDetection