@onecraft/wallet 0.0.0-stage → 0.1.145

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 (248) hide show
  1. package/.claude-plugin/marketplace.json +20 -0
  2. package/.openclaw/AGENTS.md +100 -0
  3. package/.openclaw/extensions/agent-wallet/README.md +195 -0
  4. package/.openclaw/extensions/agent-wallet/dist/index.js +2198 -0
  5. package/.openclaw/extensions/agent-wallet/index.ts +2198 -0
  6. package/.openclaw/extensions/agent-wallet/openclaw.plugin.json +251 -0
  7. package/.openclaw/extensions/agent-wallet/package.json +49 -0
  8. package/.openclaw/extensions/agent-wallet/skills/cards/SKILL.md +211 -0
  9. package/.openclaw/extensions/agent-wallet/skills/wallet-operator/SKILL.md +30 -0
  10. package/CHANGELOG.md +1232 -0
  11. package/LICENSE +104 -0
  12. package/README.md +193 -2
  13. package/VERSION +1 -0
  14. package/agent-wallet/.env.example +63 -0
  15. package/agent-wallet/AGENTS.md +130 -0
  16. package/agent-wallet/CARD_VAULT.md +640 -0
  17. package/agent-wallet/README.md +615 -0
  18. package/agent-wallet/UPGRADE_COMPATIBILITY.md +66 -0
  19. package/agent-wallet/agent_wallet/__init__.py +16 -0
  20. package/agent-wallet/agent_wallet/approval.py +165 -0
  21. package/agent-wallet/agent_wallet/autonomous_permissions.py +281 -0
  22. package/agent-wallet/agent_wallet/autonomous_policy.py +305 -0
  23. package/agent-wallet/agent_wallet/autonomous_session.py +236 -0
  24. package/agent-wallet/agent_wallet/boot_key_migration.py +155 -0
  25. package/agent-wallet/agent_wallet/boot_key_recovery.py +57 -0
  26. package/agent-wallet/agent_wallet/bootstrap.py +194 -0
  27. package/agent-wallet/agent_wallet/card_catalog.py +243 -0
  28. package/agent-wallet/agent_wallet/card_runtime_secrets.py +108 -0
  29. package/agent-wallet/agent_wallet/card_vault.py +331 -0
  30. package/agent-wallet/agent_wallet/card_vault_cli.py +174 -0
  31. package/agent-wallet/agent_wallet/card_vault_import.py +65 -0
  32. package/agent-wallet/agent_wallet/card_vault_keychain.py +239 -0
  33. package/agent-wallet/agent_wallet/config.py +719 -0
  34. package/agent-wallet/agent_wallet/connector_cli.py +198 -0
  35. package/agent-wallet/agent_wallet/connectors/__init__.py +28 -0
  36. package/agent-wallet/agent_wallet/connectors/catalog.py +68 -0
  37. package/agent-wallet/agent_wallet/connectors/client.py +308 -0
  38. package/agent-wallet/agent_wallet/connectors/intent_policy.py +243 -0
  39. package/agent-wallet/agent_wallet/connectors/manifest.py +192 -0
  40. package/agent-wallet/agent_wallet/connectors/registry.py +341 -0
  41. package/agent-wallet/agent_wallet/encrypted_storage.py +314 -0
  42. package/agent-wallet/agent_wallet/evm_user_wallets.py +910 -0
  43. package/agent-wallet/agent_wallet/exceptions.py +10 -0
  44. package/agent-wallet/agent_wallet/file_ops.py +34 -0
  45. package/agent-wallet/agent_wallet/http_client.py +25 -0
  46. package/agent-wallet/agent_wallet/kernel_browser.py +479 -0
  47. package/agent-wallet/agent_wallet/kernel_cli.py +57 -0
  48. package/agent-wallet/agent_wallet/kernel_gateway.py +95 -0
  49. package/agent-wallet/agent_wallet/keystore.py +503 -0
  50. package/agent-wallet/agent_wallet/laso_card_vault.py +246 -0
  51. package/agent-wallet/agent_wallet/models.py +66 -0
  52. package/agent-wallet/agent_wallet/morpho_monitor.py +298 -0
  53. package/agent-wallet/agent_wallet/nonce_registry.py +59 -0
  54. package/agent-wallet/agent_wallet/openclaw_adapter.py +9129 -0
  55. package/agent-wallet/agent_wallet/openclaw_cli.py +658 -0
  56. package/agent-wallet/agent_wallet/openclaw_runtime.py +194 -0
  57. package/agent-wallet/agent_wallet/plugin_bundle.py +44 -0
  58. package/agent-wallet/agent_wallet/providers/__init__.py +1 -0
  59. package/agent-wallet/agent_wallet/providers/bags.py +202 -0
  60. package/agent-wallet/agent_wallet/providers/dexscreener.py +147 -0
  61. package/agent-wallet/agent_wallet/providers/evm_activity.py +257 -0
  62. package/agent-wallet/agent_wallet/providers/evm_portfolio.py +459 -0
  63. package/agent-wallet/agent_wallet/providers/imd.py +720 -0
  64. package/agent-wallet/agent_wallet/providers/jupiter.py +519 -0
  65. package/agent-wallet/agent_wallet/providers/kamino.py +404 -0
  66. package/agent-wallet/agent_wallet/providers/lifi.py +302 -0
  67. package/agent-wallet/agent_wallet/providers/solana_rpc.py +447 -0
  68. package/agent-wallet/agent_wallet/providers/tokenized_stocks.py +189 -0
  69. package/agent-wallet/agent_wallet/providers/wdk_evm_local.py +346 -0
  70. package/agent-wallet/agent_wallet/providers/x402.py +1972 -0
  71. package/agent-wallet/agent_wallet/sealed_keys.py +118 -0
  72. package/agent-wallet/agent_wallet/solana_stake.py +103 -0
  73. package/agent-wallet/agent_wallet/solana_tx.py +93 -0
  74. package/agent-wallet/agent_wallet/spending_limits.py +119 -0
  75. package/agent-wallet/agent_wallet/telemetry.py +481 -0
  76. package/agent-wallet/agent_wallet/transaction_policy.py +573 -0
  77. package/agent-wallet/agent_wallet/update_check.py +190 -0
  78. package/agent-wallet/agent_wallet/user_wallets.py +573 -0
  79. package/agent-wallet/agent_wallet/validation.py +31 -0
  80. package/agent-wallet/agent_wallet/vault_executor.py +456 -0
  81. package/agent-wallet/agent_wallet/wallet_layer/__init__.py +1 -0
  82. package/agent-wallet/agent_wallet/wallet_layer/base.py +1204 -0
  83. package/agent-wallet/agent_wallet/wallet_layer/base58.py +44 -0
  84. package/agent-wallet/agent_wallet/wallet_layer/factory.py +117 -0
  85. package/agent-wallet/agent_wallet/wallet_layer/solana.py +5246 -0
  86. package/agent-wallet/agent_wallet/wallet_layer/wdk_evm.py +2705 -0
  87. package/agent-wallet/examples/bootstrap_wallet.py +21 -0
  88. package/agent-wallet/examples/openclaw_runtime_onboarding.py +28 -0
  89. package/agent-wallet/examples/openclaw_user_wallet_example.py +31 -0
  90. package/agent-wallet/examples/openclaw_wallet_adapter_example.py +33 -0
  91. package/agent-wallet/openclaw.plugin.json +118 -0
  92. package/agent-wallet/pyproject.toml +36 -0
  93. package/agent-wallet/scripts/bootstrap_openclaw_evm.py +312 -0
  94. package/agent-wallet/scripts/build_release_bundle.py +210 -0
  95. package/agent-wallet/scripts/finalize_openclaw_local_wallet_config.py +121 -0
  96. package/agent-wallet/scripts/install_agent_wallet.py +1357 -0
  97. package/agent-wallet/scripts/install_openclaw_local_config.py +421 -0
  98. package/agent-wallet/scripts/install_openclaw_sealed_keys.py +117 -0
  99. package/agent-wallet/scripts/manage_openclaw_evm_wallet.py +333 -0
  100. package/agent-wallet/scripts/security_utils.py +37 -0
  101. package/agent-wallet/scripts/setup_evm_wallet.sh +140 -0
  102. package/agent-wallet/scripts/switch_openclaw_wallet_network.py +109 -0
  103. package/agent-wallet/skills/wallet-operator/SKILL.md +157 -0
  104. package/bin/lib/boot-key.mjs +184 -0
  105. package/bin/lib/evm-daemon.mjs +389 -0
  106. package/bin/lib/host-detection.mjs +259 -0
  107. package/bin/lib/integrations.mjs +578 -0
  108. package/bin/lib/release-python.mjs +9 -0
  109. package/bin/lib/update-transaction.mjs +235 -0
  110. package/bin/openclaw-agent-wallet.mjs +3354 -0
  111. package/claude-code/plugins/agent-wallet/.claude-plugin/plugin.json +19 -0
  112. package/claude-code/plugins/agent-wallet/.mcp.json +14 -0
  113. package/claude-code/plugins/agent-wallet/AGENTLAYER_AGENT_GUIDE.md +282 -0
  114. package/claude-code/plugins/agent-wallet/README.md +134 -0
  115. package/claude-code/plugins/agent-wallet/commands/agentlayer-autonomous-approve.md +39 -0
  116. package/claude-code/plugins/agent-wallet/commands/agentlayer-autonomous-revoke.md +17 -0
  117. package/claude-code/plugins/agent-wallet/commands/cards.md +129 -0
  118. package/claude-code/plugins/agent-wallet/commands/guide.md +40 -0
  119. package/claude-code/plugins/agent-wallet/commands/imd.md +125 -0
  120. package/claude-code/plugins/agent-wallet/commands/wallet-base.md +60 -0
  121. package/claude-code/plugins/agent-wallet/commands/wallet-ethereum.md +37 -0
  122. package/claude-code/plugins/agent-wallet/commands/wallet-evm.md +39 -0
  123. package/claude-code/plugins/agent-wallet/commands/wallet-setup.md +25 -0
  124. package/claude-code/plugins/agent-wallet/commands/wallet-sol.md +51 -0
  125. package/claude-code/plugins/agent-wallet/commands/wallet-statusline.md +34 -0
  126. package/claude-code/plugins/agent-wallet/commands/x402.md +121 -0
  127. package/claude-code/plugins/agent-wallet/commands/yield.md +62 -0
  128. package/claude-code/plugins/agent-wallet/hooks/hooks.json +16 -0
  129. package/claude-code/plugins/agent-wallet/scripts/bootstrap_backend.sh +136 -0
  130. package/claude-code/plugins/agent-wallet/scripts/enable_statusline.py +52 -0
  131. package/claude-code/plugins/agent-wallet/scripts/resolve_wallet_addresses.py +69 -0
  132. package/claude-code/plugins/agent-wallet/scripts/run_mcp.sh +66 -0
  133. package/claude-code/plugins/agent-wallet/scripts/wallet_statusline.py +130 -0
  134. package/claude-code/plugins/agent-wallet/scripts/wallet_statusline_setup.sh +40 -0
  135. package/claude-code/plugins/agent-wallet/skills/wallet-operator/SKILL.md +21 -0
  136. package/codex/plugins/agent-wallet/.codex-plugin/plugin.json +37 -0
  137. package/codex/plugins/agent-wallet/.mcp.json +15 -0
  138. package/codex/plugins/agent-wallet/README.md +158 -0
  139. package/codex/plugins/agent-wallet/scripts/run_mcp.sh +47 -0
  140. package/codex/plugins/agent-wallet/server.py +1797 -0
  141. package/codex/plugins/agent-wallet/skills/cards/SKILL.md +225 -0
  142. package/codex/plugins/agent-wallet/skills/imd/SKILL.md +145 -0
  143. package/codex/plugins/agent-wallet/skills/wallet-base/SKILL.md +56 -0
  144. package/codex/plugins/agent-wallet/skills/wallet-operator/SKILL.md +85 -0
  145. package/codex/plugins/agent-wallet/skills/wallet-sol/SKILL.md +29 -0
  146. package/codex/plugins/agent-wallet/skills/x402/SKILL.md +159 -0
  147. package/codex/plugins/agent-wallet/skills/yield/SKILL.md +65 -0
  148. package/connectors/AGENTS.md +37 -0
  149. package/connectors/DEVELOPER_GUIDE.md +131 -0
  150. package/connectors/README.md +139 -0
  151. package/connectors/READ_ONLY_BETA.md +54 -0
  152. package/connectors/RELEASING.md +48 -0
  153. package/connectors/conformance/README.md +31 -0
  154. package/connectors/conformance/package.json +54 -0
  155. package/connectors/conformance/scripts/sync-license.mjs +3 -0
  156. package/connectors/conformance/scripts/sync-spec.mjs +16 -0
  157. package/connectors/conformance/src/cli.ts +43 -0
  158. package/connectors/conformance/src/index.ts +7 -0
  159. package/connectors/conformance/src/runner.ts +314 -0
  160. package/connectors/conformance/src/types.ts +27 -0
  161. package/connectors/conformance/test/fixtures/invalid-response-identity.json +14 -0
  162. package/connectors/conformance/test/fixtures/missing-tool-fixture.json +4 -0
  163. package/connectors/conformance/test/runner.test.mjs +151 -0
  164. package/connectors/conformance/tsconfig.json +17 -0
  165. package/connectors/examples/reference-crypto-data/Dockerfile +21 -0
  166. package/connectors/examples/reference-crypto-data/README.md +51 -0
  167. package/connectors/examples/reference-crypto-data/conformance.json +11 -0
  168. package/connectors/examples/reference-crypto-data/connector.json +95 -0
  169. package/connectors/examples/reference-crypto-data/package.json +21 -0
  170. package/connectors/examples/reference-crypto-data/railway.toml +9 -0
  171. package/connectors/examples/reference-crypto-data/src/connector.ts +137 -0
  172. package/connectors/examples/reference-crypto-data/src/server.ts +13 -0
  173. package/connectors/examples/reference-crypto-data/test/connector.test.mjs +97 -0
  174. package/connectors/examples/reference-crypto-data/tsconfig.json +17 -0
  175. package/connectors/package-lock.json +561 -0
  176. package/connectors/package.json +19 -0
  177. package/connectors/scripts/smoke-packed-packages.mjs +121 -0
  178. package/connectors/sdk-typescript/README.md +47 -0
  179. package/connectors/sdk-typescript/package.json +49 -0
  180. package/connectors/sdk-typescript/scripts/sync-license.mjs +3 -0
  181. package/connectors/sdk-typescript/src/connector.ts +204 -0
  182. package/connectors/sdk-typescript/src/errors.ts +11 -0
  183. package/connectors/sdk-typescript/src/http.ts +116 -0
  184. package/connectors/sdk-typescript/src/index.ts +26 -0
  185. package/connectors/sdk-typescript/src/types.ts +101 -0
  186. package/connectors/sdk-typescript/test/sdk.test.mjs +181 -0
  187. package/connectors/sdk-typescript/tsconfig.json +21 -0
  188. package/connectors/spec/connector-manifest.schema.json +340 -0
  189. package/connectors/spec/connector-protocol.md +159 -0
  190. package/connectors/spec/transaction-intent.schema.json +281 -0
  191. package/connectors/templates/read-only/.env.example +1 -0
  192. package/connectors/templates/read-only/Dockerfile +11 -0
  193. package/connectors/templates/read-only/README.md +33 -0
  194. package/connectors/templates/read-only/conformance.json +11 -0
  195. package/connectors/templates/read-only/connector.json +64 -0
  196. package/connectors/templates/read-only/package.json +21 -0
  197. package/connectors/templates/read-only/railway.toml +9 -0
  198. package/connectors/templates/read-only/src/connector.ts +61 -0
  199. package/connectors/templates/read-only/src/server.ts +14 -0
  200. package/connectors/templates/read-only/test/connector.test.mjs +62 -0
  201. package/connectors/templates/read-only/tsconfig.json +17 -0
  202. package/cursor/plugins/agent-wallet/.cursor-plugin/plugin.json +14 -0
  203. package/cursor/plugins/agent-wallet/README.md +62 -0
  204. package/cursor/plugins/agent-wallet/mcp.json +16 -0
  205. package/cursor/plugins/agent-wallet/scripts/run_mcp.sh +33 -0
  206. package/cursor/plugins/agent-wallet/server.py +33 -0
  207. package/cursor/plugins/agent-wallet/skills/cards/SKILL.md +210 -0
  208. package/cursor/plugins/agent-wallet/skills/wallet-base/SKILL.md +56 -0
  209. package/cursor/plugins/agent-wallet/skills/wallet-operator/SKILL.md +23 -0
  210. package/cursor/plugins/agent-wallet/skills/wallet-sol/SKILL.md +29 -0
  211. package/cursor/plugins/agent-wallet/skills/x402/SKILL.md +130 -0
  212. package/hermes/plugins/agent_wallet/README.md +54 -0
  213. package/hermes/plugins/agent_wallet/__init__.py +55 -0
  214. package/hermes/plugins/agent_wallet/plugin.yaml +9 -0
  215. package/hermes/plugins/agent_wallet/schemas.py +211 -0
  216. package/hermes/plugins/agent_wallet/tools.py +622 -0
  217. package/install-from-github.sh +139 -0
  218. package/integrations/hedera/treasury-guard/README.md +92 -0
  219. package/integrations/hedera/treasury-guard/examples/treasury-policy.example.json +9 -0
  220. package/integrations/hedera/treasury-guard/package-lock.json +880 -0
  221. package/integrations/hedera/treasury-guard/package.json +8 -0
  222. package/integrations/hedera/treasury-guard/skills/onecraft-hedera-treasury/SKILL.md +22 -0
  223. package/integrations/hedera/treasury-guard/src/hedera-mirror-client.mjs +106 -0
  224. package/integrations/hedera/treasury-guard/src/hedera-signer.mjs +120 -0
  225. package/integrations/hedera/treasury-guard/src/treasury-cli.mjs +177 -0
  226. package/integrations/hedera/treasury-guard/src/treasury-policy.mjs +155 -0
  227. package/mcp/README.md +39 -0
  228. package/mcp/scripts/run_mcp.sh +37 -0
  229. package/mcp/server.py +33 -0
  230. package/package.json +106 -4
  231. package/scripts/check_release_version.mjs +72 -0
  232. package/scripts/version_targets.mjs +60 -0
  233. package/setup.sh +87 -0
  234. package/wdk-evm-wallet/.env.example +38 -0
  235. package/wdk-evm-wallet/README.md +254 -0
  236. package/wdk-evm-wallet/bootstrap.sh +8 -0
  237. package/wdk-evm-wallet/package-lock.json +2359 -0
  238. package/wdk-evm-wallet/package.json +43 -0
  239. package/wdk-evm-wallet/run-local.sh +12 -0
  240. package/wdk-evm-wallet/src/config.js +461 -0
  241. package/wdk-evm-wallet/src/imd.js +231 -0
  242. package/wdk-evm-wallet/src/json.js +35 -0
  243. package/wdk-evm-wallet/src/local_vault.js +407 -0
  244. package/wdk-evm-wallet/src/network_state.js +96 -0
  245. package/wdk-evm-wallet/src/pending_transactions.js +148 -0
  246. package/wdk-evm-wallet/src/server.js +849 -0
  247. package/wdk-evm-wallet/src/shutdown.js +63 -0
  248. package/wdk-evm-wallet/src/wdk_evm_wallet.js +10036 -0
