@osfactory/otel-hook 0.12.0 → 0.13.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 (39) hide show
  1. package/README.md +6 -4
  2. package/dist/{adapter-DQiPu8xF.d.ts → adapter-DyCb7y1N.d.ts} +1 -1
  3. package/dist/cli.js +137 -44
  4. package/dist/cli.js.map +1 -1
  5. package/dist/{export-destinations-CI7z4n3i.d.ts → export-destinations-Bey2djRk.d.ts} +2 -2
  6. package/dist/{filesystem-store-CmnUlj1O.d.ts → filesystem-store-B3CpiIRl.d.ts} +1 -1
  7. package/dist/{hook-vM_cgqS2.d.ts → hook-D5imE0Qc.d.ts} +3 -3
  8. package/dist/index.d.ts +10 -10
  9. package/dist/index.js +137 -44
  10. package/dist/index.js.map +1 -1
  11. package/dist/install.d.ts +3 -3
  12. package/dist/install.js +10 -1
  13. package/dist/install.js.map +1 -1
  14. package/dist/integration.d.ts +7 -7
  15. package/dist/integration.js +107 -41
  16. package/dist/integration.js.map +1 -1
  17. package/dist/lifecycle.d.ts +2 -2
  18. package/dist/lifecycle.js +1 -1
  19. package/dist/lifecycle.js.map +1 -1
  20. package/dist/{memory-DdU1U91y.d.ts → memory-B3r6sZtC.d.ts} +1 -1
  21. package/dist/{metric-model-C9lLqqpI.d.ts → metric-model-CFIeUwqd.d.ts} +2 -1
  22. package/dist/{payload-BT19hiVZ.d.ts → payload-CdDKeRpH.d.ts} +1 -1
  23. package/dist/{ports-C3k_5eOQ.d.ts → ports-DhpSDIkp.d.ts} +8 -1
  24. package/dist/providers.d.ts +27 -11
  25. package/dist/providers.js +121 -41
  26. package/dist/providers.js.map +1 -1
  27. package/dist/{registry-gyJqaWmp.d.ts → registry-BKQhhIO3.d.ts} +1 -1
  28. package/dist/runtime.d.ts +6 -6
  29. package/dist/runtime.js +12 -2
  30. package/dist/runtime.js.map +1 -1
  31. package/dist/state.d.ts +3 -3
  32. package/dist/state.js.map +1 -1
  33. package/dist/telemetry.d.ts +3 -3
  34. package/dist/telemetry.js +4 -1
  35. package/dist/telemetry.js.map +1 -1
  36. package/dist/testing.d.ts +6 -6
  37. package/dist/testing.js +52 -6
  38. package/dist/testing.js.map +1 -1
  39. package/package.json +1 -1
@@ -3,23 +3,23 @@ import { OverallHealth } from './diagnostics.js';
3
3
  import { OtelHookErrorInfo } from './errors.js';
4
4
  import { DeliveryClaimOutcome, UsageAccumulatorSnapshot, LifecycleCleanupReport, CallbackDeduplicator, UsageAccumulator, SpanCorrelator, MetricSeriesStore, LifecycleJanitor } from './lifecycle.js';
5
5
  import { P as PrivacyService } from './service-CbI9CObT.js';
6
- import { P as ProviderRegistry } from './registry-gyJqaWmp.js';
7
- import { a as DeliveryOrigin, c as DeliveryUnavailableReason, H as HookIngestInput, e as HookIngestOutcome, U as UsageObservation, O as OtelHook } from './hook-vM_cgqS2.js';
8
- import { C as Clock, I as IdGenerator, d as Logger, W as WorktreeLocator, P as PayloadEnricher, S as SessionContextReader } from './ports-C3k_5eOQ.js';
9
- import { F as FilesystemStateStore } from './filesystem-store-CmnUlj1O.js';
10
- import { w as OtlpTelemetrySink, t as OtlpLogTelemetrySink, d as DurableSpool, D as DurableLogSpool, E as ExportDestinationSinks, B as SkippedExportDestination } from './export-destinations-CI7z4n3i.js';
6
+ import { P as ProviderRegistry } from './registry-BKQhhIO3.js';
7
+ import { a as DeliveryOrigin, c as DeliveryUnavailableReason, H as HookIngestInput, e as HookIngestOutcome, U as UsageObservation, O as OtelHook } from './hook-D5imE0Qc.js';
8
+ import { C as Clock, I as IdGenerator, d as Logger, W as WorktreeLocator, P as PayloadEnricher, S as SessionContextReader } from './ports-DhpSDIkp.js';
9
+ import { F as FilesystemStateStore } from './filesystem-store-B3CpiIRl.js';
10
+ import { w as OtlpTelemetrySink, t as OtlpLogTelemetrySink, d as DurableSpool, D as DurableLogSpool, E as ExportDestinationSinks, B as SkippedExportDestination } from './export-destinations-Bey2djRk.js';
11
11
  import 'zod';
