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,353 @@
1
+ /** Shared file system helpers. `withFileLock` fails open; `pruneOldFiles` never throws. */
2
+ import { appendFileSync, existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmdirSync, rmSync, statSync, unlinkSync, writeFileSync, } from 'node:fs';
3
+ import { dirname, join, resolve } from 'node:path';
4
+ import { FILE_LOCK } from './constants.js';
5
+ import { errorMessage, writeStderr } from './format-utils.js';
6
+ import { parseJsonLines } from './jsonl-tail.js';
7
+ /** Symlink-resolved absolute path, or the lexically resolved one for a path that does not exist, so two spellings of one file compare equal. */
8
+ export function realFilePath(filePath) {
9
+ try {
10
+ return realpathSync(filePath);
11
+ }
12
+ catch {
13
+ return resolve(filePath);
14
+ }
15
+ }
16
+ /** True when two paths name the same file; resolves only when the strings differ. */
17
+ export function isSameFile(a, b) {
18
+ return a === b || realFilePath(a) === realFilePath(b);
19
+ }
20
+ export function readTextOrNull(filePath) {
21
+ try {
22
+ return readFileSync(filePath, 'utf-8');
23
+ }
24
+ catch {
25
+ return null;
26
+ }
27
+ }
28
+ function readTextOrEmpty(filePath) {
29
+ return readTextOrNull(filePath) ?? '';
30
+ }
31
+ /** Empty array on any read error (missing directory, permissions, etc.). */
32
+ export function readdirOrEmpty(dir) {
33
+ try {
34
+ return readdirSync(dir);
35
+ }
36
+ catch {
37
+ return [];
38
+ }
39
+ }
40
+ /** Null on a missing file and on a parse error alike. */
41
+ export function loadJson(filePath) {
42
+ try {
43
+ return JSON.parse(readFileSync(filePath, 'utf-8'));
44
+ }
45
+ catch {
46
+ return null;
47
+ }
48
+ }
49
+ export function isJsonObject(value) {
50
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
51
+ }
52
+ export function loadJsonObject(filePath) {
53
+ const parsed = loadJson(filePath);
54
+ return isJsonObject(parsed) ? parsed : null;
55
+ }
56
+ export function stringValues(source) {
57
+ return Object.fromEntries(Object.entries(source).filter((entry) => typeof entry[1] === 'string'));
58
+ }
59
+ /** Malformed lines (a torn final line from a crashed writer) are skipped. */
60
+ export function readJsonlFile(filePath) {
61
+ return [...parseJsonLines(readTextOrEmpty(filePath))];
62
+ }
63
+ /** `silent` suppresses the stderr line for callers that log themselves. */
64
+ export function writeJson(filePath, data, pretty = true, options) {
65
+ try {
66
+ ensureDirExists(dirname(filePath));
67
+ const content = pretty ? JSON.stringify(data, null, 2) : JSON.stringify(data);
68
+ writeFileSync(filePath, content);
69
+ return true;
70
+ }
71
+ catch (error) {
72
+ if (!options?.silent) {
73
+ writeStderr(`[file-utils] writeJson failed for ${filePath}:`, errorMessage(error));
74
+ }
75
+ return false;
76
+ }
77
+ }
78
+ /** Temp file + rename; the temp file sits beside the target so the rename is atomic. */
79
+ export function writeJsonAtomic(filePath, data, options) {
80
+ const tmpPath = `${filePath}.tmp.${process.pid}`;
81
+ try {
82
+ ensureDirExists(dirname(filePath));
83
+ writeFileSync(tmpPath, JSON.stringify(data));
84
+ renameSync(tmpPath, filePath);
85
+ return true;
86
+ }
87
+ catch (error) {
88
+ try {
89
+ unlinkSync(tmpPath);
90
+ }
91
+ catch { /* already gone */ }
92
+ if (!options?.silent) {
93
+ writeStderr(`[file-utils] writeJsonAtomic failed for ${filePath}:`, errorMessage(error));
94
+ }
95
+ return false;
96
+ }
97
+ }
98
+ const ENOENT = 'ENOENT';
99
+ /** A missing file is the goal state; any other failure is logged and reported false, never thrown. */
100
+ export function removeFile(filePath) {
101
+ try {
102
+ unlinkSync(filePath);
103
+ return true;
104
+ }
105
+ catch (error) {
106
+ if (error.code === ENOENT)
107
+ return true;
108
+ writeStderr(`[file-utils] removeFile failed for ${filePath}:`, errorMessage(error));
109
+ return false;
110
+ }
111
+ }
112
+ const knownDirs = new Set();
113
+ /** Memoized per process: a directory deleted after the first call is not recreated (see `resetDirCache`). */
114
+ export function ensureDirExists(dirPath) {
115
+ if (knownDirs.has(dirPath))
116
+ return;
117
+ mkdirSync(dirPath, { recursive: true });
118
+ knownDirs.add(dirPath);
119
+ }
120
+ /** Test seam. */
121
+ export function resetDirCache() {
122
+ knownDirs.clear();
123
+ }
124
+ /** Synchronous on purpose: a buffered appender's flush timer never fires inside a ~130 ms hook process. */
125
+ export function appendLine(filePath, line) {
126
+ ensureDirExists(dirname(filePath));
127
+ appendFileSync(filePath, line);
128
+ }
129
+ export function appendToLog(dir, filename, ...values) {
130
+ const timestamp = new Date().toISOString();
131
+ appendLine(join(dir, filename), `${[timestamp, ...values].join('\t')}\n`);
132
+ }
133
+ const UNSAFE_FILENAME_CHARS = /[^a-zA-Z0-9_-]/g;
134
+ /** Get-or-compute against `store`. `undefined` is a miss; `null` is a cacheable result. */
135
+ export function memoizeIn(store, key, compute) {
136
+ const cached = store.get(key);
137
+ if (cached !== undefined)
138
+ return cached;
139
+ const result = compute();
140
+ store.set(key, result);
141
+ return result;
142
+ }
143
+ const safeFilenameCache = new Map();
144
+ /** The single owner of this mapping: a writer and a reader sanitizing differently address different files. */
145
+ export function toSafeFilename(value) {
146
+ return memoizeIn(safeFilenameCache, value, () => value.replace(UNSAFE_FILENAME_CHARS, '_'));
147
+ }
148
+ /** The first non-null `probe(dir)` walking up from `start`; null at the root. */
149
+ export function findUp(start, probe) {
150
+ let dir = start;
151
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- loop exits via return at filesystem root
152
+ while (true) {
153
+ const result = probe(dir);
154
+ if (result !== null)
155
+ return result;
156
+ const parent = dirname(dir);
157
+ if (parent === dir)
158
+ return null;
159
+ dir = parent;
160
+ }
161
+ }
162
+ function fileMtimeMs(filePath) {
163
+ return statSync(filePath).mtimeMs;
164
+ }
165
+ /** Best-effort, never throws; subdirectories are left alone. Returns the count deleted. */
166
+ export function pruneOldFiles(dir, maxAgeMs, options = {}) {
167
+ const { extension, timestampOf = fileMtimeMs } = options;
168
+ let deleted = 0;
169
+ try {
170
+ if (!existsSync(dir))
171
+ return 0;
172
+ const cutoff = Date.now() - maxAgeMs;
173
+ for (const name of readdirSync(dir)) {
174
+ if (extension !== undefined && !name.endsWith(extension))
175
+ continue;
176
+ const filePath = join(dir, name);
177
+ try {
178
+ const timestamp = timestampOf(filePath);
179
+ if (timestamp !== null && timestamp < cutoff) {
180
+ unlinkSync(filePath);
181
+ deleted++;
182
+ }
183
+ }
184
+ catch {
185
+ // Raced away, unreadable, or a directory.
186
+ }
187
+ }
188
+ }
189
+ catch {
190
+ // Directory unreadable.
191
+ }
192
+ return deleted;
193
+ }
194
+ function sleepSync(ms) {
195
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT)), 0, 0, ms);
196
+ }
197
+ const LOCK_SUFFIX = '.lock';
198
+ const LOCK_TOMB_SUFFIX = '.tomb.';
199
+ const LOCK_OWNER_FILE = 'owner';
200
+ const ERR_EEXIST = 'EEXIST';
201
+ const TOKEN_RAND_MAX = 0xffffffff;
202
+ const HEX_RADIX = 16;
203
+ const ENCODING_UTF8 = 'utf-8';
204
+ /**
205
+ * Restores a tombstone to lockDir when it is free, otherwise deletes it (a live holder then
206
+ * runs unlocked: fail-open). The existsSync check narrows, but cannot close, the window where
207
+ * rename(2) replaces an acquirer's empty, not-yet-tokened lockDir.
208
+ */
209
+ function restoreOrDiscard(tombstone, lockDir) {
210
+ if (!existsSync(lockDir)) {
211
+ try {
212
+ renameSync(tombstone, lockDir);
213
+ return;
214
+ }
215
+ catch { /* restore race — fall through */ }
216
+ }
217
+ try {
218
+ rmSync(tombstone, { recursive: true, force: true });
219
+ }
220
+ catch { /* ignore */ }
221
+ }
222
+ /**
223
+ * Atomic `mkdirSync` lock at `lockDir`, stolen when stale. renameSync serializes stealers; a
224
+ * tombstone that is fresh after the rename means another process re-acquired it, so restore
225
+ * and back off. Tombstones carry pid and ms so PID reuse cannot collide; a crash's leftovers
226
+ * are not swept.
227
+ */
228
+ function tryAcquireLock(lockDir, stale) {
229
+ const token = `${process.pid}-${Date.now()}-${Math.floor(Math.random() * TOKEN_RAND_MAX).toString(HEX_RADIX)}`;
230
+ const ownerFile = join(lockDir, LOCK_OWNER_FILE);
231
+ const writeToken = () => {
232
+ try {
233
+ writeFileSync(ownerFile, token);
234
+ return token;
235
+ }
236
+ catch (err) {
237
+ // ENOENT: lockDir was renamed away by a concurrent stealer — nothing to clean up.
238
+ if (err.code === ENOENT)
239
+ return undefined;
240
+ // ENOSPC or similar: remove the ownerless dir so the next acquirer can retry cleanly.
241
+ try {
242
+ unlinkSync(ownerFile);
243
+ }
244
+ catch { /* already absent */ }
245
+ try {
246
+ rmdirSync(lockDir);
247
+ }
248
+ catch { /* ignore */ }
249
+ return undefined;
250
+ }
251
+ };
252
+ try {
253
+ mkdirSync(lockDir);
254
+ return writeToken();
255
+ }
256
+ catch (err) {
257
+ if (err.code !== ERR_EEXIST)
258
+ return undefined;
259
+ try {
260
+ if (Date.now() - statSync(lockDir).mtimeMs < stale)
261
+ return undefined;
262
+ const tombstone = `${lockDir}${LOCK_TOMB_SUFFIX}${process.pid}.${Date.now()}`;
263
+ renameSync(lockDir, tombstone);
264
+ if (Date.now() - statSync(tombstone).mtimeMs < stale) {
265
+ restoreOrDiscard(tombstone, lockDir);
266
+ return undefined;
267
+ }
268
+ rmSync(tombstone, { recursive: true, force: true });
269
+ mkdirSync(lockDir);
270
+ return writeToken();
271
+ }
272
+ catch {
273
+ return undefined;
274
+ }
275
+ }
276
+ }
277
+ /**
278
+ * Releases only when the owner token still matches; renameSync narrows the window where a
279
+ * timed-out holder removes a stealer's live lock. A missing or unreadable owner file means
280
+ * not ours. Any failure leaves the lock to age out at staleMs (fail-open).
281
+ */
282
+ function releaseLock(lockDir, token) {
283
+ const tombstone = `${lockDir}${LOCK_TOMB_SUFFIX}${process.pid}.${Date.now()}`;
284
+ try {
285
+ renameSync(lockDir, tombstone);
286
+ }
287
+ catch {
288
+ return; // lockDir already gone or inaccessible — fail open.
289
+ }
290
+ let isOurs;
291
+ try {
292
+ isOurs = readFileSync(join(tombstone, LOCK_OWNER_FILE), ENCODING_UTF8) === token;
293
+ }
294
+ catch {
295
+ // Owner file missing or unreadable — treat as not ours and restore.
296
+ restoreOrDiscard(tombstone, lockDir);
297
+ return;
298
+ }
299
+ if (!isOurs) {
300
+ restoreOrDiscard(tombstone, lockDir);
301
+ return;
302
+ }
303
+ // rmSync failure leaves the tombstone to age out as stale — silent fail-open.
304
+ try {
305
+ rmSync(tombstone, { recursive: true, force: true });
306
+ }
307
+ catch { /* ignore */ }
308
+ }
309
+ /**
310
+ * Exponential backoff over `tryAcquireLock`. Undefined means fail open. The last sleep is
311
+ * clamped to the deadline and followed by one attempt there, so the full `maxWaitMs` is used.
312
+ */
313
+ function acquireFileLock(lockPath, { maxRetries = FILE_LOCK.MAX_RETRIES, retryDelayMs = FILE_LOCK.RETRY_DELAY_MS, staleMs = FILE_LOCK.STALE_MS, maxWaitMs = FILE_LOCK.MAX_WAIT_MS, } = {}) {
314
+ ensureDirExists(dirname(lockPath));
315
+ const lockDir = `${lockPath}${LOCK_SUFFIX}`;
316
+ const maxDelay = retryDelayMs * FILE_LOCK.MAX_DELAY_FACTOR;
317
+ const deadline = Date.now() + maxWaitMs;
318
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
319
+ const token = tryAcquireLock(lockDir, staleMs);
320
+ if (token !== undefined)
321
+ return () => releaseLock(lockDir, token);
322
+ const remaining = deadline - Date.now();
323
+ if (attempt === maxRetries || remaining <= 0)
324
+ return undefined;
325
+ sleepSync(Math.min(retryDelayMs * 2 ** attempt, maxDelay, remaining));
326
+ }
327
+ return undefined;
328
+ }
329
+ /**
330
+ * Advisory `mkdirSync` lock, fail-open: contention never blocks a hook. `maxWaitMs` caps the
331
+ * stall; raise `staleMs` for a critical section that can outlive the default.
332
+ */
333
+ export function withFileLock(lockPath, fn, options) {
334
+ const release = acquireFileLock(lockPath, options);
335
+ try {
336
+ return fn();
337
+ }
338
+ finally {
339
+ release?.();
340
+ }
341
+ }
342
+ /** Fail-closed sibling of `withFileLock`: `fn` never runs without the lock. */
343
+ export function tryWithFileLock(lockPath, fn, options) {
344
+ const release = acquireFileLock(lockPath, options);
345
+ if (release === undefined)
346
+ return { locked: false };
347
+ try {
348
+ return { locked: true, value: fn() };
349
+ }
350
+ finally {
351
+ release();
352
+ }
353
+ }
@@ -0,0 +1,51 @@
1
+ /** String/date formatting and the stderr writer; Node builtins only, so hot-path modules can use it. */
2
+ import { format } from 'node:util';
3
+ const processStderr = (line) => { process.stderr.write(`${line}\n`); };
4
+ let stderrWriter = processStderr;
5
+ /**
6
+ * One `console.error`-formatted line on stderr. It reaches Claude only when the hook exits 2;
7
+ * otherwise it lands in the debug log or a detached job's log file.
8
+ */
9
+ export function writeStderr(...parts) {
10
+ stderrWriter(format(...parts));
11
+ }
12
+ /** Redirect stderr lines; call with no argument to restore `process.stderr`. Test seam. */
13
+ export function setStderrWriter(next) {
14
+ stderrWriter = next ?? processStderr;
15
+ }
16
+ export const TRUNCATION_SUFFIX = '... [truncated]';
17
+ /** Truncate to `maxLen`, appending `suffix` when cut. */
18
+ export function truncate(text, maxLen, suffix = TRUNCATION_SUFFIX) {
19
+ return text.length > maxLen ? text.slice(0, maxLen) + suffix : text;
20
+ }
21
+ /** Message text for a caught value: `Error.message`, or the value stringified. */
22
+ export function errorMessage(error) {
23
+ return error instanceof Error ? error.message : String(error);
24
+ }
25
+ /** Metric-label name for a caught value: `Error.name`, or the `typeof` of a non-Error throw. */
26
+ export function errorTypeName(error) {
27
+ return error instanceof Error ? error.name : typeof error;
28
+ }
29
+ /** `Name: message` for an `Error`, or the value stringified. */
30
+ export function errorSummary(error) {
31
+ return error instanceof Error ? `${error.name}: ${error.message}` : String(error);
32
+ }
33
+ const DATE_STAMP_LENGTH = 10;
34
+ /** UTC `YYYY-MM-DD` stamp used by every date-partitioned telemetry file. */
35
+ export function utcDateStamp(date = new Date()) {
36
+ return date.toISOString().slice(0, DATE_STAMP_LENGTH);
37
+ }
38
+ const TELEMETRY_FILE_EXTENSION = 'jsonl';
39
+ const TELEMETRY_FILE_PATTERN = new RegExp(`^(.+)-\\d{4}-\\d{2}-\\d{2}\\.${TELEMETRY_FILE_EXTENSION}$`);
40
+ /** Telemetry JSONL filename; lives here so consumers avoid loading the OTel SDK. */
41
+ export function telemetryFileName(prefix, date = new Date()) {
42
+ return `${prefix}-${utcDateStamp(date)}.${TELEMETRY_FILE_EXTENSION}`;
43
+ }
44
+ /** The prefix `telemetryFileName` was given, or null for any other filename. */
45
+ export function telemetryFilePrefix(file) {
46
+ return TELEMETRY_FILE_PATTERN.exec(file)?.[1] ?? null;
47
+ }
48
+ /** Lines with any non-whitespace content. */
49
+ export function countNonEmptyLines(text) {
50
+ return text.split('\n').filter((line) => line.trim()).length;
51
+ }
@@ -0,0 +1,74 @@
1
+ export const AUTHORIZATION_HEADER = 'Authorization';
2
+ export const BEARER_SCHEME = 'Bearer';
3
+ export const CONTENT_TYPE_HEADER = 'Content-Type';
4
+ export const JSON_CONTENT_TYPE = 'application/json';
5
+ /** `Bearer <token>`, shared by the OTLP shipper, the judge and the MCP launcher. */
6
+ export function bearerCredential(apiKey) {
7
+ return `${BEARER_SCHEME} ${apiKey}`;
8
+ }
9
+ export function bearerHeaders(apiKey) {
10
+ return { [AUTHORIZATION_HEADER]: bearerCredential(apiKey) };
11
+ }
12
+ /** JSON request headers; `Content-Type` last so a caller's bag cannot override it. */
13
+ export function jsonHeaders(headers = {}) {
14
+ return { ...headers, [CONTENT_TYPE_HEADER]: JSON_CONTENT_TYPE };
15
+ }
16
+ /** Status codes the hooks branch on by name. */
17
+ export const HTTP_STATUS = {
18
+ OK: 200,
19
+ MULTIPLE_CHOICES: 300,
20
+ UNAUTHORIZED: 401,
21
+ REQUEST_TIMEOUT: 408,
22
+ CONFLICT: 409,
23
+ TOO_MANY_REQUESTS: 429,
24
+ INTERNAL_SERVER_ERROR: 500,
25
+ };
26
+ /** Retried in place, along with every 5xx (529 is Anthropic's overloaded). */
27
+ const RETRYABLE_HTTP_STATUSES = new Set([
28
+ HTTP_STATUS.REQUEST_TIMEOUT,
29
+ HTTP_STATUS.CONFLICT,
30
+ HTTP_STATUS.TOO_MANY_REQUESTS,
31
+ ]);
32
+ export function isRetryableHttpStatus(status) {
33
+ return RETRYABLE_HTTP_STATUSES.has(status) || status >= HTTP_STATUS.INTERNAL_SERVER_ERROR;
34
+ }
35
+ /** 2xx, what `Response.ok` means. */
36
+ export function isSuccessHttpStatus(status) {
37
+ return status >= HTTP_STATUS.OK && status < HTTP_STATUS.MULTIPLE_CHOICES;
38
+ }
39
+ /** `error.code` when it is a string, as on Node and undici transport errors. */
40
+ export function errorCode(error) {
41
+ const code = error?.code;
42
+ return typeof code === 'string' ? code : undefined;
43
+ }
44
+ /** A cyclic cause chain must not loop forever in the process walking it. */
45
+ const MAX_CAUSE_DEPTH = 8;
46
+ /** `error`, then each `Error` on its `cause` chain, at most `MAX_CAUSE_DEPTH` causes deep. */
47
+ export function* errorCauseChain(error) {
48
+ let current = error;
49
+ yield current;
50
+ for (let depth = 0; depth < MAX_CAUSE_DEPTH; depth++) {
51
+ const { cause } = current;
52
+ if (!(cause instanceof Error))
53
+ return;
54
+ current = cause;
55
+ yield current;
56
+ }
57
+ }
58
+ /** `AbortSignal.timeout` throws `TimeoutError`; `AbortError` keeps the series continuous with older spans. */
59
+ const TIMEOUT_ERROR_NAMES = new Set(['TimeoutError', 'AbortError']);
60
+ const TIMEOUT_ERROR_CODES = new Set(['UND_ERR_HEADERS_TIMEOUT', 'UND_ERR_BODY_TIMEOUT', 'UND_ERR_ABORTED']);
61
+ /** A request that ran out of time or was aborted, from either `fetch` or undici's dispatcher. */
62
+ export function isHttpTimeoutError(error) {
63
+ if (!(error instanceof Error))
64
+ return false;
65
+ const code = errorCode(error);
66
+ return TIMEOUT_ERROR_NAMES.has(error.name) || (code !== undefined && TIMEOUT_ERROR_CODES.has(code));
67
+ }
68
+ /**
69
+ * `fetch` with an `AbortSignal.timeout` deadline covering the body read too. Async so a
70
+ * synchronous throw from `fetchFn` (or an invalid `timeoutMs`) still arrives as a rejection.
71
+ */
72
+ export async function fetchWithTimeout(url, init, timeoutMs, fetchFn = (input, requestInit) => globalThis.fetch(input, requestInit)) {
73
+ return fetchFn(url, { ...init, signal: AbortSignal.timeout(timeoutMs) });
74
+ }
@@ -0,0 +1,14 @@
1
+ /**
2
+ * HTTP/1.1 `fetch`: Node 26's built-in fetch reuses a destroyed HTTP/2 session, failing every
3
+ * later request with `ERR_HTTP2_INVALID_SESSION`. Lazy paths only, to keep undici off the hot path.
4
+ */
5
+ import { Agent, fetch as undiciFetch } from 'undici';
6
+ let dispatcher;
7
+ /** HTTP/1.1-only pool, created on first use; shared by `http1Fetch` and the judge transport. */
8
+ export function http1Dispatcher() {
9
+ dispatcher ??= new Agent({ allowH2: false });
10
+ return dispatcher;
11
+ }
12
+ export const http1Fetch = (input, init) =>
13
+ // Cast: Node 26's built-in Response type has textStream, which undici's lacks.
14
+ undiciFetch(input, { ...init, dispatcher: http1Dispatcher() });
@@ -0,0 +1,149 @@
1
+ /**
2
+ * Signed-in OAuth email (`~/.claude.json`) → Doppler secret name
3
+ * (`config/identity-key-map.json`) → plaintext obtool key via the Doppler CLI.
4
+ * Precedence: identity-resolved key, then `OBTOOL_API_KEY` from env, then
5
+ * `OTEL_EXPORTER_OTLP_*_HEADERS`. An unmapped account fails closed.
6
+ */
7
+ import { execFileSync } from 'node:child_process';
8
+ import { statSync } from 'node:fs';
9
+ import { homedir } from 'node:os';
10
+ import { join } from 'node:path';
11
+ import { hostStateDir } from '../session/session-state.js';
12
+ import { claudeConfigDir } from './config-dir-recovery.js';
13
+ import { isJsonObject, loadJsonObject, memoizeIn, stringValues, writeJson } from './file-utils.js';
14
+ import { OTLP_ENV } from './settings-env.js';
15
+ import { DURATION_MS } from './units.js';
16
+ export const DOPPLER_BIN = '/opt/homebrew/bin/doppler';
17
+ export const DOPPLER_PROJECT = 'integrity-studio';
18
+ export const DOPPLER_CONFIGS = {
19
+ PRD: 'prd',
20
+ DEV: 'dev',
21
+ };
22
+ /** `~/.claude.json`, NOT `~/.claude/.claude.json`: the latter is a stale copy that would pin the resolver to an old account. */
23
+ export function claudeJsonPath() {
24
+ const configDir = process.env.CLAUDE_CONFIG_DIR;
25
+ return configDir ? join(configDir, '.claude.json') : join(homedir(), '.claude.json');
26
+ }
27
+ function identityMapPath() {
28
+ return join(claudeConfigDir(), 'config', 'identity-key-map.json');
29
+ }
30
+ // Email sidecar: one statSync per spawn instead of parsing the ~200 KB account file.
31
+ // Under `hostStateDir()`, so CLAUDE_HOME-rooted regardless of CLAUDE_CONFIG_DIR.
32
+ export const EMAIL_CACHE_FILE = 'email-cache.json';
33
+ function emailCachePath() {
34
+ return join(hostStateDir(), EMAIL_CACHE_FILE);
35
+ }
36
+ /** Valid while the source's mtime and size match the record. */
37
+ function readEmailFromSidecar(jsonPath) {
38
+ const r = loadJsonObject(emailCachePath());
39
+ if (r?.path !== jsonPath ||
40
+ typeof r.mtimeMs !== 'number' ||
41
+ typeof r.size !== 'number' ||
42
+ typeof r.email !== 'string') {
43
+ return undefined;
44
+ }
45
+ try {
46
+ const st = statSync(jsonPath);
47
+ if (st.mtimeMs === r.mtimeMs && st.size === r.size)
48
+ return r.email;
49
+ }
50
+ catch {
51
+ // Source absent: cache miss.
52
+ }
53
+ return undefined;
54
+ }
55
+ /** A skipped write costs one full parse on the next spawn. */
56
+ function writeEmailToSidecar(jsonPath, email) {
57
+ let st;
58
+ try {
59
+ st = statSync(jsonPath);
60
+ }
61
+ catch {
62
+ return;
63
+ }
64
+ const record = { path: jsonPath, mtimeMs: st.mtimeMs, size: st.size, email };
65
+ writeJson(emailCachePath(), record, false, { silent: true });
66
+ }
67
+ // Per-process caches: undefined (unchecked), null (checked, absent), or a value.
68
+ let cachedEmail = undefined;
69
+ /** Keyed by config and name: one shipper run resolves a key per account, in `prd` or `dev`. */
70
+ const cachedKeys = new Map();
71
+ export function getSignedInEmail() {
72
+ if (cachedEmail !== undefined)
73
+ return cachedEmail ?? undefined;
74
+ const jsonPath = claudeJsonPath();
75
+ const sidecar = readEmailFromSidecar(jsonPath);
76
+ if (sidecar !== undefined) {
77
+ cachedEmail = sidecar;
78
+ return sidecar;
79
+ }
80
+ const account = loadJsonObject(jsonPath)?.oauthAccount;
81
+ const email = isJsonObject(account) ? account.emailAddress : undefined;
82
+ if (typeof email === 'string' && email) {
83
+ cachedEmail = email;
84
+ writeEmailToSidecar(jsonPath, email);
85
+ return email;
86
+ }
87
+ cachedEmail = null;
88
+ return undefined;
89
+ }
90
+ /** Keyed by path so a test that repoints the config dir re-reads. */
91
+ let cachedMap;
92
+ function loadIdentityMap() {
93
+ const path = identityMapPath();
94
+ if (cachedMap?.path === path)
95
+ return cachedMap.map;
96
+ // Non-string values dropped, so a hand-edit cannot hand Doppler a non-name.
97
+ const map = stringValues(loadJsonObject(path) ?? {});
98
+ cachedMap = { path, map };
99
+ return map;
100
+ }
101
+ /** Two local file reads, never a Doppler spawn. */
102
+ export function resolveKeySecretName(email) {
103
+ const e = email ?? getSignedInEmail();
104
+ if (!e)
105
+ return undefined;
106
+ return loadIdentityMap()[e];
107
+ }
108
+ /** One per org the shipper writes to. */
109
+ export function mappedKeySecretNames() {
110
+ return [...new Set(Object.values(loadIdentityMap()))];
111
+ }
112
+ /** The shipper's spawn guard: true means the detached process will be able to resolve a key. */
113
+ export function canResolveIdentityKey(email) {
114
+ return resolveKeySecretName(email) !== undefined;
115
+ }
116
+ /** A 241–676 ms CLI spawn, once per secret per process: only from a detached process, never an event hook. */
117
+ export function readDopplerSecret(secretName, config = DOPPLER_CONFIGS.PRD) {
118
+ const key = memoizeIn(cachedKeys, `${config}/${secretName}`, () => {
119
+ try {
120
+ const out = execFileSync(DOPPLER_BIN, ['secrets', 'get', secretName, '--plain', '--project', DOPPLER_PROJECT, '--config', config], { encoding: 'utf8', timeout: DURATION_MS.TEN_SECONDS }).trim();
121
+ return out || null;
122
+ }
123
+ catch {
124
+ // Missing CLI, timeout or secret not found; the caller decides the fallback.
125
+ return null;
126
+ }
127
+ });
128
+ return key ?? undefined;
129
+ }
130
+ /**
131
+ * The one source order for a mapped org key, shared by the shipper, the trace reader, the headers
132
+ * CLI and the MCP launcher: the environment first (a `doppler run` shell already holds it, so no
133
+ * spawn), then Doppler. Rotation caveat: a shell that exported the secret before a rotation keeps
134
+ * sending the old key (401s once it is revoked) until that shell is restarted; Doppler is not consulted.
135
+ */
136
+ export function readMappedKey(secretName, env = process.env) {
137
+ return env[secretName] || readDopplerSecret(secretName);
138
+ }
139
+ /** The signed-in account's mapped key, else `OBTOOL_API_KEY`. */
140
+ export function resolveOtlpApiKey(env = process.env) {
141
+ const secretName = resolveKeySecretName();
142
+ return (secretName ? readMappedKey(secretName, env) : undefined) ?? env[OTLP_ENV.API_KEY] ?? undefined;
143
+ }
144
+ /** Tests only. */
145
+ export function resetIdentityKeyCache() {
146
+ cachedEmail = undefined;
147
+ cachedMap = undefined;
148
+ cachedKeys.clear();
149
+ }