@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
package/README.md CHANGED
@@ -639,10 +639,12 @@ resource), no content, and no per-event ids.
639
639
  retried, records nothing. A callback replayed after a crash restates its series'
640
640
  totals instead of adding to them.
641
641
 
642
- These numbers are **hook-derived**. They can differ from a provider's own
643
- telemetry: for example, Claude Code's native `claude_code.token.usage` counts
644
- subagent spend that hooks do not see yet (#68). A harness that already books Claude
645
- Code usage from native telemetry should not add both.
642
+ These numbers are **hook-derived**. For Claude Code, tokens exist only with
643
+ `providers.claudeCode.readTranscriptUsage` on: each turn's main-thread requests are
644
+ counted on its `Stop` generation, and each subagent's requests on a generation of
645
+ its own at `SubagentStop` (#68), named for the subagent's model and carrying
646
+ `otelhook.subagent.id`. A harness that already books Claude Code usage from native
647
+ telemetry should not add both.
646
648
 
647
649
  | Field | Default | Flag | Variable |
648
650
  | --- | --- | --- | --- |
@@ -5,7 +5,7 @@ import { I as IdentityClaim, d as InvocationIdentity } from './identity-BrVBs901
5
5
  import { R as ResolvedProviderId, g as ProviderId, h as SourceTransport, d as EventId } from './primitives-CJ8-rn-f.js';
6
6
  import { e as PrivacyLimits } from './policy-CimmCfRp.js';
7
7
  import { P as PrivacyService } from './service-CbI9CObT.js';
8
- import { C as Clock, I as IdGenerator, d as Logger } from './ports-C3k_5eOQ.js';
8
+ import { C as Clock, I as IdGenerator, d as Logger } from './ports-DhpSDIkp.js';
9
9
  import { A as AttributionOutcome, a as AttributionReason } from './taxonomy-DwhTtuWd.js';
10
10
 
11
11
  /** Raw input offered to adapters. `payload` is `unknown` on purpose. */
package/dist/cli.js CHANGED
@@ -4267,7 +4267,16 @@ var subagentStopPayloadSchema = z19.object({
4267
4267
  last_assistant_message: z19.string().optional(),
4268
4268
  /** True when this stop fired because a hook continued the subagent's turn. */
4269
4269
  stop_hook_active: z19.boolean().optional(),
4270
- usage: claudeUsageSchema.optional()
4270
+ /**
4271
+ * The subagent run's tokens since its previous stop — harness- or
4272
+ * enricher-supplied, never upstream. Reported on the subagent's own
4273
+ * generation, never on the parent turn (issue #68).
4274
+ */
4275
+ usage: claudeUsageSchema.optional(),
4276
+ /** Harness-supplied, never upstream: the subagent's model, from its transcript. */
4277
+ model: z19.string().min(1).max(256).optional().catch(void 0),
4278
+ /** Harness-supplied, never upstream: see `stopPayloadSchema.usage_partial`. */
4279
+ usage_partial: z19.boolean().optional().catch(void 0)
4271
4280
  });
4272
4281
  var preCompactPayloadSchema = z19.object({
4273
4282
  ...commonFields2,
@@ -4865,6 +4874,8 @@ var BUILT_IN_TOOL_KIND = Object.freeze({
4865
4874
  WebFetch: "network",
4866
4875
  WebSearch: "network",
4867
4876
  Task: "delegate",
4877
+ // Current Claude Code releases (observed on 2.1.332) name the subagent tool `Agent`.
4878
+ Agent: "delegate",
4868
4879
  TodoWrite: "other",
4869
4880
  ExitPlanMode: "other",
4870
4881
  AskUserQuestion: "other",
@@ -5038,14 +5049,39 @@ var parseClaudeCode = (input, context) => {
5038
5049
  delegationDepth: 1
5039
5050
  });
5040
5051
  break;
5041
- case "SubagentStop":
5052
+ case "SubagentStop": {
5053
+ const usage = withPartialUsage(extractedUsage ?? payload.usage, payload.usage_partial);
5054
+ if (usage.usage !== void 0 || payload.model !== void 0) {
5055
+ const generationId = context.ids.newOpaqueId([
5056
+ "claude-subagent-generation",
5057
+ payload.session_id,
5058
+ payload.agent_id,
5059
+ ...payload.stop_hook_active === true ? [String(input.sequenceBase)] : []
5060
+ ]);
5061
+ const models = generationModels(payload.model, void 0);
5062
+ factory.build({ type: "generation.start", generationId, model: models.request });
5063
+ factory.build({
5064
+ type: "generation.end",
5065
+ generationId,
5066
+ model: models.response,
5067
+ outcome: "ok",
5068
+ outputContent: [
5069
+ payload.last_assistant_message === void 0 ? context.privacy.describeUnavailableContent({ kind: "response", role: "assistant" }) : context.privacy.describeContent({
5070
+ kind: "response",
5071
+ role: "assistant",
5072
+ text: payload.last_assistant_message
5073
+ })
5074
+ ],
5075
+ ...usage
5076
+ });
5077
+ }
5042
5078
  factory.build({
5043
5079
  type: "subagent.end",
5044
5080
  subagentInvocationId: subagentInvocationIdFor(context, payload.session_id, payload.agent_id),
5045
- outcome: "ok",
5046
- ...withUsage(payload.usage)
5081
+ outcome: "ok"
5047
5082
  });
5048
5083
  break;
5084
+ }
5049
5085
  case "PreCompact":
5050
5086
  return {
5051
5087
  status: "ignored",
@@ -8702,7 +8738,7 @@ import {
8702
8738
  } from "@opentelemetry/semantic-conventions/incubating";
8703
8739
 
8704
8740
  // src/version.ts
8705
- var VERSION = "0.12.0";
8741
+ var VERSION = "0.13.0";
8706
8742
 
8707
8743
  // src/telemetry/semconv.ts
8708
8744
  var SCOPE_NAME = "@osfactory/otel-hook";
@@ -10222,6 +10258,9 @@ var deriveMetricObservations = (input) => {
10222
10258
  if (recovered !== void 0) {
10223
10259
  return end.occurredAt - recovered.startMillis;
10224
10260
  }
10261
+ if (end.subagentId !== void 0) {
10262
+ return void 0;
10263
+ }
10225
10264
  const turn = lastPromptInBatch?.get(end.sessionId) ?? input.turnStart?.(end.sessionId);
10226
10265
  return turn === void 0 || turn > end.occurredAt ? void 0 : end.occurredAt - turn;
10227
10266
  };
@@ -13747,7 +13786,8 @@ var clamp = (value, fallback, min, max) => {
13747
13786
  };
13748
13787
  var asRecord7 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
13749
13788
  var isTranscriptPath = (transcriptPath) => typeof transcriptPath === "string" && transcriptPath.length > 0 && !transcriptPath.includes("\0") && path10.isAbsolute(transcriptPath) && path10.extname(transcriptPath) === ".jsonl";
13750
- var assistantRecordOf = (line) => {
13789
+ var isRecordOfAgent = (record, agentId) => record.isSidechain === true && (typeof record.agentId !== "string" || record.agentId === agentId);
13790
+ var assistantRecordOf = (line, agentId) => {
13751
13791
  if (!line.includes('"assistant"')) {
13752
13792
  return void 0;
13753
13793
  }
@@ -13758,7 +13798,10 @@ var assistantRecordOf = (line) => {
13758
13798
  return void 0;
13759
13799
  }
13760
13800
  const record = asRecord7(parsed);
13761
- if (record === void 0 || record.type !== "assistant" || record.isSidechain === true) {
13801
+ if (record === void 0 || record.type !== "assistant") {
13802
+ return void 0;
13803
+ }
13804
+ if (agentId === void 0 ? record.isSidechain === true : !isRecordOfAgent(record, agentId)) {
13762
13805
  return void 0;
13763
13806
  }
13764
13807
  const message = asRecord7(record.message);
@@ -13851,7 +13894,7 @@ var completeLinesEnd = (bytes, start) => {
13851
13894
  const lastNewline = bytes.lastIndexOf(10);
13852
13895
  return lastNewline < 0 ? start : start + lastNewline + 1;
13853
13896
  };
13854
- var readTail = (transcriptPath, maxTailBytes) => withRegularFile(transcriptPath, async (handle, size) => {
13897
+ var readTail = (transcriptPath, maxTailBytes, agentId) => withRegularFile(transcriptPath, async (handle, size) => {
13855
13898
  const length = Math.min(size, maxTailBytes);
13856
13899
  const start = size - length;
13857
13900
  const bytes = await readBytes(handle, start, length);
@@ -13861,7 +13904,7 @@ var readTail = (transcriptPath, maxTailBytes) => withRegularFile(transcriptPath,
13861
13904
  lines.shift();
13862
13905
  }
13863
13906
  for (let index = lines.length - 1; index >= 0; index -= 1) {
13864
- const record = assistantRecordOf((lines[index] ?? "").trim());
13907
+ const record = assistantRecordOf((lines[index] ?? "").trim(), agentId);
13865
13908
  if (record !== void 0) {
13866
13909
  return {
13867
13910
  turn: {
@@ -13875,10 +13918,11 @@ var readTail = (transcriptPath, maxTailBytes) => withRegularFile(transcriptPath,
13875
13918
  }
13876
13919
  return { turn: { status: "unavailable", reason: "no-assistant-message" }, endOffset };
13877
13920
  });
13878
- var boundedTail = async (transcriptPath, options) => withTimeout(
13921
+ var boundedTail = async (transcriptPath, options, agentId) => withTimeout(
13879
13922
  readTail(
13880
13923
  transcriptPath,
13881
- clamp(options.maxTailBytes, DEFAULT_CLAUDE_TRANSCRIPT_TAIL_BYTES, MIN_TAIL_BYTES, MAX_TAIL_BYTES)
13924
+ clamp(options.maxTailBytes, DEFAULT_CLAUDE_TRANSCRIPT_TAIL_BYTES, MIN_TAIL_BYTES, MAX_TAIL_BYTES),
13925
+ agentId
13882
13926
  ),
13883
13927
  clamp(options.timeoutMillis, DEFAULT_CLAUDE_TRANSCRIPT_TIMEOUT_MILLIS, MIN_TIMEOUT_MILLIS, MAX_TIMEOUT_MILLIS),
13884
13928
  { status: "unavailable", reason: "unreadable" }
@@ -13908,7 +13952,7 @@ var readClaudeTranscriptRange = async (transcriptPath, fromOffset, options = {})
13908
13952
  let anonymous = 0;
13909
13953
  let model;
13910
13954
  for (const line of complete.split("\n")) {
13911
- const record = assistantRecordOf(line.trim());
13955
+ const record = assistantRecordOf(line.trim(), options.agentId);
13912
13956
  if (record === void 0) {
13913
13957
  continue;
13914
13958
  }
@@ -13942,6 +13986,20 @@ var eventNameOf = (record) => record.hook_event_name ?? record.hookEventName;
13942
13986
  var transcriptPathOf = (record) => record.transcript_path ?? record.transcriptPath;
13943
13987
  var CLAUDE_TRANSCRIPT_USAGE_ENRICHER_ID = "claude-transcript-usage";
13944
13988
  var sourceDigest = (transcriptPath) => createHash5("sha256").update(transcriptPath, "utf8").digest("hex").slice(0, 32);
13989
+ var SUBAGENT_STOP = "SubagentStop";
13990
+ var agentIdOf = (record) => {
13991
+ const agentId = record.agent_id ?? record.agentId;
13992
+ return typeof agentId === "string" && agentId.length > 0 && agentId.length <= 256 ? agentId : void 0;
13993
+ };
13994
+ var agentTranscriptPathOf = (record) => record.agent_transcript_path ?? record.agentTranscriptPath;
13995
+ var subagentCursorScope = (payload) => {
13996
+ const record = asRecord7(payload);
13997
+ if (record === void 0 || eventNameOf(record) !== SUBAGENT_STOP) {
13998
+ return void 0;
13999
+ }
14000
+ const agentId = agentIdOf(record);
14001
+ return agentId === void 0 ? void 0 : `agent-${createHash5("sha256").update(agentId, "utf8").digest("hex").slice(0, 32)}`;
14002
+ };
13945
14003
  var createClaudeTranscriptUsageEnricher = (options = {}) => {
13946
14004
  const fileSize = async (transcriptPath) => {
13947
14005
  try {
@@ -13951,6 +14009,46 @@ var createClaudeTranscriptUsageEnricher = (options = {}) => {
13951
14009
  return thrown?.code === "ENOENT" ? "absent" : void 0;
13952
14010
  }
13953
14011
  };
14012
+ const readOptions = (agentId) => ({
14013
+ ...options.maxRangeBytes === void 0 ? {} : { maxRangeBytes: options.maxRangeBytes },
14014
+ ...options.rangeTimeoutMillis === void 0 ? {} : { rangeTimeoutMillis: options.rangeTimeoutMillis },
14015
+ ...agentId === void 0 ? {} : { agentId }
14016
+ });
14017
+ const attachSince = async (record, transcriptPath, fromOffset, agentId) => {
14018
+ const source = sourceDigest(transcriptPath);
14019
+ const attach = (model, usage, partial) => ({
14020
+ ...record,
14021
+ ...record.model === void 0 && model !== void 0 ? { model } : {},
14022
+ ...usage === void 0 ? {} : { usage, usage_partial: partial }
14023
+ });
14024
+ if (fromOffset !== void 0) {
14025
+ const range = await readClaudeTranscriptRange(transcriptPath, fromOffset, readOptions(agentId));
14026
+ if (range.status === "found") {
14027
+ return {
14028
+ payload: attach(range.model, range.usage, false),
14029
+ cursor: { source, offset: range.endOffset },
14030
+ notes: [`summed ${String(range.requestCount)} request(s) since the last stop`]
14031
+ };
14032
+ }
14033
+ if (range.reason !== "truncated" && range.reason !== "over-cap") {
14034
+ return { payload: record, notes: [`transcript range not read (${range.reason}); cursor kept`] };
14035
+ }
14036
+ }
14037
+ const tail = await boundedTail(transcriptPath, options, agentId);
14038
+ if (tail === TIMED_OUT || !("turn" in tail)) {
14039
+ return { payload: record, notes: [`transcript tail not read (${tail === TIMED_OUT ? "timeout" : tail.reason})`] };
14040
+ }
14041
+ const why = fromOffset === void 0 ? "no cursor for this transcript" : "range not summable within bounds";
14042
+ return {
14043
+ payload: tail.turn.status === "found" ? attach(tail.turn.model, tail.turn.usage, true) : record,
14044
+ cursor: { source, offset: tail.endOffset },
14045
+ notes: [`${why}; attached the last request only (usage_partial)`]
14046
+ };
14047
+ };
14048
+ const skipAttached = async (payload, transcriptPath) => {
14049
+ const size = await fileSize(transcriptPath);
14050
+ return typeof size === "number" ? { payload, cursor: { source: sourceDigest(transcriptPath), offset: size } } : { payload };
14051
+ };
13954
14052
  const enrich = async (input) => {
13955
14053
  const unchanged = { payload: input.payload };
13956
14054
  const record = asRecord7(input.payload);
@@ -13958,6 +14056,18 @@ var createClaudeTranscriptUsageEnricher = (options = {}) => {
13958
14056
  return unchanged;
13959
14057
  }
13960
14058
  const eventName = eventNameOf(record);
14059
+ if (eventName === SUBAGENT_STOP) {
14060
+ const agentTranscriptPath = agentTranscriptPathOf(record);
14061
+ const agentId = agentIdOf(record);
14062
+ if (agentId === void 0 || !isTranscriptPath(agentTranscriptPath)) {
14063
+ return unchanged;
14064
+ }
14065
+ if (hasUsage(record)) {
14066
+ return skipAttached(input.payload, agentTranscriptPath);
14067
+ }
14068
+ const cursor2 = input.cursor?.source === sourceDigest(agentTranscriptPath) ? input.cursor : void 0;
14069
+ return attachSince(record, agentTranscriptPath, cursor2?.offset ?? 0, agentId);
14070
+ }
13961
14071
  const transcriptPath = transcriptPathOf(record);
13962
14072
  if (typeof eventName !== "string" || !isTranscriptPath(transcriptPath)) {
13963
14073
  return unchanged;
@@ -13978,41 +14088,14 @@ var createClaudeTranscriptUsageEnricher = (options = {}) => {
13978
14088
  return unchanged;
13979
14089
  }
13980
14090
  if (hasUsage(record)) {
13981
- const size = await fileSize(transcriptPath);
13982
- return typeof size === "number" ? { payload: input.payload, cursor: { source, offset: size } } : unchanged;
13983
- }
13984
- const attach = (model, usage, partial) => ({
13985
- ...record,
13986
- ...record.model === void 0 && model !== void 0 ? { model } : {},
13987
- ...usage === void 0 ? {} : { usage, usage_partial: partial }
13988
- });
13989
- if (cursor !== void 0) {
13990
- const range = await readClaudeTranscriptRange(transcriptPath, cursor.offset, options);
13991
- if (range.status === "found") {
13992
- return {
13993
- payload: attach(range.model, range.usage, false),
13994
- cursor: { source, offset: range.endOffset },
13995
- notes: [`summed ${String(range.requestCount)} request(s) since the last stop`]
13996
- };
13997
- }
13998
- if (range.reason !== "truncated" && range.reason !== "over-cap") {
13999
- return { ...unchanged, notes: [`transcript range not read (${range.reason}); cursor kept`] };
14000
- }
14091
+ return skipAttached(input.payload, transcriptPath);
14001
14092
  }
14002
- const tail = await boundedTail(transcriptPath, options);
14003
- if (tail === TIMED_OUT || !("turn" in tail)) {
14004
- return { ...unchanged, notes: [`transcript tail not read (${tail === TIMED_OUT ? "timeout" : tail.reason})`] };
14005
- }
14006
- const why = cursor === void 0 ? "no cursor for this transcript" : "range not summable within bounds";
14007
- return {
14008
- payload: tail.turn.status === "found" ? attach(tail.turn.model, tail.turn.usage, true) : input.payload,
14009
- cursor: { source, offset: tail.endOffset },
14010
- notes: [`${why}; attached the last request only (usage_partial)`]
14011
- };
14093
+ return attachSince(record, transcriptPath, cursor?.offset, void 0);
14012
14094
  };
14013
14095
  return Object.freeze({
14014
14096
  id: CLAUDE_TRANSCRIPT_USAGE_ENRICHER_ID,
14015
14097
  providerId: CLAUDE_CODE_PROVIDER_ID,
14098
+ cursorScope: subagentCursorScope,
14016
14099
  enrich
14017
14100
  });
14018
14101
  };
@@ -14430,7 +14513,7 @@ var usageScopeOf = (event3) => {
14430
14513
  };
14431
14514
  var sequenceKey = (sessionId) => `sequence:${sessionId}`;
14432
14515
  var sessionModelKey = (sessionId) => `model:${sessionId}`;
14433
- var readCursorKey = (enricherId, sessionId) => `cursor:${enricherId}:${sessionId}`;
14516
+ var readCursorKey = (enricherId, sessionId, scope) => scope === void 0 ? `cursor:${enricherId}:${sessionId}` : `cursor:${enricherId}:${sessionId}:${scope}`;
14434
14517
  var UNKNOWN_MODEL_ID = "unknown";
14435
14518
  var latestSessionModel = (events) => {
14436
14519
  let latest;
@@ -14498,7 +14581,17 @@ var createOtelHook = (deps) => {
14498
14581
  if (enricher.providerId !== providerId) {
14499
14582
  continue;
14500
14583
  }
14501
- const key = readCursorKey(enricher.id, sessionId);
14584
+ let scope;
14585
+ try {
14586
+ scope = enricher.cursorScope?.(current);
14587
+ } catch (thrown) {
14588
+ logger.warn("payload enricher failed; parsing the payload as delivered", {
14589
+ "enricher.id": enricher.id,
14590
+ "error.name": thrown instanceof Error ? thrown.name : typeof thrown
14591
+ });
14592
+ continue;
14593
+ }
14594
+ const key = readCursorKey(enricher.id, sessionId, scope);
14502
14595
  let cursor;
14503
14596
  try {
14504
14597
  const record = await deps.stateStore.read(key);