@osfactory/otel-hook 0.13.1 → 0.14.0

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 (41) hide show
  1. package/README.md +94 -3
  2. package/dist/{adapter-DyCb7y1N.d.ts → adapter-D5R8lhfl.d.ts} +1 -1
  3. package/dist/cli.js +1240 -200
  4. package/dist/cli.js.map +1 -1
  5. package/dist/config.d.ts +32 -4
  6. package/dist/config.js +200 -14
  7. package/dist/config.js.map +1 -1
  8. package/dist/{destinations-DvqsPulb.d.ts → destinations-2KrcRslo.d.ts} +92 -2
  9. package/dist/{export-destinations-DUeQKr_C.d.ts → export-destinations-DvoH4QOe.d.ts} +135 -11
  10. package/dist/{hook-D5imE0Qc.d.ts → hook-DVK8Don-.d.ts} +4 -4
  11. package/dist/index.d.ts +11 -11
  12. package/dist/index.js +1262 -228
  13. package/dist/index.js.map +1 -1
  14. package/dist/install.d.ts +3 -3
  15. package/dist/install.js +1 -0
  16. package/dist/install.js.map +1 -1
  17. package/dist/integration.d.ts +16 -9
  18. package/dist/integration.js +1298 -205
  19. package/dist/integration.js.map +1 -1
  20. package/dist/lifecycle.js +1 -1
  21. package/dist/lifecycle.js.map +1 -1
  22. package/dist/{payload-CdDKeRpH.d.ts → payload-D4r71EL-.d.ts} +18 -2
  23. package/dist/privacy.d.ts +2 -2
  24. package/dist/privacy.js +42 -1
  25. package/dist/privacy.js.map +1 -1
  26. package/dist/providers.d.ts +94 -9
  27. package/dist/providers.js +300 -2
  28. package/dist/providers.js.map +1 -1
  29. package/dist/{registry-BKQhhIO3.d.ts → registry-DOJh9mzB.d.ts} +2 -2
  30. package/dist/runtime.d.ts +5 -5
  31. package/dist/runtime.js +151 -5
  32. package/dist/runtime.js.map +1 -1
  33. package/dist/{schema-SpFM6YQY.d.ts → schema-oRsbo7WO.d.ts} +77 -3
  34. package/dist/{service-CbI9CObT.d.ts → service-DySC7KQM.d.ts} +6 -1
  35. package/dist/telemetry.d.ts +5 -4
  36. package/dist/telemetry.js +1076 -476
  37. package/dist/telemetry.js.map +1 -1
  38. package/dist/testing.d.ts +5 -5
  39. package/dist/testing.js +178 -21
  40. package/dist/testing.js.map +1 -1
  41. package/package.json +1 -1
package/dist/providers.js CHANGED
@@ -3641,6 +3641,7 @@ var permissionModeSchema = z14.enum([
3641
3641
  var codexUsageSchema = z14.object({
3642
3642
  input_tokens: z14.number().int().min(0).optional(),
3643
3643
  cached_input_tokens: z14.number().int().min(0).optional(),
3644
+ cache_write_input_tokens: z14.number().int().min(0).optional(),
3644
3645
  output_tokens: z14.number().int().min(0).optional(),
3645
3646
  reasoning_output_tokens: z14.number().int().min(0).optional(),
3646
3647
  total_tokens: z14.number().int().min(0).optional()
@@ -3896,6 +3897,10 @@ var codexUsageToReport = (usage, temporality) => ({
3896
3897
  temporality,
3897
3898
  ...usage.input_tokens === void 0 ? {} : { inputTokens: usage.input_tokens },
3898
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
+ },
3899
3904
  ...usage.output_tokens === void 0 ? {} : { outputTokens: usage.output_tokens },
3900
3905
  ...usage.reasoning_output_tokens === void 0 ? {} : { reasoningOutputTokens: usage.reasoning_output_tokens },
3901
3906
  ...usage.total_tokens === void 0 ? {} : { providerTotalTokens: usage.total_tokens }
@@ -3924,8 +3929,9 @@ var CODEX_CAPABILITIES = Object.freeze({
3924
3929
  // turn; see docs/usage-semantics.md.
3925
3930
  cumulativeUsageSeries: "session-lifetime",
3926
3931
  reportsCachedInput: true,
3927
- reportsCacheCreation: false,
3928
- 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",
3929
3935
  reportsReasoningOutput: true,
3930
3936
  reportsProviderTotal: true,
3931
3937
  reportsCost: false,
@@ -4284,6 +4290,291 @@ var createCodexAdapter = () => ({
4284
4290
  hookResponse
4285
4291
  });
4286
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
+
4287
4578
  // src/providers/gemini/delivery.ts
4288
4579
  var GEMINI_UNIDENTIFIABLE_CALLBACKS = Object.freeze({
4289
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",
@@ -5316,6 +5607,7 @@ export {
5316
5607
  CODEX_CAPABILITIES,
5317
5608
  CODEX_HOOK_EVENT_NAMES,
5318
5609
  CODEX_PROVIDER_ID,
5610
+ CODEX_ROLLOUT_USAGE_ENRICHER_ID,
5319
5611
  CURSOR_ADAPTER_VERSION,
5320
5612
  CURSOR_CAPABILITIES,
5321
5613
  CURSOR_DECISION_EVENTS,
@@ -5326,6 +5618,10 @@ export {
5326
5618
  DEFAULT_CLAUDE_TRANSCRIPT_RANGE_TIMEOUT_MILLIS,
5327
5619
  DEFAULT_CLAUDE_TRANSCRIPT_TAIL_BYTES,
5328
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,
5329
5625
  DEFAULT_GEMINI_CAPABILITIES,
5330
5626
  DELIVERY_COMPONENT_PATTERN,
5331
5627
  DELIVERY_GAP_REASON_PATTERN,
@@ -5345,6 +5641,7 @@ export {
5345
5641
  createClaudeCodeAdapter,
5346
5642
  createClaudeTranscriptUsageEnricher,
5347
5643
  createCodexAdapter,
5644
+ createCodexRolloutUsageEnricher,
5348
5645
  createCursorAdapter,
5349
5646
  createDefaultProviderRegistry,
5350
5647
  createEventFactory,
@@ -5364,6 +5661,7 @@ export {
5364
5661
  providerHookResponseSchema,
5365
5662
  readClaudeTranscriptRange,
5366
5663
  readClaudeTranscriptTurn,
5664
+ readCodexRolloutUsage,
5367
5665
  readDeliveryClaim,
5368
5666
  readDeliveryGap,
5369
5667
  unknownDetection