@@ -0,0 +1,481 @@
1
+ """Anonymous, privacy-first adoption telemetry for the OneCraft wallet.
2
+
3
+ Why this exists: we want to know how many people use the wallet and through which
4
+ host (Claude Code / Codex / Cursor / Hermes / OpenClaw) — nothing more. It deliberately
5
+ records NO PII: no wallet addresses, balances, amounts, tx hashes, tool
6
+ arguments, or secrets. Only a random local install id, the host name, the
7
+ invoked tool's registered name, the backend family, the plugin version, a
8
+ success flag, the preview/execute mode, and a coarse error class.
9
+
10
+ Design for a short-lived CLI subprocess:
11
+ - `record()` appends one JSON line to a local spool file. This is instant and
12
+ durable: a single small append is atomic on POSIX, and the event survives
13
+ even if this process exits before any network call completes.
14
+ - A throttled, best-effort flush claims the spool (atomic rename), POSTs each
15
+ event to the provider-gateway, and re-spools anything that failed. Because
16
+ durability lives in the spool, a killed flush never loses data — the next
17
+ invocation (or a longer-lived process) ships it.
18
+
19
+ Everything here swallows its own errors. Telemetry must never slow down or break
20
+ a wallet operation. Users opt out with AGENT_WALLET_NO_TELEMETRY=1.
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ import json
26
+ import os
27
+ import subprocess
28
+ import sys
29
+ import time
30
+ import urllib.request
31
+ import uuid
32
+ from decimal import Decimal, InvalidOperation
33
+ from pathlib import Path
34
+ from typing import Any
35
+
36
+ from . import __version__
37
+ from .config import DEFAULT_PROVIDER_GATEWAY_URL, resolve_openclaw_home
38
+
39
+ ALLOWED_HOSTS = {"claude-code", "codex", "cursor", "hermes", "mcp", "openclaw"}
40
+ ALLOWED_MODES = {"preview", "execute", "intent_preview", "intent_execute"}
41
+
42
+ # Set by the MCP bridge (codex server.py, shared by Claude Code / Codex / Cursor /
43
+ # universal MCP) on its wallet subprocesses. The bridge then records each
44
+ # tool_invoke itself — it alone sees resident-worker reads and bridge-only
45
+ # tools under their public names — so the CLI must not record it again.
46
+ BRIDGE_ENV = "AGENT_WALLET_TELEMETRY_BRIDGE"
47
+
48
+ SPOOL_NAME = "telemetry_spool.jsonl"
49
+ ID_NAME = "telemetry_id"
50
+ LAST_FLUSH_NAME = "telemetry_last_flush"
51
+
52
+ # Keep the spool bounded if the gateway is unreachable for a long time.
53
+ MAX_SPOOL_LINES = 500
54
+ # Don't attempt a network flush more than this often (seconds), unless the spool
55
+ # has grown past the soft cap below.
56
+ FLUSH_THROTTLE_SECONDS = 20
57
+ FLUSH_FORCE_LINES = 50
58
+ # Tight network bounds: telemetry never blocks meaningfully.
59
+ HTTP_TIMEOUT_SECONDS = 1.5
60
+ MAX_EVENTS_PER_FLUSH = 100
61
+
62
+
63
+ def _enabled() -> bool:
64
+ raw = os.getenv("AGENT_WALLET_NO_TELEMETRY", "").strip().lower()
65
+ return raw not in ("1", "true", "yes", "on")
66
+
67
+
68
+ def _home() -> Path:
69
+ return resolve_openclaw_home()
70
+
71
+
72
+ def _gateway_url() -> str:
73
+ url = os.getenv("PROVIDER_GATEWAY_URL", "").strip() or DEFAULT_PROVIDER_GATEWAY_URL
74
+ return url.rstrip("/")
75
+
76
+
77
+ def _host() -> str:
78
+ host = os.getenv("AGENT_WALLET_HOST", "").strip().lower()
79
+ return host if host in ALLOWED_HOSTS else "unknown"
80
+
81
+
82
+ def bridge_records_tool_calls() -> bool:
83
+ return os.getenv(BRIDGE_ENV, "").strip() == "1"
84
+
85
+
86
+ def tool_mode(arguments: Any) -> str:
87
+ """The preview/execute mode of a write-tool call, or "" for reads."""
88
+ if not isinstance(arguments, dict):
89
+ return ""
90
+ mode = str(arguments.get("mode") or "").strip().lower()
91
+ return mode if mode in ALLOWED_MODES else ""
92
+
93
+
94
+ def classify_tool_error(code: Any = "", message: Any = "") -> str:
95
+ """Map a failure to a coarse class. Only the class leaves the machine."""
96
+ text = f"{code or ''} {message or ''}".lower()
97
+ if not text.strip():
98
+ return "unknown"
99
+ if "approval" in text or "confirm" in text:
100
+ return "approval"
101
+ if "insufficient" in text or "not enough" in text:
102
+ return "insufficient_funds"
103
+ if "rate limit" in text or "429" in text or "too many requests" in text:
104
+ return "rate_limited"
105
+ if "timeout" in text or "timed out" in text or "connection" in text or "network error" in text:
106
+ return "network"
107
+ if any(part in text for part in ("locked", "not installed", "not configured", "onboard", "boot key", "keychain")):
108
+ return "not_ready"
109
+ if any(part in text for part in ("invalid", "required", "must be", "unsupported", "not allowed", "validation")):
110
+ return "validation"
111
+ if any(part in text for part in ("provider", "upstream", "http ", "status 5")):
112
+ return "provider"
113
+ return "wallet"
114
+
115
+
116
+ def _install_id() -> str:
117
+ """Stable, random, non-identifying id for this install. Created once."""
118
+ path = _home() / ID_NAME
119
+ try:
120
+ existing = path.read_text(encoding="utf-8").strip()
121
+ if existing:
122
+ return existing
123
+ except OSError:
124
+ pass
125
+ new_id = uuid.uuid4().hex
126
+ try:
127
+ path.parent.mkdir(parents=True, exist_ok=True)
128
+ path.write_text(new_id, encoding="utf-8")
129
+ except OSError:
130
+ pass
131
+ return new_id
132
+
133
+
134
+ def record(
135
+ tool: str,
136
+ *,
137
+ backend: str = "",
138
+ ok: bool = True,
139
+ event: str = "tool_invoke",
140
+ network: str = "",
141
+ scheme: str = "",
142
+ asset_family: str = "",
143
+ amount_bucket: str = "",
144
+ settlement_status: str = "",
145
+ error_class: str = "",
146
+ mode: str = "",
147
+ ) -> None:
148
+ """Append an anonymous event to the spool and best-effort flush. Never raises."""
149
+ try:
150
+ if not _enabled():
151
+ return
152
+ payload = {
153
+ "event": event,
154
+ "install_id": _install_id(),
155
+ "host": _host(),
156
+ "tool": tool or "",
157
+ "backend": backend or "",
158
+ "plugin_version": __version__,
159
+ "ok": bool(ok),
160
+ "ts": int(time.time()),
161
+ "network": network,
162
+ "scheme": scheme,
163
+ "asset_family": asset_family,
164
+ "amount_bucket": amount_bucket,
165
+ "settlement_status": settlement_status,
166
+ "error_class": error_class,
167
+ }
168
+ if mode in ALLOWED_MODES:
169
+ payload["mode"] = mode
170
+ _append_spool(payload)
171
+ _maybe_spawn_flush()
172
+ except Exception:
173
+ # Telemetry is never allowed to affect the wallet call.
174
+ pass
175
+
176
+
177
+ def record_cli_invoke(tool: str, arguments_json: Any, *, backend: str, payload: Any) -> None:
178
+ """Record one ``openclaw_cli invoke`` tool call (Hermes, OpenClaw, cold paths).
179
+
180
+ Skipped when the MCP bridge launched this process: it records the call
181
+ itself, so recording here would double count. Never raises.
182
+ """
183
+ try:
184
+ if bridge_records_tool_calls():
185
+ return
186
+ try:
187
+ arguments = json.loads(arguments_json) if isinstance(arguments_json, str) else arguments_json
188
+ except ValueError:
189
+ arguments = None
190
+ result = payload if isinstance(payload, dict) else {}
191
+ ok = bool(result.get("ok", False))
192
+ record(
193
+ tool,
194
+ backend=backend,
195
+ ok=ok,
196
+ mode=tool_mode(arguments),
197
+ error_class="" if ok else classify_tool_error(
198
+ result.get("error_code") or result.get("code"), result.get("error")
199
+ ),
200
+ )
201
+ except Exception:
202
+ pass
203
+
204
+
205
+ def _x402_amount_bucket(value: Any) -> str:
206
+ try:
207
+ amount = Decimal(str(value))
208
+ except (InvalidOperation, TypeError, ValueError):
209
+ return "unknown"
210
+ if amount < 0:
211
+ return "unknown"
212
+ if amount < Decimal("2"):
213
+ return "lt_2_usd"
214
+ if amount < Decimal("10"):
215
+ return "2_to_10_usd"
216
+ if amount < Decimal("100"):
217
+ return "10_to_100_usd"
218
+ return "gte_100_usd"
219
+
220
+
221
+ def _x402_asset_family(asset: Any, amount_display: Any) -> str:
222
+ # amount_display is populated only for confidently identified USDC.
223
+ if amount_display is not None:
224
+ return "usdc"
225
+ return "other" if str(asset or "").strip() else "unknown"
226
+
227
+
228
+ def _x402_error_class(value: Any) -> str:
229
+ code = str(value or "").strip().lower()
230
+ if not code:
231
+ return "unknown"
232
+ if "approval" in code:
233
+ return "approval"
234
+ if "policy" in code or "validate" in code:
235
+ return "validation"
236
+ if "timeout" in code or "network" in code or "http" in code:
237
+ return "network"
238
+ if code.startswith("x402-") or "provider" in code:
239
+ return "provider"
240
+ return "wallet"
241
+
242
+
243
+ def _x402_dimensions(payload: dict[str, Any], data: dict[str, Any]) -> dict[str, str]:
244
+ return {
245
+ "network": str(data.get("x402_network") or "unknown"),
246
+ "scheme": str(data.get("x402_scheme") or "unknown"),
247
+ "asset_family": _x402_asset_family(data.get("x402_asset"), data.get("x402_amount_display")),
248
+ "amount_bucket": _x402_amount_bucket(data.get("x402_amount_display")),
249
+ "error_class": _x402_error_class(payload.get("error_code")),
250
+ }
251
+
252
+
253
+ def record_x402_lifecycle(tool: str, result: dict[str, Any] | None) -> None:
254
+ """Record privacy-safe x402 lifecycle stages alongside ``tool_invoke``.
255
+
256
+ The generic tool event remains the source of truth for tool-call volume.
257
+ These additional events only describe progress through the paid-request
258
+ flow; they intentionally exclude request URLs, addresses, amounts,
259
+ transaction hashes, response bodies, and signed payment payloads.
260
+ """
261
+ if tool not in {"x402_preview_request", "x402_pay_request"}:
262
+ return
263
+ payload = result if isinstance(result, dict) else {}
264
+ ok = bool(payload.get("ok", False))
265
+ data = payload.get("data") if isinstance(payload.get("data"), dict) else {}
266
+ dimensions = _x402_dimensions(payload, data)
267
+
268
+ if tool == "x402_preview_request":
269
+ record("", event="x402_previewed" if ok else "x402_preview_failed", ok=ok, **dimensions)
270
+ return
271
+
272
+ # This is deliberately distinct from tool_invoke: it gives the x402 funnel
273
+ # a stable entry stage while retaining x402_pay_request call volume.
274
+ record("", event="x402_payment_attempted", ok=True, **dimensions)
275
+ if not ok:
276
+ record("", event="x402_payment_failed", ok=False, settlement_status="failed", **dimensions)
277
+ return
278
+ if not bool(data.get("paid", False)):
279
+ record("", event="x402_payment_not_required", ok=True, settlement_status="not_required", **dimensions)
280
+ return
281
+ settlement = data.get("payment_settlement")
282
+ if isinstance(settlement, dict) and settlement.get("success") is True:
283
+ record("", event="x402_payment_settled", ok=True, settlement_status="settled", **dimensions)
284
+ else:
285
+ record("", event="x402_payment_failed", ok=False, settlement_status="unconfirmed", **dimensions)
286
+
287
+
288
+ # --- spool I/O --------------------------------------------------------------
289
+
290
+
291
+ def _spool_path() -> Path:
292
+ return _home() / SPOOL_NAME
293
+
294
+
295
+ def _append_spool(payload: dict[str, Any]) -> None:
296
+ path = _spool_path()
297
+ line = json.dumps(payload, separators=(",", ":")) + "\n"
298
+ path.parent.mkdir(parents=True, exist_ok=True)
299
+ # A single write of a short line is atomic across processes on POSIX.
300
+ with open(path, "a", encoding="utf-8") as fh:
301
+ fh.write(line)
302
+
303
+
304
+ def _spool_line_count() -> int:
305
+ try:
306
+ with open(_spool_path(), "r", encoding="utf-8") as fh:
307
+ return sum(1 for _ in fh)
308
+ except OSError:
309
+ return 0
310
+
311
+
312
+ def _should_flush_now() -> bool:
313
+ count = _spool_line_count()
314
+ if count == 0:
315
+ return False
316
+ if count >= FLUSH_FORCE_LINES:
317
+ return True
318
+ last_path = _home() / LAST_FLUSH_NAME
319
+ try:
320
+ last = float(last_path.read_text(encoding="utf-8").strip() or "0")
321
+ except (OSError, ValueError):
322
+ last = 0.0
323
+ return (time.time() - last) >= FLUSH_THROTTLE_SECONDS
324
+
325
+
326
+ def _mark_flush_attempt() -> None:
327
+ try:
328
+ (_home() / LAST_FLUSH_NAME).write_text(str(time.time()), encoding="utf-8")
329
+ except OSError:
330
+ pass
331
+
332
+
333
+ def _maybe_spawn_flush() -> None:
334
+ """Trigger a flush in a DETACHED subprocess that outlives this process.
335
+
336
+ A per-tool CLI invocation exits microseconds after recording, so a thread
337
+ would be killed mid-flush. A detached child (its own session, no wait) runs
338
+ the network call on its own time and re-spools failures reliably. Throttling
339
+ keeps this to roughly one spawn per FLUSH_THROTTLE_SECONDS, so most calls
340
+ just append to the spool and return.
341
+ """
342
+ if not _should_flush_now():
343
+ return
344
+ _mark_flush_attempt()
345
+ try:
346
+ # The MCP bridge imports this module via a temporary sys.path entry, so
347
+ # PYTHONPATH may not reach the package; pass it explicitly.
348
+ env = dict(os.environ)
349
+ package_root = str(Path(__file__).resolve().parents[1])
350
+ current = env.get("PYTHONPATH", "")
351
+ env["PYTHONPATH"] = f"{package_root}{os.pathsep}{current}" if current else package_root
352
+ subprocess.Popen(
353
+ [sys.executable, "-m", "agent_wallet.telemetry", "--flush"],
354
+ env=env,
355
+ stdout=subprocess.DEVNULL,
356
+ stderr=subprocess.DEVNULL,
357
+ stdin=subprocess.DEVNULL,
358
+ start_new_session=True, # detach so parent exit doesn't kill it
359
+ )
360
+ except Exception:
361
+ pass
362
+
363
+
364
+ def _pid_alive(pid: int) -> bool:
365
+ try:
366
+ os.kill(pid, 0)
367
+ except ProcessLookupError:
368
+ return False
369
+ except PermissionError:
370
+ return True # exists but owned by another user
371
+ except OSError:
372
+ return True
373
+ return True
374
+
375
+
376
+ def _claim_suffix_pid(path: Path) -> int | None:
377
+ # ...telemetry_spool.jsonl.flushing.<pid>
378
+ try:
379
+ return int(path.name.rsplit(".flushing.", 1)[1])
380
+ except (IndexError, ValueError):
381
+ return None
382
+
383
+
384
+ def _flush() -> None:
385
+ """Claim the spool atomically, adopt dead-PID orphans, POST, re-spool failures."""
386
+ spool = _spool_path()
387
+ home = _home()
388
+ claim = spool.with_suffix(spool.suffix + f".flushing.{os.getpid()}")
389
+
390
+ claims: list[Path] = []
391
+ try:
392
+ os.rename(spool, claim) # atomic; only one process wins the live spool
393
+ claims.append(claim)
394
+ except OSError:
395
+ pass # nothing to flush, or another process claimed it
396
+
397
+ # Recover orphans left by a flush that died mid-run (crash/exit after the
398
+ # rename but before re-spooling). Only adopt claims whose PID is gone so we
399
+ # never steal a batch a live sibling is still working.
400
+ try:
401
+ for orphan in home.glob(SPOOL_NAME + ".flushing.*"):
402
+ if orphan == claim:
403
+ continue
404
+ pid = _claim_suffix_pid(orphan)
405
+ if pid is None or not _pid_alive(pid):
406
+ claims.append(orphan)
407
+ except OSError:
408
+ pass
409
+
410
+ if not claims:
411
+ return
412
+
413
+ lines: list[str] = []
414
+ for c in claims:
415
+ try:
416
+ lines.extend(c.read_text(encoding="utf-8").splitlines())
417
+ except OSError:
418
+ pass
419
+
420
+ # Bound a long backlog (gateway down for a while): keep the most recent.
421
+ if len(lines) > MAX_SPOOL_LINES:
422
+ lines = lines[-MAX_SPOOL_LINES:]
423
+
424
+ url = _gateway_url() + "/v1/telemetry"
425
+ failed: list[str] = []
426
+ sent = 0
427
+ for line in lines:
428
+ line = line.strip()
429
+ if not line:
430
+ continue
431
+ if sent >= MAX_EVENTS_PER_FLUSH:
432
+ failed.append(line) # defer the rest to the next flush
433
+ continue
434
+ if _post(url, line):
435
+ sent += 1
436
+ else:
437
+ failed.append(line)
438
+
439
+ # Re-spool failures BEFORE removing claims: favors at-least-once delivery
440
+ # (a crash here re-sends, never drops). Successes are gone from the claims.
441
+ if failed:
442
+ try:
443
+ with open(spool, "a", encoding="utf-8") as fh:
444
+ fh.write("\n".join(failed) + "\n")
445
+ except OSError:
446
+ pass
447
+
448
+ for c in claims:
449
+ try:
450
+ c.unlink()
451
+ except OSError:
452
+ pass
453
+
454
+
455
+ def _post(url: str, body: str) -> bool:
456
+ try:
457
+ req = urllib.request.Request(
458
+ url,
459
+ data=body.encode("utf-8"),
460
+ headers={"Content-Type": "application/json"},
461
+ method="POST",
462
+ )
463
+ with urllib.request.urlopen(req, timeout=HTTP_TIMEOUT_SECONDS) as resp:
464
+ return 200 <= resp.status < 300
465
+ except Exception:
466
+ return False
467
+
468
+
469
+ def _flush_main() -> int:
470
+ """Entry point for the detached flush subprocess (`-m agent_wallet.telemetry --flush`)."""
471
+ try:
472
+ _flush()
473
+ except Exception:
474
+ pass
475
+ return 0
476
+
477
+
478
+ if __name__ == "__main__":
479
+ if "--flush" in sys.argv[1:]:
480
+ raise SystemExit(_flush_main())
481
+ raise SystemExit(0)