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,181 @@
1
+ /** `instrumentHook(name, fn, attrs)`: one span, duration histogram and execution counter per handler; `attrs` names the `hook.type`. */
2
+ import { UNITS } from '../core/units.js';
3
+ import { HOOK_NAME_ATTR, HOOK_STATUS_ATTR, HOOK_TRIGGER_ATTR, HOOK_TYPE_ATTR, hookSpanName, SESSION_ATTRIBUTES, UNKNOWN_HOOK_TYPE, } from './attributes.js';
4
+ import { initTelemetry, shutdownTelemetry, getTracer, getHistogram, withSpan, startLinkedSpan as startLinkedSpanCore, getTraceId, otelApi, log, recordMetric, } from './otel.js';
5
+ import { loadSessionContext } from './trace-context.js';
6
+ let _sessionAttr = {};
7
+ /** Once at hook-runner startup (L6). */
8
+ export function setSessionId(id) {
9
+ _sessionAttr = { [SESSION_ATTRIBUTES.SESSION_ID]: id };
10
+ }
11
+ let _eventAttr = {};
12
+ /** Once per tool event, by its router: the agent identity and prompt link every handler span of the event carries. A span's own attributes win. */
13
+ export function setEventAttributes(attrs) {
14
+ _eventAttr = attrs;
15
+ }
16
+ let _sessionParent;
17
+ /** Read once per process: the id is fixed at startup and Stop opens several spans. A miss is not kept, since session-start writes the file inside its own span. */
18
+ function sessionParentContext(sessionId) {
19
+ if (_sessionParent?.sessionId !== sessionId) {
20
+ const ctx = loadSessionContext(sessionId);
21
+ if (!ctx)
22
+ return null;
23
+ _sessionParent = { sessionId, ctx };
24
+ }
25
+ return _sessionParent.ctx;
26
+ }
27
+ // HTR38: the Claude Code event that invoked this process. Stamped only on the handler span,
28
+ // where semconv puts the invocation trigger; child, linked and log records omit it
29
+ // (https://opentelemetry.io/docs/specs/semconv/faas/faas-spans/). `faas.trigger` itself is
30
+ // not reused: its enum and SERVER kind do not fit hook events, and custom values in semconv
31
+ // namespaces are discouraged (https://opentelemetry.io/docs/specs/semconv/general/naming/).
32
+ // Set at span creation, since samplers see only creation-time attributes
33
+ // (https://opentelemetry.io/docs/specs/otel/trace/api/).
34
+ let _triggerAttr = {};
35
+ /** Once at hook-runner startup; not in detached modes. */
36
+ export function setHookTrigger(eventName) {
37
+ _triggerAttr = { [HOOK_TRIGGER_ATTR]: eventName };
38
+ }
39
+ /** The event name `setHookTrigger` stamped; `UNKNOWN_HOOK_TYPE` before it ran (detached modes, unit tests). */
40
+ export function getHookTrigger() {
41
+ return _triggerAttr[HOOK_TRIGGER_ATTR] ?? UNKNOWN_HOOK_TYPE;
42
+ }
43
+ // Re-exported so tests assert on the emitter's constant (HTR35).
44
+ export { HOOK_NAME_ATTR, HOOK_TYPE_ATTR, HOOK_TRIGGER_ATTR };
45
+ function toChildSpanContext(span) {
46
+ // The SDK logs a diag error on a second end(), so cleanup paths can end unconditionally.
47
+ let ended = false;
48
+ return {
49
+ end: () => {
50
+ if (ended)
51
+ return;
52
+ ended = true;
53
+ span.end();
54
+ },
55
+ endWithError: (error) => {
56
+ if (ended)
57
+ return;
58
+ ended = true;
59
+ span.setStatus({ code: otelApi.SpanStatusCode.ERROR, message: error.message });
60
+ span.recordException(error);
61
+ span.end();
62
+ },
63
+ addAttribute: (key, value) => {
64
+ span.setAttributes({ [key]: value });
65
+ },
66
+ };
67
+ }
68
+ export class HookMonitor {
69
+ hookName;
70
+ attributes;
71
+ constructor(hookName, attributes = {}) {
72
+ this.hookName = hookName;
73
+ this.attributes = {
74
+ [HOOK_TYPE_ATTR]: UNKNOWN_HOOK_TYPE,
75
+ ..._triggerAttr,
76
+ ..._sessionAttr,
77
+ ..._eventAttr,
78
+ ...attributes,
79
+ // Last: the span name and metric attributes derive from hookName, so it is authoritative.
80
+ [HOOK_NAME_ATTR]: hookName,
81
+ };
82
+ }
83
+ async run(fn) {
84
+ initTelemetry();
85
+ const startTime = Date.now();
86
+ const durationHistogram = getHistogram('integritystudio.hook.duration', { description: 'Hook execution duration in milliseconds', unit: UNITS.MILLISECOND });
87
+ let status = 'success';
88
+ // HRF7: TRACEPARENT from Claude Code roots the span under the caller's trace, else
89
+ // trace-ctx session correlation (HOOKS_ARCHITECTURE.md § Trace & Session Model).
90
+ let parentContext;
91
+ let parentSource;
92
+ const envTraceparent = process.env.TRACEPARENT;
93
+ if (envTraceparent) {
94
+ const extracted = otelApi.propagation.extract(otelApi.ROOT_CONTEXT, { traceparent: envTraceparent });
95
+ if (otelApi.trace.getSpanContext(extracted)) {
96
+ parentContext = extracted;
97
+ parentSource = 'traceparent';
98
+ }
99
+ }
100
+ if (!parentContext) {
101
+ const sessionId = _sessionAttr[SESSION_ATTRIBUTES.SESSION_ID];
102
+ const sessionCtx = sessionId ? sessionParentContext(sessionId) : null;
103
+ if (sessionCtx) {
104
+ parentContext = otelApi.trace.setSpanContext(otelApi.ROOT_CONTEXT, {
105
+ traceId: sessionCtx.traceId,
106
+ spanId: sessionCtx.spanId,
107
+ traceFlags: otelApi.TraceFlags.SAMPLED,
108
+ isRemote: true,
109
+ });
110
+ parentSource = 'trace_ctx';
111
+ }
112
+ }
113
+ const spanAttributes = parentSource
114
+ ? { ...this.attributes, 'integritystudio.hook.parent_source': parentSource }
115
+ : this.attributes;
116
+ try {
117
+ return await withSpan(hookSpanName(this.hookName), spanAttributes, async (span) => fn(this.createContext(span)), parentContext);
118
+ }
119
+ catch (e) {
120
+ status = 'error';
121
+ throw e;
122
+ }
123
+ finally {
124
+ const durationMs = Date.now() - startTime;
125
+ const metricAttrs = {
126
+ [HOOK_NAME_ATTR]: this.hookName,
127
+ [HOOK_STATUS_ATTR]: status,
128
+ };
129
+ durationHistogram.record(durationMs, metricAttrs);
130
+ // No shutdown() here: a handler calls instrumentHook several times (Stop opens
131
+ // one per phase), and a shutdown after the first would drop every later span silently.
132
+ }
133
+ }
134
+ createContext(span) {
135
+ const hookName = this.hookName;
136
+ const createLogFn = (level) => (message, attributes) => log(level, message, {
137
+ ..._sessionAttr,
138
+ ...attributes,
139
+ // Last, as in the constructor: the record must name the hook its span does.
140
+ [HOOK_NAME_ATTR]: hookName,
141
+ });
142
+ return {
143
+ span,
144
+ addAttribute: (key, value) => {
145
+ // The monitor owns session.id: a '' or 'default' fallback would merge all id-less events.
146
+ if (key === SESSION_ATTRIBUTES.SESSION_ID)
147
+ return;
148
+ span.setAttributes({ [key]: value });
149
+ },
150
+ addAttributes: (attrs) => {
151
+ const filtered = Object.fromEntries(Object.entries(attrs).filter(([k]) => k !== SESSION_ATTRIBUTES.SESSION_ID));
152
+ span.setAttributes(filtered);
153
+ },
154
+ recordEvent: (name, attributes) => {
155
+ span.addEvent(name, attributes);
156
+ },
157
+ recordMetric,
158
+ logger: {
159
+ trace: createLogFn('TRACE'),
160
+ debug: createLogFn('DEBUG'),
161
+ info: createLogFn('INFO'),
162
+ warn: createLogFn('WARN'),
163
+ error: createLogFn('ERROR'),
164
+ },
165
+ startLinkedSpan: (name, linkedSpans, attributes) => {
166
+ return toChildSpanContext(startLinkedSpanCore(name, linkedSpans, { ..._sessionAttr, ...attributes }));
167
+ },
168
+ };
169
+ }
170
+ }
171
+ export async function instrumentHook(hookName, fn, attributes) {
172
+ const monitor = new HookMonitor(hookName, attributes);
173
+ return monitor.run(fn);
174
+ }
175
+ /** Saves this hook's span so later hooks in the session can parent or link to it. */
176
+ export function persistSpanContext(ctx, sessionId, save) {
177
+ const traceId = getTraceId();
178
+ if (traceId)
179
+ save(sessionId, traceId, ctx.span.spanContext().spanId);
180
+ }
181
+ export { shutdownTelemetry, getTracer, getTraceId };
@@ -0,0 +1,235 @@
1
+ /**
2
+ * OTel bootstrap for the spawn-per-event hook process: file-only export to
3
+ * traces/logs/metrics-*.jsonl, forwarded by the detached shipper (span-shipper.ts).
4
+ * Deliberately shares no code with the MCP server's NodeSDK bootstrap (INF-1):
5
+ * see docs/architecture/HOOKS_ARCHITECTURE.md § Bootstrap before changing.
6
+ */
7
+ import '../core/load-envrc.js';
8
+ import * as path from 'node:path';
9
+ import * as api from '@opentelemetry/api';
10
+ import { DiagConsoleLogger, DiagLogLevel } from '@opentelemetry/api';
11
+ import { SeverityNumber } from '@opentelemetry/api-logs';
12
+ import * as logsApi from '@opentelemetry/api-logs';
13
+ import { diagLogLevelFromString } from '@opentelemetry/core';
14
+ import { detectResources, resourceFromAttributes, } from '@opentelemetry/resources';
15
+ import { LoggerProvider, SimpleLogRecordProcessor } from '@opentelemetry/sdk-logs';
16
+ import { MeterProvider, PeriodicExportingMetricReader, AggregationType } from '@opentelemetry/sdk-metrics';
17
+ import { NodeTracerProvider, SimpleSpanProcessor } from '@opentelemetry/sdk-trace-node';
18
+ import { ATTR_SERVICE_NAME, ATTR_SERVICE_VERSION } from '@opentelemetry/semantic-conventions';
19
+ import { memoizeIn } from '../core/file-utils.js';
20
+ import { writeStderr } from '../core/format-utils.js';
21
+ import { DURATION_MS } from '../core/units.js';
22
+ import { getGitHubRepo, splitOwnerRepo } from '../git/git-cache.js';
23
+ import { GENAI_EXECUTE_TOOL_DURATION_METRIC, PROCESS_ATTRIBUTES, VCS_ATTRIBUTES, RESOURCE_ATTRIBUTES } from './attributes.js';
24
+ import { FileLogExporter, FileMetricExporter, FileSpanExporter } from './file-exporters.js';
25
+ import { hostResourceDetector } from './host-resource.js';
26
+ import { getServiceName, SERVICE_VERSION } from './service-identity.js';
27
+ const SHUTDOWN_SIGNALS = ['SIGTERM', 'SIGINT'];
28
+ /** `OTEL_LOG_LEVEL` sets the verbosity of the SDK's own diagnostics; the severity of records written by `log()` is `LogLevelKey`. */
29
+ const OTEL_LOG_LEVEL = process.env.OTEL_LOG_LEVEL?.toLowerCase();
30
+ if (OTEL_LOG_LEVEL) {
31
+ const diagLevel = diagLogLevelFromString(OTEL_LOG_LEVEL) ?? DiagLogLevel.INFO;
32
+ api.diag.setLogger(new DiagConsoleLogger(), diagLevel);
33
+ if (diagLevel >= DiagLogLevel.DEBUG) {
34
+ // stderr: on SessionStart/UserPromptSubmit stdout is injected into Claude's context.
35
+ writeStderr(`OpenTelemetry: Debug mode enabled (level: ${OTEL_LOG_LEVEL})`);
36
+ }
37
+ }
38
+ // File-only export: an inline OTLP flush held each hook process open 1.4–2.8 s (H12).
39
+ // Module scope, so it resolves after the load-envrc side-effect import.
40
+ const SERVICE_NAME = getServiceName();
41
+ let tracerProvider = null;
42
+ let meterProvider = null;
43
+ let loggerProvider = null;
44
+ let initialized = false;
45
+ let signalHandlersRegistered = false;
46
+ let shutdownInProgress = false;
47
+ function buildResource() {
48
+ const githubRepo = getGitHubRepo();
49
+ const repo = githubRepo ? splitOwnerRepo(githubRepo) : undefined;
50
+ // Only metrics-*.jsonl carries these (the span and log exporters project the resource
51
+ // down to service name/version). `process.pid` alone, not processDetector: its argv,
52
+ // executable path and runtime keys repeat on every metrics line and nothing reads them.
53
+ // No env detector: Claude Code strips OTEL_RESOURCE_ATTRIBUTES from hooks.
54
+ return resourceFromAttributes({
55
+ [ATTR_SERVICE_NAME]: SERVICE_NAME,
56
+ [ATTR_SERVICE_VERSION]: SERVICE_VERSION,
57
+ // The cwd's name, not the package.json name the session-start span records separately.
58
+ [RESOURCE_ATTRIBUTES.PROJECT_DIRECTORY]: path.basename(process.cwd()),
59
+ [PROCESS_ATTRIBUTES.PID]: process.pid,
60
+ ...(repo && { [VCS_ATTRIBUTES.REPOSITORY_NAME]: repo.name }),
61
+ ...(repo?.owner && { [VCS_ATTRIBUTES.OWNER_NAME]: repo.owner }),
62
+ }).merge(detectResources({ detectors: [hostResourceDetector] }));
63
+ }
64
+ function registerShutdownSignalHandlers() {
65
+ if (signalHandlersRegistered)
66
+ return;
67
+ for (const signal of SHUTDOWN_SIGNALS) {
68
+ process.on(signal, () => {
69
+ void shutdownTelemetry();
70
+ });
71
+ }
72
+ signalHandlersRegistered = true;
73
+ }
74
+ export function initTelemetry() {
75
+ if (initialized)
76
+ return;
77
+ const resource = buildResource();
78
+ // Simple processors: a hook process is too short-lived for batching. Metrics
79
+ // collect at shutdown; the reader's interval never elapses inside one process.
80
+ const spanProcessors = [new SimpleSpanProcessor(new FileSpanExporter())];
81
+ const metricReader = new PeriodicExportingMetricReader({
82
+ exporter: new FileMetricExporter(),
83
+ exportIntervalMillis: DURATION_MS.TEN_SECONDS,
84
+ });
85
+ const logProcessors = [new SimpleLogRecordProcessor({ exporter: new FileLogExporter() })];
86
+ loggerProvider = new LoggerProvider({ resource, processors: logProcessors });
87
+ logsApi.logs.setGlobalLoggerProvider(loggerProvider);
88
+ // Providers registered directly, not via NodeSDK: its env auto-configuration read
89
+ // OTEL_*_EXPORTER and stood OTLP exporters up against localhost:4318, a retry loop
90
+ // that held every hook process open 2.7–4.7 s (H10/H12). otel-exporter-env.test.ts
91
+ // guards both the env vars and the exit latency.
92
+ tracerProvider = new NodeTracerProvider({ resource, spanProcessors });
93
+ tracerProvider.register();
94
+ // OBP13b: execute_tool.duration spans five orders of magnitude (0.3 s p50 → 40,426 s
95
+ // tail). A View with a non-default aggregation overrides the instrument's bucket
96
+ // advisory, which stays in place as the fallback.
97
+ meterProvider = new MeterProvider({
98
+ resource,
99
+ readers: [metricReader],
100
+ views: [
101
+ {
102
+ instrumentName: GENAI_EXECUTE_TOOL_DURATION_METRIC,
103
+ aggregation: { type: AggregationType.EXPONENTIAL_HISTOGRAM },
104
+ },
105
+ ],
106
+ });
107
+ api.metrics.setGlobalMeterProvider(meterProvider);
108
+ initialized = true;
109
+ registerShutdownSignalHandlers();
110
+ }
111
+ async function shutdownProviders() {
112
+ if (shutdownInProgress)
113
+ return;
114
+ shutdownInProgress = true;
115
+ try {
116
+ // Settled independently: one failed provider must not skip the meter, whose metrics land only at its shutdown.
117
+ const results = await Promise.allSettled([loggerProvider, tracerProvider, meterProvider].map(async (provider) => provider?.shutdown()));
118
+ const failure = results.find((result) => result.status === 'rejected');
119
+ if (failure)
120
+ throw failure.reason;
121
+ }
122
+ finally {
123
+ loggerProvider = null;
124
+ tracerProvider = null;
125
+ meterProvider = null;
126
+ initialized = false;
127
+ shutdownInProgress = false;
128
+ }
129
+ }
130
+ /**
131
+ * Never rejects, so a failed provider shutdown cannot cost the caller its exit code
132
+ * (HTR1). A caller about to process.exit() must await it: metrics are collected only
133
+ * at meter shutdown and are not on disk before then.
134
+ */
135
+ export function shutdownTelemetry() {
136
+ return shutdownProviders().catch((err) => {
137
+ if (OTEL_LOG_LEVEL === 'debug')
138
+ writeStderr('[otel] shutdown error:', err);
139
+ });
140
+ }
141
+ export function getTracer() {
142
+ return api.trace.getTracer(SERVICE_NAME, SERVICE_VERSION);
143
+ }
144
+ /** `parentContext` (e.g. restored from the session-start span) makes the span a child of a remote parent. */
145
+ export function withSpan(name, attributes = {}, fn, parentContext) {
146
+ const ctx = parentContext ?? api.context.active();
147
+ return getTracer().startActiveSpan(name, { attributes }, ctx, runInSpan(fn));
148
+ }
149
+ function runInSpan(fn) {
150
+ return async (span) => {
151
+ try {
152
+ return await fn(span);
153
+ }
154
+ catch (error) {
155
+ const exception = error instanceof Error ? error : new Error(String(error));
156
+ span.setStatus({ code: api.SpanStatusCode.ERROR, message: exception.message });
157
+ span.recordException(exception);
158
+ throw error;
159
+ }
160
+ finally {
161
+ span.end();
162
+ }
163
+ };
164
+ }
165
+ export function withLinkedSpan(name, linkedSpans, attributes = {}, fn) {
166
+ const links = toSpanLinks(linkedSpans);
167
+ return getTracer().startActiveSpan(name, { attributes, links }, runInSpan(fn));
168
+ }
169
+ function toSpanLinks(linkedSpans) {
170
+ return linkedSpans.map(({ span, attributes }) => ({
171
+ context: span.spanContext(),
172
+ attributes,
173
+ }));
174
+ }
175
+ /** Caller must end the span. */
176
+ export function startLinkedSpan(name, linkedSpans, attributes = {}) {
177
+ return getTracer().startSpan(name, { attributes, links: toSpanLinks(linkedSpans) });
178
+ }
179
+ export function createLinkFromContext(traceId, spanId, attributes) {
180
+ return {
181
+ context: {
182
+ traceId,
183
+ spanId,
184
+ traceFlags: api.TraceFlags.SAMPLED,
185
+ },
186
+ attributes,
187
+ };
188
+ }
189
+ export function getTraceId() {
190
+ return api.trace.getActiveSpan()?.spanContext().traceId ?? null;
191
+ }
192
+ export function addEvent(name, attributes = {}) {
193
+ api.trace.getActiveSpan()?.addEvent(name, attributes);
194
+ }
195
+ function getMeter() {
196
+ return api.metrics.getMeter(SERVICE_NAME, SERVICE_VERSION);
197
+ }
198
+ const histogramCache = new Map();
199
+ const counterCache = new Map();
200
+ /**
201
+ * The single owner of histogram creation: two same-named instruments differing in
202
+ * unit or description export two streams and split the series. Options apply on
203
+ * first registration only.
204
+ */
205
+ export function getHistogram(name, options) {
206
+ return memoizeIn(histogramCache, name, () => getMeter().createHistogram(name, {
207
+ description: options?.description,
208
+ unit: options?.unit,
209
+ ...(options?.boundaries ? { advice: { explicitBucketBoundaries: [...options.boundaries] } } : {}),
210
+ }));
211
+ }
212
+ /** Same single-owner rule as getHistogram. */
213
+ export function getCounter(name, options) {
214
+ return memoizeIn(counterCache, name, () => getMeter().createCounter(name, {
215
+ description: options?.description,
216
+ unit: options?.unit,
217
+ }));
218
+ }
219
+ /** Counter sibling of {@link recordMetric}. Neither initializes telemetry: without `initTelemetry` they record into the no-op meter. */
220
+ export function recordCounter(name, value, attributes = {}, options) {
221
+ getCounter(name, options).add(value, attributes);
222
+ }
223
+ export function recordMetric(name, value, attributes = {}, options) {
224
+ getHistogram(name, options).record(value, attributes);
225
+ }
226
+ export function log(level, message, attributes = {}) {
227
+ // The SDK stamps the active span context; a spanContext passed here is silently ignored.
228
+ logsApi.logs.getLogger(SERVICE_NAME, SERVICE_VERSION).emit({
229
+ severityNumber: SeverityNumber[level],
230
+ severityText: level,
231
+ body: message,
232
+ attributes,
233
+ });
234
+ }
235
+ export { api as otelApi };
@@ -0,0 +1,101 @@
1
+ /**
2
+ * `OTEL_EXPORTER_OTLP_*_HEADERS` resolution, mirroring otlp-exporter-base's
3
+ * `parsePairKeyValue` deliberately: a divergence is a bug. The whole bag is
4
+ * carried, not just `Authorization`, since vendor schemes (`api-key=`) are credentials too.
5
+ */
6
+ import { AUTHORIZATION_HEADER, BEARER_SCHEME, bearerHeaders } from '../core/http-utils.js';
7
+ import { OTLP_ENV } from '../core/settings-env.js';
8
+ import { OTLP_SIGNALS } from './otlp-signal.js';
9
+ // ==================== Signals and environment ====================
10
+ const SIGNAL_HEADERS_ENV = {
11
+ traces: 'OTEL_EXPORTER_OTLP_TRACES_HEADERS',
12
+ logs: 'OTEL_EXPORTER_OTLP_LOGS_HEADERS',
13
+ metrics: 'OTEL_EXPORTER_OTLP_METRICS_HEADERS',
14
+ };
15
+ /** Generic first, so a conflict present in both is reported against the generic var. */
16
+ const HEADER_ENV_VARS = [OTLP_ENV.HEADERS, ...Object.values(SIGNAL_HEADERS_ENV)];
17
+ // ==================== Header-bag parsing ====================
18
+ const ITEMS_SEPARATOR = ',';
19
+ const PROPERTIES_SEPARATOR = ';';
20
+ const KEY_PAIR_SEPARATOR = '=';
21
+ /** `key=value[;metadata]`; null wherever the reference drops the entry. `<= 0` rejects a missing `=` and an empty key alike. */
22
+ function parseHeaderEntry(entry) {
23
+ const [pair = ''] = entry.split(PROPERTIES_SEPARATOR, 1);
24
+ const eq = pair.indexOf(KEY_PAIR_SEPARATOR);
25
+ if (eq <= 0)
26
+ return null;
27
+ const rawKey = pair.slice(0, eq).trim();
28
+ const rawValue = pair.slice(eq + 1).trim();
29
+ if (!rawKey || !rawValue)
30
+ return null;
31
+ try {
32
+ return [decodeURIComponent(rawKey), decodeURIComponent(rawValue)];
33
+ }
34
+ catch {
35
+ return null;
36
+ }
37
+ }
38
+ const isHeaderEntry = (entry) => entry !== null;
39
+ /** Last duplicate wins. Undecodable entries are dropped like the reference: a raw fallback once put a wrong credential on the wire as an unexplained 401. */
40
+ export function parseOtlpHeaders(raw) {
41
+ if (!raw)
42
+ return {};
43
+ return Object.fromEntries(raw.split(ITEMS_SEPARATOR).map(parseHeaderEntry).filter(isHeaderEntry));
44
+ }
45
+ /** Inverse of `parseOtlpHeaders`: percent-encodes each key and value so the bag round-trips cleanly. A `%` in a value that is not encoded would throw on decode. */
46
+ export function formatOtlpHeaders(headers) {
47
+ return Object.entries(headers)
48
+ .map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`)
49
+ .join(ITEMS_SEPARATOR);
50
+ }
51
+ // ==================== Credential rules ====================
52
+ /**
53
+ * A bare `Bearer`, which `export Authorization=Bearer ${OBTOOL_API_KEY}` yields when the
54
+ * key is unset; counting it as a credential made the shipper spawn and 401 on every
55
+ * flush. Only `Authorization` has a grammar to check; vendor headers are opaque.
56
+ */
57
+ const SCHEME_TOKEN_CHARS = "A-Za-z0-9!#$%&'*+\\-.^_`|~";
58
+ const BARE_AUTH_SCHEME = new RegExp(`^[A-Za-z][${SCHEME_TOKEN_CHARS}]*$`);
59
+ function isUsableCredential(name, value) {
60
+ if (name.toLowerCase() !== AUTHORIZATION_HEADER.toLowerCase())
61
+ return true;
62
+ return !BARE_AUTH_SCHEME.test(value);
63
+ }
64
+ const BEARER_PREFIX = new RegExp(`^${BEARER_SCHEME}\\s+`, 'i');
65
+ function headerBagBearerToken(raw) {
66
+ const token = parseOtlpHeaders(raw)[AUTHORIZATION_HEADER]?.replace(BEARER_PREFIX, '');
67
+ return token || undefined;
68
+ }
69
+ // ==================== Resolution ====================
70
+ /** `OBTOOL_API_KEY` outranks both env bags. */
71
+ export function otlpAuthHeaders(signal, env = process.env) {
72
+ const merged = {
73
+ ...parseOtlpHeaders(env[OTLP_ENV.HEADERS]),
74
+ ...parseOtlpHeaders(env[SIGNAL_HEADERS_ENV[signal]]),
75
+ };
76
+ const headers = Object.fromEntries(Object.entries(merged).filter(([name, value]) => isUsableCredential(name, value)));
77
+ const apiKey = env[OTLP_ENV.API_KEY];
78
+ return apiKey ? { ...headers, ...bearerHeaders(apiKey) } : headers;
79
+ }
80
+ /** Shared by the shipper's spawn and run guards, which drifted when each encoded it. Any header counts: the credential's name is vendor-specific. */
81
+ export function hasOtlpAuth(env = process.env) {
82
+ if (env[OTLP_ENV.API_KEY])
83
+ return true;
84
+ return OTLP_SIGNALS.some((signal) => Object.keys(otlpAuthHeaders(signal, env)).length > 0);
85
+ }
86
+ /** Precedence hides a disagreeing env-bag credential here, but SDK exporters read only the env bag and 401 without explanation. */
87
+ export function describeOtlpCredentialConflict(env = process.env) {
88
+ const apiKey = env[OTLP_ENV.API_KEY];
89
+ if (!apiKey)
90
+ return undefined;
91
+ const disagrees = (varName) => {
92
+ const token = headerBagBearerToken(env[varName]);
93
+ return token !== undefined && token !== apiKey;
94
+ };
95
+ const conflicting = HEADER_ENV_VARS.find(disagrees);
96
+ if (!conflicting)
97
+ return undefined;
98
+ // Only the names, never the credentials.
99
+ return `${conflicting} carries a different credential than ${OTLP_ENV.API_KEY}; ` +
100
+ `${OTLP_ENV.API_KEY} wins here, but SDK exporters read ${conflicting} and would use the other one`;
101
+ }
@@ -0,0 +1,122 @@
1
+ /**
2
+ * The hooks package's one network path: OTLP/HTTP protobuf POSTs for the detached
3
+ * shipper. Serialization and reporting stay with the caller; the outcome is structured.
4
+ */
5
+ import { createHash } from 'node:crypto';
6
+ import { THRESHOLDS } from '../core/constants.js';
7
+ import { CONTENT_TYPE_HEADER, errorCauseChain, errorCode, fetchWithTimeout } from '../core/http-utils.js';
8
+ import { http1Fetch } from '../core/http1-fetch.js';
9
+ import { DURATION_MS } from '../core/units.js';
10
+ /** OTLP/HTTP path prefix; the signal name completes it (`/v1/traces`). */
11
+ const OTLP_PATH_PREFIX = '/v1/';
12
+ export function otlpPathFor(signal) {
13
+ return `${OTLP_PATH_PREFIX}${signal}`;
14
+ }
15
+ /**
16
+ * 5 s suits the per-Stop shipper, not a backlog: a batch fails whole when one body
17
+ * trips it and the cursor never advances. `OTLP_POST_TIMEOUT_MS` raises it for a
18
+ * backfill; read at call time. Invalid values fall back rather than disable the
19
+ * timeout, or an un-aborted POST hangs the shipper.
20
+ */
21
+ function otlpPostTimeoutMs() {
22
+ const raw = Number(process.env.OTLP_POST_TIMEOUT_MS);
23
+ return Number.isFinite(raw) && raw > 0 ? raw : DURATION_MS.FIVE_SECONDS;
24
+ }
25
+ /** `OTLP_MAX_CONCURRENT_POSTS` override; 1 makes the delivered prefix exact for a backfill. `0` must not mean unlimited. */
26
+ function otlpMaxConcurrentPosts() {
27
+ const raw = Number(process.env.OTLP_MAX_CONCURRENT_POSTS);
28
+ return Number.isInteger(raw) && raw > 0 ? raw : THRESHOLDS.OTLP_MAX_CONCURRENT_POSTS;
29
+ }
30
+ const OTLP_PROTOBUF_CONTENT_TYPE = 'application/x-protobuf';
31
+ /** `Content-Type` last, so an operator-supplied header bag cannot override it (as otlp-exporter-base merges). */
32
+ function otlpPostHeaders(authHeaders = {}) {
33
+ return { ...authHeaders, [CONTENT_TYPE_HEADER]: OTLP_PROTOBUF_CONTENT_TYPE };
34
+ }
35
+ export const IDEMPOTENCY_KEY_HEADER = 'X-Idempotency-Key';
36
+ /** From the body's bytes, so a retry is a dedup hit at ingest. 64 hex chars, inside ingest's 256 limit. */
37
+ export function idempotencyKeyFor(body) {
38
+ return createHash('sha256').update(body).digest('hex');
39
+ }
40
+ const SOCKET_CLOSED_CODES = new Set(['UND_ERR_SOCKET', 'EPIPE', 'ECONNRESET']);
41
+ /** Walks the cause chain: undici wraps the socket error in `TypeError: fetch failed` (SHIP1). */
42
+ function isSocketClosed(error) {
43
+ if (!(error instanceof Error))
44
+ return false;
45
+ for (const link of errorCauseChain(error)) {
46
+ const code = errorCode(link);
47
+ if (code !== undefined && SOCKET_CLOSED_CODES.has(code))
48
+ return true;
49
+ if (link.message.includes('other side closed'))
50
+ return true;
51
+ }
52
+ return false;
53
+ }
54
+ /** Stops at the first body that does not deliver. Never throws for a transport failure. */
55
+ export async function postOtlpBodies(request) {
56
+ const { url, headers, bodies } = request;
57
+ if (bodies.length === 0)
58
+ return { delivered: false, reason: 'empty-batch', deliveredPrefix: 0 };
59
+ const postHeaders = otlpPostHeaders(headers);
60
+ let retriedSocketErrors = 0;
61
+ const postOne = async (body) => {
62
+ const attempt = async () => {
63
+ try {
64
+ const res = await fetchWithTimeout(url, {
65
+ method: 'POST',
66
+ headers: { ...postHeaders, [IDEMPOTENCY_KEY_HEADER]: idempotencyKeyFor(body) },
67
+ body,
68
+ }, otlpPostTimeoutMs(),
69
+ // HTTP/1.1: one destroyed HTTP/2 session failed every later post in the run.
70
+ http1Fetch);
71
+ await res.body?.cancel();
72
+ if (!res.ok) {
73
+ return { delivered: false, reason: 'rejected', statusCode: res.status, deliveredPrefix: 0 };
74
+ }
75
+ }
76
+ catch (error) {
77
+ return { delivered: false, reason: 'threw', error, deliveredPrefix: 0 };
78
+ }
79
+ return { delivered: true, deliveredPrefix: 1 };
80
+ };
81
+ const first = await attempt();
82
+ // SHIP1: one retry on a socket closed under a reused keep-alive connection; never
83
+ // on timeouts or HTTP rejections. Safe because the idempotency key is body-derived;
84
+ // past its 300 s TTL a re-sent body is absorbed by the D1 row dedup indexes, which
85
+ // cover span-less logs since ingest migration 0022 (SHIP3).
86
+ if (!first.delivered && first.reason === 'threw' && isSocketClosed(first.error)) {
87
+ const retry = await attempt();
88
+ if (retry.delivered) {
89
+ retriedSocketErrors++;
90
+ return retry;
91
+ }
92
+ }
93
+ return first;
94
+ };
95
+ // Waves, not one at a time: a metrics batch is ~1,000 small bodies and sequential
96
+ // posting took minutes. `deliveredPrefix` is the CONTIGUOUS count from index 0, the
97
+ // only count a byte-offset cursor can act on; a body landing after the first failure
98
+ // is re-sent next run, a row-level no-op at ingest since migrations 0013/0014 but an
99
+ // extra R2 object. Read at call time: a module-scope read breaks tests that mock constants.js.
100
+ const maxConcurrent = request.maxConcurrent ?? otlpMaxConcurrentPosts();
101
+ let prefix = 0;
102
+ for (let i = 0; i < bodies.length; i += maxConcurrent) {
103
+ const wave = bodies.slice(i, i + maxConcurrent);
104
+ // eslint-disable-next-line no-await-in-loop -- waves cap concurrent POSTs at maxConcurrent and stop at the first failed wave
105
+ const outcomes = await Promise.all(wave.map(postOne));
106
+ const failedAt = outcomes.findIndex((o) => !o.delivered);
107
+ if (failedAt !== -1) {
108
+ const failed = outcomes[failedAt];
109
+ return {
110
+ ...failed,
111
+ deliveredPrefix: prefix + failedAt,
112
+ ...(retriedSocketErrors > 0 ? { retriedSocketErrors } : {}),
113
+ };
114
+ }
115
+ prefix += wave.length;
116
+ }
117
+ return {
118
+ delivered: true,
119
+ deliveredPrefix: prefix,
120
+ ...(retriedSocketErrors > 0 ? { retriedSocketErrors } : {}),
121
+ };
122
+ }