@agent-watch-ai/edge 0.5.0 → 0.7.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 (298) hide show
  1. package/CHANGELOG.md +238 -7
  2. package/README.md +308 -8
  3. package/dist/billing/billing-mode.d.ts +37 -5
  4. package/dist/billing/billing-mode.js +28 -19
  5. package/dist/billing/constants/billing.constants.d.ts +0 -2
  6. package/dist/billing/constants/billing.constants.js +0 -2
  7. package/dist/billing/index.d.ts +2 -1
  8. package/dist/billing/index.js +1 -1
  9. package/dist/billing/session-billing.d.ts +3 -2
  10. package/dist/billing/session-billing.js +8 -8
  11. package/dist/billing/types/billing.types.d.ts +7 -0
  12. package/dist/capture/capture-env.d.ts +147 -0
  13. package/dist/capture/capture-env.js +301 -0
  14. package/dist/capture/captured-step.d.ts +88 -0
  15. package/dist/capture/captured-step.js +479 -0
  16. package/dist/capture/constants/capture.constants.d.ts +70 -0
  17. package/dist/capture/constants/capture.constants.js +72 -0
  18. package/dist/capture/launched-runs.d.ts +16 -0
  19. package/dist/capture/launched-runs.js +151 -0
  20. package/dist/capture/node.cjs +697 -0
  21. package/dist/capture/node.d.cts +32 -0
  22. package/dist/capture/python/sitecustomize.py +823 -0
  23. package/dist/capture/schemas/capture.schema.d.ts +35 -0
  24. package/dist/capture/schemas/capture.schema.js +31 -0
  25. package/dist/capture/types/capture.types.d.ts +20 -0
  26. package/dist/cli/constants/cli.constants.d.ts +2 -6
  27. package/dist/cli/constants/cli.constants.js +3 -7
  28. package/dist/cli/context.d.ts +19 -22
  29. package/dist/cli/context.js +23 -54
  30. package/dist/cli/doctor-run-capture.d.ts +13 -0
  31. package/dist/cli/doctor-run-capture.js +19 -0
  32. package/dist/cli/doctor.js +16 -67
  33. package/dist/cli/hook.d.ts +14 -0
  34. package/dist/cli/hook.js +40 -0
  35. package/dist/cli/index.d.ts +1 -1
  36. package/dist/cli/index.js +1 -1
  37. package/dist/cli/misc.js +10 -2
  38. package/dist/cli/replay.d.ts +33 -0
  39. package/dist/cli/replay.js +193 -0
  40. package/dist/cli/setup.d.ts +10 -2
  41. package/dist/cli/setup.js +154 -26
  42. package/dist/cli/status.js +45 -5
  43. package/dist/cli/toggle.js +10 -0
  44. package/dist/cli/types/cli.types.d.ts +15 -1
  45. package/dist/cli/uninstall.js +8 -22
  46. package/dist/cli.js +104 -17
  47. package/dist/config/config.d.ts +0 -2
  48. package/dist/config/config.js +0 -1
  49. package/dist/config/constants/config.constants.js +2 -0
  50. package/dist/config/events-transport.d.ts +15 -0
  51. package/dist/config/events-transport.js +29 -0
  52. package/dist/config/index.d.ts +2 -1
  53. package/dist/config/index.js +1 -0
  54. package/dist/config/root-config.d.ts +12 -0
  55. package/dist/config/root-config.js +24 -0
  56. package/dist/config/schemas/config.schema.d.ts +13 -0
  57. package/dist/config/schemas/config.schema.js +42 -6
  58. package/dist/config/types/config.types.d.ts +7 -0
  59. package/dist/core/index.d.ts +1 -1
  60. package/dist/core/index.js +1 -1
  61. package/dist/core/version.d.ts +9 -0
  62. package/dist/core/version.js +14 -0
  63. package/dist/core/which.d.ts +11 -0
  64. package/dist/core/which.js +18 -0
  65. package/dist/credentials/cloud-claim.d.ts +32 -0
  66. package/dist/credentials/cloud-claim.js +42 -0
  67. package/dist/credentials/constants/credentials.constants.d.ts +8 -1
  68. package/dist/credentials/constants/credentials.constants.js +9 -2
  69. package/dist/credentials/device-api.d.ts +15 -1
  70. package/dist/credentials/device-api.js +12 -1
  71. package/dist/credentials/sign-in.d.ts +27 -0
  72. package/dist/credentials/sign-in.js +31 -1
  73. package/dist/credentials/token-refresher.d.ts +5 -1
  74. package/dist/credentials/token-refresher.js +10 -2
  75. package/dist/events/constants/events.constants.d.ts +8 -2
  76. package/dist/events/constants/events.constants.js +7 -1
  77. package/dist/events/index.d.ts +2 -0
  78. package/dist/events/product-event.d.ts +10 -4
  79. package/dist/events/types/events.types.d.ts +6 -0
  80. package/dist/events/types/replay-progress.types.d.ts +26 -0
  81. package/dist/events/types/replay-progress.types.js +1 -0
  82. package/dist/events/types/repo-snapshot.types.d.ts +1 -4
  83. package/dist/events/types/repo-tree.types.d.ts +25 -0
  84. package/dist/events/types/repo-tree.types.js +1 -0
  85. package/dist/feature/ticket-candidates.d.ts +1 -1
  86. package/dist/git/checkout-root.d.ts +15 -0
  87. package/dist/git/checkout-root.js +18 -0
  88. package/dist/git/code-state.d.ts +2 -16
  89. package/dist/git/code-state.js +11 -12
  90. package/dist/git/constants/git.constants.d.ts +31 -11
  91. package/dist/git/constants/git.constants.js +36 -12
  92. package/dist/git/constants/tree.constants.d.ts +71 -0
  93. package/dist/git/constants/tree.constants.js +92 -0
  94. package/dist/git/fingerprint.d.ts +3 -6
  95. package/dist/git/fingerprint.js +5 -8
  96. package/dist/git/git-context.d.ts +1 -0
  97. package/dist/git/git-context.js +8 -3
  98. package/dist/git/index.d.ts +1 -2
  99. package/dist/git/index.js +1 -1
  100. package/dist/git/repo-snapshot.d.ts +13 -4
  101. package/dist/git/repo-snapshot.js +47 -9
  102. package/dist/git/repo-tree.d.ts +69 -0
  103. package/dist/git/repo-tree.js +130 -0
  104. package/dist/git/types/git.types.d.ts +5 -2
  105. package/dist/git/types/snapshot.types.d.ts +14 -0
  106. package/dist/pipeline/constants/pipeline.constants.d.ts +3 -0
  107. package/dist/pipeline/constants/pipeline.constants.js +3 -0
  108. package/dist/pipeline/hook-pipeline.js +112 -72
  109. package/dist/privacy/product-capture.js +36 -5
  110. package/dist/providers/antigravity/antigravity.capture.d.ts +2 -0
  111. package/dist/providers/antigravity/antigravity.capture.js +5 -0
  112. package/dist/providers/antigravity/antigravity.detect.js +8 -22
  113. package/dist/providers/antigravity/antigravity.provider.js +10 -3
  114. package/dist/providers/antigravity/constants/antigravity.constants.d.ts +1 -0
  115. package/dist/providers/antigravity/constants/antigravity.constants.js +1 -0
  116. package/dist/providers/claude/claude.adapter.js +9 -6
  117. package/dist/providers/claude/claude.detect.js +2 -17
  118. package/dist/providers/claude/claude.otel.d.ts +21 -3
  119. package/dist/providers/claude/claude.otel.js +216 -61
  120. package/dist/providers/claude/claude.provider.js +17 -1
  121. package/dist/providers/claude/claude.version.d.ts +9 -0
  122. package/dist/providers/claude/claude.version.js +28 -0
  123. package/dist/providers/claude/constants/claude.constants.d.ts +27 -0
  124. package/dist/providers/claude/constants/claude.constants.js +27 -0
  125. package/dist/providers/claude/constants/claude.otel.constants.d.ts +27 -0
  126. package/dist/providers/claude/constants/claude.otel.constants.js +45 -5
  127. package/dist/providers/claude/types/claude.types.d.ts +13 -0
  128. package/dist/providers/codex/codex.capture.d.ts +76 -0
  129. package/dist/providers/codex/codex.capture.js +454 -0
  130. package/dist/providers/codex/codex.detect.js +2 -4
  131. package/dist/providers/codex/codex.otel.d.ts +38 -2
  132. package/dist/providers/codex/codex.otel.js +50 -6
  133. package/dist/providers/codex/codex.provider.js +8 -0
  134. package/dist/providers/codex/codex.surface.d.ts +9 -0
  135. package/dist/{turns/codex-originator.js → providers/codex/codex.surface.js} +17 -3
  136. package/dist/providers/codex/codex.titles.d.ts +14 -0
  137. package/dist/providers/codex/codex.titles.js +35 -0
  138. package/dist/providers/codex/constants/codex.constants.d.ts +4 -0
  139. package/dist/providers/codex/constants/codex.constants.js +4 -0
  140. package/dist/providers/cursor/constants/cursor.constants.d.ts +17 -4
  141. package/dist/providers/cursor/constants/cursor.constants.js +25 -5
  142. package/dist/providers/cursor/cursor-mcp-memo.d.ts +34 -0
  143. package/dist/providers/cursor/cursor-mcp-memo.js +94 -0
  144. package/dist/providers/cursor/cursor.adapter.js +20 -82
  145. package/dist/providers/cursor/cursor.capture.d.ts +1 -0
  146. package/dist/providers/cursor/cursor.capture.js +4 -0
  147. package/dist/providers/cursor/cursor.detect.d.ts +5 -1
  148. package/dist/providers/cursor/cursor.detect.js +11 -26
  149. package/dist/providers/cursor/cursor.hooks.js +2 -2
  150. package/dist/providers/cursor/cursor.provider.js +16 -7
  151. package/dist/providers/cursor/cursor.titles.d.ts +14 -0
  152. package/dist/providers/cursor/cursor.titles.js +20 -0
  153. package/dist/providers/cursor/schemas/cursor.schema.d.ts +3 -3
  154. package/dist/providers/cursor/schemas/cursor.schema.js +5 -3
  155. package/dist/providers/gemini/constants/gemini.constants.d.ts +16 -0
  156. package/dist/providers/gemini/constants/gemini.constants.js +17 -0
  157. package/dist/providers/gemini/gemini.capture.d.ts +81 -0
  158. package/dist/providers/gemini/gemini.capture.js +210 -0
  159. package/dist/providers/gemini/gemini.detect.js +57 -24
  160. package/dist/providers/gemini/gemini.otel.d.ts +38 -2
  161. package/dist/providers/gemini/gemini.otel.js +56 -125
  162. package/dist/providers/gemini/gemini.provider.js +5 -0
  163. package/dist/providers/index.d.ts +1 -0
  164. package/dist/providers/index.js +1 -0
  165. package/dist/providers/provider.d.ts +8 -0
  166. package/dist/providers/provider.js +9 -0
  167. package/dist/providers/registry.d.ts +14 -0
  168. package/dist/providers/registry.js +14 -0
  169. package/dist/providers/shared/constants/hook-config.constants.d.ts +2 -0
  170. package/dist/providers/shared/constants/hook-config.constants.js +2 -0
  171. package/dist/providers/shared/constants/terminal-capture.constants.d.ts +6 -0
  172. package/dist/providers/shared/constants/terminal-capture.constants.js +6 -0
  173. package/dist/providers/shared/editor-paths.d.ts +8 -0
  174. package/dist/providers/shared/editor-paths.js +18 -0
  175. package/dist/providers/shared/hook-config.d.ts +5 -0
  176. package/dist/providers/shared/hook-config.js +39 -1
  177. package/dist/providers/shared/hooks-marker.d.ts +14 -0
  178. package/dist/providers/shared/hooks-marker.js +23 -0
  179. package/dist/providers/shared/install-record.d.ts +29 -0
  180. package/dist/providers/shared/install-record.js +52 -0
  181. package/dist/providers/shared/session-title-store.d.ts +23 -0
  182. package/dist/providers/shared/session-title-store.js +50 -0
  183. package/dist/providers/shared/terminal-capture.d.ts +41 -0
  184. package/dist/providers/shared/terminal-capture.js +109 -0
  185. package/dist/providers/shared/tooling.d.ts +21 -0
  186. package/dist/providers/shared/tooling.js +36 -1
  187. package/dist/providers/types/provider.types.d.ts +57 -4
  188. package/dist/replay/checkout-resolver.d.ts +29 -0
  189. package/dist/replay/checkout-resolver.js +69 -0
  190. package/dist/replay/codex-turns.d.ts +24 -0
  191. package/dist/replay/codex-turns.js +221 -0
  192. package/dist/replay/constants/replay.constants.d.ts +99 -0
  193. package/dist/replay/constants/replay.constants.js +102 -0
  194. package/dist/replay/describe.d.ts +10 -0
  195. package/dist/replay/describe.js +31 -0
  196. package/dist/replay/gemini-turns.d.ts +36 -0
  197. package/dist/replay/gemini-turns.js +192 -0
  198. package/dist/replay/machine.d.ts +34 -0
  199. package/dist/replay/machine.js +68 -0
  200. package/dist/replay/progress-event.d.ts +21 -0
  201. package/dist/replay/progress-event.js +45 -0
  202. package/dist/replay/replay-runner.d.ts +58 -0
  203. package/dist/replay/replay-runner.js +529 -0
  204. package/dist/replay/replay-scan.d.ts +83 -0
  205. package/dist/replay/replay-scan.js +170 -0
  206. package/dist/replay/replay-state.d.ts +108 -0
  207. package/dist/replay/replay-state.js +199 -0
  208. package/dist/replay/resume.d.ts +18 -0
  209. package/dist/replay/resume.js +34 -0
  210. package/dist/replay/start.d.ts +23 -0
  211. package/dist/replay/start.js +39 -0
  212. package/dist/replay/throttle.d.ts +35 -0
  213. package/dist/replay/throttle.js +41 -0
  214. package/dist/replay/transcript-turns.d.ts +35 -0
  215. package/dist/replay/transcript-turns.js +215 -0
  216. package/dist/replay/turn-event.d.ts +38 -0
  217. package/dist/replay/turn-event.js +116 -0
  218. package/dist/replay/types/replay.types.d.ts +162 -0
  219. package/dist/replay/types/replay.types.js +1 -0
  220. package/dist/replay/window.d.ts +28 -0
  221. package/dist/replay/window.js +41 -0
  222. package/dist/snapshot/branch-selection.d.ts +40 -23
  223. package/dist/snapshot/branch-selection.js +74 -42
  224. package/dist/snapshot/budget.js +2 -2
  225. package/dist/snapshot/constants/snapshot-stages.constants.d.ts +10 -0
  226. package/dist/snapshot/constants/snapshot-stages.constants.js +10 -0
  227. package/dist/snapshot/constants/snapshot.constants.d.ts +37 -4
  228. package/dist/snapshot/constants/snapshot.constants.js +37 -4
  229. package/dist/snapshot/index.d.ts +6 -1
  230. package/dist/snapshot/index.js +3 -1
  231. package/dist/snapshot/snapshot-event.d.ts +7 -0
  232. package/dist/snapshot/snapshot-event.js +8 -5
  233. package/dist/snapshot/snapshot-pipeline.js +89 -26
  234. package/dist/snapshot/snapshot-state.js +24 -2
  235. package/dist/snapshot/tree-event.d.ts +14 -0
  236. package/dist/snapshot/tree-event.js +91 -0
  237. package/dist/snapshot/tree-pipeline.d.ts +12 -0
  238. package/dist/snapshot/tree-pipeline.js +172 -0
  239. package/dist/snapshot/types/snapshot.types.d.ts +62 -2
  240. package/dist/storage/schemas/storage.schema.d.ts +2 -0
  241. package/dist/storage/schemas/storage.schema.js +6 -0
  242. package/dist/transport/constants/transport.constants.d.ts +5 -0
  243. package/dist/transport/constants/transport.constants.js +5 -0
  244. package/dist/transport/delivery-stats.d.ts +13 -1
  245. package/dist/transport/delivery-stats.js +18 -2
  246. package/dist/transport/delivery.d.ts +4 -3
  247. package/dist/transport/delivery.js +21 -7
  248. package/dist/transport/identity-delivery.d.ts +20 -0
  249. package/dist/transport/identity-delivery.js +41 -0
  250. package/dist/transport/index.d.ts +2 -0
  251. package/dist/transport/index.js +1 -0
  252. package/dist/transport/queue.js +40 -6
  253. package/dist/transport/types/delivery-flow.types.d.ts +7 -0
  254. package/dist/turns/claude-transcript.js +4 -12
  255. package/dist/turns/codex-transcript.d.ts +9 -0
  256. package/dist/turns/codex-transcript.js +27 -19
  257. package/dist/turns/constants/turns.constants.d.ts +13 -12
  258. package/dist/turns/constants/turns.constants.js +15 -19
  259. package/dist/turns/gemini-transcript.d.ts +19 -1
  260. package/dist/turns/gemini-transcript.js +29 -18
  261. package/dist/turns/index.d.ts +3 -4
  262. package/dist/turns/index.js +2 -3
  263. package/dist/turns/run-state.d.ts +71 -0
  264. package/dist/turns/run-state.js +114 -0
  265. package/dist/turns/tool-events.d.ts +11 -1
  266. package/dist/turns/tool-events.js +32 -9
  267. package/dist/turns/transcript.d.ts +15 -14
  268. package/dist/turns/transcript.js +23 -4
  269. package/dist/turns/turn-state.d.ts +49 -7
  270. package/dist/turns/turn-state.js +78 -10
  271. package/dist/turns/turn-summary.js +10 -6
  272. package/dist/turns/turn-tracker.d.ts +9 -16
  273. package/dist/turns/turn-tracker.js +162 -86
  274. package/dist/turns/types/transcript.types.d.ts +11 -1
  275. package/dist/turns/types/turn-provider.types.d.ts +33 -0
  276. package/dist/turns/types/turn-provider.types.js +1 -0
  277. package/dist/turns/types/turn-state.types.d.ts +9 -0
  278. package/dist/turns/types/turn-summary.types.d.ts +20 -6
  279. package/dist/turns/types/turn-tracker.types.d.ts +3 -1
  280. package/dist/turns/work-checkout.js +1 -2
  281. package/docs/AUDIT_PROMPT.md +10 -0
  282. package/docs/DATA_HANDLING.md +269 -32
  283. package/docs/ENTERPRISE_DEPLOYMENT.md +1 -1
  284. package/docs/PERFORMANCE.md +27 -0
  285. package/package.json +3 -2
  286. package/dist/events/canonical-event.d.ts +0 -10
  287. package/dist/events/canonical-event.js +0 -9
  288. package/dist/git/repository-root.d.ts +0 -39
  289. package/dist/git/repository-root.js +0 -131
  290. package/dist/git/types/repository-root.types.d.ts +0 -11
  291. package/dist/transport/transport.d.ts +0 -6
  292. package/dist/turns/codex-originator.d.ts +0 -11
  293. package/dist/turns/cursor-transcript.d.ts +0 -21
  294. package/dist/turns/cursor-transcript.js +0 -66
  295. package/dist/turns/native-session-titles.d.ts +0 -26
  296. package/dist/turns/native-session-titles.js +0 -102
  297. /package/dist/{git/types/repository-root.types.js → billing/types/billing.types.js} +0 -0
  298. /package/dist/{transport/transport.js → capture/types/capture.types.js} +0 -0