12
12
  import './primitives-CJ8-rn-f.js';
13
13
  import './taxonomy-DwhTtuWd.js';
14
14
  import '@opentelemetry/api';
15
15
  import './events-fcomX6d5.js';
16
- import './metric-model-C9lLqqpI.js';
16
+ import './metric-model-CFIeUwqd.js';
17
17
  import '@opentelemetry/core';
18
18
  import '@opentelemetry/resources';
19
19
  import '@opentelemetry/sdk-trace';
20
20
  import './content-M9xIKG7h.js';
21
21
  import './policy-CimmCfRp.js';
22
- import './adapter-DQiPu8xF.js';
22
+ import './adapter-DyCb7y1N.js';
23
23
  import './identity-BrVBs901.js';
24
24
  import './keys-Dej5bN3L.js';
25
25
  import './destinations-DvqsPulb.js';
@@ -2085,6 +2085,9 @@ var deriveMetricObservations = (input) => {
2085
2085
  if (recovered !== void 0) {
2086
2086
  return end.occurredAt - recovered.startMillis;
2087
2087
  }
2088
+ if (end.subagentId !== void 0) {
2089
+ return void 0;
2090
+ }
2088
2091
  const turn = lastPromptInBatch?.get(end.sessionId) ?? input.turnStart?.(end.sessionId);
2089
2092
  return turn === void 0 || turn > end.occurredAt ? void 0 : end.occurredAt - turn;
2090
2093
  };
@@ -2416,7 +2419,7 @@ import {
2416
2419
  } from "@opentelemetry/semantic-conventions/incubating";
2417
2420
 
2418
2421
  // src/version.ts
2419
- var VERSION = "0.12.0";
2422
+ var VERSION = "0.13.0";
2420
2423
 
2421
2424
  // src/telemetry/semconv.ts
2422
2425
  var SCOPE_NAME = "@osfactory/otel-hook";
@@ -4048,7 +4051,16 @@ var subagentStopPayloadSchema = z16.object({
4048
4051
  last_assistant_message: z16.string().optional(),
4049
4052
  /** True when this stop fired because a hook continued the subagent's turn. */
4050
4053
  stop_hook_active: z16.boolean().optional(),
4051
- usage: claudeUsageSchema.optional()
4054
+ /**
4055
+ * The subagent run's tokens since its previous stop — harness- or
4056
+ * enricher-supplied, never upstream. Reported on the subagent's own
4057
+ * generation, never on the parent turn (issue #68).
4058
+ */
4059
+ usage: claudeUsageSchema.optional(),
4060
+ /** Harness-supplied, never upstream: the subagent's model, from its transcript. */
4061
+ model: z16.string().min(1).max(256).optional().catch(void 0),
4062
+ /** Harness-supplied, never upstream: see `stopPayloadSchema.usage_partial`. */
4063
+ usage_partial: z16.boolean().optional().catch(void 0)
4052
4064
  });
