@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,305 @@
1
+ """Autonomous execution policy engine for agent wallets.
2
+
3
+ The default execute path in :mod:`agent_wallet` is human-in-the-loop: the
4
+ host issues an approval token (see :mod:`agent_wallet.approval`) *after* a
5
+ person reviews the preview summary. This module adds an opt-in alternative
6
+ that lets an operation execute **without a human confirming each transaction**
7
+ — but only when it passes a deterministic risk gate that the operator
8
+ configures up front.
9
+
10
+ The design mirrors the "programmable controls set in advance" model used by
11
+ Coinbase AgentKit / CDP Agentic Wallets (session caps, per-transaction
12
+ limits, allow-lists) and the ``WalletProvider`` guard pattern: a thin policy
13
+ layer wraps the existing execute path instead of replacing it.
14
+
15
+ Key safety properties:
16
+
17
+ * **Deny by default.** A freshly constructed :class:`AutonomousSessionConfig`
18
+ approves nothing. Every capability (tool, network, recipient, spend
19
+ amount, mainnet access) must be explicitly enabled.
20
+ * **Same downstream verification.** When the gate passes, the engine issues
21
+ the *exact same* signed approval token the host would issue — only the
22
+ ``issued_by`` field differs (``"autonomous-policy"``). Nothing downstream
23
+ has to change or trust a new code path.
24
+ * **Bounded sessions.** Spend limits (reusing :class:`SpendingLedger`),
25
+ operation counts, and a session TTL bound the blast radius of a
26
+ compromised or misbehaving agent.
27
+
28
+ This module performs *no* network or signing I/O and has no dependency on a
29
+ live wallet backend, so it is cheap to unit-test in isolation.
30
+ """
31
+
32
+ from __future__ import annotations
33
+
34
+ import threading
35
+ import time
36
+ from dataclasses import dataclass, field
37
+ from typing import Callable
38
+
39
+ from agent_wallet.approval import issue_approval_token
40
+ from agent_wallet.spending_limits import SpendingConfig, SpendingLedger
41
+ from agent_wallet.wallet_layer.base import WalletBackendError
42
+
43
+ #: Issuer label stamped onto autonomously-approved tokens so audit logs can
44
+ #: distinguish them from host/human approvals.
45
+ AUTONOMOUS_ISSUER = "autonomous-policy"
46
+
47
+ #: Networks treated as "real money" and therefore gated behind
48
+ #: ``allow_mainnet`` regardless of the per-tool allow-list.
49
+ MAINNET_NETWORKS = frozenset({"mainnet", "mainnet-beta", "ethereum", "base", "robinhood", "arbitrum", "optimism", "polygon"})
50
+
51
+ TokenIssuer = Callable[..., str]
52
+
53
+
54
+ def _norm_network(network: str) -> str:
55
+ return str(network or "").strip().lower()
56
+
57
+
58
+ def _norm_addr(address: str | None) -> str:
59
+ """Normalize an address for allow-list comparison.
60
+
61
+ EVM ``0x`` addresses are case-insensitive, so they are lower-cased.
62
+ Other addresses (e.g. base58 Solana keys) are compared verbatim.
63
+ """
64
+ value = str(address or "").strip()
65
+ if value.lower().startswith("0x"):
66
+ return value.lower()
67
+ return value
68
+
69
+
70
+ @dataclass(frozen=True)
71
+ class AutonomousSessionConfig:
72
+ """Up-front authorization envelope for a single autonomous session.
73
+
74
+ All capabilities are off by default. A session that is not ``enabled``,
75
+ or whose allow-lists are empty, approves nothing.
76
+ """
77
+
78
+ enabled: bool = False
79
+ allowed_tools: frozenset[str] = frozenset()
80
+ allowed_networks: frozenset[str] = frozenset()
81
+ #: Mainnet is gated separately from the network allow-list so an operator
82
+ #: cannot enable "real money" execution by accident.
83
+ allow_mainnet: bool = False
84
+ #: Destination addresses / program ids the agent may interact with.
85
+ allowed_recipients: frozenset[str] = frozenset()
86
+ #: Escape hatch for flows where the destination is not known in advance
87
+ #: (e.g. router-built swaps). Spend caps and simulation still apply.
88
+ allow_any_recipient: bool = False
89
+ #: Require a passing simulation/dry-run before approving. Strongly
90
+ #: recommended; this is the autonomous analogue of a human eyeballing
91
+ #: the preview.
92
+ require_simulation: bool = True
93
+ #: Reused spend ledger configuration (per-tx / hourly / daily / rate).
94
+ spending: SpendingConfig = SpendingConfig()
95
+ #: Maximum number of operations the session may approve (0 = unlimited).
96
+ max_operations: int = 0
97
+ #: Session lifetime in seconds (0 = no expiry).
98
+ session_ttl_seconds: int = 0
99
+ #: TTL applied to each issued approval token.
100
+ approval_ttl_seconds: int = 120
101
+
102
+ def normalized(self) -> "AutonomousSessionConfig":
103
+ """Return a copy with networks/recipients normalized for matching."""
104
+ return AutonomousSessionConfig(
105
+ enabled=self.enabled,
106
+ allowed_tools=frozenset(str(t).strip() for t in self.allowed_tools),
107
+ allowed_networks=frozenset(_norm_network(n) for n in self.allowed_networks),
108
+ allow_mainnet=self.allow_mainnet,
109
+ allowed_recipients=frozenset(_norm_addr(a) for a in self.allowed_recipients),
110
+ allow_any_recipient=self.allow_any_recipient,
111
+ require_simulation=self.require_simulation,
112
+ spending=self.spending,
113
+ max_operations=self.max_operations,
114
+ session_ttl_seconds=self.session_ttl_seconds,
115
+ approval_ttl_seconds=self.approval_ttl_seconds,
116
+ )
117
+
118
+
119
+ @dataclass(frozen=True)
120
+ class OperationRequest:
121
+ """A single execute request submitted to the policy gate."""
122
+
123
+ tool_name: str
124
+ network: str
125
+ #: The confirmation summary that will be bound into the approval token.
126
+ #: It must be the same object the downstream verifier reconstructs.
127
+ summary: dict
128
+ #: Normalized notional spend used for limit accounting. Callers should
129
+ #: pass the outflow in the wallet's smallest unit (lamports/wei). Use 0
130
+ #: for read-shaped or zero-value operations, or ``None`` when the amount
131
+ #: could not be determined (the session layer treats unknown spend as a
132
+ #: hard denial whenever spend caps are configured).
133
+ spend_amount: int | None = 0
134
+ #: Destination address or program id, if known.
135
+ recipient: str | None = None
136
+ #: Whether a simulation/dry-run already succeeded for this operation.
137
+ simulated: bool = False
138
+
139
+
140
+ @dataclass(frozen=True)
141
+ class AutonomousDecision:
142
+ """Outcome of a policy evaluation."""
143
+
144
+ approved: bool
145
+ reason: str
146
+ rule: str | None = None
147
+ approval_token: str | None = None
148
+
149
+
150
+ @dataclass
151
+ class _SessionState:
152
+ started_at: float
153
+ operations: int = 0
154
+
155
+
156
+ class AutonomousPolicyEngine:
157
+ """Deterministic risk gate that programmatically issues approval tokens.
158
+
159
+ Construct one engine per autonomous session. Call :meth:`evaluate` for a
160
+ non-raising decision, or :meth:`authorize` to get a token back (raising
161
+ :class:`WalletBackendError` on denial, matching the rest of the wallet
162
+ layer's error contract).
163
+
164
+ ``token_issuer`` is injectable so tests can run without a sealed approval
165
+ secret; in production it defaults to the real
166
+ :func:`agent_wallet.approval.issue_approval_token`.
167
+ """
168
+
169
+ def __init__(
170
+ self,
171
+ config: AutonomousSessionConfig,
172
+ *,
173
+ token_issuer: TokenIssuer = issue_approval_token,
174
+ ledger: SpendingLedger | None = None,
175
+ clock: Callable[[], float] = time.time,
176
+ started_at: float | None = None,
177
+ operations_used: int = 0,
178
+ ) -> None:
179
+ self.config = config.normalized()
180
+ self._issuer = token_issuer
181
+ self._ledger = ledger if ledger is not None else SpendingLedger(self.config.spending)
182
+ self._clock = clock
183
+ self._lock = threading.Lock()
184
+ # ``started_at`` / ``operations_used`` are injectable so a session can
185
+ # be rehydrated from a persisted record across processes.
186
+ self._state = _SessionState(
187
+ started_at=clock() if started_at is None else started_at,
188
+ operations=int(operations_used),
189
+ )
190
+
191
+ # -- public API ----------------------------------------------------------
192
+
193
+ def evaluate(self, op: OperationRequest) -> AutonomousDecision:
194
+ """Evaluate *op* against the session policy without raising.
195
+
196
+ On approval the returned decision carries a freshly issued, signed
197
+ approval token bound to ``op.tool_name`` / ``op.network`` /
198
+ ``op.summary``.
199
+ """
200
+ cfg = self.config
201
+ network = _norm_network(op.network)
202
+
203
+ with self._lock:
204
+ # 1. Master switch.
205
+ if not cfg.enabled:
206
+ return self._deny("autonomous execution is disabled for this session", "enabled")
207
+
208
+ # 2. Session lifetime.
209
+ if cfg.session_ttl_seconds > 0:
210
+ age = self._clock() - self._state.started_at
211
+ if age > cfg.session_ttl_seconds:
212
+ return self._deny(
213
+ f"autonomous session expired ({age:.0f}s > {cfg.session_ttl_seconds}s)",
214
+ "session_ttl",
215
+ )
216
+
217
+ # 3. Operation budget.
218
+ if cfg.max_operations > 0 and self._state.operations >= cfg.max_operations:
219
+ return self._deny(
220
+ f"autonomous operation budget exhausted ({cfg.max_operations} ops)",
221
+ "max_operations",
222
+ )
223
+
224
+ # 4. Tool allow-list.
225
+ if op.tool_name not in cfg.allowed_tools:
226
+ return self._deny(f"tool '{op.tool_name}' is not autonomously allowed", "allowed_tools")
227
+
228
+ # 5. Network allow-list.
229
+ if network not in cfg.allowed_networks:
230
+ return self._deny(f"network '{network}' is not autonomously allowed", "allowed_networks")
231
+
232
+ # 6. Mainnet gate (separate from the network allow-list).
233
+ if network in MAINNET_NETWORKS and not cfg.allow_mainnet:
234
+ return self._deny(
235
+ f"mainnet network '{network}' requires allow_mainnet for autonomous execution",
236
+ "allow_mainnet",
237
+ )
238
+
239
+ # 7. Recipient allow-list.
240
+ if not cfg.allow_any_recipient:
241
+ recipient = _norm_addr(op.recipient)
242
+ if not recipient:
243
+ return self._deny("operation has no recipient and allow_any_recipient is false", "recipient")
244
+ if recipient not in cfg.allowed_recipients:
245
+ return self._deny(f"recipient '{op.recipient}' is not on the allow-list", "recipient")
246
+
247
+ # 8. Mandatory simulation.
248
+ if cfg.require_simulation and not op.simulated:
249
+ return self._deny("operation has no passing simulation and require_simulation is true", "simulation")
250
+
251
+ # 9. Spend limits (per-tx / rate / hourly / daily). Records on pass.
252
+ try:
253
+ self._ledger.check_and_record(int(op.spend_amount or 0))
254
+ except WalletBackendError as exc:
255
+ return self._deny(str(exc), "spending")
256
+
257
+ # 10. Issue the same signed token the host path would issue.
258
+ try:
259
+ token = self._issuer(
260
+ tool_name=op.tool_name,
261
+ network=op.network,
262
+ summary=op.summary,
263
+ mainnet_confirmed=network in MAINNET_NETWORKS and cfg.allow_mainnet,
264
+ ttl_seconds=cfg.approval_ttl_seconds,
265
+ issued_by=AUTONOMOUS_ISSUER,
266
+ )
267
+ except Exception as exc: # noqa: BLE001 - surface issuer failures verbatim
268
+ return self._deny(f"approval token issuance failed: {exc}", "issuer")
269
+
270
+ self._state.operations += 1
271
+ return AutonomousDecision(
272
+ approved=True,
273
+ reason="approved by autonomous policy",
274
+ rule="approved",
275
+ approval_token=token,
276
+ )
277
+
278
+ def authorize(self, op: OperationRequest) -> str:
279
+ """Like :meth:`evaluate` but return the token or raise on denial."""
280
+ decision = self.evaluate(op)
281
+ if not decision.approved or not decision.approval_token:
282
+ raise WalletBackendError(f"autonomous policy denied operation: {decision.reason}")
283
+ return decision.approval_token
284
+
285
+ def snapshot(self) -> dict:
286
+ """Return a JSON-serializable view of session state for auditing."""
287
+ with self._lock:
288
+ return {
289
+ "enabled": self.config.enabled,
290
+ "operations": self._state.operations,
291
+ "max_operations": self.config.max_operations,
292
+ "started_at": self._state.started_at,
293
+ "session_ttl_seconds": self.config.session_ttl_seconds,
294
+ "allow_mainnet": self.config.allow_mainnet,
295
+ }
296
+
297
+ def export_spend(self) -> list[tuple[float, int]]:
298
+ """Return the spend ledger entries so they can be persisted."""
299
+ return self._ledger.export()
300
+
301
+ # -- internal ------------------------------------------------------------
302
+
303
+ @staticmethod
304
+ def _deny(reason: str, rule: str) -> AutonomousDecision:
305
+ return AutonomousDecision(approved=False, reason=reason, rule=rule)
@@ -0,0 +1,236 @@
1
+ """Persistent autonomous-session store.
2
+
3
+ The OpenClaw wallet CLI is invoked as a fresh subprocess per tool call, so an
4
+ autonomous session (the "envelope" a human authorizes once, inside which the
5
+ agent may execute without per-transaction confirmation) cannot live in memory.
6
+ This module persists the session — its :class:`AutonomousSessionConfig`, start
7
+ time, operation count, and spend ledger — to a JSON file under
8
+ ``OPENCLAW_HOME`` so the same limits are enforced across every subprocess.
9
+
10
+ Trust model:
11
+
12
+ * ``start_session`` writes the envelope. It is expected to be called only after
13
+ a human authorizes the exact limits (the adapter gates the agent-facing
14
+ ``start_autonomous_session`` tool behind a host-issued approval token, so the
15
+ agent cannot widen its own permissions).
16
+ * ``stop_session`` removes the envelope and is always safe to call (it can only
17
+ *reduce* what the agent may do).
18
+ * ``authorize_operation`` rehydrates the engine from the persisted record,
19
+ evaluates the operation, persists the updated counters/spend, and returns a
20
+ signed approval token — or raises :class:`WalletBackendError` on denial.
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ import json
26
+ import os
27
+ import threading
28
+ import time
29
+ from pathlib import Path
30
+ from typing import Any
31
+
32
+ from agent_wallet.autonomous_policy import (
33
+ AutonomousPolicyEngine,
34
+ AutonomousSessionConfig,
35
+ OperationRequest,
36
+ )
37
+ from agent_wallet.config import resolve_openclaw_home
38
+ from agent_wallet.spending_limits import SpendingConfig, SpendingLedger
39
+ from agent_wallet.wallet_layer.base import WalletBackendError
40
+
41
+ SESSION_VERSION = 1
42
+ _SESSION_FILENAME = "autonomous_session.json"
43
+ _lock = threading.Lock()
44
+
45
+
46
+ def _session_path() -> Path:
47
+ return resolve_openclaw_home() / _SESSION_FILENAME
48
+
49
+
50
+ # ---------------------------------------------------------------------------
51
+ # Config (de)serialization
52
+ # ---------------------------------------------------------------------------
53
+
54
+ def config_to_dict(config: AutonomousSessionConfig) -> dict[str, Any]:
55
+ cfg = config.normalized()
56
+ return {
57
+ "enabled": cfg.enabled,
58
+ "allowed_tools": sorted(cfg.allowed_tools),
59
+ "allowed_networks": sorted(cfg.allowed_networks),
60
+ "allow_mainnet": cfg.allow_mainnet,
61
+ "allowed_recipients": sorted(cfg.allowed_recipients),
62
+ "allow_any_recipient": cfg.allow_any_recipient,
63
+ "require_simulation": cfg.require_simulation,
64
+ "spending": {
65
+ "max_per_tx_lamports": cfg.spending.max_per_tx_lamports,
66
+ "max_hourly_lamports": cfg.spending.max_hourly_lamports,
67
+ "max_daily_lamports": cfg.spending.max_daily_lamports,
68
+ "max_txs_per_minute": cfg.spending.max_txs_per_minute,
69
+ },
70
+ "max_operations": cfg.max_operations,
71
+ "session_ttl_seconds": cfg.session_ttl_seconds,
72
+ "approval_ttl_seconds": cfg.approval_ttl_seconds,
73
+ }
74
+
75
+
76
+ def config_from_dict(data: dict[str, Any]) -> AutonomousSessionConfig:
77
+ spending = data.get("spending") or {}
78
+ return AutonomousSessionConfig(
79
+ enabled=bool(data.get("enabled", False)),
80
+ allowed_tools=frozenset(data.get("allowed_tools") or []),
81
+ allowed_networks=frozenset(data.get("allowed_networks") or []),
82
+ allow_mainnet=bool(data.get("allow_mainnet", False)),
83
+ allowed_recipients=frozenset(data.get("allowed_recipients") or []),
84
+ allow_any_recipient=bool(data.get("allow_any_recipient", False)),
85
+ require_simulation=bool(data.get("require_simulation", True)),
86
+ spending=SpendingConfig(
87
+ max_per_tx_lamports=int(spending.get("max_per_tx_lamports", 0) or 0),
88
+ max_hourly_lamports=int(spending.get("max_hourly_lamports", 0) or 0),
89
+ max_daily_lamports=int(spending.get("max_daily_lamports", 0) or 0),
90
+ max_txs_per_minute=int(spending.get("max_txs_per_minute", 0) or 0),
91
+ ),
92
+ max_operations=int(data.get("max_operations", 0) or 0),
93
+ session_ttl_seconds=int(data.get("session_ttl_seconds", 0) or 0),
94
+ approval_ttl_seconds=int(data.get("approval_ttl_seconds", 120) or 120),
95
+ )
96
+
97
+
98
+ # ---------------------------------------------------------------------------
99
+ # Record persistence
100
+ # ---------------------------------------------------------------------------
101
+
102
+ def _load_record() -> dict[str, Any] | None:
103
+ path = _session_path()
104
+ if not path.exists():
105
+ return None
106
+ try:
107
+ record = json.loads(path.read_text(encoding="utf-8"))
108
+ except (OSError, ValueError):
109
+ return None
110
+ if not isinstance(record, dict) or int(record.get("version") or 0) != SESSION_VERSION:
111
+ return None
112
+ return record
113
+
114
+
115
+ def _write_record(record: dict[str, Any]) -> None:
116
+ path = _session_path()
117
+ path.parent.mkdir(parents=True, exist_ok=True)
118
+ tmp = path.with_suffix(".json.tmp")
119
+ tmp.write_text(json.dumps(record, separators=(",", ":")), encoding="utf-8")
120
+ os.replace(tmp, path) # atomic on POSIX
121
+
122
+
123
+ # ---------------------------------------------------------------------------
124
+ # Public API
125
+ # ---------------------------------------------------------------------------
126
+
127
+ def start_session(config: AutonomousSessionConfig) -> dict[str, Any]:
128
+ """Persist a new autonomous session envelope and return its status."""
129
+ if not config.enabled:
130
+ raise WalletBackendError("Cannot start an autonomous session with enabled=false.")
131
+ record = {
132
+ "version": SESSION_VERSION,
133
+ "started_at": time.time(),
134
+ "operations": 0,
135
+ "spend_entries": [],
136
+ "config": config_to_dict(config),
137
+ }
138
+ with _lock:
139
+ _write_record(record)
140
+ return session_status()
141
+
142
+
143
+ def stop_session() -> dict[str, Any]:
144
+ """Remove any active session. Always safe (only reduces permissions)."""
145
+ with _lock:
146
+ path = _session_path()
147
+ existed = path.exists()
148
+ try:
149
+ path.unlink()
150
+ except FileNotFoundError:
151
+ existed = False
152
+ return {"active": False, "stopped": existed}
153
+
154
+
155
+ def is_active() -> bool:
156
+ record = _load_record()
157
+ return bool(record and (record.get("config") or {}).get("enabled"))
158
+
159
+
160
+ def session_status() -> dict[str, Any]:
161
+ """Return a non-secret view of the current session for the agent/host."""
162
+ record = _load_record()
163
+ if not record:
164
+ return {"active": False}
165
+ cfg = record.get("config") or {}
166
+ started_at = float(record.get("started_at") or 0.0)
167
+ ttl = int(cfg.get("session_ttl_seconds", 0) or 0)
168
+ status: dict[str, Any] = {
169
+ "active": bool(cfg.get("enabled")),
170
+ "started_at": started_at,
171
+ "operations": int(record.get("operations") or 0),
172
+ "max_operations": int(cfg.get("max_operations", 0) or 0),
173
+ "allow_mainnet": bool(cfg.get("allow_mainnet", False)),
174
+ "allowed_tools": cfg.get("allowed_tools") or [],
175
+ "allowed_networks": cfg.get("allowed_networks") or [],
176
+ "allow_any_recipient": bool(cfg.get("allow_any_recipient", False)),
177
+ "require_simulation": bool(cfg.get("require_simulation", True)),
178
+ "spending": cfg.get("spending") or {},
179
+ }
180
+ if ttl > 0:
181
+ status["expires_at"] = started_at + ttl
182
+ status["expired"] = (time.time() - started_at) > ttl
183
+ return status
184
+
185
+
186
+ def authorize_operation(op: OperationRequest) -> str:
187
+ """Authorize *op* against the persisted session, returning an approval token.
188
+
189
+ Raises :class:`WalletBackendError` if there is no active session or the
190
+ operation is denied by the policy gate.
191
+ """
192
+ with _lock:
193
+ record = _load_record()
194
+ if not record:
195
+ raise WalletBackendError(
196
+ "No active autonomous session. A host must start one with "
197
+ "start_autonomous_session before unattended execution is allowed."
198
+ )
199
+ config = config_from_dict(record.get("config") or {})
200
+
201
+ # Fail closed: if spend caps are configured but the spend amount for
202
+ # this operation could not be determined, deny rather than approve.
203
+ spend_caps_set = any(
204
+ v > 0
205
+ for v in (
206
+ config.spending.max_per_tx_lamports,
207
+ config.spending.max_hourly_lamports,
208
+ config.spending.max_daily_lamports,
209
+ )
210
+ )
211
+ if op.spend_amount is None and spend_caps_set:
212
+ raise WalletBackendError(
213
+ "autonomous policy denied operation: spend amount could not be "
214
+ "verified while spend limits are configured."
215
+ )
216
+
217
+ ledger = SpendingLedger(
218
+ config.spending,
219
+ clock=time.time,
220
+ entries=[(float(ts), int(amt)) for ts, amt in record.get("spend_entries") or []],
221
+ )
222
+ engine = AutonomousPolicyEngine(
223
+ config,
224
+ ledger=ledger,
225
+ clock=time.time,
226
+ started_at=float(record.get("started_at") or time.time()),
227
+ operations_used=int(record.get("operations") or 0),
228
+ )
229
+ decision = engine.evaluate(op)
230
+ if not decision.approved or not decision.approval_token:
231
+ raise WalletBackendError(f"autonomous policy denied operation: {decision.reason}")
232
+
233
+ record["operations"] = engine.snapshot()["operations"]
234
+ record["spend_entries"] = [[ts, amt] for ts, amt in engine.export_spend()]
235
+ _write_record(record)
236
+ return decision.approval_token