observability-toolkit-hooks 0.0.0-stage → 1.0.1

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 (306) hide show
  1. package/CONFIG.md +144 -0
  2. package/LICENSE +95 -0
  3. package/README.md +201 -2
  4. package/dist/handlers/compact.js +38 -0
  5. package/dist/handlers/mcp-status.js +66 -0
  6. package/dist/handlers/notification.js +45 -0
  7. package/dist/handlers/post-tool-agent.js +157 -0
  8. package/dist/handlers/post-tool-changelog-sync.js +148 -0
  9. package/dist/handlers/post-tool-code-structure.js +116 -0
  10. package/dist/handlers/post-tool-edit-ledger.js +15 -0
  11. package/dist/handlers/post-tool-failure.js +83 -0
  12. package/dist/handlers/post-tool-git.js +79 -0
  13. package/dist/handlers/post-tool-mcp.js +105 -0
  14. package/dist/handlers/post-tool-outcome.js +48 -0
  15. package/dist/handlers/post-tool-task-state.js +74 -0
  16. package/dist/handlers/post-tool.js +132 -0
  17. package/dist/handlers/pre-tool-agent.js +192 -0
  18. package/dist/handlers/pre-tool.js +218 -0
  19. package/dist/handlers/session-end.js +39 -0
  20. package/dist/handlers/session-start.js +262 -0
  21. package/dist/handlers/stop-error-reminder.js +195 -0
  22. package/dist/handlers/stop-quality-evaluation.js +58 -0
  23. package/dist/handlers/stop-session-summary.js +62 -0
  24. package/dist/handlers/stop-token-metrics.js +83 -0
  25. package/dist/handlers/stop.js +25 -0
  26. package/dist/handlers/subagent.js +105 -0
  27. package/dist/handlers/tool-event-router.js +39 -0
  28. package/dist/handlers/user-prompt.js +218 -0
  29. package/dist/hook-runner.js +10 -0
  30. package/dist/hook-runner.js.map +7 -0
  31. package/dist/lib/agent/agent-context.js +123 -0
  32. package/dist/lib/agent/agent-evaluations.js +155 -0
  33. package/dist/lib/agent/agent-file-budget.js +65 -0
  34. package/dist/lib/agent/agent-sources.js +165 -0
  35. package/dist/lib/agent/synth-spans.js +51 -0
  36. package/dist/lib/core/bounded-label.js +6 -0
  37. package/dist/lib/core/category-rules.js +11 -0
  38. package/dist/lib/core/child-result.js +19 -0
  39. package/dist/lib/core/config-dir-recovery.js +22 -0
  40. package/dist/lib/core/constants.js +171 -0
  41. package/dist/lib/core/detached-runner.js +55 -0
  42. package/dist/lib/core/file-utils.js +353 -0
  43. package/dist/lib/core/format-utils.js +51 -0
  44. package/dist/lib/core/http-utils.js +74 -0
  45. package/dist/lib/core/http1-fetch.js +14 -0
  46. package/dist/lib/core/identity-key-resolver.js +149 -0
  47. package/dist/lib/core/jsonl-tail.js +207 -0
  48. package/dist/lib/core/load-envrc.js +72 -0
  49. package/dist/lib/core/parsers.js +43 -0
  50. package/dist/lib/core/regex.js +27 -0
  51. package/dist/lib/core/settings-env.js +31 -0
  52. package/dist/lib/core/shell-command.js +122 -0
  53. package/dist/lib/core/units.js +97 -0
  54. package/dist/lib/git/git-cache.js +158 -0
  55. package/dist/lib/git/git-commit.js +189 -0
  56. package/dist/lib/git/git-exec.js +30 -0
  57. package/dist/lib/mcp/mcp-completeness.js +40 -0
  58. package/dist/lib/mcp/mcp-config.js +118 -0
  59. package/dist/lib/mcp/mcp-failure-latch.js +22 -0
  60. package/dist/lib/mcp/mcp-identity-launcher.js +43 -0
  61. package/dist/lib/otel/attributes.js +322 -0
  62. package/dist/lib/otel/evaluation-attrs.js +51 -0
  63. package/dist/lib/otel/file-exporters.js +169 -0
  64. package/dist/lib/otel/host-resource.js +61 -0
  65. package/dist/lib/otel/otel-headers-helper.js +26 -0
  66. package/dist/lib/otel/otel-monitor.js +181 -0
  67. package/dist/lib/otel/otel.js +235 -0
  68. package/dist/lib/otel/otlp-headers.js +101 -0
  69. package/dist/lib/otel/otlp-post.js +122 -0
  70. package/dist/lib/otel/otlp-serialize.js +142 -0
  71. package/dist/lib/otel/otlp-signal.js +2 -0
  72. package/dist/lib/otel/remote-spans.js +142 -0
  73. package/dist/lib/otel/service-identity.js +10 -0
  74. package/dist/lib/otel/telemetry-alerts.js +43 -0
  75. package/dist/lib/otel/token-metrics.js +122 -0
  76. package/dist/lib/otel/trace-context.js +81 -0
  77. package/dist/lib/quality/judge-meta-eval.js +70 -0
  78. package/dist/lib/quality/judge-prompts.js +104 -0
  79. package/dist/lib/quality/judge-providers.js +193 -0
  80. package/dist/lib/quality/judge-transport.js +93 -0
  81. package/dist/lib/quality/llm-judge.js +170 -0
  82. package/dist/lib/quality/quality-budget.js +99 -0
  83. package/dist/lib/quality/quality-degradation.js +156 -0
  84. package/dist/lib/quality/quality-eval-handoff.js +74 -0
  85. package/dist/lib/quality/quality-evaluator.js +178 -0
  86. package/dist/lib/quality/quality-sampler.js +43 -0
  87. package/dist/lib/quality/quality-signals.js +150 -0
  88. package/dist/lib/runtime/categorizers.js +101 -0
  89. package/dist/lib/runtime/hook-input.js +16 -0
  90. package/dist/lib/runtime/hook-output.js +50 -0
  91. package/dist/lib/runtime/output-analyzer.js +160 -0
  92. package/dist/lib/runtime/run-handlers.js +32 -0
  93. package/dist/lib/runtime/tool-input.js +111 -0
  94. package/dist/lib/runtime/tool-output.js +44 -0
  95. package/dist/lib/runtime/unknown-tool.js +32 -0
  96. package/dist/lib/session/edit-ledger.js +29 -0
  97. package/dist/lib/session/forked-skill.js +39 -0
  98. package/dist/lib/session/handoffs.js +77 -0
  99. package/dist/lib/session/session-state.js +169 -0
  100. package/dist/lib/session/skill-rules.js +196 -0
  101. package/dist/lib/session/task-tracker.js +83 -0
  102. package/dist/lib/shipper/shipper-credentials.js +38 -0
  103. package/dist/lib/shipper/shipper-cursor.js +89 -0
  104. package/dist/lib/shipper/shipper-status.js +174 -0
  105. package/dist/lib/shipper/span-shipper.js +272 -0
  106. package/dist/lib/shipper/telemetry-shipper.js +39 -0
  107. package/dist/lib/transcript/agent-transcript-metrics.js +34 -0
  108. package/dist/lib/transcript/context-breakdown.js +134 -0
  109. package/dist/lib/transcript/context-history.js +69 -0
  110. package/dist/lib/transcript/context-tracker.js +226 -0
  111. package/dist/lib/transcript/message-count.js +49 -0
  112. package/dist/lib/transcript/model-ids.js +36 -0
  113. package/dist/lib/transcript/model-pricing.js +153 -0
  114. package/dist/lib/transcript/token-metrics-checkpoint.js +152 -0
  115. package/dist/lib/transcript/tool-call-durations.js +64 -0
  116. package/dist/lib/transcript/transcript-entry.js +67 -0
  117. package/dist/lib/transcript/transcript-fold.js +130 -0
  118. package/dist/lib/transcript/transcript-layout.js +39 -0
  119. package/dist/lib/transcript/transcript-parser.js +117 -0
  120. package/dist/runner/agent-context-4XTCLMLZ.js +23 -0
  121. package/dist/runner/agent-context-4XTCLMLZ.js.map +7 -0
  122. package/dist/runner/agent-file-budget-Q33ESBBE.js +68 -0
  123. package/dist/runner/agent-file-budget-Q33ESBBE.js.map +7 -0
  124. package/dist/runner/agent-transcript-metrics-W5CZZFMI.js +39 -0
  125. package/dist/runner/agent-transcript-metrics-W5CZZFMI.js.map +7 -0
  126. package/dist/runner/chunk-2NTNAJZE.js +49 -0
  127. package/dist/runner/chunk-2NTNAJZE.js.map +7 -0
  128. package/dist/runner/chunk-4KWBQTTG.js +78 -0
  129. package/dist/runner/chunk-4KWBQTTG.js.map +7 -0
  130. package/dist/runner/chunk-52RY6LQT.js +699 -0
  131. package/dist/runner/chunk-52RY6LQT.js.map +7 -0
  132. package/dist/runner/chunk-7OM5CYES.js +8695 -0
  133. package/dist/runner/chunk-7OM5CYES.js.map +7 -0
  134. package/dist/runner/chunk-7PEOKGYR.js +1568 -0
  135. package/dist/runner/chunk-7PEOKGYR.js.map +7 -0
  136. package/dist/runner/chunk-AGSGKELQ.js +126 -0
  137. package/dist/runner/chunk-AGSGKELQ.js.map +7 -0
  138. package/dist/runner/chunk-AVM7PJFW.js +12 -0
  139. package/dist/runner/chunk-AVM7PJFW.js.map +7 -0
  140. package/dist/runner/chunk-C3WHUMU5.js +178 -0
  141. package/dist/runner/chunk-C3WHUMU5.js.map +7 -0
  142. package/dist/runner/chunk-DGB4NSSD.js +157 -0
  143. package/dist/runner/chunk-DGB4NSSD.js.map +7 -0
  144. package/dist/runner/chunk-DNSTWC26.js +151 -0
  145. package/dist/runner/chunk-DNSTWC26.js.map +7 -0
  146. package/dist/runner/chunk-FDJJ3TYU.js +449 -0
  147. package/dist/runner/chunk-FDJJ3TYU.js.map +7 -0
  148. package/dist/runner/chunk-FGKYDQHZ.js +137 -0
  149. package/dist/runner/chunk-FGKYDQHZ.js.map +7 -0
  150. package/dist/runner/chunk-GG2I4TGI.js +582 -0
  151. package/dist/runner/chunk-GG2I4TGI.js.map +7 -0
  152. package/dist/runner/chunk-GNNKUMRF.js +60 -0
  153. package/dist/runner/chunk-GNNKUMRF.js.map +7 -0
  154. package/dist/runner/chunk-I7TD2QVR.js +118 -0
  155. package/dist/runner/chunk-I7TD2QVR.js.map +7 -0
  156. package/dist/runner/chunk-IJ4SLUBV.js +78 -0
  157. package/dist/runner/chunk-IJ4SLUBV.js.map +7 -0
  158. package/dist/runner/chunk-IY7AP7NA.js +32 -0
  159. package/dist/runner/chunk-IY7AP7NA.js.map +7 -0
  160. package/dist/runner/chunk-J3F3Z3EQ.js +177 -0
  161. package/dist/runner/chunk-J3F3Z3EQ.js.map +7 -0
  162. package/dist/runner/chunk-JLEO5OHU.js +104 -0
  163. package/dist/runner/chunk-JLEO5OHU.js.map +7 -0
  164. package/dist/runner/chunk-JRNNLOPR.js +168 -0
  165. package/dist/runner/chunk-JRNNLOPR.js.map +7 -0
  166. package/dist/runner/chunk-KGSA5JYP.js +82 -0
  167. package/dist/runner/chunk-KGSA5JYP.js.map +7 -0
  168. package/dist/runner/chunk-LBCZAYFR.js +125 -0
  169. package/dist/runner/chunk-LBCZAYFR.js.map +7 -0
  170. package/dist/runner/chunk-LHWRXY2G.js +41 -0
  171. package/dist/runner/chunk-LHWRXY2G.js.map +7 -0
  172. package/dist/runner/chunk-LQ2LGUYJ.js +41 -0
  173. package/dist/runner/chunk-LQ2LGUYJ.js.map +7 -0
  174. package/dist/runner/chunk-LYY6RCIE.js +158 -0
  175. package/dist/runner/chunk-LYY6RCIE.js.map +7 -0
  176. package/dist/runner/chunk-M4R4QIQH.js +41 -0
  177. package/dist/runner/chunk-M4R4QIQH.js.map +7 -0
  178. package/dist/runner/chunk-MC75VXMX.js +207 -0
  179. package/dist/runner/chunk-MC75VXMX.js.map +7 -0
  180. package/dist/runner/chunk-NKZU4RRG.js +104 -0
  181. package/dist/runner/chunk-NKZU4RRG.js.map +7 -0
  182. package/dist/runner/chunk-PJHWHJ3K.js +56 -0
  183. package/dist/runner/chunk-PJHWHJ3K.js.map +7 -0
  184. package/dist/runner/chunk-RIGVYJ2O.js +114 -0
  185. package/dist/runner/chunk-RIGVYJ2O.js.map +7 -0
  186. package/dist/runner/chunk-RWRGC7ZK.js +93 -0
  187. package/dist/runner/chunk-RWRGC7ZK.js.map +7 -0
  188. package/dist/runner/chunk-SRMAJQMV.js +54 -0
  189. package/dist/runner/chunk-SRMAJQMV.js.map +7 -0
  190. package/dist/runner/chunk-TRMFD36J.js +47 -0
  191. package/dist/runner/chunk-TRMFD36J.js.map +7 -0
  192. package/dist/runner/chunk-U4IOZYQ3.js +21 -0
  193. package/dist/runner/chunk-U4IOZYQ3.js.map +7 -0
  194. package/dist/runner/chunk-UEXDE3WP.js +83 -0
  195. package/dist/runner/chunk-UEXDE3WP.js.map +7 -0
  196. package/dist/runner/chunk-UW3GQZSM.js +50 -0
  197. package/dist/runner/chunk-UW3GQZSM.js.map +7 -0
  198. package/dist/runner/chunk-V2GSP6VR.js +46 -0
  199. package/dist/runner/chunk-V2GSP6VR.js.map +7 -0
  200. package/dist/runner/chunk-VOV4Y5VU.js +81 -0
  201. package/dist/runner/chunk-VOV4Y5VU.js.map +7 -0
  202. package/dist/runner/chunk-VT5T6OEI.js +65 -0
  203. package/dist/runner/chunk-VT5T6OEI.js.map +7 -0
  204. package/dist/runner/chunk-VUYVFWIN.js +12 -0
  205. package/dist/runner/chunk-VUYVFWIN.js.map +7 -0
  206. package/dist/runner/chunk-VVGOPPEN.js +36 -0
  207. package/dist/runner/chunk-VVGOPPEN.js.map +7 -0
  208. package/dist/runner/chunk-VXFSLM6P.js +14 -0
  209. package/dist/runner/chunk-VXFSLM6P.js.map +7 -0
  210. package/dist/runner/chunk-W3EK7JUT.js +26125 -0
  211. package/dist/runner/chunk-W3EK7JUT.js.map +7 -0
  212. package/dist/runner/chunk-WJHNCOUF.js +52 -0
  213. package/dist/runner/chunk-WJHNCOUF.js.map +7 -0
  214. package/dist/runner/chunk-WU7ANGCW.js +269 -0
  215. package/dist/runner/chunk-WU7ANGCW.js.map +7 -0
  216. package/dist/runner/chunk-X7XLMSZX.js +44 -0
  217. package/dist/runner/chunk-X7XLMSZX.js.map +7 -0
  218. package/dist/runner/chunk-XSO3B4QN.js +124 -0
  219. package/dist/runner/chunk-XSO3B4QN.js.map +7 -0
  220. package/dist/runner/chunk-YGFN3LN2.js +174 -0
  221. package/dist/runner/chunk-YGFN3LN2.js.map +7 -0
  222. package/dist/runner/chunk-YHYDBLVB.js +33 -0
  223. package/dist/runner/chunk-YHYDBLVB.js.map +7 -0
  224. package/dist/runner/compact-36NP3PKT.js +60 -0
  225. package/dist/runner/compact-36NP3PKT.js.map +7 -0
  226. package/dist/runner/getMachineId-bsd-AGENNHN6.js +42 -0
  227. package/dist/runner/getMachineId-bsd-AGENNHN6.js.map +7 -0
  228. package/dist/runner/getMachineId-bsd-I5WZGCL4.js +33 -0
  229. package/dist/runner/getMachineId-bsd-I5WZGCL4.js.map +7 -0
  230. package/dist/runner/getMachineId-bsd-ZXK225P7.js +33 -0
  231. package/dist/runner/getMachineId-bsd-ZXK225P7.js.map +7 -0
  232. package/dist/runner/getMachineId-darwin-47GDLEXL.js +42 -0
  233. package/dist/runner/getMachineId-darwin-47GDLEXL.js.map +7 -0
  234. package/dist/runner/getMachineId-darwin-5CRLMDD6.js +33 -0
  235. package/dist/runner/getMachineId-darwin-5CRLMDD6.js.map +7 -0
  236. package/dist/runner/getMachineId-darwin-ADG4I32N.js +33 -0
  237. package/dist/runner/getMachineId-darwin-ADG4I32N.js.map +7 -0
  238. package/dist/runner/getMachineId-linux-5KVS3T2M.js +27 -0
  239. package/dist/runner/getMachineId-linux-5KVS3T2M.js.map +7 -0
  240. package/dist/runner/getMachineId-linux-GDFB5GSO.js +34 -0
  241. package/dist/runner/getMachineId-linux-GDFB5GSO.js.map +7 -0
  242. package/dist/runner/getMachineId-linux-NQMWCRO3.js +27 -0
  243. package/dist/runner/getMachineId-linux-NQMWCRO3.js.map +7 -0
  244. package/dist/runner/getMachineId-unsupported-5PFIGMVX.js +18 -0
  245. package/dist/runner/getMachineId-unsupported-5PFIGMVX.js.map +7 -0
  246. package/dist/runner/getMachineId-unsupported-DW27K3ZX.js +18 -0
  247. package/dist/runner/getMachineId-unsupported-DW27K3ZX.js.map +7 -0
  248. package/dist/runner/getMachineId-unsupported-XV3FHTHD.js +25 -0
  249. package/dist/runner/getMachineId-unsupported-XV3FHTHD.js.map +7 -0
  250. package/dist/runner/getMachineId-win-5JVMW3EI.js +44 -0
  251. package/dist/runner/getMachineId-win-5JVMW3EI.js.map +7 -0
  252. package/dist/runner/getMachineId-win-SNESQF7R.js +35 -0
  253. package/dist/runner/getMachineId-win-SNESQF7R.js.map +7 -0
  254. package/dist/runner/getMachineId-win-UJYHSBM2.js +35 -0
  255. package/dist/runner/getMachineId-win-UJYHSBM2.js.map +7 -0
  256. package/dist/runner/git-commit-BA53DOJQ.js +30 -0
  257. package/dist/runner/git-commit-BA53DOJQ.js.map +7 -0
  258. package/dist/runner/hook-runner-JHH6PGKE.js +220 -0
  259. package/dist/runner/hook-runner-JHH6PGKE.js.map +7 -0
  260. package/dist/runner/judge-transport-R4TF5LEH.js +91 -0
  261. package/dist/runner/judge-transport-R4TF5LEH.js.map +7 -0
  262. package/dist/runner/mcp-status-QEUH2KGX.js +89 -0
  263. package/dist/runner/mcp-status-QEUH2KGX.js.map +7 -0
  264. package/dist/runner/notification-FKMBCSXF.js +69 -0
  265. package/dist/runner/notification-FKMBCSXF.js.map +7 -0
  266. package/dist/runner/post-tool-3MRHTBKH.js +192 -0
  267. package/dist/runner/post-tool-3MRHTBKH.js.map +7 -0
  268. package/dist/runner/post-tool-agent-BB34MNHI.js +370 -0
  269. package/dist/runner/post-tool-agent-BB34MNHI.js.map +7 -0
  270. package/dist/runner/post-tool-changelog-sync-OP2TT2I7.js +147 -0
  271. package/dist/runner/post-tool-changelog-sync-OP2TT2I7.js.map +7 -0
  272. package/dist/runner/post-tool-code-structure-LE7J2SC2.js +130 -0
  273. package/dist/runner/post-tool-code-structure-LE7J2SC2.js.map +7 -0
  274. package/dist/runner/post-tool-edit-ledger-IJMEYHKF.js +30 -0
  275. package/dist/runner/post-tool-edit-ledger-IJMEYHKF.js.map +7 -0
  276. package/dist/runner/post-tool-failure-XTH2I2Z7.js +111 -0
  277. package/dist/runner/post-tool-failure-XTH2I2Z7.js.map +7 -0
  278. package/dist/runner/post-tool-git-E46HZGZO.js +94 -0
  279. package/dist/runner/post-tool-git-E46HZGZO.js.map +7 -0
  280. package/dist/runner/post-tool-mcp-AMCDY5GH.js +144 -0
  281. package/dist/runner/post-tool-mcp-AMCDY5GH.js.map +7 -0
  282. package/dist/runner/post-tool-task-state-TLDOI33H.js +100 -0
  283. package/dist/runner/post-tool-task-state-TLDOI33H.js.map +7 -0
  284. package/dist/runner/pre-tool-SQE2FZQO.js +245 -0
  285. package/dist/runner/pre-tool-SQE2FZQO.js.map +7 -0
  286. package/dist/runner/pre-tool-agent-OZUPVFUI.js +218 -0
  287. package/dist/runner/pre-tool-agent-OZUPVFUI.js.map +7 -0
  288. package/dist/runner/quality-evaluator-XYNDKDRG.js +901 -0
  289. package/dist/runner/quality-evaluator-XYNDKDRG.js.map +7 -0
  290. package/dist/runner/session-end-3MJTDLLA.js +57 -0
  291. package/dist/runner/session-end-3MJTDLLA.js.map +7 -0
  292. package/dist/runner/session-start-5ZMCLKBS.js +352 -0
  293. package/dist/runner/session-start-5ZMCLKBS.js.map +7 -0
  294. package/dist/runner/shipper-status-MADX6SPG.js +37 -0
  295. package/dist/runner/shipper-status-MADX6SPG.js.map +7 -0
  296. package/dist/runner/span-shipper-4HQDHC47.js +3408 -0
  297. package/dist/runner/span-shipper-4HQDHC47.js.map +7 -0
  298. package/dist/runner/stop-RTKSIYJV.js +596 -0
  299. package/dist/runner/stop-RTKSIYJV.js.map +7 -0
  300. package/dist/runner/subagent-CBCG4OLZ.js +116 -0
  301. package/dist/runner/subagent-CBCG4OLZ.js.map +7 -0
  302. package/dist/runner/token-metrics-AD2RAFGM.js +31 -0
  303. package/dist/runner/token-metrics-AD2RAFGM.js.map +7 -0
  304. package/dist/runner/user-prompt-T5NZ2UJD.js +376 -0
  305. package/dist/runner/user-prompt-T5NZ2UJD.js.map +7 -0
  306. package/package.json +70 -5
