@agent-watch-ai/edge 0.6.0 → 0.7.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 (309) hide show
  1. package/CHANGELOG.md +288 -9
  2. package/README.md +307 -5
  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 +7 -3
  10. package/dist/billing/session-billing.js +34 -13
  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 +503 -0
  16. package/dist/capture/constants/capture.constants.d.ts +85 -0
  17. package/dist/capture/constants/capture.constants.js +87 -0
  18. package/dist/capture/launched-runs.d.ts +43 -0
  19. package/dist/capture/launched-runs.js +157 -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 +832 -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/capture/venv-loader.d.ts +68 -0
  27. package/dist/capture/venv-loader.js +189 -0
  28. package/dist/cli/constants/cli.constants.d.ts +23 -6
  29. package/dist/cli/constants/cli.constants.js +24 -7
  30. package/dist/cli/context.d.ts +19 -22
  31. package/dist/cli/context.js +23 -54
  32. package/dist/cli/doctor-run-capture.d.ts +21 -0
  33. package/dist/cli/doctor-run-capture.js +33 -0
  34. package/dist/cli/doctor.js +21 -68
  35. package/dist/cli/hook-check.d.ts +7 -2
  36. package/dist/cli/hook-check.js +30 -15
  37. package/dist/cli/hook.d.ts +14 -0
  38. package/dist/cli/hook.js +82 -1
  39. package/dist/cli/index.d.ts +1 -1
  40. package/dist/cli/index.js +1 -1
  41. package/dist/cli/misc.js +10 -2
  42. package/dist/cli/npm-global.d.ts +24 -0
  43. package/dist/cli/npm-global.js +77 -0
  44. package/dist/cli/npx-install.js +22 -6
  45. package/dist/cli/replay.d.ts +33 -0
  46. package/dist/cli/replay.js +228 -0
  47. package/dist/cli/setup.d.ts +10 -2
  48. package/dist/cli/setup.js +200 -31
  49. package/dist/cli/status.js +45 -5
  50. package/dist/cli/toggle.js +10 -0
  51. package/dist/cli/types/cli.types.d.ts +15 -1
  52. package/dist/cli/uninstall.js +42 -23
  53. package/dist/cli/update.js +3 -2
  54. package/dist/cli.js +104 -17
  55. package/dist/config/config-store.d.ts +15 -4
  56. package/dist/config/config-store.js +31 -7
  57. package/dist/config/config.d.ts +0 -2
  58. package/dist/config/config.js +0 -1
  59. package/dist/config/constants/config.constants.d.ts +8 -1
  60. package/dist/config/constants/config.constants.js +10 -1
  61. package/dist/config/events-transport.d.ts +15 -0
  62. package/dist/config/events-transport.js +29 -0
  63. package/dist/config/index.d.ts +2 -1
  64. package/dist/config/index.js +1 -0
  65. package/dist/config/root-config.d.ts +12 -0
  66. package/dist/config/root-config.js +24 -0
  67. package/dist/config/schemas/config.schema.d.ts +15 -2
  68. package/dist/config/schemas/config.schema.js +52 -8
  69. package/dist/config/types/config.types.d.ts +7 -0
  70. package/dist/core/index.d.ts +1 -1
  71. package/dist/core/index.js +1 -1
  72. package/dist/core/version.d.ts +9 -0
  73. package/dist/core/version.js +14 -0
  74. package/dist/core/which.d.ts +11 -0
  75. package/dist/core/which.js +18 -0
  76. package/dist/credentials/cloud-claim.d.ts +34 -0
  77. package/dist/credentials/cloud-claim.js +61 -0
  78. package/dist/credentials/constants/credentials.constants.d.ts +16 -1
  79. package/dist/credentials/constants/credentials.constants.js +17 -2
  80. package/dist/credentials/credential-status.js +1 -1
  81. package/dist/credentials/credentials.d.ts +3 -3
  82. package/dist/credentials/credentials.js +26 -12
  83. package/dist/credentials/device-api.d.ts +15 -1
  84. package/dist/credentials/device-api.js +12 -1
  85. package/dist/credentials/identity.d.ts +2 -2
  86. package/dist/credentials/identity.js +2 -2
  87. package/dist/credentials/install-key.d.ts +31 -0
  88. package/dist/credentials/install-key.js +58 -0
  89. package/dist/credentials/migration.d.ts +9 -7
  90. package/dist/credentials/migration.js +58 -18
  91. package/dist/credentials/secret-store.d.ts +12 -0
  92. package/dist/credentials/secret-store.js +18 -1
  93. package/dist/credentials/sign-in.d.ts +27 -0
  94. package/dist/credentials/sign-in.js +31 -1
  95. package/dist/credentials/token-refresher.d.ts +5 -1
  96. package/dist/credentials/token-refresher.js +10 -2
  97. package/dist/enforcement/enforcement.js +1 -1
  98. package/dist/events/constants/events.constants.d.ts +5 -2
  99. package/dist/events/constants/events.constants.js +4 -1
  100. package/dist/events/enrich.d.ts +14 -0
  101. package/dist/events/enrich.js +1 -1
  102. package/dist/events/index.d.ts +1 -0
  103. package/dist/events/product-event.d.ts +6 -3
  104. package/dist/events/types/events.types.d.ts +6 -0
  105. package/dist/events/types/replay-progress.types.d.ts +26 -0
  106. package/dist/events/types/replay-progress.types.js +1 -0
  107. package/dist/events/types/repo-tree.types.d.ts +2 -1
  108. package/dist/feature/ticket-candidates.d.ts +1 -1
  109. package/dist/git/checkout-root.d.ts +15 -0
  110. package/dist/git/checkout-root.js +18 -0
  111. package/dist/git/code-state.d.ts +2 -16
  112. package/dist/git/code-state.js +11 -12
  113. package/dist/git/constants/git.constants.d.ts +33 -11
  114. package/dist/git/constants/git.constants.js +45 -12
  115. package/dist/git/fingerprint.d.ts +3 -6
  116. package/dist/git/fingerprint.js +5 -8
  117. package/dist/git/git-context.js +5 -1
  118. package/dist/git/index.d.ts +1 -2
  119. package/dist/git/index.js +1 -1
  120. package/dist/git/repo-snapshot.d.ts +13 -4
  121. package/dist/git/repo-snapshot.js +53 -9
  122. package/dist/git/types/snapshot.types.d.ts +6 -0
  123. package/dist/pipeline/constants/pipeline.constants.d.ts +3 -0
  124. package/dist/pipeline/constants/pipeline.constants.js +3 -0
  125. package/dist/pipeline/hook-pipeline.js +82 -57
  126. package/dist/privacy/product-capture.js +2 -0
  127. package/dist/providers/antigravity/antigravity.capture.d.ts +2 -0
  128. package/dist/providers/antigravity/antigravity.capture.js +5 -0
  129. package/dist/providers/antigravity/antigravity.detect.js +8 -22
  130. package/dist/providers/antigravity/antigravity.provider.js +10 -3
  131. package/dist/providers/antigravity/constants/antigravity.constants.d.ts +1 -0
  132. package/dist/providers/antigravity/constants/antigravity.constants.js +1 -0
  133. package/dist/providers/claude/claude.adapter.js +9 -6
  134. package/dist/providers/claude/claude.detect.js +2 -17
  135. package/dist/providers/claude/claude.otel.d.ts +21 -3
  136. package/dist/providers/claude/claude.otel.js +216 -61
  137. package/dist/providers/claude/claude.provider.js +21 -1
  138. package/dist/providers/claude/claude.version.d.ts +9 -0
  139. package/dist/providers/claude/claude.version.js +28 -0
  140. package/dist/providers/claude/constants/claude.constants.d.ts +27 -0
  141. package/dist/providers/claude/constants/claude.constants.js +27 -0
  142. package/dist/providers/claude/constants/claude.otel.constants.d.ts +27 -0
  143. package/dist/providers/claude/constants/claude.otel.constants.js +45 -5
  144. package/dist/providers/claude/types/claude.types.d.ts +13 -0
  145. package/dist/providers/codex/codex.capture.d.ts +76 -0
  146. package/dist/providers/codex/codex.capture.js +454 -0
  147. package/dist/providers/codex/codex.detect.js +2 -4
  148. package/dist/providers/codex/codex.otel.d.ts +38 -2
  149. package/dist/providers/codex/codex.otel.js +50 -6
  150. package/dist/providers/codex/codex.provider.js +8 -0
  151. package/dist/providers/codex/codex.surface.d.ts +9 -0
  152. package/dist/{turns/codex-originator.js → providers/codex/codex.surface.js} +17 -3
  153. package/dist/providers/codex/codex.titles.d.ts +14 -0
  154. package/dist/providers/codex/codex.titles.js +35 -0
  155. package/dist/providers/codex/constants/codex.constants.d.ts +4 -0
  156. package/dist/providers/codex/constants/codex.constants.js +4 -0
  157. package/dist/providers/cursor/constants/cursor.constants.d.ts +17 -4
  158. package/dist/providers/cursor/constants/cursor.constants.js +25 -5
  159. package/dist/providers/cursor/cursor-mcp-memo.d.ts +34 -0
  160. package/dist/providers/cursor/cursor-mcp-memo.js +94 -0
  161. package/dist/providers/cursor/cursor.adapter.js +20 -82
  162. package/dist/providers/cursor/cursor.capture.d.ts +1 -0
  163. package/dist/providers/cursor/cursor.capture.js +4 -0
  164. package/dist/providers/cursor/cursor.detect.d.ts +5 -1
  165. package/dist/providers/cursor/cursor.detect.js +11 -26
  166. package/dist/providers/cursor/cursor.hooks.js +2 -2
  167. package/dist/providers/cursor/cursor.provider.js +16 -7
  168. package/dist/providers/cursor/cursor.titles.d.ts +14 -0
  169. package/dist/providers/cursor/cursor.titles.js +20 -0
  170. package/dist/providers/cursor/schemas/cursor.schema.d.ts +3 -3
  171. package/dist/providers/cursor/schemas/cursor.schema.js +5 -3
  172. package/dist/providers/gemini/constants/gemini.constants.d.ts +16 -0
  173. package/dist/providers/gemini/constants/gemini.constants.js +17 -0
  174. package/dist/providers/gemini/gemini.capture.d.ts +81 -0
  175. package/dist/providers/gemini/gemini.capture.js +210 -0
  176. package/dist/providers/gemini/gemini.detect.js +57 -24
  177. package/dist/providers/gemini/gemini.otel.d.ts +38 -2
  178. package/dist/providers/gemini/gemini.otel.js +56 -125
  179. package/dist/providers/gemini/gemini.provider.js +5 -0
  180. package/dist/providers/index.d.ts +1 -0
  181. package/dist/providers/index.js +1 -0
  182. package/dist/providers/provider.d.ts +8 -0
  183. package/dist/providers/provider.js +9 -0
  184. package/dist/providers/registry.d.ts +14 -0
  185. package/dist/providers/registry.js +14 -0
  186. package/dist/providers/shared/constants/hook-config.constants.d.ts +2 -0
  187. package/dist/providers/shared/constants/hook-config.constants.js +2 -0
  188. package/dist/providers/shared/constants/terminal-capture.constants.d.ts +6 -0
  189. package/dist/providers/shared/constants/terminal-capture.constants.js +6 -0
  190. package/dist/providers/shared/editor-paths.d.ts +8 -0
  191. package/dist/providers/shared/editor-paths.js +18 -0
  192. package/dist/providers/shared/hook-config.d.ts +5 -0
  193. package/dist/providers/shared/hook-config.js +39 -1
  194. package/dist/providers/shared/hooks-marker.d.ts +14 -0
  195. package/dist/providers/shared/hooks-marker.js +23 -0
  196. package/dist/providers/shared/install-record.d.ts +29 -0
  197. package/dist/providers/shared/install-record.js +52 -0
  198. package/dist/providers/shared/session-title-store.d.ts +23 -0
  199. package/dist/providers/shared/session-title-store.js +50 -0
  200. package/dist/providers/shared/terminal-capture.d.ts +41 -0
  201. package/dist/providers/shared/terminal-capture.js +109 -0
  202. package/dist/providers/shared/tooling.d.ts +21 -0
  203. package/dist/providers/shared/tooling.js +36 -1
  204. package/dist/providers/types/provider.types.d.ts +57 -4
  205. package/dist/replay/checkout-resolver.d.ts +56 -0
  206. package/dist/replay/checkout-resolver.js +173 -0
  207. package/dist/replay/codex-turns.d.ts +24 -0
  208. package/dist/replay/codex-turns.js +221 -0
  209. package/dist/replay/constants/replay.constants.d.ts +99 -0
  210. package/dist/replay/constants/replay.constants.js +102 -0
  211. package/dist/replay/describe.d.ts +10 -0
  212. package/dist/replay/describe.js +31 -0
  213. package/dist/replay/gemini-turns.d.ts +36 -0
  214. package/dist/replay/gemini-turns.js +192 -0
  215. package/dist/replay/machine.d.ts +34 -0
  216. package/dist/replay/machine.js +68 -0
  217. package/dist/replay/progress-event.d.ts +21 -0
  218. package/dist/replay/progress-event.js +45 -0
  219. package/dist/replay/replay-runner.d.ts +60 -0
  220. package/dist/replay/replay-runner.js +581 -0
  221. package/dist/replay/replay-scan.d.ts +84 -0
  222. package/dist/replay/replay-scan.js +182 -0
  223. package/dist/replay/replay-state.d.ts +108 -0
  224. package/dist/replay/replay-state.js +199 -0
  225. package/dist/replay/resume.d.ts +18 -0
  226. package/dist/replay/resume.js +34 -0
  227. package/dist/replay/start.d.ts +23 -0
  228. package/dist/replay/start.js +39 -0
  229. package/dist/replay/throttle.d.ts +36 -0
  230. package/dist/replay/throttle.js +44 -0
  231. package/dist/replay/transcript-turns.d.ts +35 -0
  232. package/dist/replay/transcript-turns.js +241 -0
  233. package/dist/replay/turn-event.d.ts +40 -0
  234. package/dist/replay/turn-event.js +127 -0
  235. package/dist/replay/types/replay.types.d.ts +198 -0
  236. package/dist/replay/types/replay.types.js +1 -0
  237. package/dist/replay/window.d.ts +28 -0
  238. package/dist/replay/window.js +41 -0
  239. package/dist/replay/worktree-map.d.ts +42 -0
  240. package/dist/replay/worktree-map.js +134 -0
  241. package/dist/snapshot/branch-selection.d.ts +40 -23
  242. package/dist/snapshot/branch-selection.js +71 -41
  243. package/dist/snapshot/constants/snapshot-stages.constants.d.ts +3 -1
  244. package/dist/snapshot/constants/snapshot-stages.constants.js +3 -1
  245. package/dist/snapshot/constants/snapshot.constants.d.ts +34 -7
  246. package/dist/snapshot/constants/snapshot.constants.js +34 -7
  247. package/dist/snapshot/index.d.ts +2 -2
  248. package/dist/snapshot/index.js +1 -1
  249. package/dist/snapshot/snapshot-pipeline.js +100 -26
  250. package/dist/snapshot/snapshot-state.js +6 -2
  251. package/dist/snapshot/tree-pipeline.d.ts +1 -1
  252. package/dist/snapshot/tree-pipeline.js +34 -15
  253. package/dist/snapshot/types/snapshot.types.d.ts +22 -3
  254. package/dist/storage/schemas/storage.schema.d.ts +2 -0
  255. package/dist/storage/schemas/storage.schema.js +6 -0
  256. package/dist/transport/delivery-stats.d.ts +13 -1
  257. package/dist/transport/delivery-stats.js +18 -2
  258. package/dist/transport/delivery.d.ts +4 -3
  259. package/dist/transport/delivery.js +21 -7
  260. package/dist/transport/identity-delivery.d.ts +20 -0
  261. package/dist/transport/identity-delivery.js +41 -0
  262. package/dist/transport/index.d.ts +2 -0
  263. package/dist/transport/index.js +1 -0
  264. package/dist/transport/types/delivery-flow.types.d.ts +7 -0
  265. package/dist/turns/claude-transcript.js +4 -12
  266. package/dist/turns/codex-transcript.d.ts +9 -0
  267. package/dist/turns/codex-transcript.js +27 -19
  268. package/dist/turns/constants/turns.constants.d.ts +29 -12
  269. package/dist/turns/constants/turns.constants.js +31 -19
  270. package/dist/turns/gemini-transcript.d.ts +19 -1
  271. package/dist/turns/gemini-transcript.js +29 -18
  272. package/dist/turns/index.d.ts +3 -4
  273. package/dist/turns/index.js +2 -3
  274. package/dist/turns/run-state.d.ts +71 -0
  275. package/dist/turns/run-state.js +114 -0
  276. package/dist/turns/tool-events.d.ts +11 -1
  277. package/dist/turns/tool-events.js +32 -9
  278. package/dist/turns/transcript.d.ts +15 -14
  279. package/dist/turns/transcript.js +23 -4
  280. package/dist/turns/turn-state.d.ts +82 -7
  281. package/dist/turns/turn-state.js +157 -10
  282. package/dist/turns/turn-summary.js +7 -2
  283. package/dist/turns/turn-tracker.d.ts +9 -16
  284. package/dist/turns/turn-tracker.js +163 -87
  285. package/dist/turns/types/transcript.types.d.ts +11 -1
  286. package/dist/turns/types/turn-provider.types.d.ts +33 -0
  287. package/dist/turns/types/turn-provider.types.js +1 -0
  288. package/dist/turns/types/turn-state.types.d.ts +9 -0
  289. package/dist/turns/types/turn-summary.types.d.ts +17 -1
  290. package/dist/turns/types/turn-tracker.types.d.ts +3 -1
  291. package/dist/turns/work-checkout.js +1 -2
  292. package/docs/AUDIT_PROMPT.md +10 -0
  293. package/docs/DATA_HANDLING.md +201 -13
  294. package/docs/ENTERPRISE_DEPLOYMENT.md +3 -3
  295. package/docs/PERFORMANCE.md +10 -0
  296. package/package.json +3 -2
  297. package/dist/events/canonical-event.d.ts +0 -10
  298. package/dist/events/canonical-event.js +0 -9
  299. package/dist/git/repository-root.d.ts +0 -39
  300. package/dist/git/repository-root.js +0 -131
  301. package/dist/git/types/repository-root.types.d.ts +0 -11
  302. package/dist/transport/transport.d.ts +0 -6
  303. package/dist/turns/codex-originator.d.ts +0 -11
  304. package/dist/turns/cursor-transcript.d.ts +0 -21
  305. package/dist/turns/cursor-transcript.js +0 -66
  306. package/dist/turns/native-session-titles.d.ts +0 -26
  307. package/dist/turns/native-session-titles.js +0 -102
  308. /package/dist/{git/types/repository-root.types.js → billing/types/billing.types.js} +0 -0
  309. /package/dist/{transport/transport.js → capture/types/capture.types.js} +0 -0
