observability-toolkit-hooks 0.0.0-stage → 1.0.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 (305) hide show
  1. package/CONFIG.md +144 -0
  2. package/README.md +201 -2
  3. package/dist/handlers/compact.js +38 -0
  4. package/dist/handlers/mcp-status.js +66 -0
  5. package/dist/handlers/notification.js +45 -0
  6. package/dist/handlers/post-tool-agent.js +157 -0
  7. package/dist/handlers/post-tool-changelog-sync.js +148 -0
  8. package/dist/handlers/post-tool-code-structure.js +116 -0
  9. package/dist/handlers/post-tool-edit-ledger.js +15 -0
  10. package/dist/handlers/post-tool-failure.js +83 -0
  11. package/dist/handlers/post-tool-git.js +79 -0
  12. package/dist/handlers/post-tool-mcp.js +105 -0
  13. package/dist/handlers/post-tool-outcome.js +48 -0
  14. package/dist/handlers/post-tool-task-state.js +74 -0
  15. package/dist/handlers/post-tool.js +132 -0
  16. package/dist/handlers/pre-tool-agent.js +192 -0
  17. package/dist/handlers/pre-tool.js +218 -0
  18. package/dist/handlers/session-end.js +39 -0
  19. package/dist/handlers/session-start.js +262 -0
  20. package/dist/handlers/stop-error-reminder.js +195 -0
  21. package/dist/handlers/stop-quality-evaluation.js +58 -0
  22. package/dist/handlers/stop-session-summary.js +62 -0
  23. package/dist/handlers/stop-token-metrics.js +83 -0
  24. package/dist/handlers/stop.js +25 -0
  25. package/dist/handlers/subagent.js +105 -0
  26. package/dist/handlers/tool-event-router.js +39 -0
  27. package/dist/handlers/user-prompt.js +218 -0
  28. package/dist/hook-runner.js +10 -0
  29. package/dist/hook-runner.js.map +7 -0
  30. package/dist/lib/agent/agent-context.js +123 -0
  31. package/dist/lib/agent/agent-evaluations.js +155 -0
  32. package/dist/lib/agent/agent-file-budget.js +65 -0
  33. package/dist/lib/agent/agent-sources.js +165 -0
  34. package/dist/lib/agent/synth-spans.js +51 -0
  35. package/dist/lib/core/bounded-label.js +6 -0
  36. package/dist/lib/core/category-rules.js +11 -0
  37. package/dist/lib/core/child-result.js +19 -0
  38. package/dist/lib/core/config-dir-recovery.js +22 -0
  39. package/dist/lib/core/constants.js +171 -0
  40. package/dist/lib/core/detached-runner.js +55 -0
  41. package/dist/lib/core/file-utils.js +353 -0
  42. package/dist/lib/core/format-utils.js +51 -0
  43. package/dist/lib/core/http-utils.js +74 -0
  44. package/dist/lib/core/http1-fetch.js +14 -0
  45. package/dist/lib/core/identity-key-resolver.js +149 -0
  46. package/dist/lib/core/jsonl-tail.js +207 -0
  47. package/dist/lib/core/load-envrc.js +72 -0
  48. package/dist/lib/core/parsers.js +43 -0
  49. package/dist/lib/core/regex.js +27 -0
  50. package/dist/lib/core/settings-env.js +31 -0
  51. package/dist/lib/core/shell-command.js +122 -0
  52. package/dist/lib/core/units.js +97 -0
  53. package/dist/lib/git/git-cache.js +158 -0
  54. package/dist/lib/git/git-commit.js +189 -0
  55. package/dist/lib/git/git-exec.js +30 -0
  56. package/dist/lib/mcp/mcp-completeness.js +40 -0
  57. package/dist/lib/mcp/mcp-config.js +118 -0
  58. package/dist/lib/mcp/mcp-failure-latch.js +22 -0
  59. package/dist/lib/mcp/mcp-identity-launcher.js +43 -0
  60. package/dist/lib/otel/attributes.js +322 -0
  61. package/dist/lib/otel/evaluation-attrs.js +51 -0
  62. package/dist/lib/otel/file-exporters.js +169 -0
  63. package/dist/lib/otel/host-resource.js +61 -0
  64. package/dist/lib/otel/otel-headers-helper.js +26 -0
  65. package/dist/lib/otel/otel-monitor.js +181 -0
  66. package/dist/lib/otel/otel.js +235 -0
  67. package/dist/lib/otel/otlp-headers.js +101 -0
  68. package/dist/lib/otel/otlp-post.js +122 -0
  69. package/dist/lib/otel/otlp-serialize.js +142 -0
  70. package/dist/lib/otel/otlp-signal.js +2 -0
  71. package/dist/lib/otel/remote-spans.js +142 -0
  72. package/dist/lib/otel/service-identity.js +10 -0
  73. package/dist/lib/otel/telemetry-alerts.js +43 -0
  74. package/dist/lib/otel/token-metrics.js +122 -0
  75. package/dist/lib/otel/trace-context.js +81 -0
  76. package/dist/lib/quality/judge-meta-eval.js +70 -0
  77. package/dist/lib/quality/judge-prompts.js +104 -0
  78. package/dist/lib/quality/judge-providers.js +193 -0
  79. package/dist/lib/quality/judge-transport.js +93 -0
  80. package/dist/lib/quality/llm-judge.js +170 -0
  81. package/dist/lib/quality/quality-budget.js +99 -0
  82. package/dist/lib/quality/quality-degradation.js +156 -0
  83. package/dist/lib/quality/quality-eval-handoff.js +74 -0
  84. package/dist/lib/quality/quality-evaluator.js +178 -0
  85. package/dist/lib/quality/quality-sampler.js +43 -0
  86. package/dist/lib/quality/quality-signals.js +150 -0
  87. package/dist/lib/runtime/categorizers.js +101 -0
  88. package/dist/lib/runtime/hook-input.js +16 -0
  89. package/dist/lib/runtime/hook-output.js +50 -0
  90. package/dist/lib/runtime/output-analyzer.js +160 -0
  91. package/dist/lib/runtime/run-handlers.js +32 -0
  92. package/dist/lib/runtime/tool-input.js +111 -0
  93. package/dist/lib/runtime/tool-output.js +44 -0
  94. package/dist/lib/runtime/unknown-tool.js +32 -0
  95. package/dist/lib/session/edit-ledger.js +29 -0
  96. package/dist/lib/session/forked-skill.js +39 -0
  97. package/dist/lib/session/handoffs.js +77 -0
  98. package/dist/lib/session/session-state.js +169 -0
  99. package/dist/lib/session/skill-rules.js +196 -0
  100. package/dist/lib/session/task-tracker.js +83 -0
  101. package/dist/lib/shipper/shipper-credentials.js +38 -0
  102. package/dist/lib/shipper/shipper-cursor.js +89 -0
  103. package/dist/lib/shipper/shipper-status.js +174 -0
  104. package/dist/lib/shipper/span-shipper.js +272 -0
  105. package/dist/lib/shipper/telemetry-shipper.js +39 -0
  106. package/dist/lib/transcript/agent-transcript-metrics.js +34 -0
  107. package/dist/lib/transcript/context-breakdown.js +134 -0
  108. package/dist/lib/transcript/context-history.js +69 -0
  109. package/dist/lib/transcript/context-tracker.js +226 -0
  110. package/dist/lib/transcript/message-count.js +49 -0
  111. package/dist/lib/transcript/model-ids.js +36 -0
  112. package/dist/lib/transcript/model-pricing.js +153 -0
  113. package/dist/lib/transcript/token-metrics-checkpoint.js +152 -0
  114. package/dist/lib/transcript/tool-call-durations.js +64 -0
  115. package/dist/lib/transcript/transcript-entry.js +67 -0
  116. package/dist/lib/transcript/transcript-fold.js +130 -0
  117. package/dist/lib/transcript/transcript-layout.js +39 -0
  118. package/dist/lib/transcript/transcript-parser.js +117 -0
  119. package/dist/runner/agent-context-4XTCLMLZ.js +23 -0
  120. package/dist/runner/agent-context-4XTCLMLZ.js.map +7 -0
  121. package/dist/runner/agent-file-budget-Q33ESBBE.js +68 -0
  122. package/dist/runner/agent-file-budget-Q33ESBBE.js.map +7 -0
  123. package/dist/runner/agent-transcript-metrics-W5CZZFMI.js +39 -0
  124. package/dist/runner/agent-transcript-metrics-W5CZZFMI.js.map +7 -0
  125. package/dist/runner/chunk-2NTNAJZE.js +49 -0
  126. package/dist/runner/chunk-2NTNAJZE.js.map +7 -0
  127. package/dist/runner/chunk-4KWBQTTG.js +78 -0
  128. package/dist/runner/chunk-4KWBQTTG.js.map +7 -0
  129. package/dist/runner/chunk-52RY6LQT.js +699 -0
  130. package/dist/runner/chunk-52RY6LQT.js.map +7 -0
  131. package/dist/runner/chunk-7OM5CYES.js +8695 -0
  132. package/dist/runner/chunk-7OM5CYES.js.map +7 -0
  133. package/dist/runner/chunk-7PEOKGYR.js +1568 -0
  134. package/dist/runner/chunk-7PEOKGYR.js.map +7 -0
  135. package/dist/runner/chunk-AGSGKELQ.js +126 -0
  136. package/dist/runner/chunk-AGSGKELQ.js.map +7 -0
  137. package/dist/runner/chunk-AVM7PJFW.js +12 -0
  138. package/dist/runner/chunk-AVM7PJFW.js.map +7 -0
  139. package/dist/runner/chunk-C3WHUMU5.js +178 -0
  140. package/dist/runner/chunk-C3WHUMU5.js.map +7 -0
  141. package/dist/runner/chunk-DGB4NSSD.js +157 -0
  142. package/dist/runner/chunk-DGB4NSSD.js.map +7 -0
  143. package/dist/runner/chunk-DNSTWC26.js +151 -0
  144. package/dist/runner/chunk-DNSTWC26.js.map +7 -0
  145. package/dist/runner/chunk-FDJJ3TYU.js +449 -0
  146. package/dist/runner/chunk-FDJJ3TYU.js.map +7 -0
  147. package/dist/runner/chunk-FGKYDQHZ.js +137 -0
  148. package/dist/runner/chunk-FGKYDQHZ.js.map +7 -0
  149. package/dist/runner/chunk-GG2I4TGI.js +582 -0
  150. package/dist/runner/chunk-GG2I4TGI.js.map +7 -0
  151. package/dist/runner/chunk-GNNKUMRF.js +60 -0
  152. package/dist/runner/chunk-GNNKUMRF.js.map +7 -0
  153. package/dist/runner/chunk-I7TD2QVR.js +118 -0
  154. package/dist/runner/chunk-I7TD2QVR.js.map +7 -0
  155. package/dist/runner/chunk-IJ4SLUBV.js +78 -0
  156. package/dist/runner/chunk-IJ4SLUBV.js.map +7 -0
  157. package/dist/runner/chunk-IY7AP7NA.js +32 -0
  158. package/dist/runner/chunk-IY7AP7NA.js.map +7 -0
  159. package/dist/runner/chunk-J3F3Z3EQ.js +177 -0
  160. package/dist/runner/chunk-J3F3Z3EQ.js.map +7 -0
  161. package/dist/runner/chunk-JLEO5OHU.js +104 -0
  162. package/dist/runner/chunk-JLEO5OHU.js.map +7 -0
  163. package/dist/runner/chunk-JRNNLOPR.js +168 -0
  164. package/dist/runner/chunk-JRNNLOPR.js.map +7 -0
  165. package/dist/runner/chunk-KGSA5JYP.js +82 -0
  166. package/dist/runner/chunk-KGSA5JYP.js.map +7 -0
  167. package/dist/runner/chunk-LBCZAYFR.js +125 -0
  168. package/dist/runner/chunk-LBCZAYFR.js.map +7 -0
  169. package/dist/runner/chunk-LHWRXY2G.js +41 -0
  170. package/dist/runner/chunk-LHWRXY2G.js.map +7 -0
  171. package/dist/runner/chunk-LQ2LGUYJ.js +41 -0
  172. package/dist/runner/chunk-LQ2LGUYJ.js.map +7 -0
  173. package/dist/runner/chunk-LYY6RCIE.js +158 -0
  174. package/dist/runner/chunk-LYY6RCIE.js.map +7 -0
  175. package/dist/runner/chunk-M4R4QIQH.js +41 -0
  176. package/dist/runner/chunk-M4R4QIQH.js.map +7 -0
  177. package/dist/runner/chunk-MC75VXMX.js +207 -0
  178. package/dist/runner/chunk-MC75VXMX.js.map +7 -0
  179. package/dist/runner/chunk-NKZU4RRG.js +104 -0
  180. package/dist/runner/chunk-NKZU4RRG.js.map +7 -0
  181. package/dist/runner/chunk-PJHWHJ3K.js +56 -0
  182. package/dist/runner/chunk-PJHWHJ3K.js.map +7 -0
  183. package/dist/runner/chunk-RIGVYJ2O.js +114 -0
  184. package/dist/runner/chunk-RIGVYJ2O.js.map +7 -0
  185. package/dist/runner/chunk-RWRGC7ZK.js +93 -0
  186. package/dist/runner/chunk-RWRGC7ZK.js.map +7 -0
  187. package/dist/runner/chunk-SRMAJQMV.js +54 -0
  188. package/dist/runner/chunk-SRMAJQMV.js.map +7 -0
  189. package/dist/runner/chunk-TRMFD36J.js +47 -0
  190. package/dist/runner/chunk-TRMFD36J.js.map +7 -0
  191. package/dist/runner/chunk-U4IOZYQ3.js +21 -0
  192. package/dist/runner/chunk-U4IOZYQ3.js.map +7 -0
  193. package/dist/runner/chunk-UEXDE3WP.js +83 -0
  194. package/dist/runner/chunk-UEXDE3WP.js.map +7 -0
  195. package/dist/runner/chunk-UW3GQZSM.js +50 -0
  196. package/dist/runner/chunk-UW3GQZSM.js.map +7 -0
  197. package/dist/runner/chunk-V2GSP6VR.js +46 -0
  198. package/dist/runner/chunk-V2GSP6VR.js.map +7 -0
  199. package/dist/runner/chunk-VOV4Y5VU.js +81 -0
  200. package/dist/runner/chunk-VOV4Y5VU.js.map +7 -0
  201. package/dist/runner/chunk-VT5T6OEI.js +65 -0
  202. package/dist/runner/chunk-VT5T6OEI.js.map +7 -0
  203. package/dist/runner/chunk-VUYVFWIN.js +12 -0
  204. package/dist/runner/chunk-VUYVFWIN.js.map +7 -0
  205. package/dist/runner/chunk-VVGOPPEN.js +36 -0
  206. package/dist/runner/chunk-VVGOPPEN.js.map +7 -0
  207. package/dist/runner/chunk-VXFSLM6P.js +14 -0
  208. package/dist/runner/chunk-VXFSLM6P.js.map +7 -0
  209. package/dist/runner/chunk-W3EK7JUT.js +26125 -0
  210. package/dist/runner/chunk-W3EK7JUT.js.map +7 -0
  211. package/dist/runner/chunk-WJHNCOUF.js +52 -0
  212. package/dist/runner/chunk-WJHNCOUF.js.map +7 -0
  213. package/dist/runner/chunk-WU7ANGCW.js +269 -0
  214. package/dist/runner/chunk-WU7ANGCW.js.map +7 -0
  215. package/dist/runner/chunk-X7XLMSZX.js +44 -0
  216. package/dist/runner/chunk-X7XLMSZX.js.map +7 -0
  217. package/dist/runner/chunk-XSO3B4QN.js +124 -0
  218. package/dist/runner/chunk-XSO3B4QN.js.map +7 -0
  219. package/dist/runner/chunk-YGFN3LN2.js +174 -0
  220. package/dist/runner/chunk-YGFN3LN2.js.map +7 -0
  221. package/dist/runner/chunk-YHYDBLVB.js +33 -0
  222. package/dist/runner/chunk-YHYDBLVB.js.map +7 -0
  223. package/dist/runner/compact-36NP3PKT.js +60 -0
  224. package/dist/runner/compact-36NP3PKT.js.map +7 -0
  225. package/dist/runner/getMachineId-bsd-AGENNHN6.js +42 -0
  226. package/dist/runner/getMachineId-bsd-AGENNHN6.js.map +7 -0
  227. package/dist/runner/getMachineId-bsd-I5WZGCL4.js +33 -0
  228. package/dist/runner/getMachineId-bsd-I5WZGCL4.js.map +7 -0
  229. package/dist/runner/getMachineId-bsd-ZXK225P7.js +33 -0
  230. package/dist/runner/getMachineId-bsd-ZXK225P7.js.map +7 -0
  231. package/dist/runner/getMachineId-darwin-47GDLEXL.js +42 -0
  232. package/dist/runner/getMachineId-darwin-47GDLEXL.js.map +7 -0
  233. package/dist/runner/getMachineId-darwin-5CRLMDD6.js +33 -0
  234. package/dist/runner/getMachineId-darwin-5CRLMDD6.js.map +7 -0
  235. package/dist/runner/getMachineId-darwin-ADG4I32N.js +33 -0
  236. package/dist/runner/getMachineId-darwin-ADG4I32N.js.map +7 -0
  237. package/dist/runner/getMachineId-linux-5KVS3T2M.js +27 -0
  238. package/dist/runner/getMachineId-linux-5KVS3T2M.js.map +7 -0
  239. package/dist/runner/getMachineId-linux-GDFB5GSO.js +34 -0
  240. package/dist/runner/getMachineId-linux-GDFB5GSO.js.map +7 -0
  241. package/dist/runner/getMachineId-linux-NQMWCRO3.js +27 -0
  242. package/dist/runner/getMachineId-linux-NQMWCRO3.js.map +7 -0
  243. package/dist/runner/getMachineId-unsupported-5PFIGMVX.js +18 -0
  244. package/dist/runner/getMachineId-unsupported-5PFIGMVX.js.map +7 -0
  245. package/dist/runner/getMachineId-unsupported-DW27K3ZX.js +18 -0
  246. package/dist/runner/getMachineId-unsupported-DW27K3ZX.js.map +7 -0
  247. package/dist/runner/getMachineId-unsupported-XV3FHTHD.js +25 -0
  248. package/dist/runner/getMachineId-unsupported-XV3FHTHD.js.map +7 -0
  249. package/dist/runner/getMachineId-win-5JVMW3EI.js +44 -0
  250. package/dist/runner/getMachineId-win-5JVMW3EI.js.map +7 -0
  251. package/dist/runner/getMachineId-win-SNESQF7R.js +35 -0
  252. package/dist/runner/getMachineId-win-SNESQF7R.js.map +7 -0
  253. package/dist/runner/getMachineId-win-UJYHSBM2.js +35 -0
  254. package/dist/runner/getMachineId-win-UJYHSBM2.js.map +7 -0
  255. package/dist/runner/git-commit-BA53DOJQ.js +30 -0
  256. package/dist/runner/git-commit-BA53DOJQ.js.map +7 -0
  257. package/dist/runner/hook-runner-JHH6PGKE.js +220 -0
  258. package/dist/runner/hook-runner-JHH6PGKE.js.map +7 -0
  259. package/dist/runner/judge-transport-R4TF5LEH.js +91 -0
  260. package/dist/runner/judge-transport-R4TF5LEH.js.map +7 -0
  261. package/dist/runner/mcp-status-QEUH2KGX.js +89 -0
  262. package/dist/runner/mcp-status-QEUH2KGX.js.map +7 -0
  263. package/dist/runner/notification-FKMBCSXF.js +69 -0
  264. package/dist/runner/notification-FKMBCSXF.js.map +7 -0
  265. package/dist/runner/post-tool-3MRHTBKH.js +192 -0
  266. package/dist/runner/post-tool-3MRHTBKH.js.map +7 -0
  267. package/dist/runner/post-tool-agent-BB34MNHI.js +370 -0
  268. package/dist/runner/post-tool-agent-BB34MNHI.js.map +7 -0
  269. package/dist/runner/post-tool-changelog-sync-OP2TT2I7.js +147 -0
  270. package/dist/runner/post-tool-changelog-sync-OP2TT2I7.js.map +7 -0
  271. package/dist/runner/post-tool-code-structure-LE7J2SC2.js +130 -0
  272. package/dist/runner/post-tool-code-structure-LE7J2SC2.js.map +7 -0
  273. package/dist/runner/post-tool-edit-ledger-IJMEYHKF.js +30 -0
  274. package/dist/runner/post-tool-edit-ledger-IJMEYHKF.js.map +7 -0
  275. package/dist/runner/post-tool-failure-XTH2I2Z7.js +111 -0
  276. package/dist/runner/post-tool-failure-XTH2I2Z7.js.map +7 -0
  277. package/dist/runner/post-tool-git-E46HZGZO.js +94 -0
  278. package/dist/runner/post-tool-git-E46HZGZO.js.map +7 -0
  279. package/dist/runner/post-tool-mcp-AMCDY5GH.js +144 -0
  280. package/dist/runner/post-tool-mcp-AMCDY5GH.js.map +7 -0
  281. package/dist/runner/post-tool-task-state-TLDOI33H.js +100 -0
  282. package/dist/runner/post-tool-task-state-TLDOI33H.js.map +7 -0
  283. package/dist/runner/pre-tool-SQE2FZQO.js +245 -0
  284. package/dist/runner/pre-tool-SQE2FZQO.js.map +7 -0
  285. package/dist/runner/pre-tool-agent-OZUPVFUI.js +218 -0
  286. package/dist/runner/pre-tool-agent-OZUPVFUI.js.map +7 -0
  287. package/dist/runner/quality-evaluator-XYNDKDRG.js +901 -0
  288. package/dist/runner/quality-evaluator-XYNDKDRG.js.map +7 -0
  289. package/dist/runner/session-end-3MJTDLLA.js +57 -0
  290. package/dist/runner/session-end-3MJTDLLA.js.map +7 -0
  291. package/dist/runner/session-start-5ZMCLKBS.js +352 -0
  292. package/dist/runner/session-start-5ZMCLKBS.js.map +7 -0
  293. package/dist/runner/shipper-status-MADX6SPG.js +37 -0
  294. package/dist/runner/shipper-status-MADX6SPG.js.map +7 -0
  295. package/dist/runner/span-shipper-4HQDHC47.js +3408 -0
  296. package/dist/runner/span-shipper-4HQDHC47.js.map +7 -0
  297. package/dist/runner/stop-RTKSIYJV.js +596 -0
  298. package/dist/runner/stop-RTKSIYJV.js.map +7 -0
  299. package/dist/runner/subagent-CBCG4OLZ.js +116 -0
  300. package/dist/runner/subagent-CBCG4OLZ.js.map +7 -0
  301. package/dist/runner/token-metrics-AD2RAFGM.js +31 -0
  302. package/dist/runner/token-metrics-AD2RAFGM.js.map +7 -0
  303. package/dist/runner/user-prompt-T5NZ2UJD.js +376 -0
  304. package/dist/runner/user-prompt-T5NZ2UJD.js.map +7 -0
  305. package/package.json +68 -5