@@ -0,0 +1,165 @@
1
+ /** Where an agent or skill is defined: active file, lazy file, builtin, skill-bundled, or settings-only. */
2
+ import { existsSync, readdirSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+ import { CLAUDE_HOME } from '../core/constants.js';
5
+ import { readdirOrEmpty } from '../core/file-utils.js';
6
+ import { AGENT_ATTRS, GENAI_AGENT_ATTRIBUTES } from '../otel/attributes.js';
7
+ import { promptLinkAttrs } from '../otel/trace-context.js';
8
+ import { readString } from '../runtime/tool-input.js';
9
+ import { resolveAgentName } from '../session/forked-skill.js';
10
+ export const BUILTIN_AGENTS = new Set([
11
+ 'Bash', 'general-purpose', 'statusline-setup', 'Explore', 'Plan',
12
+ 'claude-code-guide', 'code-reviewer', 'auto-error-resolver',
13
+ 'webscraping-research-analyst', 'typescript-type-validator',
14
+ ]);
15
+ const AGENTS_DIR = 'agents';
16
+ const SKILLS_DIR = 'skills';
17
+ const LAZY_AGENTS_DIR = 'lazy-agents';
18
+ const LAZY_SKILLS_DIR = 'lazy-skills';
19
+ const AGENT_FILE_EXT = '.md';
20
+ const SOURCE_LOOKUPS = {
21
+ agent: {
22
+ suffix: AGENT_FILE_EXT,
23
+ dirs: [
24
+ { dir: AGENTS_DIR, sourceType: 'active' },
25
+ { dir: LAZY_AGENTS_DIR, sourceType: 'lazy' },
26
+ ],
27
+ },
28
+ skill: {
29
+ suffix: '',
30
+ dirs: [
31
+ { dir: SKILLS_DIR, sourceType: 'active' },
32
+ { dir: LAZY_SKILLS_DIR, sourceType: 'lazy' },
33
+ ],
34
+ },
35
+ };
36
+ function findInSourceDirs(kind, name) {
37
+ const { suffix, dirs } = SOURCE_LOOKUPS[kind];
38
+ const entry = `${name}${suffix}`;
39
+ for (const { dir, sourceType } of dirs) {
40
+ if (existsSync(join(CLAUDE_HOME, dir, entry)))
41
+ return sourceType;
42
+ }
43
+ return undefined;
44
+ }
45
+ /** agent name → owning skill, built on first miss since the scan walks every skill directory. */
46
+ let skillAgentIndex = null;
47
+ /** A duplicate agent name across skills resolves in filesystem order, which is not stable; treat it as ambiguous. */
48
+ function buildSkillAgentIndex() {
49
+ const index = new Map();
50
+ const skillsDir = join(CLAUDE_HOME, SKILLS_DIR);
51
+ let skillNames;
52
+ try {
53
+ skillNames = readdirSync(skillsDir, { withFileTypes: true })
54
+ .filter(entry => entry.isDirectory())
55
+ .map(entry => entry.name);
56
+ }
57
+ catch {
58
+ return index;
59
+ }
60
+ for (const skillName of skillNames) {
61
+ const agentsDir = join(skillsDir, skillName, AGENTS_DIR);
62
+ for (const file of readdirOrEmpty(agentsDir)) {
63
+ // Extension folded so the index agrees with the case-insensitive existsSync lookups.
64
+ if (!file.toLowerCase().endsWith(AGENT_FILE_EXT))
65
+ continue;
66
+ const agentName = file.slice(0, -AGENT_FILE_EXT.length);
67
+ if (!index.has(agentName))
68
+ index.set(agentName, skillName);
69
+ }
70
+ }
71
+ return index;
72
+ }
73
+ /** Tests only. */
74
+ export function resetSkillAgentCache() {
75
+ skillAgentIndex = null;
76
+ }
77
+ const agentSourceCache = new Map();
78
+ /** Tests only. */
79
+ export function resetAgentSourceCache() {
80
+ agentSourceCache.clear();
81
+ }
82
+ function resolveAgentSource(agentName) {
83
+ const dirSource = findInSourceDirs('agent', agentName);
84
+ if (dirSource)
85
+ return { sourceType: dirSource };
86
+ if (BUILTIN_AGENTS.has(agentName))
87
+ return { sourceType: 'builtin' };
88
+ skillAgentIndex ??= buildSkillAgentIndex();
89
+ const parentSkill = skillAgentIndex.get(agentName);
90
+ return parentSkill ? { sourceType: 'skill', parentSkill } : { sourceType: 'settings' };
91
+ }
92
+ /** Priority: active file > lazy file > builtin > skill > settings. */
93
+ export function getAgentSourceType(agentName) {
94
+ const cached = agentSourceCache.get(agentName);
95
+ if (cached)
96
+ return cached;
97
+ const result = resolveAgentSource(agentName);
98
+ agentSourceCache.set(agentName, result);
99
+ return result;
100
+ }
101
+ /** Priority: active dir > lazy dir > settings. */
102
+ export function getSkillSourceType(skillName) {
103
+ return findInSourceDirs('skill', skillName) ?? 'settings';
104
+ }
105
+ /**
106
+ * Agent attribution for tool spans (agent-auditor Q6); absent fields contribute
107
+ * nothing. `agent_id` is the harness's per-run id and goes under the instance key,
108
+ * not `gen_ai.agent.id`, which is the stable `composeAgentId` identity.
109
+ */
110
+ export function agentAttribution(input) {
111
+ const agentName = resolveAgentName(input);
112
+ return {
113
+ ...(agentName ? { [GENAI_AGENT_ATTRIBUTES.AGENT_NAME]: agentName } : {}),
114
+ ...(input.agent_id ? { [AGENT_ATTRS.INSTANCE_ID]: input.agent_id } : {}),
115
+ };
116
+ }
117
+ /** What every span of a tool event carries: agent attribution plus the prompt link. Stamped once per event by its router. */
118
+ export function toolEventAttributes(input) {
119
+ return { ...agentAttribution(input), ...promptLinkAttrs(input.session_id) };
120
+ }
121
+ /** `source[:parentSkill]:type`, composed once so the pre- and post-tool spans cannot drift. */
122
+ export function composeAgentId(agentType, info) {
123
+ return info.parentSkill
124
+ ? `${info.sourceType}:${info.parentSkill}:${agentType}`
125
+ : `${info.sourceType}:${agentType}`;
126
+ }
127
+ /** Built once for both agent spans so neither drops a key: a finalize span without `source_type` made the dashboard count every invocation as 'other'. */
128
+ function agentIdentityAttributes(agentType, info) {
129
+ const agentId = composeAgentId(agentType, info);
130
+ return {
131
+ attrs: {
132
+ [GENAI_AGENT_ATTRIBUTES.AGENT_NAME]: agentType,
133
+ [GENAI_AGENT_ATTRIBUTES.AGENT_ID]: agentId,
134
+ [AGENT_ATTRS.SOURCE_TYPE]: info.sourceType,
135
+ ...(info.parentSkill ? { [AGENT_ATTRS.PARENT_SKILL]: info.parentSkill } : {}),
136
+ },
137
+ agentId,
138
+ };
139
+ }
140
+ /**
141
+ * Full invocation attributes built once for prepare and rebuilt in finalize (PostToolUse
142
+ * carries the same `tool_input`, so both calls produce the same attrs — no store needed).
143
+ * Identity attrs + per-call flags; call sites add the span-assigned invocation_id separately.
144
+ */
145
+ export function agentInvocationAttributes(agentType, info, toolInput) {
146
+ const { attrs: identityAttrs, agentId } = agentIdentityAttributes(agentType, info);
147
+ const description = readString(toolInput, 'description');
148
+ const requestedModel = readString(toolInput, 'model');
149
+ const isResume = !!readString(toolInput, 'resume');
150
+ const isBackground = toolInput.run_in_background === true;
151
+ return {
152
+ attrs: {
153
+ ...identityAttrs,
154
+ [AGENT_ATTRS.IS_RESUME]: isResume,
155
+ [AGENT_ATTRS.IS_BACKGROUND]: isBackground,
156
+ ...(requestedModel ? { [AGENT_ATTRS.REQUESTED_MODEL]: requestedModel } : {}),
157
+ ...(description ? { [AGENT_ATTRS.TASK_DESCRIPTION]: description } : {}),
158
+ },
159
+ agentId,
160
+ description,
161
+ requestedModel,
162
+ isResume,
163
+ isBackground,
164
+ };
165
+ }
@@ -0,0 +1,51 @@
1
+ /** Builds ExportedSpan records and appends them to the traces JSONL, so the shipper carries them like any other span. */
2
+ import { SpanKind, SpanStatusCode, TraceFlags } from '@opentelemetry/api';
3
+ import { NANOSECONDS_PER_MILLISECOND, TIME_MS } from '../core/units.js';
4
+ import { appendSpanRecords } from '../otel/file-exporters.js';
5
+ import { getServiceName, SERVICE_VERSION } from '../otel/service-identity.js';
6
+ const SCOPE = { name: 'claude-hooks-synth', version: SERVICE_VERSION };
7
+ /** Not `millisToHrTime`: that rounds, and a sub-nanosecond fraction must truncate out of the fixed64 field. */
8
+ function msToHrTime(ms) {
9
+ const sec = Math.floor(ms / TIME_MS.SECOND);
10
+ return [sec, Math.floor((ms - sec * TIME_MS.SECOND) * NANOSECONDS_PER_MILLISECOND)];
11
+ }
12
+ /** @internal Exported for testing. */
13
+ export function toReadableSpan(s) {
14
+ // Cross-trace links (OBP6): the target is in another trace, so isRemote, with real sampling flags.
15
+ const links = (s.links ?? []).map((l) => ({
16
+ context: {
17
+ traceId: l.traceId,
18
+ spanId: l.spanId,
19
+ traceFlags: l.traceFlags ?? TraceFlags.SAMPLED,
20
+ isRemote: true,
21
+ },
22
+ attributes: l.attributes,
23
+ droppedAttributesCount: 0,
24
+ }));
25
+ return {
26
+ traceId: s.traceId,
27
+ spanId: s.spanId,
28
+ parentSpanId: s.parentSpanId,
29
+ name: s.name,
30
+ // SpanKind defaults to INTERNAL: synth spans model in-process agent invocation (OBP6/F14).
31
+ kind: s.kind ?? SpanKind.INTERNAL,
32
+ startTime: msToHrTime(s.startTimeMs),
33
+ endTime: msToHrTime(s.endTimeMs),
34
+ duration: msToHrTime(Math.max(0, s.endTimeMs - s.startTimeMs)),
35
+ status: s.status ?? { code: SpanStatusCode.UNSET },
36
+ attributes: s.attributes,
37
+ events: [],
38
+ links,
39
+ resource: {
40
+ serviceName: getServiceName(),
41
+ serviceVersion: SERVICE_VERSION,
42
+ },
43
+ instrumentationScope: SCOPE,
44
+ };
45
+ }
46
+ /** Append to today's traces file; no-op for an empty batch. */
47
+ export function appendSynthSpans(spans) {
48
+ if (spans.length === 0)
49
+ return;
50
+ appendSpanRecords(spans.map(toReadableSpan));
51
+ }
@@ -0,0 +1,6 @@
1
+ /** Bounded metric labels: an unknown value becomes `other`, so a payload change cannot mint a new series. */
2
+ export const OTHER_LABEL = 'other';
3
+ /** `value` when `known` contains it; otherwise `other`. */
4
+ export function boundedLabel(value, known) {
5
+ return value && known.has(value) ? value : OTHER_LABEL;
6
+ }
@@ -0,0 +1,11 @@
1
+ /** First-match-wins rule tables. Imports nothing, so hot-path modules can use it. */
2
+ /** First rule with a matching substring or pattern wins; `fallback` if none match. */
3
+ export function matchCategory(value, rules, fallback) {
4
+ for (const rule of rules) {
5
+ if (rule.substrings.some(s => value.includes(s)))
6
+ return rule.category;
7
+ if (rule.pattern?.test(value))
8
+ return rule.category;
9
+ }
10
+ return fallback;
11
+ }
@@ -0,0 +1,19 @@
1
+ /** Child-process outcome classification shared by every handler that spawns one. */
2
+ const MAX_BUFFER_EXCEEDED_CODE = 'ERR_CHILD_PROCESS_STDIO_MAXBUFFER';
3
+ export function classifyExecError(error) {
4
+ if (!error || typeof error !== 'object')
5
+ return 'verdict';
6
+ const e = error;
7
+ // Checked before `killed`, which Node also sets on this error.
8
+ if (e.code === MAX_BUFFER_EXCEEDED_CODE)
9
+ return 'output-overflow';
10
+ if (e.killed === true || e.code === 'ETIMEDOUT')
11
+ return 'timeout';
12
+ if (e.code === 'ENOENT' || e.code === 'EACCES')
13
+ return 'not-found';
14
+ return 'verdict';
15
+ }
16
+ /** Resolved value of an `allSettled` result, or undefined when it rejected. */
17
+ export function settledValue(result) {
18
+ return result.status === 'fulfilled' ? result.value : undefined;
19
+ }
@@ -0,0 +1,22 @@
1
+ /** Config-dir helpers with no hooks/lib imports, safe for hot path and shipper alike. */
2
+ import { homedir } from 'node:os';
3
+ import { join } from 'node:path';
4
+ /** The Claude Code config directory; `CLAUDE_CONFIG_DIR` wins. */
5
+ export function claudeConfigDir() {
6
+ return process.env.CLAUDE_CONFIG_DIR ?? join(homedir(), '.claude');
7
+ }
8
+ const PROJECTS_SEPARATOR = '/projects/';
9
+ /**
10
+ * The config dir recovered from `transcript_path` (`<config-dir>/projects/<slug>/<id>.jsonl`)
11
+ * when `CLAUDE_CODE_SUBPROCESS_ENV_SCRUB=1` stripped `CLAUDE_CONFIG_DIR`; undefined when it is the default.
12
+ */
13
+ export function configDirFromTranscriptPath(transcriptPath, defaultConfigDir) {
14
+ if (!transcriptPath)
15
+ return undefined;
16
+ // Last occurrence: a slug never contains `/`, the config dir's path may.
17
+ const idx = transcriptPath.lastIndexOf(PROJECTS_SEPARATOR);
18
+ if (idx <= 0)
19
+ return undefined;
20
+ const candidate = transcriptPath.slice(0, idx);
21
+ return candidate !== defaultConfigDir ? candidate : undefined;
22
+ }
@@ -0,0 +1,171 @@
1
+ import { join } from 'node:path';
2
+ import { BYTES, DURATION_MS, TIME_MS } from './units.js';
3
+ // ---- Paths and entry points ----
4
+ export const CLAUDE_HOME = join(process.env.HOME ?? '', '.claude');
5
+ export const TELEMETRY_DIR = process.env.TELEMETRY_DIR || join(process.env.HOME ?? '', '.claude-history', 'telemetry');
6
+ /** `process.argv` index of the first argument after the script path, for every CLI entry point here. */
7
+ export const FIRST_CLI_ARG_INDEX = 2;
8
+ /** Detached hook-runner subcommands; `scripts/otel/ship-telemetry-backlog.py` hardcodes SHIP_TELEMETRY_ARG. */
9
+ export const SHIP_TELEMETRY_ARG = 'ship-telemetry';
10
+ /** Detached T2 quality evaluator; takes the queued record path. */
11
+ export const EVALUATE_QUALITY_ARG = 'evaluate-quality';
12
+ // ---- Hook runner contract ----
13
+ /** Runner hook type → the `hook_event_name` Claude Code sends on stdin; read by detached modes and the registration test. */
14
+ export const HOOK_EVENT_NAMES = {
15
+ 'session-start': 'SessionStart',
16
+ 'pre-tool': 'PreToolUse',
17
+ 'post-tool': 'PostToolUse',
18
+ 'stop': 'Stop',
19
+ 'user-prompt': 'UserPromptSubmit',
20
+ 'notification': 'Notification',
21
+ 'subagent-start': 'SubagentStart',
22
+ 'subagent-stop': 'SubagentStop',
23
+ 'post-tool-failure': 'PostToolUseFailure',
24
+ 'pre-compact': 'PreCompact',
25
+ 'post-compact': 'PostCompact',
26
+ 'session-end': 'SessionEnd',
27
+ };
28
+ /**
29
+ * 0: stdout reaches Claude only on SessionStart / UserPromptSubmit / UserPromptExpansion.
30
+ * 2: blocks the action; stderr reaches Claude. Any other non-zero fails open silently.
31
+ */
32
+ export const HOOK_EXIT = {
33
+ OK: 0,
34
+ NONBLOCKING_ERROR: 1,
35
+ BLOCKING: 2,
36
+ };
37
+ /** A detached mode blocks no Claude action; non-zero only marks a failed job for the launchd or shipper log. */
38
+ export const DETACHED_EXIT = {
39
+ OK: 0,
40
+ FAILED: 1,
41
+ };
42
+ /** Mirrors each hook's `timeout` in settings.json; Claude Code kills the process here, so graceful guards must fire first. */
43
+ export const HOOK_TIMEOUT_MS = DURATION_MS.FIFTEEN_SECONDS;
44
+ // ---- Timeouts, caps and thresholds ----
45
+ /** `git()` defaults to HOOK_PATH, under `HOOK_TIMEOUT_MS`, so an unnamed ceiling still beats the harness kill. */
46
+ export const GIT_TIMEOUT_MS = {
47
+ HOOK_PATH: DURATION_MS.FIVE_SECONDS,
48
+ /** The synchronous remote-url probe inside initTelemetry's resource build. */
49
+ REMOTE_PROBE: DURATION_MS.THREE_SECONDS,
50
+ };
51
+ export const THRESHOLDS = {
52
+ LARGE_OUTPUT_BYTES: 50000,
53
+ PROMPT_CONTEXT_TTL_MS: DURATION_MS.TEN_MINUTES,
54
+ /** Short negative TTL for `git remote get-url`: `git init` + `git remote add` can make a repo at any moment. */
55
+ GIT_REMOTE_MISS_TTL_MS: DURATION_MS.TEN_MINUTES,
56
+ /**
57
+ * Concurrent metrics POSTs (traces and logs send one body). 8 timed out the ingest and
58
+ * stalled the cursor; throughput scales linearly to 4. Override with
59
+ * `OTLP_MAX_CONCURRENT_POSTS`; 1 makes backfill accounting exact.
60
+ */
61
+ OTLP_MAX_CONCURRENT_POSTS: 4,
62
+ ERROR_MESSAGE_TRUNCATE: 500,
63
+ AGENT_TASK_DESCRIPTION_TRUNCATE: 200,
64
+ TASK_COMPLETION_RATIO: 0.85,
65
+ MAX_PATTERN_LENGTH: 200,
66
+ MAX_PROMPT_TEST_LENGTH: 2000,
67
+ MAX_JSON_SIZE_BYTES: 10_000_000,
68
+ PROMPT_PREVIEW_LENGTH: 500,
69
+ /** Larger content is not structure-scored: regex passes over a minified bundle cost hundreds of ms. */
70
+ CODE_STRUCTURE_SKIP_ABOVE_BYTES: 500 * BYTES.KB,
71
+ /** A 21-day diff of a busy repo exceeds Node's 1 MiB default. */
72
+ GIT_MAX_BUFFER_BYTES: 256 * BYTES.MB,
73
+ /** Bound on one message-count read; a 70 MB transcript is not worth buffering whole. */
74
+ MESSAGE_COUNT_MAX_READ_BYTES: 4 * BYTES.MB,
75
+ /** Larger subagent transcripts yield no measures rather than a slow hook; observed max 4.8 MB, p99 845 KB. */
76
+ AGENT_TRANSCRIPT_MAX_READ_BYTES: 8 * BYTES.MB,
77
+ };
78
+ export const FILE_LOCK = {
79
+ STALE_MS: DURATION_MS.FIVE_SECONDS,
80
+ /** Conservative, to survive process hangs; normal hold is milliseconds. */
81
+ BUDGET_STALE_MS: DURATION_MS.THIRTY_SECONDS,
82
+ /** Total wait across retries. Acquisition is fail-open, so waiting longer only stalls exit (H10). */
83
+ MAX_WAIT_MS: 250 * TIME_MS.MS,
84
+ MAX_RETRIES: 10,
85
+ /** First backoff; each retry doubles it up to MAX_DELAY_FACTOR× */
86
+ RETRY_DELAY_MS: 50 * TIME_MS.MS,
87
+ MAX_DELAY_FACTOR: 4,
88
+ BUDGET_RETRY_DELAY_MS: 25 * TIME_MS.MS,
89
+ BUDGET_MAX_RETRIES: 60,
90
+ LAST_SESSION_RETRY_DELAY_MS: 10 * TIME_MS.MS,
91
+ LAST_SESSION_MAX_RETRIES: 20,
92
+ };
93
+ export const SHIPPER_LIMITS = {
94
+ MAX_RECORDS_PER_BATCH: 1_000,
95
+ /**
96
+ * Source JSONL bytes per POST, every signal. Ingest accepts 10 MB, but each POST
97
+ * becomes one R2 object, and the drain under `cpu_ms = 500` cannot commit an
98
+ * object much past ~512 KB (`BYTES_PER_COMMIT` in obtool-ingest); a backfill's
99
+ * 800 KB–1.5 MB objects stalled it (TRC4). A single larger record still ships whole.
100
+ */
101
+ MAX_BYTES_PER_POST: 128 * BYTES.KB,
102
+ /** Per file per run; the remainder ships next run. */
103
+ MAX_BYTES_PER_RUN: 4 * BYTES.MB,
104
+ /** A longer line is discarded unread. Ingest's protobuf body limit, used as a proxy for the JSON line. */
105
+ MAX_BYTES_PER_LINE: 10 * BYTES.MB,
106
+ };
107
+ /** Per-call transcript scan cap in context-tracker.ts, head and tail alike; categorization cost is linear in it. */
108
+ export const TRANSCRIPT_SCAN_BYTES = 512 * BYTES.KB;
109
+ /** Labels built from runtime values are bounded; fixed labels need no cap. */
110
+ export const MAX_METRIC_LABEL_LENGTH = 64;
111
+ // ---- Identifiers, patterns and text ----
112
+ export const SPAN_ID_BYTES = 8;
113
+ export const TRACE_ID_BYTES = 16;
114
+ /** Short `truncate` suffix for bounded single-line values: console lines, status details, span attributes. */
115
+ export const ELLIPSIS = '…';
116
+ /** Characters of user-supplied text kept as a diagnostic preview (stdin payloads, web prompts). */
117
+ export const INPUT_PREVIEW_CHARS = 200;
118
+ /** Every command `isGitCommitCommand` accepts contains it, so routers pre-screen before loading `git-commit.js`. */
119
+ export const GIT_COMMIT_SUBCOMMAND = 'commit';
120
+ /** Both changelog routes need it in their path or command, so the router pre-screens before loading the handler. */
121
+ export const CHANGELOG_DIR_SEGMENT = 'docs/changelog/';
122
+ /** Transcript `message.model` on entries Claude Code writes itself rather than receiving from the API. */
123
+ export const SYNTHETIC_MODEL = '<synthetic>';
124
+ // ---- Tool names ----
125
+ export const MCP_TOOL_PREFIX = 'mcp__';
126
+ /** `KillShell` and `TaskOutput` belong here: background shells are tasks to the harness. */
127
+ export const TASK_TOOLS = {
128
+ KILL_SHELL: 'KillShell',
129
+ OUTPUT: 'TaskOutput',
130
+ CREATE: 'TaskCreate',
131
+ UPDATE: 'TaskUpdate',
132
+ LIST: 'TaskList',
133
+ GET: 'TaskGet',
134
+ STOP: 'TaskStop',
135
+ };
136
+ /**
137
+ * Every first-party tool except MCP, `Skill` and `Agent`/`Task`, by `integritystudio.tool.category`;
138
+ * the only list of builtin names. A name missing here loses its telemetry and counts under
139
+ * `integritystudio.tool.unknown`.
140
+ */
141
+ export const BUILTIN_TOOLS_BY_CATEGORY = {
142
+ file: ['Read', 'Write', 'Edit', 'MultiEdit'],
143
+ shell: ['Bash'],
144
+ search: ['Glob', 'Grep', 'LSP'],
145
+ web: ['WebFetch', 'WebSearch'],
146
+ planning: ['TodoWrite'],
147
+ notebook: ['NotebookEdit'],
148
+ interaction: ['EnterPlanMode', 'ExitPlanMode', 'AskUserQuestion', 'EndConversation', 'PushNotification', 'SendFeedback'],
149
+ 'task-management': [TASK_TOOLS.KILL_SHELL, TASK_TOOLS.OUTPUT, TASK_TOOLS.CREATE, TASK_TOOLS.UPDATE, TASK_TOOLS.LIST, TASK_TOOLS.GET, TASK_TOOLS.STOP],
150
+ discovery: ['ToolSearch'],
151
+ scheduling: ['ScheduleWakeup', 'Monitor', 'CronCreate', 'CronDelete', 'CronList'],
152
+ orchestration: ['Workflow', 'SendMessage', 'RemoteTrigger', 'SubagentHandback', 'ListAgents', 'SendToProject', 'SendToProjectContext'],
153
+ worktree: ['EnterWorktree', 'ExitWorktree'],
154
+ output: ['StructuredOutput', 'ReportFindings', 'Artifact', 'ArtifactData', 'ArtifactComments', 'ArtifactCheck', 'ShareOnboardingGuide', 'PublishPlugin'],
155
+ 'mcp-resource': ['ListMcpResourcesTool', 'ReadMcpResourceTool', 'ReadMcpResourceDirTool'],
156
+ other: ['DesignSync'],
157
+ };
158
+ export const BUILTIN_TOOLS = new Set(Object.values(BUILTIN_TOOLS_BY_CATEGORY).flat());
159
+ /** A subset of `BUILTIN_TOOLS`: a name only here would fail `handleBuiltinPostTool`'s guard. */
160
+ export const MCP_RESOURCE_TOOLS = new Set(BUILTIN_TOOLS_BY_CATEGORY['mcp-resource']);
161
+ export const EDIT_TOOLS = new Set(BUILTIN_TOOLS_BY_CATEGORY.file.filter((tool) => tool !== 'Read'));
162
+ export const TASK_STATE_TOOLS = new Set([TASK_TOOLS.CREATE, TASK_TOOLS.UPDATE]);
163
+ export const PLUGIN_TOOLS = new Set(['Skill']);
164
+ /** `Task` is the pre-rename name of `Agent`. */
165
+ export const AGENT_TOOLS = new Set(['Agent', 'Task']);
166
+ /** Tools that block on the user by contract; not the whole `interaction` category, the rest return immediately. */
167
+ export const USER_WAIT_TOOLS = new Set(['AskUserQuestion', 'ExitPlanMode']);
168
+ /** `TOOL_ATTRS.CATEGORY` for a tool with no `BUILTIN_TOOLS_BY_CATEGORY` row; the table's own `other` row is a real category. */
169
+ export const UNKNOWN_TOOL_CATEGORY = 'unknown';
170
+ /** `gen_ai.tool.name` when the payload or transcript names no tool, so the series never carries an empty label. */
171
+ export const UNKNOWN_TOOL_NAME = 'unknown';
@@ -0,0 +1,55 @@
1
+ /**
2
+ * Start `hook-runner.js <args>` as a detached, unref'd child. The environment is inherited
3
+ * (stripped by CLAUDE_CODE_SUBPROCESS_ENV_SCRUB). Pass a `commandPrefix` such as a doppler
4
+ * run command to inject secrets into the child's environment before the node invocation.
5
+ */
6
+ import { spawn } from 'node:child_process';
7
+ import { existsSync } from 'node:fs';
8
+ import { dirname, join } from 'node:path';
9
+ import { fileURLToPath } from 'node:url';
10
+ import { CLAUDE_HOME } from './constants.js';
11
+ import { findUp } from './file-utils.js';
12
+ import { errorSummary } from './format-utils.js';
13
+ const HOOK_RUNNER_FILE = 'hook-runner.js';
14
+ const INSTALLED_RUNNER_PATH = join(CLAUDE_HOME, 'hooks', 'dist', HOOK_RUNNER_FILE);
15
+ /** This build's own runner; running from source (tests) finds none and falls back. */
16
+ function hookRunnerPath() {
17
+ const ownBuildRunner = findUp(dirname(fileURLToPath(import.meta.url)), (dir) => {
18
+ const candidate = join(dir, HOOK_RUNNER_FILE);
19
+ return existsSync(candidate) ? candidate : null;
20
+ });
21
+ return ownBuildRunner ?? INSTALLED_RUNNER_PATH;
22
+ }
23
+ /**
24
+ * When `commandPrefix` is provided (e.g. `['doppler', 'run', '--project', 'p', '--config', 'c', '--']`),
25
+ * the full command becomes `commandPrefix[0] commandPrefix[1..] node hook-runner.js args`.
26
+ */
27
+ export function spawnDetachedRunner(args, commandPrefix) {
28
+ const runnerPath = hookRunnerPath();
29
+ if (!existsSync(runnerPath)) {
30
+ return { ok: false, reason: 'no-runner', detail: runnerPath };
31
+ }
32
+ try {
33
+ const nodeArgs = [runnerPath, ...args];
34
+ const fullArgs = commandPrefix
35
+ ? [...commandPrefix, process.execPath, ...nodeArgs]
36
+ : [process.execPath, ...nodeArgs];
37
+ const command = fullArgs[0];
38
+ const spawnArgs = fullArgs.slice(1);
39
+ const child = spawn(command, spawnArgs, {
40
+ detached: true,
41
+ stdio: 'ignore',
42
+ });
43
+ // Absorb async ENOENT/EPERM errors; a missing executable emits these after spawn()
44
+ // returns and would otherwise raise an uncaught exception in the Stop hook.
45
+ // Accepted trade-off: spawnDetachedRunner already returned ok:true, so the caller
46
+ // cannot distinguish this from a successful spawn. The binary is a system-level
47
+ // requirement; this listener only prevents a crash, not the silent evaluation drop.
48
+ child.on('error', () => { });
49
+ child.unref();
50
+ return { ok: true };
51
+ }
52
+ catch (error) {
53
+ return { ok: false, reason: 'spawn-failed', detail: errorSummary(error) };
54
+ }
55
+ }