4053
4065
  var preCompactPayloadSchema = z16.object({
4054
4066
  ...commonFields,
@@ -4277,7 +4289,8 @@ var clamp = (value, fallback, min, max) => {
4277
4289
  };
4278
4290
  var asRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
4279
4291
  var isTranscriptPath = (transcriptPath) => typeof transcriptPath === "string" && transcriptPath.length > 0 && !transcriptPath.includes("\0") && path.isAbsolute(transcriptPath) && path.extname(transcriptPath) === ".jsonl";
4280
- var assistantRecordOf = (line) => {
4292
+ var isRecordOfAgent = (record, agentId) => record.isSidechain === true && (typeof record.agentId !== "string" || record.agentId === agentId);
4293
+ var assistantRecordOf = (line, agentId) => {
4281
4294
  if (!line.includes('"assistant"')) {
4282
4295
  return void 0;
4283
4296
  }
@@ -4288,7 +4301,10 @@ var assistantRecordOf = (line) => {
4288
4301
  return void 0;
4289
4302
  }
4290
4303
  const record = asRecord2(parsed);
4291
- if (record === void 0 || record.type !== "assistant" || record.isSidechain === true) {
4304
+ if (record === void 0 || record.type !== "assistant") {
4305
+ return void 0;
4306
+ }
4307
+ if (agentId === void 0 ? record.isSidechain === true : !isRecordOfAgent(record, agentId)) {
4292
4308
  return void 0;
4293
4309
  }
4294
4310
  const message = asRecord2(record.message);
@@ -4381,7 +4397,7 @@ var completeLinesEnd = (bytes, start) => {
4381
4397
  const lastNewline = bytes.lastIndexOf(10);
4382
4398
  return lastNewline < 0 ? start : start + lastNewline + 1;
4383
4399
  };
4384
- var readTail = (transcriptPath, maxTailBytes) => withRegularFile(transcriptPath, async (handle, size) => {
4400
+ var readTail = (transcriptPath, maxTailBytes, agentId) => withRegularFile(transcriptPath, async (handle, size) => {
4385
4401
  const length = Math.min(size, maxTailBytes);
4386
4402
  const start = size - length;
4387
4403
  const bytes = await readBytes(handle, start, length);
@@ -4391,7 +4407,7 @@ var readTail = (transcriptPath, maxTailBytes) => withRegularFile(transcriptPath,
4391
4407
  lines.shift();
4392
4408
  }
4393
4409
  for (let index = lines.length - 1; index >= 0; index -= 1) {
4394
- const record = assistantRecordOf((lines[index] ?? "").trim());
4410
+ const record = assistantRecordOf((lines[index] ?? "").trim(), agentId);
4395
4411
  if (record !== void 0) {
4396
4412
  return {
4397
4413
  turn: {
@@ -4405,10 +4421,11 @@ var readTail = (transcriptPath, maxTailBytes) => withRegularFile(transcriptPath,
4405
4421
  }
4406
4422
  return { turn: { status: "unavailable", reason: "no-assistant-message" }, endOffset };
4407
4423
  });
4408
- var boundedTail = async (transcriptPath, options) => withTimeout(
4424
+ var boundedTail = async (transcriptPath, options, agentId) => withTimeout(
4409
4425
  readTail(
4410
4426
  transcriptPath,
4411
- clamp(options.maxTailBytes, DEFAULT_CLAUDE_TRANSCRIPT_TAIL_BYTES, MIN_TAIL_BYTES, MAX_TAIL_BYTES)
4427
+ clamp(options.maxTailBytes, DEFAULT_CLAUDE_TRANSCRIPT_TAIL_BYTES, MIN_TAIL_BYTES, MAX_TAIL_BYTES),
4428
+ agentId
4412
4429
  ),
4413
4430
  clamp(options.timeoutMillis, DEFAULT_CLAUDE_TRANSCRIPT_TIMEOUT_MILLIS, MIN_TIMEOUT_MILLIS, MAX_TIMEOUT_MILLIS),
4414
4431
  { status: "unavailable", reason: "unreadable" }
@@ -4438,7 +4455,7 @@ var readClaudeTranscriptRange = async (transcriptPath, fromOffset, options = {})
4438
4455
  let anonymous = 0;
4439
4456
  let model;
4440
4457
  for (const line of complete.split("\n")) {
4441
- const record = assistantRecordOf(line.trim());
4458
+ const record = assistantRecordOf(line.trim(), options.agentId);
4442
4459
  if (record === void 0) {
4443
4460
  continue;
4444
4461
  }
@@ -4472,6 +4489,20 @@ var eventNameOf = (record) => record.hook_event_name ?? record.hookEventName;
4472
4489
  var transcriptPathOf = (record) => record.transcript_path ?? record.transcriptPath;
4473
4490
  var CLAUDE_TRANSCRIPT_USAGE_ENRICHER_ID = "claude-transcript-usage";
4474
4491
  var sourceDigest = (transcriptPath) => createHash4("sha256").update(transcriptPath, "utf8").digest("hex").slice(0, 32);
4492
+ var SUBAGENT_STOP = "SubagentStop";
4493
+ var agentIdOf = (record) => {
4494
+ const agentId = record.agent_id ?? record.agentId;
4495
+ return typeof agentId === "string" && agentId.length > 0 && agentId.length <= 256 ? agentId : void 0;
4496
+ };
4497
+ var agentTranscriptPathOf = (record) => record.agent_transcript_path ?? record.agentTranscriptPath;
4498
+ var subagentCursorScope = (payload) => {
4499
+ const record = asRecord2(payload);
4500
+ if (record === void 0 || eventNameOf(record) !== SUBAGENT_STOP) {
4501
+ return void 0;
4502
+ }
4503
+ const agentId = agentIdOf(record);
4504
+ return agentId === void 0 ? void 0 : `agent-${createHash4("sha256").update(agentId, "utf8").digest("hex").slice(0, 32)}`;
4505
+ };
4475
4506
  var createClaudeTranscriptUsageEnricher = (options = {}) => {
4476
4507
  const fileSize = async (transcriptPath) => {
4477
4508
  try {
@@ -4481,6 +4512,46 @@ var createClaudeTranscriptUsageEnricher = (options = {}) => {
4481
4512
  return thrown?.code === "ENOENT" ? "absent" : void 0;
4482
4513
  }
4483
4514
  };
4515
+ const readOptions = (agentId) => ({
4516
+ ...options.maxRangeBytes === void 0 ? {} : { maxRangeBytes: options.maxRangeBytes },
4517
+ ...options.rangeTimeoutMillis === void 0 ? {} : { rangeTimeoutMillis: options.rangeTimeoutMillis },
4518
+ ...agentId === void 0 ? {} : { agentId }
4519
+ });
4520
+ const attachSince = async (record, transcriptPath, fromOffset, agentId) => {
4521
+ const source = sourceDigest(transcriptPath);
4522
+ const attach = (model, usage, partial) => ({
4523
+ ...record,
4524
+ ...record.model === void 0 && model !== void 0 ? { model } : {},
4525
+ ...usage === void 0 ? {} : { usage, usage_partial: partial }
4526
+ });
4527
+ if (fromOffset !== void 0) {
4528
+ const range = await readClaudeTranscriptRange(transcriptPath, fromOffset, readOptions(agentId));
4529
+ if (range.status === "found") {
4530
+ return {
4531
+ payload: attach(range.model, range.usage, false),
4532
+ cursor: { source, offset: range.endOffset },
4533
+ notes: [`summed ${String(range.requestCount)} request(s) since the last stop`]
4534
+ };
4535
+ }
4536
+ if (range.reason !== "truncated" && range.reason !== "over-cap") {
4537
+ return { payload: record, notes: [`transcript range not read (${range.reason}); cursor kept`] };
4538
+ }
4539
+ }
4540
+ const tail = await boundedTail(transcriptPath, options, agentId);
4541
+ if (tail === TIMED_OUT || !("turn" in tail)) {
4542
+ return { payload: record, notes: [`transcript tail not read (${tail === TIMED_OUT ? "timeout" : tail.reason})`] };
4543
+ }
4544
+ const why = fromOffset === void 0 ? "no cursor for this transcript" : "range not summable within bounds";
4545
+ return {
4546
+ payload: tail.turn.status === "found" ? attach(tail.turn.model, tail.turn.usage, true) : record,
4547
+ cursor: { source, offset: tail.endOffset },
4548
+ notes: [`${why}; attached the last request only (usage_partial)`]
4549
+ };
4550
+ };
4551
+ const skipAttached = async (payload, transcriptPath) => {
4552
+ const size = await fileSize(transcriptPath);
4553
+ return typeof size === "number" ? { payload, cursor: { source: sourceDigest(transcriptPath), offset: size } } : { payload };
4554
+ };
4484
4555
  const enrich = async (input) => {
4485
4556
  const unchanged = { payload: input.payload };
4486
4557
  const record = asRecord2(input.payload);
@@ -4488,6 +4559,18 @@ var createClaudeTranscriptUsageEnricher = (options = {}) => {
4488
4559
  return unchanged;
4489
4560
  }
4490
4561
  const eventName = eventNameOf(record);
4562
+ if (eventName === SUBAGENT_STOP) {
4563
+ const agentTranscriptPath = agentTranscriptPathOf(record);
4564
+ const agentId = agentIdOf(record);
4565
+ if (agentId === void 0 || !isTranscriptPath(agentTranscriptPath)) {
4566
+ return unchanged;
4567
+ }
4568
+ if (hasUsage(record)) {
4569
+ return skipAttached(input.payload, agentTranscriptPath);
4570
+ }
4571
+ const cursor2 = input.cursor?.source === sourceDigest(agentTranscriptPath) ? input.cursor : void 0;
4572
+ return attachSince(record, agentTranscriptPath, cursor2?.offset ?? 0, agentId);
4573
+ }
4491
4574
  const transcriptPath = transcriptPathOf(record);
4492
4575
  if (typeof eventName !== "string" || !isTranscriptPath(transcriptPath)) {
4493
4576
  return unchanged;
@@ -4508,41 +4591,14 @@ var createClaudeTranscriptUsageEnricher = (options = {}) => {
4508
4591
  return unchanged;
4509
4592
  }
4510
4593
  if (hasUsage(record)) {
4511
- const size = await fileSize(transcriptPath);
4512
- return typeof size === "number" ? { payload: input.payload, cursor: { source, offset: size } } : unchanged;
4513
- }
4514
- const attach = (model, usage, partial) => ({
4515
- ...record,
4516
- ...record.model === void 0 && model !== void 0 ? { model } : {},
4517
- ...usage === void 0 ? {} : { usage, usage_partial: partial }
4518
- });
4519
- if (cursor !== void 0) {
4520
- const range = await readClaudeTranscriptRange(transcriptPath, cursor.offset, options);
4521
- if (range.status === "found") {
4522
- return {
4523
- payload: attach(range.model, range.usage, false),
4524
- cursor: { source, offset: range.endOffset },
4525
- notes: [`summed ${String(range.requestCount)} request(s) since the last stop`]
4526
- };
4527
- }
4528
- if (range.reason !== "truncated" && range.reason !== "over-cap") {
4529
- return { ...unchanged, notes: [`transcript range not read (${range.reason}); cursor kept`] };
4530
- }
4594
+ return skipAttached(input.payload, transcriptPath);
4531
4595
  }
4532
- const tail = await boundedTail(transcriptPath, options);
4533
- if (tail === TIMED_OUT || !("turn" in tail)) {
4534
- return { ...unchanged, notes: [`transcript tail not read (${tail === TIMED_OUT ? "timeout" : tail.reason})`] };
4535
- }
4536
- const why = cursor === void 0 ? "no cursor for this transcript" : "range not summable within bounds";
4537
- return {
4538
- payload: tail.turn.status === "found" ? attach(tail.turn.model, tail.turn.usage, true) : input.payload,
4539
- cursor: { source, offset: tail.endOffset },
4540
- notes: [`${why}; attached the last request only (usage_partial)`]
4541
- };
4596
+ return attachSince(record, transcriptPath, cursor?.offset, void 0);
4542
4597
  };
4543
4598
  return Object.freeze({
4544
4599
  id: CLAUDE_TRANSCRIPT_USAGE_ENRICHER_ID,
4545
4600
  providerId: CLAUDE_CODE_PROVIDER_ID,
4601
+ cursorScope: subagentCursorScope,
4546
4602
  enrich
4547
4603
  });
4548
4604
  };
@@ -5231,7 +5287,7 @@ var usageScopeOf = (event2) => {
5231
5287
  };
5232
5288
  var sequenceKey = (sessionId) => `sequence:${sessionId}`;
5233
5289
  var sessionModelKey = (sessionId) => `model:${sessionId}`;
5234
- var readCursorKey = (enricherId, sessionId) => `cursor:${enricherId}:${sessionId}`;
5290
+ var readCursorKey = (enricherId, sessionId, scope) => scope === void 0 ? `cursor:${enricherId}:${sessionId}` : `cursor:${enricherId}:${sessionId}:${scope}`;
5235
5291
  var UNKNOWN_MODEL_ID = "unknown";
5236
5292
  var latestSessionModel = (events) => {
5237
5293
  let latest;
@@ -5299,7 +5355,17 @@ var createOtelHook = (deps) => {
5299
5355
  if (enricher.providerId !== providerId) {
5300
5356
  continue;
5301
5357
  }
5302
- const key = readCursorKey(enricher.id, sessionId);
5358
+ let scope;
5359
+ try {
5360
+ scope = enricher.cursorScope?.(current);
5361
+ } catch (thrown) {
5362
+ logger.warn("payload enricher failed; parsing the payload as delivered", {
5363
+ "enricher.id": enricher.id,
5364
+ "error.name": thrown instanceof Error ? thrown.name : typeof thrown
5365
+ });
5366
+ continue;
5367
+ }
5368
+ const key = readCursorKey(enricher.id, sessionId, scope);
5303
5369
  let cursor;
5304
5370
  try {
5305
5371
  const record = await deps.stateStore.read(key);