@@ -0,0 +1,207 @@
1
+ /**
2
+ * Incremental JSONL tail-reader: read [start, EOF) bounded by maxBytes and consume
3
+ * only complete lines. Callers detect truncation via `fileSize < start` and choose
4
+ * their own reset policy.
5
+ */
6
+ import { closeSync, openSync, readSync, statSync } from 'node:fs';
7
+ const NEWLINE = 0x0a;
8
+ /** At most `maxBytes` raw bytes from `position`, without loading the whole file. */
9
+ export function readFileBytes(filePath, maxBytes, position = 0) {
10
+ const fd = openSync(filePath, 'r');
11
+ try {
12
+ const buffer = Buffer.allocUnsafe(maxBytes);
13
+ const bytesRead = readSync(fd, buffer, 0, maxBytes, position);
14
+ return buffer.subarray(0, bytesRead);
15
+ }
16
+ finally {
17
+ closeSync(fd);
18
+ }
19
+ }
20
+ /** `readFileBytes` decoded as UTF-8. */
21
+ export function readFileSlice(filePath, maxBytes, position = 0) {
22
+ return readFileBytes(filePath, maxBytes, position).toString('utf-8');
23
+ }
24
+ /** Offset just past the first newline at or after `from`, scanned `chunkBytes` at a time; undefined when the file ends first. */
25
+ export function nextLineStart(filePath, from, chunkBytes) {
26
+ for (let position = from;;) {
27
+ const chunk = readFileBytes(filePath, chunkBytes, position);
28
+ if (chunk.length === 0)
29
+ return undefined;
30
+ const newline = chunk.indexOf(NEWLINE);
31
+ if (newline !== -1)
32
+ return position + newline + 1;
33
+ position += chunk.length;
34
+ }
35
+ }
36
+ /** Every newline-terminated line of `buf[0, completeEnd)`, empty ones included; offsets are absolute, given `buf` starts at `base`. */
37
+ function* splitCompleteLines(buf, base, completeEnd) {
38
+ for (let lineStart = 0; lineStart < completeEnd;) {
39
+ const newline = buf.indexOf(NEWLINE, lineStart);
40
+ yield { bytes: buf.subarray(lineStart, newline), startOffset: base + lineStart, endOffset: base + newline + 1 };
41
+ lineStart = newline + 1;
42
+ }
43
+ }
44
+ /** One line parsed as JSON; undefined when it is not. */
45
+ export function parseJsonLine(line) {
46
+ try {
47
+ return JSON.parse(line);
48
+ }
49
+ catch {
50
+ return undefined;
51
+ }
52
+ }
53
+ /** Each line parsed as JSON, skipping empty and unparseable lines, and lines `accept` rejects before parsing. */
54
+ export function* parseJsonLines(content, accept) {
55
+ for (const line of content.split('\n')) {
56
+ if (!line || (accept && !accept(line)))
57
+ continue;
58
+ const parsed = parseJsonLine(line);
59
+ if (parsed !== undefined)
60
+ yield parsed;
61
+ }
62
+ }
63
+ /**
64
+ * Complete lines from `start`, verbatim with end offsets; `consumedEnd` advances past empty
65
+ * lines so cursors never stall. A trailing fragment `acceptFragment` approves counts as a line.
66
+ */
67
+ export function readCompleteLines(filePath, start, maxBytes = Number.POSITIVE_INFINITY, acceptFragment) {
68
+ const fileSize = statSync(filePath).size;
69
+ const length = Math.min(fileSize - start, maxBytes);
70
+ if (length <= 0)
71
+ return { lines: [], consumedEnd: start, fileSize };
72
+ const buf = readFileBytes(filePath, length, start);
73
+ const bytesRead = buf.length;
74
+ // A negative offset would make lastIndexOf search from the buffer's end, past the bytes read.
75
+ if (bytesRead === 0)
76
+ return { lines: [], consumedEnd: start, fileSize };
77
+ const completeEnd = buf.lastIndexOf(NEWLINE, bytesRead - 1) + 1; // 0 when no newline found
78
+ // Offsets from byte positions, not re-encoded text: invalid UTF-8 decodes to a 3-byte U+FFFD.
79
+ const lines = [];
80
+ for (const { bytes, startOffset, endOffset } of splitCompleteLines(buf, start, completeEnd)) {
81
+ if (bytes.length > 0)
82
+ lines.push({ text: bytes.toString('utf-8'), startOffset, endOffset });
83
+ }
84
+ // The fragment past the last newline is offered only when the read reached EOF, not when maxBytes cut it.
85
+ if (completeEnd < bytesRead && start + bytesRead === fileSize) {
86
+ const text = buf.toString('utf-8', completeEnd, bytesRead);
87
+ if (acceptFragment?.(text)) {
88
+ lines.push({ text, startOffset: start + completeEnd, endOffset: start + bytesRead });
89
+ return { lines, consumedEnd: start + bytesRead, fileSize };
90
+ }
91
+ }
92
+ return { lines, consumedEnd: start + completeEnd, fileSize };
93
+ }
94
+ /** Markers for filtering raw lines before decoding; an ASCII marker matches a UTF-8 line exactly. */
95
+ export function byteMarkers(markers) {
96
+ return [...markers].map((marker) => Buffer.from(marker, 'utf-8'));
97
+ }
98
+ export function hasAnyMarker(bytes, markers) {
99
+ return markers.some((marker) => bytes.includes(marker));
100
+ }
101
+ /**
102
+ * Yields every line from `start` as raw bytes (newline excluded), read `chunkBytes` at a time.
103
+ * A line longer than `chunkBytes` is read into one buffer (the longest line in 90 days of
104
+ * transcripts was 1.3 MB against a 4 MiB chunk, so this path is rare). Empty lines are yielded too, so the last
105
+ * `endOffset` is always the cursor's advance point. The trailing fragment past the last newline
106
+ * is yielded, with `endOffset` at EOF, only when `acceptFragment` approves it.
107
+ */
108
+ export function* readLinesFrom(filePath, start, chunkBytes, acceptFragment) {
109
+ const fileSize = statSync(filePath).size;
110
+ let pos = start;
111
+ while (pos < fileSize) {
112
+ const buf = readFileBytes(filePath, Math.min(fileSize - pos, chunkBytes), pos);
113
+ if (buf.length === 0)
114
+ return;
115
+ const completeEnd = buf.lastIndexOf(NEWLINE, buf.length - 1) + 1;
116
+ if (completeEnd === 0) {
117
+ const lineEnd = nextLineStart(filePath, pos, chunkBytes);
118
+ if (lineEnd === undefined) {
119
+ if (!acceptFragment)
120
+ return;
121
+ const fragment = readFileBytes(filePath, fileSize - pos, pos);
122
+ if (acceptFragment(fragment))
123
+ yield { bytes: fragment, startOffset: pos, endOffset: pos + fragment.length };
124
+ return;
125
+ }
126
+ yield { bytes: readFileBytes(filePath, lineEnd - pos - 1, pos), startOffset: pos, endOffset: lineEnd };
127
+ pos = lineEnd;
128
+ continue;
129
+ }
130
+ yield* splitCompleteLines(buf, pos, completeEnd);
131
+ pos += completeEnd;
132
+ }
133
+ }
134
+ /** Runs `onLine` over `lines` read from `start` (`readLinesFrom`); returns the offset consumed through, never mid-line, and `start` when there were none. */
135
+ export function consumeLines(lines, start, onLine) {
136
+ let consumedEnd = start;
137
+ for (const { bytes, endOffset } of lines) {
138
+ onLine(bytes);
139
+ consumedEnd = endOffset;
140
+ }
141
+ return consumedEnd;
142
+ }
143
+ /** Non-empty lines of `content`, last first. */
144
+ export function* linesNewestFirst(content) {
145
+ const lines = content.split('\n');
146
+ for (let i = lines.length - 1; i >= 0; i--) {
147
+ const line = lines[i];
148
+ if (line)
149
+ yield line;
150
+ }
151
+ }
152
+ /**
153
+ * Lines from `fileSize` backward in a single `windowBytes` read, yielded
154
+ * newest-first; a leading partial line is excluded unless at file start.
155
+ */
156
+ export function* readLinesBackward(filePath, fileSize, windowBytes) {
157
+ const readStart = Math.max(0, fileSize - windowBytes);
158
+ const slice = readFileSlice(filePath, fileSize - readStart, readStart);
159
+ let content;
160
+ if (readStart > 0) {
161
+ const first = slice.indexOf('\n');
162
+ if (first === -1)
163
+ return; // whole window is one partial line; nothing complete to yield
164
+ content = slice.slice(first + 1);
165
+ }
166
+ else {
167
+ content = slice;
168
+ }
169
+ yield* linesNewestFirst(content);
170
+ }
171
+ const READ_WINDOW_GROWTH_FACTOR = 2;
172
+ /**
173
+ * The window grows until it holds a complete line, reaches EOF or reaches
174
+ * `maxLineBytes`: a line longer than `windowBytes` would otherwise yield
175
+ * nothing, report nothing and pin the cursor in front of it on every read.
176
+ */
177
+ function readGrowingWindow(filePath, start, { windowBytes, maxLineBytes, acceptFragment }) {
178
+ let maxBytes = windowBytes;
179
+ let read = readCompleteLines(filePath, start, maxBytes, acceptFragment);
180
+ while (read.consumedEnd === start && start + maxBytes < read.fileSize && maxBytes < maxLineBytes) {
181
+ maxBytes = Math.min(maxBytes * READ_WINDOW_GROWTH_FACTOR, maxLineBytes);
182
+ read = readCompleteLines(filePath, start, maxBytes, acceptFragment);
183
+ }
184
+ return read;
185
+ }
186
+ /**
187
+ * `readCompleteLines` for lines of unknown length: a line over `maxLineBytes`
188
+ * is counted and the read resumes behind it. An unterminated oversized line may
189
+ * still be growing, so it holds `consumedEnd` in front of it unless `eofTerminates`.
190
+ */
191
+ export function readBoundedLines(filePath, start, limits) {
192
+ const { windowBytes, maxLineBytes, eofTerminates } = limits;
193
+ const resolved = { ...limits, acceptFragment: limits.acceptFragment ?? (eofTerminates ? () => true : undefined) };
194
+ let from = start;
195
+ let read = readGrowingWindow(filePath, from, resolved);
196
+ let skippedOversized = 0;
197
+ // A full-size window that held no newline, with more file behind it.
198
+ while (read.consumedEnd === from && from + maxLineBytes < read.fileSize) {
199
+ const lineEnd = nextLineStart(filePath, from + maxLineBytes, windowBytes);
200
+ if (lineEnd === undefined && !eofTerminates)
201
+ return { lines: [], consumedEnd: from, skippedOversized };
202
+ skippedOversized++;
203
+ from = lineEnd ?? read.fileSize;
204
+ read = readGrowingWindow(filePath, from, resolved);
205
+ }
206
+ return { lines: read.lines, consumedEnd: read.consumedEnd, skippedOversized };
207
+ }
@@ -0,0 +1,72 @@
1
+ /** Side-effect import: loads a bash-style .envrc into process.env with `$VAR` expansion. */
2
+ import * as fs from 'node:fs';
3
+ import * as path from 'node:path';
4
+ import { SHELL_IDENTIFIER_SOURCE } from './regex.js';
5
+ // NOT constants.CLAUDE_HOME: otel.ts imports this before constants.js so
6
+ // TELEMETRY_DIR is set before constants.TELEMETRY_DIR is computed.
7
+ const ENVRC_PATH = path.join(process.env.HOME ?? '', '.claude', '.envrc');
8
+ const EXPORT_LINE_PATTERN = new RegExp(`^export\\s+(${SHELL_IDENTIFIER_SOURCE})=(.*)$`);
9
+ const BRACED_VARIABLE_PATTERN = new RegExp(`\\$\\{(${SHELL_IDENTIFIER_SOURCE})\\}`, 'g');
10
+ const BARE_VARIABLE_PATTERN = new RegExp(`\\$(${SHELL_IDENTIFIER_SOURCE})`, 'g');
11
+ let loaded = false;
12
+ /** Load .envrc once per process. */
13
+ export function loadEnvrc(envrcPath = ENVRC_PATH) {
14
+ if (loaded)
15
+ return;
16
+ if (!fs.existsSync(envrcPath)) {
17
+ console.warn(`[load-envrc] File not found: ${envrcPath}`);
18
+ return;
19
+ }
20
+ const content = fs.readFileSync(envrcPath, 'utf-8');
21
+ const lines = content.split('\n');
22
+ for (const line of lines) {
23
+ const trimmed = line.trim();
24
+ if (!trimmed || trimmed.startsWith('#'))
25
+ continue;
26
+ const match = trimmed.match(EXPORT_LINE_PATTERN);
27
+ if (!match)
28
+ continue;
29
+ const [, key, rawValue] = match;
30
+ if (key === undefined || rawValue === undefined || process.env[key] !== undefined)
31
+ continue;
32
+ const { value, singleQuoted } = parseValue(rawValue);
33
+ const expanded = singleQuoted ? value : expandVariables(value);
34
+ process.env[key] = expanded;
35
+ }
36
+ loaded = true;
37
+ }
38
+ /**
39
+ * In an unquoted value, `#` opens a comment only when whitespace precedes it,
40
+ * following shell word-splitting: `export C=#4B0082` and `export U=host/#frag`
41
+ * keep their `#`, while `export U=host # note` drops the note.
42
+ */
43
+ const INLINE_COMMENT_PATTERN = /\s#/;
44
+ function parseValue(raw) {
45
+ const trimmed = raw.trim();
46
+ // Match the closing quote, not the line end, so a trailing comment cannot embed the quotes.
47
+ const quote = trimmed[0];
48
+ if (quote === '"' || quote === "'") {
49
+ const closing = trimmed.indexOf(quote, 1);
50
+ if (closing !== -1) {
51
+ return { value: trimmed.slice(1, closing), singleQuoted: quote === "'" };
52
+ }
53
+ }
54
+ const commentIndex = trimmed.search(INLINE_COMMENT_PATTERN);
55
+ return {
56
+ value: commentIndex === -1 ? trimmed : trimmed.slice(0, commentIndex).trim(),
57
+ singleQuoted: false,
58
+ };
59
+ }
60
+ function expandVariables(value) {
61
+ let result = value.replace(BRACED_VARIABLE_PATTERN, (_, varName) => {
62
+ return process.env[varName] ?? '';
63
+ });
64
+ result = result.replace(BARE_VARIABLE_PATTERN, (_, varName) => {
65
+ return process.env[varName] ?? '';
66
+ });
67
+ return result;
68
+ }
69
+ // Auto-load on import if not in test mode
70
+ if (process.env.NODE_ENV !== 'test') {
71
+ loadEnvrc();
72
+ }
@@ -0,0 +1,43 @@
1
+ /** Tool name and input parsers. */
2
+ import { MCP_ATTRS, PLUGIN_ATTRS } from '../otel/attributes.js';
3
+ import { MCP_TOOL_PREFIX } from './constants.js';
4
+ const MCP_NAME_SEPARATOR = '__';
5
+ const MAX_SUMMARY_KEYS = 3;
6
+ /** Log and metric label for a skill invoked without a namespace. */
7
+ export const DEFAULT_PLUGIN_NAMESPACE = 'default';
8
+ export function parseSkillName(skillName) {
9
+ const parts = skillName.split(':');
10
+ if (parts.length === 2) {
11
+ const [namespace = '', name = ''] = parts;
12
+ return { namespace, name, fullName: skillName };
13
+ }
14
+ return { name: skillName, fullName: skillName };
15
+ }
16
+ export function parseMcpToolName(toolName) {
17
+ if (!toolName.startsWith(MCP_TOOL_PREFIX))
18
+ return null;
19
+ const rest = toolName.slice(MCP_TOOL_PREFIX.length);
20
+ const idx = rest.indexOf(MCP_NAME_SEPARATOR);
21
+ if (idx <= 0)
22
+ return null;
23
+ const tool = rest.slice(idx + MCP_NAME_SEPARATOR.length);
24
+ if (tool.length === 0)
25
+ return null;
26
+ return { server: rest.slice(0, idx), tool, fullName: toolName };
27
+ }
28
+ /** Server and tool labels, built once so the pre- and post-tool series join. */
29
+ export function mcpLabelsOf(info) {
30
+ return { [MCP_ATTRS.SERVER]: info.server, [MCP_ATTRS.TOOL]: info.tool };
31
+ }
32
+ /** Name and defaulted namespace labels, built once so plugin invocations and completions join. */
33
+ export function pluginLabelsOf(info) {
34
+ return { [PLUGIN_ATTRS.NAME]: info.name, [PLUGIN_ATTRS.NAMESPACE]: info.namespace || DEFAULT_PLUGIN_NAMESPACE };
35
+ }
36
+ export function getInputSummary(input) {
37
+ const keys = Object.keys(input);
38
+ if (keys.length === 0)
39
+ return 'no params';
40
+ if (keys.length <= MAX_SUMMARY_KEYS)
41
+ return keys.join(', ');
42
+ return `${keys.slice(0, MAX_SUMMARY_KEYS).join(', ')} +${keys.length - MAX_SUMMARY_KEYS} more`;
43
+ }
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Regex building blocks shared across lib. A `*_SOURCE` is a string for interpolation
3
+ * into `new RegExp`; a `*_PATTERN` is the one compiled spelling of that grammar.
4
+ * None carry `g`, so sharing them leaks no `lastIndex`.
5
+ */
6
+ /** Quotes regex metacharacters so `text` matches itself inside `new RegExp`. */
7
+ export function escapeRegExp(text) {
8
+ return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
9
+ }
10
+ /** `(?:a|b|c)` with every value escaped: a list of literals as one non-capturing alternative. */
11
+ export function alternation(values) {
12
+ return `(?:${values.map(escapeRegExp).join('|')})`;
13
+ }
14
+ export const TS_EXTENSIONS = ['ts', 'tsx', 'mts', 'cts'];
15
+ export const JS_EXTENSIONS = ['js', 'jsx', 'mjs', 'cjs'];
16
+ /** `\.(ts|tsx)$`: a path ending in one of the extensions, given without their dots. */
17
+ export function fileExtensionPattern(extensions, flags = '') {
18
+ return new RegExp(`\\.${alternation(extensions)}$`, flags);
19
+ }
20
+ /** A POSIX shell variable name, as in `export NAME=`, `$NAME` and a `NAME=value` command prefix. */
21
+ export const SHELL_IDENTIFIER_SOURCE = '[A-Za-z_][A-Za-z0-9_]*';
22
+ const UUID_SOURCE = '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}';
23
+ /** Full-string; also guards against path traversal. */
24
+ export const SESSION_ID_PATTERN = new RegExp(`^${UUID_SOURCE}$`, 'i');
25
+ export const TRANSCRIPT_SESSION_ID_PATTERN = new RegExp(`(${UUID_SOURCE})\\.jsonl$`, 'i');
26
+ /** The directory immediately above the session JSONL. */
27
+ export const TRANSCRIPT_PROJECT_SLUG_PATTERN = new RegExp(`/([^/]+)/${UUID_SOURCE}\\.jsonl$`, 'i');
@@ -0,0 +1,31 @@
1
+ /**
2
+ * `settings.json` `env` as a fallback for the `OTEL_*` vars Claude Code strips from hooks.
3
+ * The real environment always wins: settings.json is drifting local state.
4
+ */
5
+ import { join } from 'node:path';
6
+ import { claudeConfigDir } from './config-dir-recovery.js';
7
+ import { isJsonObject, loadJsonObject, stringValues } from './file-utils.js';
8
+ /** Read by the exporter config, header parser, key resolver and MCP launcher. */
9
+ export const OTLP_ENV = {
10
+ ENDPOINT: 'OTEL_EXPORTER_OTLP_ENDPOINT',
11
+ HEADERS: 'OTEL_EXPORTER_OTLP_HEADERS',
12
+ API_KEY: 'OBTOOL_API_KEY',
13
+ };
14
+ let cache = null;
15
+ /** String values of `settings.json`'s `env`; `{}` when missing or malformed, never throws. */
16
+ function loadSettingsEnv() {
17
+ const env = loadJsonObject(join(claudeConfigDir(), 'settings.json'))?.env;
18
+ return isJsonObject(env) ? stringValues(env) : {};
19
+ }
20
+ function settingsEnv(name) {
21
+ cache ??= loadSettingsEnv();
22
+ return cache[name];
23
+ }
24
+ /** Spawn guard and shipper MUST both resolve through here, or the guard makes the child's resolution unreachable. */
25
+ export function resolveOtlpEndpoint(env = process.env) {
26
+ return env[OTLP_ENV.ENDPOINT] ?? settingsEnv(OTLP_ENV.ENDPOINT);
27
+ }
28
+ /** Tests only. */
29
+ export function resetSettingsEnvCache() {
30
+ cache = null;
31
+ }
@@ -0,0 +1,122 @@
1
+ /**
2
+ * Just enough shell splitting for "is X the command here" heuristics.
3
+ * Not a shell parser: `$(...)` inside double quotes is plain text, heredoc bodies
4
+ * split like any line, redirections stay in argv. A wrong answer must cost an
5
+ * extra check, never gate something that must not be missed.
6
+ */
7
+ import { basename } from 'node:path';
8
+ import { SHELL_IDENTIFIER_SOURCE } from './regex.js';
9
+ const SINGLE_QUOTE = "'";
10
+ const DOUBLE_QUOTE = '"';
11
+ const BACKSLASH = '\\';
12
+ const COMMAND_SUBSTITUTION_OPEN = '$(';
13
+ const OPTION_PREFIX = '-';
14
+ /** Characters that end one simple command outside quotes. `&&`, `||` are two of these. */
15
+ const SEPARATOR_CHARS = new Set([';', '&', '|', '\n', '(', ')', '`']);
16
+ const WORD_BREAK_CHARS = new Set([' ', '\t', '\r']);
17
+ /** `FOO=bar git commit` — an assignment prefix, not the program. */
18
+ const ASSIGNMENT_PATTERN = new RegExp(`^${SHELL_IDENTIFIER_SOURCE}=`);
19
+ /** Words that run the rest of the line as the command, when used without options. */
20
+ const PREFIX_WORDS = new Set(['env', 'command', 'exec', 'time', 'nohup', 'sudo', 'builtin', '{', '!']);
21
+ /** Shells that resolve to what they run: a `-c` script's commands, else the script file. */
22
+ const SCRIPT_SHELLS = new Set(['bash', 'sh', 'zsh']);
23
+ /** `-c`, and combined short flags that include it (`-lc`, `-ec`). */
24
+ const SCRIPT_FLAG_PATTERN = /^-[a-z]*c[a-z]*$/;
25
+ /** Inside double quotes a backslash escapes the next character; a trailing one is kept as-is. Single quotes escape nothing. */
26
+ function readQuoted(command, openIndex, quote) {
27
+ let text = '';
28
+ let i = openIndex + 1;
29
+ while (i < command.length && command[i] !== quote) {
30
+ if (quote === DOUBLE_QUOTE && command[i] === BACKSLASH && i + 1 < command.length)
31
+ i++;
32
+ text += command[i];
33
+ i++;
34
+ }
35
+ return { text, end: i };
36
+ }
37
+ /** Unquoted words of each simple command, in order; empty commands are dropped. */
38
+ function splitSimpleCommands(command) {
39
+ const commands = [];
40
+ let words = [];
41
+ let word = '';
42
+ let inWord = false;
43
+ const appendToWord = (text) => {
44
+ word += text;
45
+ inWord = true;
46
+ };
47
+ const endWord = () => {
48
+ if (inWord)
49
+ words.push(word);
50
+ word = '';
51
+ inWord = false;
52
+ };
53
+ const endCommand = () => {
54
+ endWord();
55
+ if (words.length > 0)
56
+ commands.push(words);
57
+ words = [];
58
+ };
59
+ for (let i = 0; i < command.length; i++) {
60
+ const char = command.charAt(i);
61
+ if (char === SINGLE_QUOTE || char === DOUBLE_QUOTE) {
62
+ const span = readQuoted(command, i, char);
63
+ appendToWord(span.text);
64
+ i = span.end;
65
+ }
66
+ else if (char === BACKSLASH && i + 1 < command.length) {
67
+ appendToWord(command.charAt(i + 1));
68
+ i++;
69
+ }
70
+ else if (command.startsWith(COMMAND_SUBSTITUTION_OPEN, i)) {
71
+ endCommand();
72
+ i++;
73
+ }
74
+ else if (SEPARATOR_CHARS.has(char)) {
75
+ endCommand();
76
+ }
77
+ else if (WORD_BREAK_CHARS.has(char)) {
78
+ endWord();
79
+ }
80
+ else {
81
+ appendToWord(char);
82
+ }
83
+ }
84
+ endCommand();
85
+ return commands;
86
+ }
87
+ /** Drops assignment prefixes and wrapper words, leaving the program first. */
88
+ function stripPrefixes(words) {
89
+ const start = words.findIndex((word) => !ASSIGNMENT_PATTERN.test(word) && !PREFIX_WORDS.has(word));
90
+ return start === -1 ? [] : words.slice(start);
91
+ }
92
+ /** The program an argv runs, without its directory (`/usr/bin/git` → `git`). */
93
+ export const programOf = (argv) => basename(argv[0] ?? '');
94
+ /** `-x` or `--flag`: an option rather than an operand. */
95
+ export const isOptionArg = (arg) => arg.startsWith(OPTION_PREFIX);
96
+ /**
97
+ * The argv of every simple command, program first. A shell resolves to what it runs:
98
+ * `bash -c <script>` contributes the script's commands, `bash [options] run.sh args`
99
+ * contributes `run.sh args`. A nested `-c` script is always shorter than the command
100
+ * holding it, so the recursion needs no depth guard.
101
+ */
102
+ export function commandInvocations(command) {
103
+ const invocations = [];
104
+ for (const words of splitSimpleCommands(command)) {
105
+ const argv = stripPrefixes(words);
106
+ if (argv.length === 0)
107
+ continue;
108
+ if (!SCRIPT_SHELLS.has(programOf(argv))) {
109
+ invocations.push(argv);
110
+ continue;
111
+ }
112
+ const scriptFlag = argv.findIndex((arg) => SCRIPT_FLAG_PATTERN.test(arg));
113
+ const script = scriptFlag === -1 ? undefined : argv[scriptFlag + 1];
114
+ if (script !== undefined) {
115
+ invocations.push(...commandInvocations(script));
116
+ continue;
117
+ }
118
+ const scriptFile = argv.findIndex((arg, i) => i > 0 && !isOptionArg(arg));
119
+ invocations.push(scriptFile === -1 ? argv : argv.slice(scriptFile));
120
+ }
121
+ return invocations;
122
+ }
@@ -0,0 +1,97 @@
1
+ /**
2
+ * Unit multipliers, named durations, and OTel instrument unit strings.
3
+ * Use a `DURATION_MS` entry when one matches exactly; otherwise compose from `TIME_MS`.
4
+ */
5
+ export const TIME_MS = {
6
+ MS: 1,
7
+ SECOND: 1_000,
8
+ MINUTE: 60_000,
9
+ DAY: 86_400_000,
10
+ WEEK: 604_800_000,
11
+ };
12
+ export const DURATION_MS = {
13
+ THREE_SECONDS: 3_000,
14
+ FIVE_SECONDS: 5_000,
15
+ TEN_SECONDS: 10_000,
16
+ FIFTEEN_SECONDS: 15_000,
17
+ THIRTY_SECONDS: 30_000,
18
+ FIVE_MINUTES: 300_000,
19
+ TEN_MINUTES: 600_000,
20
+ THIRTY_MINUTES: 1_800_000,
21
+ THREE_DAYS: 259_200_000,
22
+ THIRTY_DAYS: 2_592_000_000,
23
+ };
24
+ // OTel HrTime is [seconds, nanoseconds].
25
+ export const NANOSECONDS_PER_SECOND = 1_000_000_000;
26
+ export const NANOSECONDS_PER_MILLISECOND = 1_000_000;
27
+ // Semconv: "Instruments for utilization metrics ... SHOULD use the default unit 1", so percentages divide by this.
28
+ export const PERCENT_PER_UNIT = 100;
29
+ /** Scale for rounding to one decimal place: `roundTo(x, TENTHS_PER_UNIT)`. */
30
+ export const TENTHS_PER_UNIT = 10;
31
+ /** Round to the decimal place `scale` names (10 → tenths, 100 → hundredths). */
32
+ export function roundTo(value, scale) {
33
+ return Math.round(value * scale) / scale;
34
+ }
35
+ /** A 0–1 ratio as a whole-number percentage for banner text, `42%`. */
36
+ export function formatPercent(ratio) {
37
+ return `${(ratio * PERCENT_PER_UNIT).toFixed(0)}%`;
38
+ }
39
+ export const KB = 1 << 10; // 1024 bytes per KB
40
+ /** Binary (1024-based) byte multipliers. */
41
+ export const BYTES = {
42
+ KB,
43
+ MB: KB * KB, // 1,048,576
44
+ };
45
+ /** A count of anything, as persisted state must hold it: a non-negative safe integer. */
46
+ export const isNonNegativeInteger = (value) => typeof value === 'number' && Number.isSafeInteger(value) && value >= 0;
47
+ /** A file size or read length. */
48
+ export const isByteCount = (value) => isNonNegativeInteger(value);
49
+ /** Characters per token: rough estimate used for context-window math. */
50
+ export const CHARS_PER_TOKEN = 4;
51
+ /** One chars-per-token ratio for every estimate (PT7). Never for `gen_ai.usage.*`. */
52
+ export function estimateTokenCount(chars) {
53
+ return Math.ceil(chars / CHARS_PER_TOKEN);
54
+ }
55
+ /**
56
+ * Metric descriptor `unit` per the semconv units rule: UCUM for real dimensions,
57
+ * `1` for dimensionless ratios, a singular `{thing}` annotation for counts.
58
+ * https://opentelemetry.io/docs/specs/semconv/general/metrics/#instrument-units
59
+ *
60
+ * - Arbitrary 0–1 scores (judge, tool correctness, structure score) correctly have
61
+ * no unit; `RATIO` is only for genuine fractions.
62
+ * - A metric's unit must match at every call site: instruments are cached by name
63
+ * with first-creation options (`metric-units.test.ts` enforces this).
64
+ */
65
+ export const UNITS = {
66
+ MILLISECOND: 'ms',
67
+ /** Seconds, for the `otel.sdk.exporter.*` instruments whose semconv fixes the unit. */
68
+ SECOND: 's',
69
+ BYTE: 'By',
70
+ USD: 'USD',
71
+ /** Dimensionless fraction — utilization, hit rate, completed/total. */
72
+ RATIO: '1',
73
+ ALERT: '{alert}',
74
+ CHECK: '{check}',
75
+ COMMIT: '{commit}',
76
+ COMPLETION: '{completion}',
77
+ ERROR: '{error}',
78
+ FAILURE: '{failure}',
79
+ FILE: '{file}',
80
+ /** One LLM API response. Unit fixed by `gen_ai.invoke_agent.inference_calls`. */
81
+ INFERENCE_CALL: '{inference_call}',
82
+ INVOCATION: '{invocation}',
83
+ MATCH: '{match}',
84
+ NOTIFICATION: '{notification}',
85
+ REJECTION: '{rejection}',
86
+ RETRY: '{retry}',
87
+ RESULT: '{result}',
88
+ RUN: '{run}',
89
+ SESSION: '{session}',
90
+ SKIP: '{skip}',
91
+ SYNC: '{sync}',
92
+ TASK: '{task}',
93
+ TOKEN: '{token}',
94
+ /** One tool invocation. Unit fixed by `gen_ai.invoke_agent.tool_calls`. */
95
+ TOOL_CALL: '{tool_call}',
96
+ WARNING: '{warning}',
97
+ };