@@ -0,0 +1,832 @@
1
+ """Run capture for Python, loaded into a process a coding agent starts through PYTHONPATH.
2
+
3
+ It runs inside the customer's process, so it keeps four promises: it never opens a
4
+ socket, never reads a request body or a request header but the host, never raises
5
+ into the host, and never holds the process open (no threads, no timers; each call is
6
+ one synchronous append). A fault costs a record, never the run.
7
+
8
+ Stdlib only. Importing http.client or httpx here would cost every Python the agent
9
+ starts, so both are patched when something imports them. `src/capture/node.cts`
10
+ mirrors the table and the readers; `conformance/capture/cases.json` holds both to one
11
+ result.
12
+
13
+ Being named sitecustomize masks one further along sys.path, which the customer's
14
+ interpreter may rely on, so that one is run too.
15
+
16
+ It never sets sys.dont_write_bytecode: that would turn bytecode off for the customer's
17
+ whole process, and is too late for this file anyway, which is compiled and cached before
18
+ its first line runs. Its .pyc lands beside it, in the copy under the data dir.
19
+ """
20
+
21
+ import base64
22
+ import json
23
+ import os
24
+ import re
25
+ import sys
26
+ import time
27
+ import zlib
28
+
29
+ EXACT_HOSTS = {
30
+ "api.anthropic.com": "anthropic",
31
+ "api.openai.com": "openai",
32
+ "generativelanguage.googleapis.com": "google",
33
+ "aiplatform.googleapis.com": "vertex",
34
+ }
35
+ RE_VERTEX_HOST = re.compile(r"^[a-z0-9-]+-aiplatform\.googleapis\.com$")
36
+ RE_BEDROCK_HOST = re.compile(r"^bedrock-runtime(?:-fips)?\.[a-z0-9-]+\.amazonaws\.com(?:\.cn)?$")
37
+
38
+ REQUEST_ID_HEADERS = {
39
+ "anthropic": ("request-id", "x-request-id"),
40
+ "openai": ("x-request-id",),
41
+ "google": ("x-goog-request-id", "x-request-id"),
42
+ "vertex": ("request-id", "x-request-id", "x-goog-request-id"),
43
+ "bedrock": ("x-amzn-requestid", "x-amz-request-id"),
44
+ }
45
+
46
+ # Bedrock's plain invoke states its usage in response headers only.
47
+ BEDROCK_USAGE_HEADERS = (
48
+ ("x-amzn-bedrock-input-token-count", "input_tokens"),
49
+ ("x-amzn-bedrock-output-token-count", "output_tokens"),
50
+ ("x-amzn-bedrock-cache-read-input-token-count", "cached_input_tokens"),
51
+ ("x-amzn-bedrock-cache-write-input-token-count", "cache_creation_input_tokens"),
52
+ )
53
+
54
+ RE_URL_MODEL = re.compile(r"/models/([^/:]+):")
55
+ RE_BEDROCK_MODEL = re.compile(r"/model/([^/]+)/")
56
+ RE_ARN = re.compile(r"^arn(?::|%3a)", re.IGNORECASE)
57
+ # "bytes" is Bedrock's envelope, opened and asked this again.
58
+ RE_INTERESTING = re.compile(r'sage|Metrics|"bytes"')
59
+
60
+ # A coding agent's own process reports its own calls; capturing it would count them twice.
61
+ AGENT_ENTRIES = {"claude", "codex", "gemini", "agentwatch", "cursor", "cursor-agent", "antigravity", "agy"}
62
+ AGENT_PACKAGES = re.compile(r"[\\/](?:@anthropic-ai[\\/]claude-code|@anthropic-ai[\\/]claude-agent-sdk|@openai[\\/]codex|@google[\\/]gemini-cli|@agent-watch-ai[\\/]edge|claude[\\/]versions|cursor-agent[\\/]versions|Cursor\.app|Antigravity\.app|\.gemini[\\/]antigravity-cli)[\\/]")
63
+ # Absolute: a repository's folder on PATH must not be handed a `ps` to run.
64
+ PS_PATHS = ("/bin/ps", "/usr/bin/ps")
65
+ RE_WINDOWS_EXEC = re.compile(r"\.(?:exe|cmd)$", re.IGNORECASE)
66
+
67
+ SPOOL_DIR = "captured"
68
+ # Set on sys once installed; its presence in a file also marks that file as a copy of this one.
69
+ LOADED_FLAG = "_agentwatch_capture_loaded"
70
+ DISABLED_MARKER = "disabled.json"
71
+ MAX_LINES_PER_FILE = 10000
72
+ # Past this, a JSON or compressed body costs its usage rather than memory.
73
+ MAX_BODY_BYTES = 8 * 1024 * 1024
74
+ MAX_ANCESTORS = 16
75
+ PS_TIMEOUT_S = 2
76
+ RE_PS_ROW = re.compile(r"^\s*(\d+)\s+(\d+)\s+(\w{3} \w{3}\s+\d+ \d\d:\d\d:\d\d \d{4})")
77
+
78
+
79
+ def _count(value):
80
+ return value if isinstance(value, (int, float)) and not isinstance(value, bool) and value >= 0 else None
81
+
82
+
83
+ def _difference(whole, part):
84
+ return None if whole is None else max(0, whole - (part or 0))
85
+
86
+
87
+ def _record(value):
88
+ return value if isinstance(value, dict) else {}
89
+
90
+
91
+ # Every reader answers in one convention: input_tokens excludes cache reads and
92
+ # output_tokens includes reasoning. Which of those the ledger wants on the wire depends
93
+ # on the launching agent, and the attach step decides that.
94
+ def _read_usage_object(usage):
95
+ if usage.get("prompt_tokens") is not None or usage.get("completion_tokens") is not None:
96
+ cached = _count(_record(usage.get("prompt_tokens_details")).get("cached_tokens"))
97
+ return {
98
+ "input_tokens": _difference(_count(usage.get("prompt_tokens")), cached),
99
+ "cached_input_tokens": cached,
100
+ "output_tokens": _count(usage.get("completion_tokens")),
101
+ "reasoning_output_tokens": _count(_record(usage.get("completion_tokens_details")).get("reasoning_tokens")),
102
+ "total_tokens": _count(usage.get("total_tokens")),
103
+ }
104
+ if usage.get("input_tokens_details") is not None or usage.get("output_tokens_details") is not None:
105
+ cached = _count(_record(usage.get("input_tokens_details")).get("cached_tokens"))
106
+ return {
107
+ "input_tokens": _difference(_count(usage.get("input_tokens")), cached),
108
+ "cached_input_tokens": cached,
109
+ "output_tokens": _count(usage.get("output_tokens")),
110
+ "reasoning_output_tokens": _count(_record(usage.get("output_tokens_details")).get("reasoning_tokens")),
111
+ "total_tokens": _count(usage.get("total_tokens")),
112
+ }
113
+ if usage.get("inputTokens") is not None or usage.get("outputTokens") is not None:
114
+ return {
115
+ "input_tokens": _count(usage.get("inputTokens")),
116
+ "cached_input_tokens": _count(usage.get("cacheReadInputTokens")),
117
+ "cache_creation_input_tokens": _count(usage.get("cacheWriteInputTokens")),
118
+ "output_tokens": _count(usage.get("outputTokens")),
119
+ "total_tokens": _count(usage.get("totalTokens")),
120
+ }
121
+ return {
122
+ "input_tokens": _count(usage.get("input_tokens")),
123
+ "cached_input_tokens": _count(usage.get("cache_read_input_tokens")),
124
+ "cache_creation_input_tokens": _count(usage.get("cache_creation_input_tokens")),
125
+ "output_tokens": _count(usage.get("output_tokens")),
126
+ }
127
+
128
+
129
+ def _read_gemini_usage(usage):
130
+ cached = _count(usage.get("cachedContentTokenCount"))
131
+ reasoning = _count(usage.get("thoughtsTokenCount"))
132
+ candidates = _count(usage.get("candidatesTokenCount"))
133
+ return {
134
+ "input_tokens": _difference(_count(usage.get("promptTokenCount")), cached),
135
+ "cached_input_tokens": cached,
136
+ "output_tokens": None if candidates is None and reasoning is None else (candidates or 0) + (reasoning or 0),
137
+ "reasoning_output_tokens": reasoning,
138
+ "total_tokens": _count(usage.get("totalTokenCount")),
139
+ }
140
+
141
+
142
+ def _read_bedrock_metrics(metrics):
143
+ return {
144
+ "input_tokens": _count(metrics.get("inputTokenCount")),
145
+ "cached_input_tokens": _count(metrics.get("cacheReadInputTokenCount")),
146
+ "cache_creation_input_tokens": _count(metrics.get("cacheWriteInputTokenCount")),
147
+ "output_tokens": _count(metrics.get("outputTokenCount")),
148
+ }
149
+
150
+
151
+ # The usage readers, by the key each provider's usage sits under.
152
+ USAGE_READERS = (
153
+ ("usage", _read_usage_object),
154
+ ("usageMetadata", _read_gemini_usage),
155
+ ("amazon-bedrock-invocationMetrics", _read_bedrock_metrics),
156
+ )
157
+
158
+
159
+ class _ResponseTap:
160
+ """One response being read: what it says so far, and its framing's leftovers."""
161
+
162
+ def __init__(self, meta, status, headers, on_finish, decoded):
163
+ self.call = {"provider": meta["provider"], "status": status}
164
+ if meta.get("model") is not None:
165
+ self.call["model"] = meta["model"]
166
+ request_id = _request_id_of(meta["provider"], headers)
167
+ if request_id is not None:
168
+ self.call["request_id"] = request_id
169
+ self.on_finish = on_finish
170
+ self.framing = _framing_of(headers("content-type"))
171
+ self.encoding = "" if decoded else (headers("content-encoding") or "").lower().strip()
172
+ self.carry = b""
173
+ self.overflowed = False
174
+ self.finished = False
175
+ self.body_request_id = None
176
+ if meta["provider"] == "bedrock":
177
+ self._absorb_headers(headers)
178
+
179
+ def _absorb_headers(self, headers):
180
+ usage = {}
181
+ for name, field in BEDROCK_USAGE_HEADERS:
182
+ value = headers(name)
183
+ if value is not None:
184
+ try:
185
+ usage[field] = int(value)
186
+ except ValueError:
187
+ pass
188
+ self._merge(usage)
189
+
190
+ def _merge(self, usage):
191
+ merged = dict(self.call.get("usage") or {})
192
+ for key, value in usage.items():
193
+ if value is not None:
194
+ merged[key] = value
195
+ if merged:
196
+ self.call["usage"] = merged
197
+
198
+ def _absorb(self, value):
199
+ if isinstance(value, list):
200
+ for item in value:
201
+ self._absorb(item)
202
+ return
203
+ event = _record(value)
204
+ # Anthropic's message_start and OpenAI's response.* nest the whole message.
205
+ if event.get("message") is not None:
206
+ self._absorb(event["message"])
207
+ if event.get("response") is not None:
208
+ self._absorb(event["response"])
209
+ if isinstance(event.get("model"), str):
210
+ self.call["model"] = _model_name(event["model"])
211
+ if isinstance(event.get("modelVersion"), str):
212
+ self.call["model"] = event["modelVersion"]
213
+ if isinstance(event.get("responseId"), str):
214
+ self.body_request_id = event["responseId"]
215
+ for key, read in USAGE_READERS:
216
+ if isinstance(event.get(key), dict):
217
+ self._merge(read(event[key]))
218
+ # A Bedrock stream chunk carries the provider's own event as base64.
219
+ if isinstance(event.get("bytes"), str):
220
+ self._absorb_text(base64.b64decode(event["bytes"]).decode("utf-8", "replace"))
221
+
222
+ # Only what can hold usage is parsed: a text delta is never looked into.
223
+ def _absorb_text(self, text):
224
+ if not RE_INTERESTING.search(text) and not ("model" not in self.call and '"model' in text) and "responseId" not in text:
225
+ return
226
+ try:
227
+ self._absorb(json.loads(text))
228
+ except ValueError:
229
+ pass # Not JSON, or cut short; it holds no usage we can read.
230
+
231
+ def _lines(self, flush):
232
+ start = 0
233
+ while True:
234
+ end = self.carry.find(b"\n", start)
235
+ if end == -1:
236
+ break
237
+ self._line(self.carry[start:end])
238
+ start = end + 1
239
+ self.carry = self.carry[start:]
240
+ if flush and self.carry:
241
+ self._line(self.carry)
242
+
243
+ def _line(self, raw):
244
+ text = raw.decode("utf-8", "replace").strip()
245
+ if text.startswith("data:"):
246
+ self._absorb_text(text[5:].strip())
247
+
248
+ def _frames(self):
249
+ while len(self.carry) >= 12:
250
+ total = int.from_bytes(self.carry[0:4], "big")
251
+ headers_length = int.from_bytes(self.carry[4:8], "big")
252
+ if total < 16 or total > MAX_BODY_BYTES or 12 + headers_length > total - 4:
253
+ self.overflowed = True
254
+ self.carry = b""
255
+ return
256
+ if len(self.carry) < total:
257
+ return
258
+ self._absorb_text(self.carry[12 + headers_length : total - 4].decode("utf-8", "replace"))
259
+ self.carry = self.carry[total:]
260
+
261
+ def feed(self, chunk):
262
+ """Take one chunk of the body as the host read it."""
263
+ if self.overflowed or self.finished:
264
+ return
265
+ self.carry = bytes(chunk) if not self.carry else self.carry + bytes(chunk)
266
+ if len(self.carry) > MAX_BODY_BYTES:
267
+ self.overflowed = True
268
+ self.carry = b""
269
+ return
270
+ if self.encoding:
271
+ return
272
+ if self.framing == "sse":
273
+ self._lines(False)
274
+ if self.framing == "eventstream":
275
+ self._frames()
276
+
277
+ # Bounded: a small compressed body can expand to gigabytes in the host's memory.
278
+ def _inflate(self, wbits):
279
+ inflater = zlib.decompressobj(wbits)
280
+ body = inflater.decompress(self.carry, MAX_BODY_BYTES)
281
+ if inflater.unconsumed_tail:
282
+ raise ValueError("too large")
283
+ return body
284
+
285
+ def _decoded_body(self):
286
+ if self.encoding in ("gzip", "x-gzip"):
287
+ return self._inflate(47)
288
+ if self.encoding == "deflate":
289
+ return self._inflate(15)
290
+ if self.encoding:
291
+ # ponytail: no brotli or zstd in the stdlib, so such a body costs its usage.
292
+ raise ValueError("encoding")
293
+ return self.carry
294
+
295
+ def finish(self):
296
+ """The body ended, failed or was abandoned: say what is known, once."""
297
+ if self.finished:
298
+ return
299
+ try:
300
+ if not self.overflowed:
301
+ self.carry = self._decoded_body()
302
+ if self.framing == "sse":
303
+ self._lines(True)
304
+ if self.framing == "eventstream":
305
+ self._frames()
306
+ if self.framing == "json" and self.carry:
307
+ self._absorb(json.loads(self.carry.decode("utf-8")))
308
+ except Exception:
309
+ pass # An unreadable body costs the usage, nothing more.
310
+ self.finished = True
311
+ self.carry = b""
312
+ if "request_id" not in self.call and self.body_request_id is not None:
313
+ self.call["request_id"] = self.body_request_id
314
+ self.on_finish(self.call)
315
+
316
+
317
+ def _framing_of(content_type):
318
+ kind = (content_type or "").lower()
319
+ if "text/event-stream" in kind:
320
+ return "sse"
321
+ if "vnd.amazon.eventstream" in kind:
322
+ return "eventstream"
323
+ return "json"
324
+
325
+
326
+ def _request_id_of(provider, headers):
327
+ for name in REQUEST_ID_HEADERS.get(provider, ()):
328
+ value = headers(name)
329
+ if value:
330
+ return value
331
+ return None
332
+
333
+
334
+ def _provider_of_host(host):
335
+ name = re.sub(r":\d+$", "", (host or "").lower())
336
+ if name in EXACT_HOSTS:
337
+ return EXACT_HOSTS[name]
338
+ if RE_VERTEX_HOST.match(name):
339
+ return "vertex"
340
+ return "bedrock" if RE_BEDROCK_HOST.match(name) else None
341
+
342
+
343
+ # Everything after ? is cut first: Gemini's API key can travel there.
344
+ def _model_from_path(raw_path):
345
+ pathname = raw_path.split("?")[0]
346
+ match = RE_BEDROCK_MODEL.search(pathname) or RE_URL_MODEL.search(pathname)
347
+ if not match:
348
+ return None
349
+ from urllib.parse import unquote
350
+
351
+ model = _model_name(unquote(match.group(1)))
352
+ # An ARN that stopped at its first /, or was encoded twice, still names the account.
353
+ return None if RE_ARN.match(model) else model
354
+
355
+
356
+ # An inference profile's ARN names the customer's account; the last segment names the model.
357
+ def _model_name(model):
358
+ return model[model.rfind("/") + 1 :] if "/" in model else model
359
+
360
+
361
+ def _call_meta(host, method, request_path):
362
+ """What the shim knows of a request, from its host, method and URL path alone.
363
+
364
+ Only a POST is a model call: a model listing or a health check is not spend.
365
+ """
366
+ provider = _provider_of_host(host)
367
+ if provider is None or str(method).upper() != "POST":
368
+ return None
369
+ meta = {"provider": provider}
370
+ model = _model_from_path(request_path or "")
371
+ if model is not None:
372
+ meta["model"] = model
373
+ return meta
374
+
375
+
376
+ def _worth_recording(call):
377
+ """A failure always (status only), a success only when it carried usage.
378
+
379
+ A success with none is no model call (count_tokens), or a body the shim could not read.
380
+ """
381
+ return call["status"] < 200 or call["status"] >= 300 or "usage" in call
382
+
383
+
384
+ def _is_agent_entry(entry):
385
+ if not entry:
386
+ return False
387
+ name = RE_WINDOWS_EXEC.sub("", os.path.basename(entry))
388
+ return name in AGENT_ENTRIES or AGENT_PACKAGES.search(entry) is not None
389
+
390
+
391
+ def _is_agent_process():
392
+ # sys.argv is not always there yet while site runs, but sys.orig_argv is from 3.10.
393
+ argv = getattr(sys, "argv", None) or []
394
+ orig = getattr(sys, "orig_argv", None) or []
395
+ entry = argv[0] if argv else None
396
+ if entry in (None, "") and len(orig) > 1 and not orig[1].startswith("-"):
397
+ entry = orig[1]
398
+ return _is_agent_entry(entry)
399
+
400
+
401
+ def _data_dir(env):
402
+ if env.get("AGENTWATCH_DATA_DIR"):
403
+ return env["AGENTWATCH_DATA_DIR"]
404
+ if sys.platform == "win32" and env.get("LOCALAPPDATA"):
405
+ return os.path.join(env["LOCALAPPDATA"], "agentwatch")
406
+ if env.get("XDG_DATA_HOME"):
407
+ return os.path.join(env["XDG_DATA_HOME"], "agentwatch")
408
+ return os.path.join(env.get("HOME") or os.path.expanduser("~"), ".local", "share", "agentwatch")
409
+
410
+
411
+ def _iso_now():
412
+ now = time.time()
413
+ return time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime(now)) + ".%03dZ" % int((now % 1) * 1000)
414
+
415
+
416
+ def _walk_ancestors(listing, pid):
417
+ rows = {}
418
+ for line in listing.split("\n"):
419
+ match = RE_PS_ROW.match(line)
420
+ if match:
421
+ rows[int(match.group(1))] = (int(match.group(2)), match.group(3))
422
+ chain = []
423
+ seen = {pid}
424
+ current = rows.get(pid)
425
+ while current and current[0] > 1 and current[0] not in seen and len(chain) < MAX_ANCESTORS:
426
+ parent = rows.get(current[0])
427
+ if not parent:
428
+ break
429
+ chain.append({"pid": current[0], "started": parent[1]})
430
+ seen.add(current[0])
431
+ current = parent
432
+ return chain
433
+
434
+
435
+ class _Spool:
436
+ """Appends records to this process's spool. Every method swallows its own faults."""
437
+
438
+ def __init__(self, env):
439
+ self.dir = os.path.join(_data_dir(env), SPOOL_DIR)
440
+ self.started = _iso_now()
441
+ self.ancestors = None
442
+ self.ancestors_pid = None
443
+ self.seq = 0
444
+ self.lines = 0
445
+
446
+ # Edge's hook creates the folder once it holds a credential. No folder, no capture.
447
+ # `agentwatch off` writes a marker beside it, and a session already running still has
448
+ # the shim loaded: asked per call, so nothing made while off is sent after `on`.
449
+ def armed(self):
450
+ return os.path.isdir(self.dir) and not os.path.exists(os.path.join(os.path.dirname(self.dir), DISABLED_MARKER))
451
+
452
+ def remember_ancestors(self):
453
+ """Read the ancestry now, while the launching shell still stands.
454
+
455
+ ponytail: one `ps -A` per process, at its first provider call, so a process with
456
+ no such call pays nothing. A process already orphaned by then (`cmd &` in a
457
+ shell that exited) attaches to no session, and is dropped and counted.
458
+ """
459
+ pid = os.getpid()
460
+ if self.ancestors is not None and self.ancestors_pid == pid:
461
+ return
462
+ self.ancestors_pid = pid
463
+ try:
464
+ import subprocess
465
+
466
+ listing = subprocess.run(
467
+ [next(path for path in PS_PATHS if os.path.exists(path)), "-A", "-o", "pid=,ppid=,lstart="],
468
+ stdin=subprocess.DEVNULL,
469
+ stdout=subprocess.PIPE,
470
+ stderr=subprocess.DEVNULL,
471
+ timeout=PS_TIMEOUT_S,
472
+ # No inherited environment: it holds the customer's keys. TZ stays, because a
473
+ # start time is compared as text with the one the hook's own ps printed.
474
+ env=dict({"LC_ALL": "C"}, **({"TZ": os.environ["TZ"]} if os.environ.get("TZ") else {})),
475
+ check=False,
476
+ )
477
+ self.ancestors = _walk_ancestors(listing.stdout.decode("utf-8", "replace"), pid)
478
+ except Exception:
479
+ self.ancestors = []
480
+
481
+ def _open(self, name):
482
+ flags = os.O_WRONLY | os.O_APPEND | os.O_CREAT | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_CLOEXEC", 0)
483
+ return os.open(os.path.join(self.dir, name), flags, 0o600)
484
+
485
+ def write(self, call):
486
+ """One synchronous append, so a call made just before exit is on disk."""
487
+ try:
488
+ self.remember_ancestors()
489
+ pid = os.getpid()
490
+ seq = self.seq
491
+ self.seq = seq + 1
492
+ fields = {"pid": pid, "started": self.started, "ancestors": self.ancestors, "at": _iso_now(), "seq": seq}
493
+ entry = (getattr(sys, "argv", None) or [""])[0]
494
+ if entry and entry not in ("-c", "-m", "-"):
495
+ fields["script"] = os.path.basename(entry)
496
+ line = json.dumps(dict(fields, **call))
497
+ fd = self._open("%d.jsonl" % pid)
498
+ try:
499
+ # The hook renames a file to consume it, so an empty one is a new count.
500
+ if os.fstat(fd).st_size == 0:
501
+ self.lines = 0
502
+ if self.lines >= MAX_LINES_PER_FILE:
503
+ self._drop(pid)
504
+ return
505
+ os.write(fd, (line + "\n").encode("utf-8"))
506
+ self.lines += 1
507
+ finally:
508
+ os.close(fd)
509
+ except Exception:
510
+ pass # A fault costs a record, never the run.
511
+
512
+ # One byte per call past the bound: the file's size is the count the hook reads.
513
+ def _drop(self, pid):
514
+ fd = self._open("%d.dropped" % pid)
515
+ try:
516
+ os.write(fd, b".")
517
+ finally:
518
+ os.close(fd)
519
+
520
+
521
+ def _safely(work, *args):
522
+ try:
523
+ return work(*args)
524
+ except Exception:
525
+ return None
526
+
527
+
528
+ class _Open:
529
+ """Responses still being read, so a process exiting mid-body still says what it saw."""
530
+
531
+ tapped = set()
532
+
533
+ @classmethod
534
+ def finish_all(cls):
535
+ for tap in list(cls.tapped):
536
+ _safely(tap.finish)
537
+
538
+
539
+ def _start_tap(meta, status, headers, spool, decoded):
540
+ def on_finish(call):
541
+ _Open.tapped.discard(tap)
542
+ if _worth_recording(call):
543
+ spool.write(call)
544
+
545
+ tap = _ResponseTap(meta, status, headers, on_finish, decoded)
546
+ _Open.tapped.add(tap)
547
+ return tap
548
+
549
+
550
+ def _patch_http_client(module, spool):
551
+ """Wrap HTTPConnection.getresponse, which urllib, urllib3 and requests all reach."""
552
+ connection = module.HTTPConnection
553
+ original_put = connection.putrequest
554
+ original_get = connection.getresponse
555
+
556
+ def putrequest(self, method, url, *args, **kwargs):
557
+ try:
558
+ self._agentwatch_call = _call_meta(getattr(self, "_tunnel_host", None) or self.host, method, url)
559
+ if self._agentwatch_call is not None:
560
+ if spool.armed():
561
+ spool.remember_ancestors()
562
+ else:
563
+ self._agentwatch_call = None
564
+ except Exception:
565
+ self._agentwatch_call = None
566
+ return original_put(self, method, url, *args, **kwargs)
567
+
568
+ def getresponse(self):
569
+ response = original_get(self)
570
+ try:
571
+ meta = getattr(self, "_agentwatch_call", None)
572
+ if meta is not None:
573
+ self._agentwatch_call = None
574
+ _tap_http_response(response, meta, spool)
575
+ except Exception:
576
+ pass # A fault costs a record, never the run.
577
+ return response
578
+
579
+ connection.putrequest = putrequest
580
+ connection.getresponse = getresponse
581
+
582
+
583
+ def _tap_http_response(response, meta, spool):
584
+ def header(name):
585
+ return response.getheader(name)
586
+
587
+ tap = _start_tap(meta, response.status, header, spool, False)
588
+ if response.status < 200 or response.status >= 300:
589
+ _safely(tap.finish)
590
+ return
591
+ base = type(response)
592
+
593
+ # The class is swapped rather than the file object wrapped: below read() the bytes
594
+ # still carry chunked framing. read() can reach readinto() on some versions, hence
595
+ # the depth check, so one chunk is seen once.
596
+ class TappedResponse(base):
597
+ def _agentwatch_observe(self, method, *args, **kwargs):
598
+ self._agentwatch_depth = getattr(self, "_agentwatch_depth", 0) + 1
599
+ try:
600
+ data = getattr(base, method)(self, *args, **kwargs)
601
+ except BaseException:
602
+ self._agentwatch_depth -= 1
603
+ _safely(tap.finish)
604
+ raise
605
+ self._agentwatch_depth -= 1
606
+ if self._agentwatch_depth == 0:
607
+ _safely(self._agentwatch_saw, method, data, args)
608
+ return data
609
+
610
+ def _agentwatch_saw(self, method, data, args):
611
+ # urllib3 decodes chunked framing itself, through _safe_read, and reads each
612
+ # chunk's trailing CRLF the same way; inside a JSON string that would corrupt it.
613
+ if method == "_safe_read" and data == b"\r\n":
614
+ return
615
+ if method == "readinto":
616
+ tap.feed(bytes(memoryview(args[0])[: data or 0]))
617
+ elif data:
618
+ tap.feed(data)
619
+ if not data or self.isclosed():
620
+ tap.finish()
621
+
622
+ def read(self, *args, **kwargs):
623
+ return self._agentwatch_observe("read", *args, **kwargs)
624
+
625
+ def _safe_read(self, *args, **kwargs):
626
+ return self._agentwatch_observe("_safe_read", *args, **kwargs)
627
+
628
+ def read1(self, *args, **kwargs):
629
+ return self._agentwatch_observe("read1", *args, **kwargs)
630
+
631
+ def readline(self, *args, **kwargs):
632
+ return self._agentwatch_observe("readline", *args, **kwargs)
633
+
634
+ def readinto(self, *args, **kwargs):
635
+ return self._agentwatch_observe("readinto", *args, **kwargs)
636
+
637
+ def close(self):
638
+ try:
639
+ return base.close(self)
640
+ finally:
641
+ _safely(tap.finish)
642
+
643
+ response.__class__ = TappedResponse
644
+
645
+
646
+ def _httpx_header(response):
647
+ def header(name):
648
+ return response.headers.get(name)
649
+
650
+ return header
651
+
652
+
653
+ def _meta_of_httpx(request, spool):
654
+ meta = _call_meta(request.url.host, request.method, request.url.path)
655
+ if meta is None or not spool.armed():
656
+ return None
657
+ spool.remember_ancestors()
658
+ return meta
659
+
660
+
661
+ def _patch_httpx(module, spool):
662
+ """Wrap Client.send and AsyncClient.send: httpx never touches http.client."""
663
+
664
+ def tap_of(response, meta):
665
+ return _start_tap(meta, response.status_code, _httpx_header(response), spool, False)
666
+
667
+ class TappedStream(module.SyncByteStream):
668
+ def __init__(self, inner, tap):
669
+ self.inner = inner
670
+ self.tap = tap
671
+
672
+ def __iter__(self):
673
+ try:
674
+ for chunk in self.inner:
675
+ _safely(self.tap.feed, chunk)
676
+ yield chunk
677
+ finally:
678
+ _safely(self.tap.finish)
679
+
680
+ def close(self):
681
+ try:
682
+ self.inner.close()
683
+ finally:
684
+ _safely(self.tap.finish)
685
+
686
+ class TappedAsyncStream(module.AsyncByteStream):
687
+ def __init__(self, inner, tap):
688
+ self.inner = inner
689
+ self.tap = tap
690
+
691
+ async def __aiter__(self):
692
+ try:
693
+ async for chunk in self.inner:
694
+ _safely(self.tap.feed, chunk)
695
+ yield chunk
696
+ finally:
697
+ _safely(self.tap.finish)
698
+
699
+ async def aclose(self):
700
+ try:
701
+ await self.inner.aclose()
702
+ finally:
703
+ _safely(self.tap.finish)
704
+
705
+ def attach(response, meta, stream_class):
706
+ tap = tap_of(response, meta)
707
+ if response.status_code < 200 or response.status_code >= 300:
708
+ _safely(tap.finish)
709
+ return
710
+ # stream=False: send() has already read the body, and decoded it.
711
+ if getattr(response, "_content", None) is not None:
712
+ tap.encoding = ""
713
+ tap.feed(response.content)
714
+ _safely(tap.finish)
715
+ return
716
+ response.stream = stream_class(response.stream, tap)
717
+
718
+ original_send = module.Client.send
719
+ original_async_send = module.AsyncClient.send
720
+
721
+ def send(self, request, *args, **kwargs):
722
+ meta = _safely(_meta_of_httpx, request, spool)
723
+ response = original_send(self, request, *args, **kwargs)
724
+ if meta is not None:
725
+ _safely(attach, response, meta, TappedStream)
726
+ return response
727
+
728
+ async def async_send(self, request, *args, **kwargs):
729
+ meta = _safely(_meta_of_httpx, request, spool)
730
+ response = await original_async_send(self, request, *args, **kwargs)
731
+ if meta is not None:
732
+ _safely(attach, response, meta, TappedAsyncStream)
733
+ return response
734
+
735
+ module.Client.send = send
736
+ module.AsyncClient.send = async_send
737
+
738
+
739
+ class _PatchOnImport:
740
+ """Patch a module the moment something imports it, and cost nothing until then."""
741
+
742
+ def __init__(self, patches):
743
+ self.patches = patches
744
+
745
+ def find_spec(self, name, path=None, target=None):
746
+ if name not in self.patches:
747
+ return None
748
+ # Any fault here would raise into the host's import, so it falls to the normal path.
749
+ try:
750
+ return self._wrapped_spec(name, path, target)
751
+ except Exception:
752
+ return None
753
+
754
+ def _wrapped_spec(self, name, path, target):
755
+ # Kept until the module really executes: find_spec alone (a library asking
756
+ # whether httpx is importable) must not use the patch up.
757
+ for finder in sys.meta_path:
758
+ if finder is self or not hasattr(finder, "find_spec"):
759
+ continue
760
+ spec = finder.find_spec(name, path, target)
761
+ if spec is not None:
762
+ loader = spec.loader
763
+ if hasattr(loader, "exec_module"):
764
+ original = loader.exec_module
765
+
766
+ def exec_module(module):
767
+ original(module)
768
+ patch = self.patches.pop(name, None)
769
+ if patch is not None:
770
+ _safely(patch, module)
771
+
772
+ loader.exec_module = exec_module
773
+ return spec
774
+ return None
775
+
776
+
777
+ def _install():
778
+ if os.environ.get("AGENTWATCH_CAPTURE") == "off" or _is_agent_process():
779
+ return
780
+ spool = _Spool(os.environ)
781
+ patches = {
782
+ "http.client": lambda module: _patch_http_client(module, spool),
783
+ "httpx": lambda module: _patch_httpx(module, spool),
784
+ }
785
+ for name in list(patches):
786
+ if name in sys.modules:
787
+ _safely(patches.pop(name), sys.modules[name])
788
+ sys.meta_path.insert(0, _PatchOnImport(patches))
789
+ import atexit
790
+
791
+ atexit.register(_Open.finish_all)
792
+
793
+
794
+ def _run_next_sitecustomize():
795
+ own = os.path.dirname(os.path.abspath(__file__))
796
+ for entry in sys.path:
797
+ folder = os.path.abspath(entry or os.getcwd())
798
+ candidate = os.path.join(folder, "sitecustomize.py")
799
+ if folder != own and os.path.isfile(candidate):
800
+ with open(candidate, "rb") as source:
801
+ code = source.read()
802
+ # Another copy of this file is passed over, not run: the developer's own may come after it.
803
+ if LOADED_FLAG.encode() in code:
804
+ continue
805
+ exec(compile(code, candidate, "exec"), {"__name__": "sitecustomize", "__file__": candidate})
806
+ return
807
+
808
+
809
+ def _replay(meta, status, headers, chunks):
810
+ """For the conformance suite only."""
811
+ call = _call_meta(meta["host"], meta["method"], meta["path"])
812
+ if call is None:
813
+ return None
814
+ result = {}
815
+
816
+ def on_finish(finished):
817
+ if _worth_recording(finished):
818
+ result.update(finished)
819
+
820
+ tap = _ResponseTap(call, status, headers.get, on_finish, False)
821
+ for chunk in chunks:
822
+ tap.feed(chunk)
823
+ tap.finish()
824
+ return result or None
825
+
826
+
827
+ # Once per process: PYTHONPATH and a venv's agentwatch-capture.pth can both load this file,
828
+ # and the sitecustomize it runs next may be another copy of it.
829
+ if __name__ == "sitecustomize" and not getattr(sys, LOADED_FLAG, False):
830
+ setattr(sys, LOADED_FLAG, True)
831
+ _safely(_install)
832
+ _safely(_run_next_sitecustomize)