package/README.md CHANGED
@@ -59,7 +59,302 @@ Per-agent notes:
59
59
  * **OpenAI Codex** — new hooks must be trusted once: launch `codex`, type `/hooks`, approve the AgentWatch entries.
60
60
  * **Gemini CLI** — telemetry is written to `~/.gemini/.env` (Gemini 0.63+ does not apply the `settings.json` `env` block): `GEMINI_TELEMETRY_ENABLED` with `GEMINI_TELEMETRY_TARGET=local`, and the access token in `OTEL_EXPORTER_OTLP_HEADERS`; Gemini has no `otelHeadersHelper`. Gemini loads that file only in a trusted folder, and a project `.env` or `.gemini/.env` found first replaces it. The switch, target and endpoint are also set in the `settings.json` `telemetry` block, and `agentwatch status` warns when a project `.env` hides the token.
61
61
  * **Google Antigravity** — a turn is one *execution*: `PreInvocation`/`PostInvocation` bracket the model calls inside it and only `Stop` closes it. The prompt comes from `common.lastUserInput`; there is no user-prompt hook.
62
- * **Cursor** — the CLI emits shell hooks only; the full lifecycle exists in IDE sessions. Cloud agents need a committed `.cursor/hooks.json` and the package installed in the cloud environment. Accepted tab edits (`afterTabFileEdit`) are monitored; high-frequency `beforeTabFileRead` is ignored.
62
+ * **Cursor** — the CLI emits shell hooks only; the full lifecycle exists in IDE sessions. Cloud agents need a committed `.cursor/hooks.json` and the package installed in the cloud environment. Tab completions (`afterTabFileEdit`, `beforeTabFileRead`) are not hooked: they fire on every accept and belong to no conversation. Background agent turns report surface `cloud`. Cursor cost comes from the Cursor Admin API connection in Integrations.
63
+
64
+ ---
65
+
66
+ ## Claude Code cloud sessions
67
+
68
+ Sessions at claude.ai/code (and `claude --cloud`) run in a fresh VM per session, and that VM never
69
+ reads `~/.claude/settings.json`. So the hooks `agentwatch setup` writes there do not run in the cloud. A
70
+ cloud session runs hooks from two places only: the repository's committed `.claude/settings.json`
71
+ (any plan), and the organization's server-managed settings (Team and Enterprise).
72
+
73
+ ### Any plan: setup script and committed hooks
74
+
75
+ Repository hooks run only in a session with **one** repository that is not a Project thread. Three
76
+ steps, all needed:
77
+
78
+ **1. Environment setup script** (in the environment dialog). It runs as root before the environment's
79
+ variables are set, so the install key has to be written into the script itself:
80
+
81
+ ```bash
82
+ npm install -g @agent-watch-ai/edge
83
+ mkdir -p ~/.claude
84
+ NODE_USE_ENV_PROXY=1 agentwatch setup --token YOUR_INSTALL_KEY \
85
+ --developer-email you@company.com --developer-name "Your Name" --no-replay || true
86
+ ```
87
+
88
+ * `mkdir -p ~/.claude`: without it, setup can find no Claude Code yet, exits 0 and writes nothing.
89
+ * `--developer-email` and `--developer-name`: the VM's git identity is `Claude <noreply@anthropic.com>`,
90
+ and without these flags every turn would be labelled with that name.
91
+ * `|| true`: a setup script that exits non-zero stops the session from starting. A failed setup
92
+ must not do that.
93
+ * Use a **personal** environment. Anyone who uses an environment can read its setup script, and
94
+ the snapshot bakes in one developer's email. In a shared organization environment, every
95
+ member's work would be reported as that one developer.
96
+
97
+ **2. Network access: Custom**, with `api.agent-watch.ai` on the allowed domains list and "Also
98
+ include default list of common package managers" checked (npm needs it). On the default Trusted
99
+ level the gateway is refused and every turn stays queued.
100
+
101
+ **3. Commit the hooks** as `.claude/settings.json` in the repository. Merge them with any hooks
102
+ already there:
103
+
104
+ ```json
105
+ {
106
+ "hooks": {
107
+ "SessionStart": [{ "hooks": [{ "type": "command", "timeout": 30, "command": "[ \"$CLAUDE_CODE_REMOTE\" = true ] && command -v agentwatch >/dev/null || exit 0; NODE_USE_ENV_PROXY=1 NODE_NO_WARNINGS=1 exec agentwatch hook --agent claude" }] }],
108
+ "SessionEnd": [{ "hooks": [{ "type": "command", "timeout": 30, "command": "[ \"$CLAUDE_CODE_REMOTE\" = true ] && command -v agentwatch >/dev/null || exit 0; NODE_USE_ENV_PROXY=1 NODE_NO_WARNINGS=1 exec agentwatch hook --agent claude" }] }],
109
+ "UserPromptSubmit": [{ "hooks": [{ "type": "command", "timeout": 30, "command": "[ \"$CLAUDE_CODE_REMOTE\" = true ] && command -v agentwatch >/dev/null || exit 0; NODE_USE_ENV_PROXY=1 NODE_NO_WARNINGS=1 exec agentwatch hook --agent claude" }] }],
110
+ "PreToolUse": [{ "matcher": "*", "hooks": [{ "type": "command", "timeout": 30, "command": "[ \"$CLAUDE_CODE_REMOTE\" = true ] && command -v agentwatch >/dev/null || exit 0; NODE_USE_ENV_PROXY=1 NODE_NO_WARNINGS=1 exec agentwatch hook --agent claude" }] }],
111
+ "PostToolUse": [{ "matcher": "*", "hooks": [{ "type": "command", "timeout": 30, "command": "[ \"$CLAUDE_CODE_REMOTE\" = true ] && command -v agentwatch >/dev/null || exit 0; NODE_USE_ENV_PROXY=1 NODE_NO_WARNINGS=1 exec agentwatch hook --agent claude" }] }],
112
+ "PostToolUseFailure": [{ "matcher": "*", "hooks": [{ "type": "command", "timeout": 30, "command": "[ \"$CLAUDE_CODE_REMOTE\" = true ] && command -v agentwatch >/dev/null || exit 0; NODE_USE_ENV_PROXY=1 NODE_NO_WARNINGS=1 exec agentwatch hook --agent claude" }] }],
113
+ "PermissionRequest": [{ "matcher": "*", "hooks": [{ "type": "command", "timeout": 30, "command": "[ \"$CLAUDE_CODE_REMOTE\" = true ] && command -v agentwatch >/dev/null || exit 0; NODE_USE_ENV_PROXY=1 NODE_NO_WARNINGS=1 exec agentwatch hook --agent claude" }] }],
114
+ "Stop": [{ "hooks": [{ "type": "command", "timeout": 30, "command": "[ \"$CLAUDE_CODE_REMOTE\" = true ] && command -v agentwatch >/dev/null || exit 0; NODE_USE_ENV_PROXY=1 NODE_NO_WARNINGS=1 exec agentwatch hook --agent claude" }] }],
115
+ "SubagentStart": [{ "hooks": [{ "type": "command", "timeout": 30, "command": "[ \"$CLAUDE_CODE_REMOTE\" = true ] && command -v agentwatch >/dev/null || exit 0; NODE_USE_ENV_PROXY=1 NODE_NO_WARNINGS=1 exec agentwatch hook --agent claude" }] }],
116
+ "SubagentStop": [{ "hooks": [{ "type": "command", "timeout": 30, "command": "[ \"$CLAUDE_CODE_REMOTE\" = true ] && command -v agentwatch >/dev/null || exit 0; NODE_USE_ENV_PROXY=1 NODE_NO_WARNINGS=1 exec agentwatch hook --agent claude" }] }]
117
+ }
118
+ }
119
+ ```
120
+
121
+ The guard makes the file a no-op everywhere except a cloud session (`CLAUDE_CODE_REMOTE=true`) that has
122
+ Edge installed. So a teammate's laptop, which reports through its own user-level hooks, is not
123
+ counted twice. `NODE_USE_ENV_PROXY=1` (Node 22.21+ or 24+) makes Node's `fetch` honour the
124
+ session's `HTTPS_PROXY`, which it otherwise ignores. Without it, records stay queued.
125
+
126
+ Known limits:
127
+
128
+ * **Not covered**: a session with several repositories reads only `enabledPlugins` and
129
+ `extraKnownMarketplaces` from each repository's settings, so no hooks run. A thread inside a
130
+ claude.ai Project reads no repository hooks or `env` at all.
131
+ * **Cost comes from the session transcript only** (`usage_status: provisional`). Telemetry export
132
+ variables never apply from a repository's `.claude/settings.json`, and the user settings file that
133
+ `setup` configures them in is not read. So there is no `llm.call` ledger for these turns.
134
+ * **A turn is sent when it ends.** If the gateway cannot be reached at that moment, the turn waits
135
+ in the queue on the VM's disk and goes with the next turn. When the session's VM is reclaimed,
136
+ whatever is still queued is lost.
137
+ * **The install key lives in the environment's setup script**, readable by anyone who can use that
138
+ environment. Rotating it means editing the script, which also rebuilds the environment's cache.
139
+
140
+ ### Team and Enterprise: server-managed settings and a cloud session key (experimental)
141
+
142
+ Not yet run in a real cloud session. Until it has been, use the any-plan path above as the
143
+ fallback.
144
+
145
+ Every cloud VM claims a device of its own, for the developer signed in to the session, with no
146
+ per-developer setup and no install key. Server-managed settings reach every cloud session,
147
+ multi-repository ones included, with no repository file.
148
+
149
+ **1. Generate the cloud session key.** An Agent Watch admin opens **Settings** and generates the
150
+ organization's cloud session key. Settings shows this block once, with your organization's id and
151
+ private key in place of the placeholders:
152
+
153
+ ```json
154
+ {
155
+ "env": {
156
+ "AGENTWATCH_CLOUD_ORGANIZATION": "YOUR_ORGANIZATION_ID",
157
+ "AGENTWATCH_CLOUD_KEY": "YOUR_CLOUD_SESSION_KEY",
158
+ "CLAUDE_CODE_ENABLE_TELEMETRY": "1",
159
+ "OTEL_LOGS_EXPORTER": "otlp",
160
+ "OTEL_METRICS_EXPORTER": "none",
161
+ "OTEL_TRACES_EXPORTER": "none",
162
+ "OTEL_EXPORTER_OTLP_PROTOCOL": "http/json",
163
+ "OTEL_EXPORTER_OTLP_ENDPOINT": "https://api.agent-watch.ai/v1/otlp",
164
+ "OTEL_LOG_USER_PROMPTS": "0",
165
+ "OTEL_LOG_TOOL_DETAILS": "0",
166
+ "OTEL_LOG_TOOL_CONTENT": "0"
167
+ },
168
+ "otelHeadersHelper": "command -v agentwatch >/dev/null || { echo '{}'; exit 0; }; NODE_USE_ENV_PROXY=1 NODE_NO_WARNINGS=1 exec agentwatch otel-headers",
169
+ "hooks": {
170
+ "SessionStart": [
171
+ {
172
+ "matcher": "startup|resume",
173
+ "hooks": [
174
+ {
175
+ "type": "command",
176
+ "command": "[ \"$CLAUDE_CODE_REMOTE\" = true ] || exit 0; NODE_USE_ENV_PROXY=1 npx -y @agent-watch-ai/edge setup --cloud --no-replay >>/tmp/agentwatch-bootstrap.log 2>&1 || true"
177
+ }
178
+ ]
179
+ },
180
+ {
181
+ "hooks": [
182
+ {
183
+ "type": "command",
184
+ "timeout": 30,
185
+ "command": "[ \"$CLAUDE_CODE_REMOTE\" = true ] && command -v agentwatch >/dev/null || exit 0; NODE_USE_ENV_PROXY=1 NODE_NO_WARNINGS=1 exec agentwatch hook --agent claude"
186
+ }
187
+ ]
188
+ }
189
+ ],
190
+ "SessionEnd": [
191
+ {
192
+ "hooks": [
193
+ {
194
+ "type": "command",
195
+ "timeout": 30,
196
+ "command": "[ \"$CLAUDE_CODE_REMOTE\" = true ] && command -v agentwatch >/dev/null || exit 0; NODE_USE_ENV_PROXY=1 NODE_NO_WARNINGS=1 exec agentwatch hook --agent claude"
197
+ }
198
+ ]
199
+ }
200
+ ],
201
+ "UserPromptSubmit": [
202
+ {
203
+ "hooks": [
204
+ {
205
+ "type": "command",
206
+ "timeout": 30,
207
+ "command": "[ \"$CLAUDE_CODE_REMOTE\" = true ] && command -v agentwatch >/dev/null || exit 0; NODE_USE_ENV_PROXY=1 NODE_NO_WARNINGS=1 exec agentwatch hook --agent claude"
208
+ }
209
+ ]
210
+ }
211
+ ],
212
+ "PreToolUse": [
213
+ {
214
+ "matcher": "*",
215
+ "hooks": [
216
+ {
217
+ "type": "command",
218
+ "timeout": 30,
219
+ "command": "[ \"$CLAUDE_CODE_REMOTE\" = true ] && command -v agentwatch >/dev/null || exit 0; NODE_USE_ENV_PROXY=1 NODE_NO_WARNINGS=1 exec agentwatch hook --agent claude"
220
+ }
221
+ ]
222
+ }
223
+ ],
224
+ "PostToolUse": [
225
+ {
226
+ "matcher": "*",
227
+ "hooks": [
228
+ {
229
+ "type": "command",
230
+ "timeout": 30,
231
+ "command": "[ \"$CLAUDE_CODE_REMOTE\" = true ] && command -v agentwatch >/dev/null || exit 0; NODE_USE_ENV_PROXY=1 NODE_NO_WARNINGS=1 exec agentwatch hook --agent claude"
232
+ }
233
+ ]
234
+ }
235
+ ],
236
+ "PostToolUseFailure": [
237
+ {
238
+ "matcher": "*",
239
+ "hooks": [
240
+ {
241
+ "type": "command",
242
+ "timeout": 30,
243
+ "command": "[ \"$CLAUDE_CODE_REMOTE\" = true ] && command -v agentwatch >/dev/null || exit 0; NODE_USE_ENV_PROXY=1 NODE_NO_WARNINGS=1 exec agentwatch hook --agent claude"
244
+ }
245
+ ]
246
+ }
247
+ ],
248
+ "PermissionRequest": [
249
+ {
250
+ "matcher": "*",
251
+ "hooks": [
252
+ {
253
+ "type": "command",
254
+ "timeout": 30,
255
+ "command": "[ \"$CLAUDE_CODE_REMOTE\" = true ] && command -v agentwatch >/dev/null || exit 0; NODE_USE_ENV_PROXY=1 NODE_NO_WARNINGS=1 exec agentwatch hook --agent claude"
256
+ }
257
+ ]
258
+ }
259
+ ],
260
+ "Stop": [
261
+ {
262
+ "hooks": [
263
+ {
264
+ "type": "command",
265
+ "timeout": 30,
266
+ "command": "[ \"$CLAUDE_CODE_REMOTE\" = true ] && command -v agentwatch >/dev/null || exit 0; NODE_USE_ENV_PROXY=1 NODE_NO_WARNINGS=1 exec agentwatch hook --agent claude"
267
+ }
268
+ ]
269
+ }
270
+ ],
271
+ "SubagentStart": [
272
+ {
273
+ "hooks": [
274
+ {
275
+ "type": "command",
276
+ "timeout": 30,
277
+ "command": "[ \"$CLAUDE_CODE_REMOTE\" = true ] && command -v agentwatch >/dev/null || exit 0; NODE_USE_ENV_PROXY=1 NODE_NO_WARNINGS=1 exec agentwatch hook --agent claude"
278
+ }
279
+ ]
280
+ }
281
+ ],
282
+ "SubagentStop": [
283
+ {
284
+ "hooks": [
285
+ {
286
+ "type": "command",
287
+ "timeout": 30,
288
+ "command": "[ \"$CLAUDE_CODE_REMOTE\" = true ] && command -v agentwatch >/dev/null || exit 0; NODE_USE_ENV_PROXY=1 NODE_NO_WARNINGS=1 exec agentwatch hook --agent claude"
289
+ }
290
+ ]
291
+ }
292
+ ]
293
+ }
294
+ }
295
+ ```
296
+
297
+ The block holds everything: the claim, the hooks that send each turn, and Claude Code's usage
298
+ export. The hooks do nothing outside a cloud session. In one, `npx` installs Edge on the VM and runs
299
+ `agentwatch setup --cloud`, which claims the device. Its output goes to
300
+ `/tmp/agentwatch-bootstrap.log`, not into the session.
301
+
302
+ **2. Paste it into managed settings**, in **Organization settings > Claude Code > Managed settings**
303
+ on claude.ai. This needs the Team or Enterprise plan and the Owner or Primary Owner role in your
304
+ Claude organization. If the organization already has managed settings, the two have to be combined.
305
+
306
+ No setup script is needed. Do not run `agentwatch setup` in one: its filesystem is snapshotted and
307
+ reused by later sessions, and every VM would then share one device.
308
+
309
+ **What `agentwatch setup --cloud` does.** Only in a cloud session (`CLAUDE_CODE_REMOTE=true`) with
310
+ no Agent Watch credential yet:
311
+
312
+ * It reads the organization id and key from the managed `env` above, and the developer's email from
313
+ the session's Claude account (`oauthAccount.emailAddress` in `~/.claude.json`). Never git's
314
+ `noreply@anthropic.com`: without an account email it installs nothing and logs one line saying so.
315
+ * It signs a claim with the key (Node's built-in Ed25519), trades it for a device of this VM's own,
316
+ and stores it the way `setup` does. Every VM is its own device, and each refreshes on its own.
317
+ * On `resume`, or anywhere a credential is already present, it returns at once, before `npx`
318
+ installs anything.
319
+ * It always exits 0: a refused claim or an unreachable Agent Watch never stops the session, and
320
+ turns stay queued on the VM.
321
+
322
+ Every member of the organization can read the key: it is in the approval dialog and in the settings
323
+ cache on each member's machine. Generating a new key in Settings replaces it at once; devices
324
+ already claimed keep working until they expire or are revoked.
325
+
326
+ **Never copy `~/.agentwatch` between VMs.** A raw copy carries the first VM's `installationId` (and,
327
+ from an install-key setup, its `token`), so two VMs would fight over one device. Let each VM claim
328
+ its own.
329
+
330
+ **What this does on laptops.** Server-managed settings apply wherever someone signs in to the
331
+ organization, laptops included:
332
+
333
+ * **The hooks do nothing there.** Each one exits at once outside a cloud session, before `npx` or
334
+ `agentwatch` runs. A laptop with Edge keeps reporting through its own user-level hooks, once.
335
+ * **The telemetry `env` applies to every member.** Every member's Claude Code exports its usage
336
+ logs (token counts, model, cost; never prompt text or tool content) to `api.agent-watch.ai`:
337
+ * On a laptop with Edge, the export carries that machine's credential and lands in the
338
+ organization's Agent Watch account. Edge already sends it there.
339
+ * On a laptop without Edge, the export still leaves the machine and reaches Agent Watch. It
340
+ has no credential, so the gateway refuses it.
341
+ * Admins who do not want that should take `CLAUDE_CODE_ENABLE_TELEMETRY`, the `OTEL_*` values and
342
+ `otelHeadersHelper` out of the block, and keep the two `AGENTWATCH_CLOUD_*` values. The hooks
343
+ then report cloud turns with cost from the transcript only.
344
+ * **Each member approves once.** Hooks, `otelHeadersHelper` and `OTEL_EXPORTER_OTLP_ENDPOINT` need a
345
+ one-time security approval in an interactive session. Declining it exits Claude Code.
346
+ Non-interactive runs apply the settings for that run without asking. The docs do not say which
347
+ of the two a cloud session at claude.ai/code is, so that is not yet verified.
348
+
349
+ **The network step.** No managed setting can add a domain to a cloud environment's allowlist. Each
350
+ environment needs network access **Custom**, with `api.agent-watch.ai` and "Also include default
351
+ list of common package managers" (`npx` needs npm). An Owner can do it once for everyone:
352
+ create an organization-shared environment with those settings on the **Cloud environments** admin
353
+ page, and make it the organization's default environment. Otherwise each developer sets it on
354
+ their own environment.
355
+
356
+ The cloud documentation behind each of these points, and the container runs that tested them, are in
357
+ [docs/CLAUDE_CODE_CLOUD.md](https://github.com/agent-watch-ai/agent-watch-edge/blob/main/docs/CLAUDE_CODE_CLOUD.md).
63
358
 
64
359
  ---
65
360
 
@@ -87,9 +382,12 @@ agentwatch otel-headers # print OTel headers f
87
382
  | `--allow-custom-endpoint` | Trust the origin of this run's `--endpoint` when it is outside the Agent Watch hosts, such as a self-hosted backend. Only that origin is stored, in `customEndpoints`, and `status` and `doctor` show it. A re-run naming an origin already trusted needs no flag. Without it, setup refuses such a URL and writes nothing, and a config that names one sends nothing there: records stay queued and `doctor` names the fix. A config written before this release keeps its backends: they are added to `customEndpoints` once, on first load. A native exporter AgentWatch wrote into an agent's own config that points at a refused host is removed by `setup`, by `doctor`, and by the hooks at most once a day; `otel-headers` gives Claude Code's exporter the bearer only when it sends to the configured, allowed host. TLS is still checked against the system trust store, with no pinning | off |
88
383
  | `--token <token>` | Bearer token for the backend | — |
89
384
  | `--developer-email <email>` | Identity on turn summaries, and what per-developer budgets key on. Setup refuses to write a config when neither this flag nor git names a developer | `git config user.email` |
90
- | `--root <path>` | File a second identity under a project root, so one machine can report to two tenants (needs its own `--token`) | — |
385
+ | `--root <path>` | With setup or replay, use the identity under this project root; setup needs its own `--token` | — |
386
+ | `--machine` | With replay, use the machine identity regardless of the shell directory | shell directory |
91
387
  | `--otel <signals>` | Signals the agents export: `logs`, `traces`, `metrics`, `all`, `none` | `logs` |
92
- | `--agent <id>` | Limit the command to one agent (`claude`, `codex`, `cursor`, `gemini`, `antigravity`) | all detected |
388
+ | `--replay-days <n>` | How many days of earlier Claude Code, Codex and Gemini CLI sessions the machine's one automatic setup replay covers; later setup runs never repeat it automatically (see "What reaches the backend") | `30` |
389
+ | `--no-replay` | Do not replay earlier sessions | replays |
390
+ | `--agent <id>` | With `setup`, `uninstall` and `hook`: limit the command to one agent (`claude`, `codex`, `cursor`, `gemini`, `antigravity`). Setup still updates the exporter of every agent installed before, since signals and endpoint are machine-wide. `off`, `on`, `doctor` and `replay` refuse it; `status` ignores it | all detected |
93
391
  | `--dry-run` | With `hook`: print the events instead of sending them | `false` |
94
392
  | `--json` | With `doctor`: machine-readable output | `false` |
95
393
  | `--verbose` | Diagnostic logs on stderr | `false` |
@@ -105,10 +403,10 @@ One global file: `~/.agentwatch/config.json`, written by `agentwatch setup`.
105
403
 
106
404
  Prompt text, tool inputs, tool outputs and session titles are off by default. Turning one on takes **two** things —
107
405
  the global `contentCaptureConsent` marker *and* the individual flag. The marker alone enables
108
- nothing; a flag alone collects nothing. With all of them off a prompt or response is recorded only
109
- as a length and a SHA-256, so turn counts and cost attribution work without the text. Ticket keys
110
- named in the opening prompt are extracted on the machine and sent as `prompt_jira_ids`, unfiltered
111
- (the platform keeps only keys it knows); the prompt text is not.
406
+ nothing; a flag alone collects nothing. With all of them off nothing about a prompt or response
407
+ is sent — no text, no length, no hash — and turn counts and cost attribution still work. The first
408
+ ticket key named in the opening prompt is extracted on the machine and sent as `prompt_jira_ids`
409
+ (the platform keeps it only if it knows the key); the prompt text is not.
112
410
 
113
411
  ```json
114
412
  {
@@ -267,9 +565,11 @@ To try it locally: `BLOCK=1 npm run example` refuses every check.
267
565
 
268
566
  | Record | How | Contents |
269
567
  |---|---|---|
270
- | `turn.summary` | Edge hooks → `POST <backend>/v1/events` | One completed turn: prompt/response length and hash, tool counts, file paths (repo-relative, and home-relative outside a checkout), Git branch, ticket keys from the branch name and the opening prompt. With Git capture on, `tool_events`: per tool call its order, status, exit code, times, a sha256 fingerprint of the normalized command or connector arguments (never the text), and for a test/lint/build check over 60 s the commit and a working-tree digest. Prompt text and shell/connector inputs only when opted in. Never response text. |
568
+ | `turn.summary` | Edge hooks → `POST <backend>/v1/events` | One completed turn: tool counts, file paths (repo-relative, and home-relative outside a checkout), Git branch, ticket keys from the branch name and the first from the opening prompt. With Git capture on, `tool_events`: per tool call its order, status, exit code, times, a sha256 fingerprint of the normalized command or connector arguments (never the text), and for a test/lint/build check over 60 s the commit and a working-tree digest; from Claude Code, also the name of a skill a `Skill` call ran (`skill`) and of the slash command the turn opened with (`command`, `/ship-it now` sends `ship-it`), names only, never arguments. Prompt text and shell/connector inputs only when opted in. Never response text. |
271
569
  | `llm.call` | The agent's own OTLP → `POST <backend>/v1/otlp/v1/logs` | Token usage, cost and latency per model request. The edge does not proxy this. |
272
570
  | `repo.snapshot` | Edge hooks, after a closed turn | Changed branch/commit metadata, including commit subjects, when Git capture is on. |
571
+ | `repo.tree` | Edge hooks, after the first closed turn in a repository, once per install identity | The default branch's source paths and top-level declaration and route names, when Git and file capture are on. Never file contents. |
572
+ | `turn.summary` (replay) | The first eligible `agentwatch setup` on a machine starts, in the background, a slow replay of the developer's earlier Claude Code, Codex and Gemini CLI sessions from `~/.claude/projects`, `~/.codex/sessions` and `~/.gemini/tmp`. A machine-wide marker prevents later setup runs—even after signing in again—from repeating it automatically (`--replay-days N`, default 30; `--no-replay` skips without claiming it; explicit `agentwatch replay` remains available). | The same metadata a live turn carries (tokens, times, repository, branch, ticket keys, touched file paths; Codex and Gemini turns carry no branch or paths), nothing from before the open charge period, no commit, no prompt text unless prompt capture is already on. Gemini turns only from before Gemini hooks were first installed. Plus `replay.progress`: counts only. |
273
573
 
274
574
  The backend joins `llm.call` to `turn.summary` on conversation and turn ids.
275
575
 
@@ -1,16 +1,48 @@
1
1
  import type { Env } from '../core/types/core.types.js';
2
2
  import type { UsageBillingMode } from '../events/types/events.types.js';
3
+ import type { BillingSource } from './types/billing.types.js';
3
4
  /**
4
- * How the developer pays for this agent.
5
+ * How the developer pays for this agent, as its provider reads it.
5
6
  *
6
7
  * A flat subscription (Claude Pro/Max, a ChatGPT plan) and per-token API billing
7
8
  * price the same turn completely differently, so a summary that guessed would be
8
9
  * worse than one that admits it does not know. Only positively recognized states
9
- * are classified; every read problem, and every value we do not recognize,
10
- * degrades to 'unknown'.
10
+ * are classified; an agent with no reader, every read problem, and every value
11
+ * we do not recognize, degrades to 'unknown'.
11
12
  *
12
- * @param agentId - Internal provider id.
13
+ * @param source - The agent's provider; its `billingMode` reads the local auth state.
13
14
  * @param env - Environment supplying HOME and the relevant variables.
14
15
  * @returns The billing mode.
15
16
  */
16
- export declare function detectBillingMode(agentId: string, env: Env): Promise<UsageBillingMode>;
17
+ export declare function billingModeOf(source: BillingSource | undefined, env: Env): Promise<UsageBillingMode>;
18
+ /**
19
+ * The email of the Claude account signed in here (`oauthAccount.emailAddress`
20
+ * in `~/.claude.json`): who a Claude Code cloud VM claims its device for. The
21
+ * one reader of that field; anything that is not a plain address is none.
22
+ *
23
+ * @param home - The home directory holding `.claude.json`.
24
+ * @returns The email, or undefined.
25
+ */
26
+ export declare function claudeAccountEmail(home: string): Promise<string | undefined>;
27
+ /**
28
+ * Claude Code's billing arrangement. May throw on a read failure; `billingModeOf` catches.
29
+ *
30
+ * @param env - Environment supplying HOME and the relevant variables.
31
+ * @returns The billing mode.
32
+ */
33
+ export declare function claudeBillingMode(env: Env): Promise<UsageBillingMode>;
34
+ /**
35
+ * Codex's billing arrangement. May throw on a read failure; `billingModeOf` catches.
36
+ *
37
+ * @param env - Environment supplying HOME.
38
+ * @returns The billing mode.
39
+ */
40
+ export declare function codexBillingMode(env: Env): Promise<UsageBillingMode>;
41
+ /**
42
+ * The billing arrangement of an agent signed in through the shared Google
43
+ * account state (Gemini CLI, Antigravity). May throw on a read failure; `billingModeOf` catches.
44
+ *
45
+ * @param env - Environment supplying HOME and the relevant variables.
46
+ * @returns The billing mode.
47
+ */
48
+ export declare function googleAccountBillingMode(env: Env): Promise<UsageBillingMode>;
@@ -1,42 +1,51 @@
1
1
  import path from 'node:path';
2
2
  import { asRecord, firstString } from '../core/object.js';
3
+ import { RE_PLAIN_EMAIL } from '../credentials/constants/credentials.constants.js';
3
4
  import { sha256Hex } from '../events/event-id.js';
4
5
  import { readJsonFile } from '../storage/json-file.js';
5
- import { ANTHROPIC_API_KEY_VAR, API_MARKER, CLAUDE_API_KEY_RESPONSES_FIELD, CLAUDE_APPROVED_FIELD, CLAUDE_BEDROCK_VAR, CLAUDE_BILLING_TYPE_FIELD, CLAUDE_OAUTH_FIELD, CLAUDE_STATE_FILE, CLAUDE_VERTEX_VAR, CODEX_API_KEY_FIELD, CODEX_API_MODE, CODEX_AUTH_FILE, CODEX_AUTH_MODE_FIELD, CODEX_SUBSCRIPTION_MODE, FALSY_ENV_VALUES, GEMINI_API_KEY_FIELDS, GEMINI_API_KEY_VARS, GEMINI_MODE_FIELDS, GEMINI_OAUTH_FILE, GEMINI_SETTINGS_FILE, GOOGLE_ACCOUNT_AGENTS, MIN_APPROVAL_ENTRY_LENGTH, SUBSCRIPTION_MARKER } from './constants/billing.constants.js';
6
+ import { ANTHROPIC_API_KEY_VAR, API_MARKER, CLAUDE_API_KEY_RESPONSES_FIELD, CLAUDE_APPROVED_FIELD, CLAUDE_BEDROCK_VAR, CLAUDE_BILLING_TYPE_FIELD, CLAUDE_OAUTH_FIELD, CLAUDE_STATE_FILE, CLAUDE_VERTEX_VAR, CODEX_API_KEY_FIELD, CODEX_API_MODE, CODEX_AUTH_FILE, CODEX_AUTH_MODE_FIELD, CODEX_SUBSCRIPTION_MODE, FALSY_ENV_VALUES, GEMINI_API_KEY_FIELDS, GEMINI_API_KEY_VARS, GEMINI_MODE_FIELDS, GEMINI_OAUTH_FILE, GEMINI_SETTINGS_FILE, MIN_APPROVAL_ENTRY_LENGTH, SUBSCRIPTION_MARKER } from './constants/billing.constants.js';
6
7
  /**
7
- * How the developer pays for this agent.
8
+ * How the developer pays for this agent, as its provider reads it.
8
9
  *
9
10
  * A flat subscription (Claude Pro/Max, a ChatGPT plan) and per-token API billing
10
11
  * price the same turn completely differently, so a summary that guessed would be
11
12
  * worse than one that admits it does not know. Only positively recognized states
12
- * are classified; every read problem, and every value we do not recognize,
13
- * degrades to 'unknown'.
13
+ * are classified; an agent with no reader, every read problem, and every value
14
+ * we do not recognize, degrades to 'unknown'.
14
15
  *
15
- * @param agentId - Internal provider id.
16
+ * @param source - The agent's provider; its `billingMode` reads the local auth state.
16
17
  * @param env - Environment supplying HOME and the relevant variables.
17
18
  * @returns The billing mode.
18
19
  */
19
- export async function detectBillingMode(agentId, env) {
20
+ export async function billingModeOf(source, env) {
20
21
  try {
21
- if (agentId === 'claude')
22
- return await detectClaude(env);
23
- if (agentId === 'codex')
24
- return await detectCodex(env);
25
- if (GOOGLE_ACCOUNT_AGENTS.has(agentId))
26
- return await detectGoogleAccount(env);
22
+ return (await source?.billingMode?.(env)) ?? 'unknown';
27
23
  }
28
24
  catch {
29
25
  // Any read or parse failure: we simply do not know.
26
+ return 'unknown';
30
27
  }
31
- return 'unknown';
32
28
  }
33
29
  /**
34
- * Claude Code's billing arrangement.
30
+ * The email of the Claude account signed in here (`oauthAccount.emailAddress`
31
+ * in `~/.claude.json`): who a Claude Code cloud VM claims its device for. The
32
+ * one reader of that field; anything that is not a plain address is none.
33
+ *
34
+ * @param home - The home directory holding `.claude.json`.
35
+ * @returns The email, or undefined.
36
+ */
37
+ export async function claudeAccountEmail(home) {
38
+ const email = asRecord((await readRecord(path.join(home, CLAUDE_STATE_FILE)))?.[CLAUDE_OAUTH_FIELD])?.['emailAddress'];
39
+ const trimmed = typeof email === 'string' ? email.trim() : undefined;
40
+ return trimmed && RE_PLAIN_EMAIL.test(trimmed) ? trimmed : undefined;
41
+ }
42
+ /**
43
+ * Claude Code's billing arrangement. May throw on a read failure; `billingModeOf` catches.
35
44
  *
36
45
  * @param env - Environment supplying HOME and the relevant variables.
37
46
  * @returns The billing mode.
38
47
  */
39
- async function detectClaude(env) {
48
+ export async function claudeBillingMode(env) {
40
49
  // Bedrock and Vertex sessions always bill per token.
41
50
  if (isSet(env.vars[CLAUDE_BEDROCK_VAR]) || isSet(env.vars[CLAUDE_VERTEX_VAR]))
42
51
  return 'api';
@@ -74,12 +83,12 @@ function envApiKeyUsed(state, apiKey) {
74
83
  return approved.some((entry) => typeof entry === 'string' && entry.length >= MIN_APPROVAL_ENTRY_LENGTH && (hash.startsWith(entry) || apiKey.endsWith(entry)));
75
84
  }
76
85
  /**
77
- * Codex's billing arrangement.
86
+ * Codex's billing arrangement. May throw on a read failure; `billingModeOf` catches.
78
87
  *
79
88
  * @param env - Environment supplying HOME.
80
89
  * @returns The billing mode.
81
90
  */
82
- async function detectCodex(env) {
91
+ export async function codexBillingMode(env) {
83
92
  const auth = await readRecord(path.join(env.home, CODEX_AUTH_FILE));
84
93
  if (!auth)
85
94
  return 'unknown';
@@ -94,12 +103,12 @@ async function detectCodex(env) {
94
103
  }
95
104
  /**
96
105
  * The billing arrangement of an agent signed in through the shared Google
97
- * account state (Gemini CLI, Antigravity).
106
+ * account state (Gemini CLI, Antigravity). May throw on a read failure; `billingModeOf` catches.
98
107
  *
99
108
  * @param env - Environment supplying HOME and the relevant variables.
100
109
  * @returns The billing mode.
101
110
  */
102
- async function detectGoogleAccount(env) {
111
+ export async function googleAccountBillingMode(env) {
103
112
  if (GEMINI_API_KEY_VARS.some((name) => isSet(env.vars[name])))
104
113
  return 'api';
105
114
  const state = (await readRecord(path.join(env.home, GEMINI_SETTINGS_FILE))) ?? (await readRecord(path.join(env.home, GEMINI_OAUTH_FILE)));
@@ -33,5 +33,3 @@ export declare const API_MARKER = "api";
33
33
  export declare const MIN_APPROVAL_ENTRY_LENGTH = 8;
34
34
  /** Environment values that mean "not set", beyond an absent variable. */
35
35
  export declare const FALSY_ENV_VALUES: ReadonlySet<string>;
36
- /** Agent ids that authenticate through the shared ~/.gemini Google account. */
37
- export declare const GOOGLE_ACCOUNT_AGENTS: ReadonlySet<string>;
@@ -34,5 +34,3 @@ export const API_MARKER = 'api';
34
34
  export const MIN_APPROVAL_ENTRY_LENGTH = 8;
35
35
  /** Environment values that mean "not set", beyond an absent variable. */
36
36
  export const FALSY_ENV_VALUES = new Set(['', '0', 'false']);
37
- /** Agent ids that authenticate through the shared ~/.gemini Google account. */
38
- export const GOOGLE_ACCOUNT_AGENTS = new Set(['gemini', 'antigravity']);
@@ -3,4 +3,5 @@
3
3
  * state. A turn priced under the wrong arrangement is worse than one that
4
4
  * admits it does not know, so only positively recognized states are reported.
5
5
  */
6
- export { detectBillingMode } from './billing-mode.js';
6
+ export { billingModeOf } from './billing-mode.js';
7
+ export type { BillingSource } from './types/billing.types.js';
@@ -3,4 +3,4 @@
3
3
  * state. A turn priced under the wrong arrangement is worse than one that
4
4
  * admits it does not know, so only positively recognized states are reported.
5
5
  */
6
- export { detectBillingMode } from './billing-mode.js';
6
+ export { billingModeOf } from './billing-mode.js';
@@ -2,6 +2,7 @@ import type { Env } from '../core/types/core.types.js';
2
2
  import type { AgentWatchEvent } from '../events/types/events.types.js';
3
3
  import type { SessionBillingEvent } from '../events/types/session-billing.types.js';
4
4
  import type { TurnStateStore } from '../turns/turn-state.js';
5
+ import type { TurnProvider } from '../turns/types/turn-provider.types.js';
5
6
  /**
6
7
  * The session's billing fact, the first time it is asked for.
7
8
  *
@@ -10,10 +11,10 @@ import type { TurnStateStore } from '../turns/turn-state.js';
10
11
  *
11
12
  * @param store - Per-session state store; remembers that the fact was taken.
12
13
  * @param events - The hook's canonical events.
13
- * @param agentId - Internal provider id.
14
+ * @param provider - The agent the hook came from, for its billing reader.
14
15
  * @param env - Environment supplying HOME and the relevant variables.
15
16
  * @param surface - Product surface the session runs on.
16
17
  * @returns The event, or undefined when the session already has one, this hook
17
18
  * does not open anything, or the mode cannot be told.
18
19
  */
19
- export declare function sessionBillingFact(store: TurnStateStore, events: readonly AgentWatchEvent[], agentId: string, env: Env, surface: string): Promise<SessionBillingEvent | undefined>;
20
+ export declare function sessionBillingFact(store: TurnStateStore, events: readonly AgentWatchEvent[], provider: TurnProvider, env: Env, surface: string): Promise<SessionBillingEvent | undefined>;
@@ -1,8 +1,8 @@
1
1
  import { compact } from '../core/object.js';
2
2
  import { deriveEventId } from '../events/event-id.js';
3
3
  import { EVENT_SCHEMA_VERSION } from '../events/constants/events.constants.js';
4
- import { PROVIDER_LABELS } from '../turns/constants/turns.constants.js';
5
- import { detectBillingMode } from './billing-mode.js';
4
+ import { CANONICAL_PROVIDER_NAMES } from '../otlp/constants/otlp.constants.js';
5
+ import { billingModeOf } from './billing-mode.js';
6
6
  /** The hooks that open a session or a turn: the earliest a collector hears from it. */
7
7
  const OPENING_TYPES = new Set(['session.started', 'prompt.submitted']);
8
8
  /**
@@ -13,17 +13,17 @@ const OPENING_TYPES = new Set(['session.started', 'prompt.submitted']);
13
13
  *
14
14
  * @param store - Per-session state store; remembers that the fact was taken.
15
15
  * @param events - The hook's canonical events.
16
- * @param agentId - Internal provider id.
16
+ * @param provider - The agent the hook came from, for its billing reader.
17
17
  * @param env - Environment supplying HOME and the relevant variables.
18
18
  * @param surface - Product surface the session runs on.
19
19
  * @returns The event, or undefined when the session already has one, this hook
20
20
  * does not open anything, or the mode cannot be told.
21
21
  */
22
- export async function sessionBillingFact(store, events, agentId, env, surface) {
22
+ export async function sessionBillingFact(store, events, provider, env, surface) {
23
23
  const opening = events.find((event) => OPENING_TYPES.has(event.event.type) && event.session.id);
24
24
  if (!opening?.session.id)
25
25
  return undefined;
26
- const mode = await detectBillingMode(agentId, env);
26
+ const mode = await billingModeOf(provider, env);
27
27
  // Unknown is not a fact, and must not use up the session's one send.
28
28
  if (mode === 'unknown')
29
29
  return undefined;
@@ -36,15 +36,15 @@ export async function sessionBillingFact(store, events, agentId, env, surface) {
36
36
  return undefined;
37
37
  const timestamp = env.now().toISOString();
38
38
  // The public label, as the turn summary and the calls carry it.
39
- const provider = PROVIDER_LABELS[opening.agent.provider] ?? opening.agent.provider;
39
+ const label = CANONICAL_PROVIDER_NAMES[opening.agent.provider] ?? opening.agent.provider;
40
40
  return compact({
41
41
  schemaVersion: EVENT_SCHEMA_VERSION,
42
42
  id: deriveEventId({ provider: opening.agent.provider, providerEventType: 'session.billing', sessionId: opening.session.id }),
43
43
  timestamp,
44
44
  event: { type: 'session.billing', providerEventType: 'session.billing' },
45
- agent: { ...opening.agent, provider },
45
+ agent: { ...opening.agent, provider: label },
46
46
  session: { id: opening.session.id, providerId: opening.session.id },
47
- provider,
47
+ provider: label,
48
48
  surface,
49
49
  session_id: opening.session.id,
50
50
  billing_mode: mode
@@ -0,0 +1,7 @@
1
+ import type { Env } from '../../core/types/core.types.js';
2
+ import type { UsageBillingMode } from '../../events/types/events.types.js';
3
+ /** An agent that can tell how its developer pays; `AgentProvider` is one. */
4
+ export interface BillingSource {
5
+ /** Read the agent's local auth state. May throw; `billingModeOf` turns that into 'unknown'. */
6
+ readonly billingMode?: (env: Env) => Promise<UsageBillingMode>;
7
+ }