@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,456 @@
1
+ """Private card use through a fixed HTTPS executor and durable approved operations.
2
+
3
+ No shell, arbitrary callback, raw provider result or secret value is exposed to
4
+ an agent. A prepared request is immutable. Approval covers its exact template;
5
+ continuations reuse that authorization without asking the owner to unlock.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import asyncio
10
+ import hashlib
11
+ import ipaddress
12
+ import json
13
+ import re
14
+ import socket
15
+ import time
16
+ import uuid
17
+ from typing import Any, Callable
18
+ from urllib.parse import urlsplit
19
+
20
+ import httpx
21
+
22
+ from agent_wallet.card_catalog import CardCatalog, TERMINAL
23
+ from agent_wallet.card_runtime_secrets import CardRuntimeSecrets, RuntimeVaultStorage
24
+ from agent_wallet.card_vault import CardVault
25
+ from agent_wallet.laso_card_vault import refresh_saved_card
26
+ from agent_wallet.wallet_layer.base import WalletBackendError
27
+
28
+ TOOL_NAME = "use_saved_card"
29
+ EXECUTOR = "https_request"
30
+ OPERATION_TTL = 48 * 3600
31
+ FIELDS = frozenset({"card.number", "card.cvv", "card.exp_month", "card.exp_year", *(
32
+ "card.billing." + key for key in ("name", "line_1", "line_2", "city", "state", "zip", "country")
33
+ )})
34
+ PLACEHOLDER = re.compile(r"\{\{(card\.[a-z_0-9.]+)\}\}")
35
+ FINAL_STATES = frozenset({"request_succeeded", "request_rejected", "outcome_unknown", "expired", "card_unavailable", "issuance_unknown", "cancelled", "checkout_submitted", "checkout_unavailable", "checkout_filled"})
36
+ BLOCKED_HEADERS = frozenset({"host", "content-length", "transfer-encoding", "connection", "upgrade", "te", "trailer", "expect", "proxy-authorization", "proxy-connection", "idempotency-key", "content-type"})
37
+
38
+
39
+ def _encoded(value: Any) -> bytes:
40
+ return json.dumps(value, sort_keys=True, separators=(",", ":"), allow_nan=False).encode()
41
+
42
+
43
+ def _url(value: Any) -> httpx.URL:
44
+ if not isinstance(value, str) or not 1 <= len(value) <= 4096 or any(ord(c) <= 32 or ord(c) >= 127 for c in value) or "\\" in value:
45
+ raise WalletBackendError("Executor URL must be an ASCII HTTPS URL.")
46
+ try:
47
+ parsed = urlsplit(value)
48
+ url = httpx.URL(value)
49
+ if (parsed.scheme != "https" or not parsed.hostname or parsed.username is not None
50
+ or parsed.password is not None or parsed.fragment or parsed.port not in {None, 443}
51
+ or url.host.endswith(".") or "{" in value or "}" in value):
52
+ raise ValueError()
53
+ except (ValueError, httpx.InvalidURL):
54
+ raise WalletBackendError("Executor requires an exact public HTTPS destination on port 443 without credentials or fragments.") from None
55
+ return url
56
+
57
+
58
+ def validate_request(value: Any) -> dict[str, Any]:
59
+ if not isinstance(value, dict) or set(value) - {"url", "method", "headers", "json", "form"}:
60
+ raise WalletBackendError("request must contain only url, method, headers and json or form.")
61
+ url = _url(value.get("url"))
62
+ method = value.get("method", "POST")
63
+ if method not in {"GET", "POST", "PUT", "PATCH", "DELETE"}:
64
+ raise WalletBackendError("Unsupported HTTPS request method.")
65
+ if ("json" in value) == ("form" in value):
66
+ raise WalletBackendError("Provide exactly one of request.json or request.form.")
67
+ headers = value.get("headers", {})
68
+ if not isinstance(headers, dict) or len(headers) > 32:
69
+ raise WalletBackendError("Invalid request headers.")
70
+ clean_headers: dict[str, str] = {}
71
+ for key, content in headers.items():
72
+ if (not isinstance(key, str) or not re.fullmatch(r"[A-Za-z0-9-]{1,80}", key)
73
+ or key.lower() in BLOCKED_HEADERS or key.lower() in clean_headers
74
+ or not isinstance(content, str) or len(content) > 4096
75
+ or any(ord(c) < 32 or ord(c) > 126 for c in content) or "{{" in content or "}}" in content):
76
+ raise WalletBackendError("Unsafe request header. Card secrets are allowed only in the request body.")
77
+ clean_headers[key.lower()] = content
78
+ kind = "json" if "json" in value else "form"
79
+ body = value[kind]
80
+ if not isinstance(body, dict):
81
+ raise WalletBackendError("The request body must be an object.")
82
+ used: set[str] = set()
83
+
84
+ def visit(item: Any, depth: int = 0) -> None:
85
+ if depth > 8:
86
+ raise WalletBackendError("Request template nesting exceeds limit.")
87
+ if isinstance(item, dict):
88
+ if len(item) > 128:
89
+ raise WalletBackendError("Request template exceeds field limit.")
90
+ for key, child in item.items():
91
+ if not isinstance(key, str) or len(key) > 256 or "{{" in key or "}}" in key:
92
+ raise WalletBackendError("Invalid template field name.")
93
+ visit(child, depth + 1)
94
+ elif isinstance(item, list):
95
+ if len(item) > 128:
96
+ raise WalletBackendError("Request template exceeds field limit.")
97
+ for child in item:
98
+ visit(child, depth + 1)
99
+ elif isinstance(item, str):
100
+ found = PLACEHOLDER.findall(item)
101
+ if set(found) - FIELDS or "{{" in PLACEHOLDER.sub("", item) or "}}" in PLACEHOLDER.sub("", item):
102
+ raise WalletBackendError("Unknown vault placeholder in request template.")
103
+ used.update(found)
104
+ elif item is not None and type(item) not in {int, float, bool}:
105
+ raise WalletBackendError("Invalid request template value.")
106
+
107
+ visit(body)
108
+ if kind == "form" and not all(isinstance(v, str) for v in body.values()):
109
+ raise WalletBackendError("Form template values must be strings.")
110
+ if not used:
111
+ raise WalletBackendError("Request template must reference a saved card field such as {{card.number}}.")
112
+ request = {"url": str(url), "method": method, "headers": clean_headers, kind: body}
113
+ try:
114
+ if len(_encoded(request)) > 24 * 1024:
115
+ raise ValueError()
116
+ except (ValueError, TypeError):
117
+ raise WalletBackendError("Request template exceeds size limit or contains invalid numbers.") from None
118
+ return request
119
+
120
+
121
+ def _render(value: Any, fields: dict[str, str]) -> Any:
122
+ if isinstance(value, dict):
123
+ return {key: _render(child, fields) for key, child in value.items()}
124
+ if isinstance(value, list):
125
+ return [_render(child, fields) for child in value]
126
+ if isinstance(value, str):
127
+ def replace(match):
128
+ if match[1] not in fields:
129
+ raise WalletBackendError("The saved card is missing a requested executor field.")
130
+ return fields[match[1]]
131
+ return PLACEHOLDER.sub(replace, value)
132
+ return value
133
+
134
+
135
+ async def resolve_public_destination(url: httpx.URL) -> str:
136
+ """Validate every DNS answer, then connect to a selected IP without re-resolving."""
137
+ try:
138
+ answers = await asyncio.wait_for(asyncio.get_running_loop().getaddrinfo(
139
+ url.host, 443, type=socket.SOCK_STREAM,
140
+ ), timeout=10)
141
+ addresses = sorted({answer[4][0] for answer in answers})
142
+ def public(address: str) -> bool:
143
+ ip = ipaddress.ip_address(address)
144
+ return (ip.is_global and not ip.is_multicast
145
+ and not (isinstance(ip, ipaddress.IPv6Address)
146
+ and (ip.ipv4_mapped is not None or ip.sixtofour is not None or ip.teredo is not None)))
147
+ if not addresses or not all(public(address) for address in addresses):
148
+ raise ValueError()
149
+ # Prefer IPv4 on dual-stack hosts; string ordering can otherwise pick
150
+ # IPv6 even when this machine has no usable IPv6 route.
151
+ return min(addresses, key=lambda address: (ipaddress.ip_address(address).version,
152
+ int(ipaddress.ip_address(address))))
153
+ except (ValueError, OSError, asyncio.TimeoutError):
154
+ raise WalletBackendError("HTTPS executor destination must resolve only to public internet addresses.") from None
155
+
156
+
157
+ async def send_private_request(request: dict[str, Any], fields: dict[str, str], *, address: str, operation_id: str) -> int:
158
+ """Only the fixed executor receives plaintext. Return no remote content."""
159
+ url = _url(request["url"])
160
+ pinned = url.copy_with(host=address)
161
+ headers = {**request["headers"], "Host": url.host, "Idempotency-Key": operation_id}
162
+ kind = "json" if "json" in request else "form"
163
+ body = _render(request[kind], fields)
164
+ kwargs = {"json" if kind == "json" else "data": body}
165
+ # Separate pool per operation. TLS verifies the original hostname while the
166
+ # connection is pinned to the validated IP (no second DNS lookup / rebinding).
167
+ async with httpx.AsyncClient(timeout=30, trust_env=False, follow_redirects=False,
168
+ transport=httpx.AsyncHTTPTransport(retries=0, trust_env=False)) as client:
169
+ async with client.stream(request["method"], pinned, headers=headers,
170
+ extensions={"sni_hostname": url.host}, **kwargs) as response:
171
+ # Do not read a body, cookies, Location or exception text into a tool
172
+ # result. A server may echo credentials even in an error response.
173
+ return response.status_code
174
+
175
+
176
+ class VaultExecutor:
177
+ def __init__(self, vault: CardVault):
178
+ self.vault = vault
179
+ self.storage = RuntimeVaultStorage(vault, "operation")
180
+
181
+ def _summary(self, reference: str, state: dict[str, Any]) -> dict[str, Any]:
182
+ checkout = state.get("checkout")
183
+ payload = checkout or state["request"]
184
+ return {
185
+ "operation": ("Private card fill only (no submit; close browser)" if checkout and checkout.get("action") == "fill_only"
186
+ else "Private Kernel checkout" if checkout else "Private saved card HTTPS request"), "operation_id": reference,
187
+ "user_scope": self.vault.scope, "network": state["network"], "owner": state["owner"],
188
+ "vault_reference": state["vault_reference"], "executor": "kernel_checkout" if checkout else EXECUTOR,
189
+ "card_issuance": (state.get("issuance") or {}).get("payment_summary"),
190
+ "purpose": state["purpose"], "destination": checkout["page_url"] if checkout else state["request"]["url"],
191
+ "request": payload,
192
+ "request_sha256": hashlib.sha256(_encoded(payload)).hexdigest(),
193
+ "valid_until_epoch_seconds": state["valid_until"],
194
+ "spend_policy": "exact-request-template; no automatic payment retry",
195
+ }
196
+
197
+ def prepare(self, *, vault_reference: Any, request: Any, purpose: Any, network: str, owner: str, mode: str, issuance: dict[str, Any] | None = None, checkout: Any = None) -> dict[str, Any]:
198
+ self.vault._config()
199
+ self.vault._path(vault_reference)
200
+ if issuance is None:
201
+ CardCatalog(self.vault).get(vault_reference)
202
+ if not isinstance(purpose, str) or not 1 <= len(purpose.strip()) <= 512:
203
+ raise WalletBackendError("A clear purpose of up to 512 characters is required.")
204
+ if (checkout is None) == (request is None):
205
+ raise WalletBackendError("Choose exactly one request or checkout plan.")
206
+ if checkout is not None:
207
+ from agent_wallet.kernel_browser import validate_checkout
208
+ checkout = validate_checkout(checkout)
209
+ state = {
210
+ "status": "prepared", "vault_reference": vault_reference,
211
+ "request": validate_request(request) if request is not None else None, "purpose": purpose.strip(),
212
+ "network": network, "owner": owner,
213
+ "valid_until": int(time.time()) + OPERATION_TTL,
214
+ "created_at": int(time.time()), "issuance": issuance,
215
+ }
216
+ if checkout is not None:
217
+ state["checkout"] = checkout
218
+ reference = uuid.uuid4().hex
219
+ state["confirmation_summary"] = self._summary(reference, state)
220
+ self.storage.save(reference, state)
221
+ return {
222
+ **self.safe(reference, state), "mode": mode,
223
+ "confirmation_summary": state["confirmation_summary"],
224
+ "confirmation_requirements": {"execute_requires_approval_token": True},
225
+ "note": "Approve this exact destination and plan through the normal wallet confirmation flow. Real card data goes to the trusted executor and merchant. Status is not independent proof of payment. No owner unlock is needed.",
226
+ }
227
+
228
+ def _load(self, reference: str) -> dict[str, Any]:
229
+ state = self.storage.load(reference)
230
+ # Authenticate not only the envelope but the relationship of the saved
231
+ # approval summary to its immutable request, card and runtime identity.
232
+ if state.get("confirmation_summary") != self._summary(reference, state):
233
+ raise WalletBackendError("Saved vault operation does not match its approved request.")
234
+ return state
235
+
236
+ @staticmethod
237
+ def safe(reference: str, state: dict[str, Any]) -> dict[str, Any]:
238
+ from agent_wallet.kernel_browser import safe_checkout_diagnostics
239
+
240
+ status = state.get("status")
241
+ if status not in FINAL_STATES and status not in {"dispatching", "issuing"} and time.time() >= state["valid_until"]:
242
+ status = "expired"
243
+ return {
244
+ "operation_id": reference, "vault_reference": state.get("vault_reference"),
245
+ "executor": "kernel_checkout" if state.get("checkout") else EXECUTOR, "status": status,
246
+ "card_issuance_requested": state.get("issuance") is not None,
247
+ "authorization_required": status == "prepared",
248
+ "can_continue": status in {"prepared", "authorized", "awaiting_card", "issuing"},
249
+ "http_status": state.get("http_status"),
250
+ "valid_until_epoch_seconds": state.get("valid_until"),
251
+ "retry_after_seconds": state.get("retry_after_seconds"),
252
+ "last_attempt_not_sent": state.get("last_attempt_not_sent", False),
253
+ "secrets_returned": False, "payment_confirmed": False,
254
+ "merchant_confirmation_observed": state.get("merchant_confirmation_observed", False),
255
+ "checkout_diagnostics": safe_checkout_diagnostics(state.get("checkout_diagnostics")),
256
+ "checkout_action": state["checkout"].get("action", "submit") if state.get("checkout") else None,
257
+ "private_fill_completed": status == "checkout_filled",
258
+ }
259
+
260
+ def get(self, reference: str) -> dict[str, Any]:
261
+ return self.safe(reference, self._load(reference))
262
+
263
+ async def _cleanup_browser(self, reference: str, state: dict[str, Any]) -> None:
264
+ if state.get("checkout"):
265
+ from agent_wallet.kernel_browser import KernelBrowser
266
+ try:
267
+ await KernelBrowser(self.vault).cleanup(state["checkout"], reference)
268
+ except Exception:
269
+ pass # Session stays inaccessible; close can retry remote cleanup.
270
+
271
+ async def cancel(self, reference: str) -> dict[str, Any]:
272
+ async with self.vault.async_record_lock(reference):
273
+ state = self._load(reference)
274
+ if state["status"] == "dispatching":
275
+ # A request may already have left the previous process.
276
+ state["status"] = "outcome_unknown"
277
+ elif state["status"] == "issuing":
278
+ state["status"] = "issuance_unknown"
279
+ elif state["status"] not in FINAL_STATES:
280
+ state["status"] = "cancelled"
281
+ state.pop("authorized_at", None)
282
+ self.storage.save(reference, state)
283
+ await self._cleanup_browser(reference, state)
284
+ return self.safe(reference, state)
285
+
286
+ async def execute(self, reference: str, *, network: str, owner: str, authorize: Callable[[dict[str, Any]], None], issue_card: Any | None = None) -> dict[str, Any]:
287
+ async with self.vault.async_record_lock(reference):
288
+ state = self._load(reference)
289
+ if state["status"] in FINAL_STATES:
290
+ await self._cleanup_browser(reference, state)
291
+ return self.safe(reference, state)
292
+ if state["status"] == "dispatching":
293
+ # A previous process may have sent the request before it died.
294
+ # Never resend an uncertain payment even with an idempotency key.
295
+ state["status"] = "outcome_unknown"
296
+ self.storage.save(reference, state)
297
+ await self._cleanup_browser(reference, state)
298
+ return self.safe(reference, state)
299
+ if state["network"] != network or state["owner"] != owner:
300
+ raise WalletBackendError("Use the same wallet and network that prepared this vault operation.")
301
+ if time.time() >= state["valid_until"]:
302
+ state["status"] = "expired"
303
+ self.storage.save(reference, state)
304
+ await self._cleanup_browser(reference, state)
305
+ return self.safe(reference, state)
306
+ if state["status"] == "prepared":
307
+ authorize(state["confirmation_summary"])
308
+ state["status"] = "authorized"
309
+ state["authorized_at"] = int(time.time())
310
+ # Durable authorization is bound to this exact request only.
311
+ self.storage.save(reference, state)
312
+ elif state["status"] not in {"authorized", "awaiting_card", "issuing"} or not state.get("authorized_at"):
313
+ raise WalletBackendError("Invalid saved vault operation authorization state.")
314
+
315
+ if state.get("checkout"):
316
+ from agent_wallet.kernel_browser import KernelBrowser
317
+ try:
318
+ await KernelBrowser(self.vault).preflight(state["checkout"], operation_id=reference)
319
+ except Exception:
320
+ # Do not buy a card when the prepared browser/page is gone.
321
+ state["status"] = "checkout_unavailable"
322
+ self.storage.save(reference, state)
323
+ await self._cleanup_browser(reference, state)
324
+ return self.safe(reference, state)
325
+
326
+ card_ref = state["vault_reference"]
327
+ if state.get("issuance") and not state.get("issuance_completed"):
328
+ if state["status"] == "issuing":
329
+ # A crash may leave a captured issuer receipt. Never pay twice.
330
+ try:
331
+ card = CardCatalog(self.vault).get(card_ref)
332
+ recovered = card.get("details_stored") or card.get("refresh_available")
333
+ except WalletBackendError:
334
+ recovered = False
335
+ if not recovered:
336
+ state["status"] = "issuance_unknown"
337
+ self.storage.save(reference, state)
338
+ await self._cleanup_browser(reference, state)
339
+ return self.safe(reference, state)
340
+ else:
341
+ if issue_card is None:
342
+ raise WalletBackendError("This operation requires its original card issuance executor.")
343
+ state["status"] = "issuing"
344
+ self.storage.save(reference, state)
345
+ try:
346
+ await issue_card(state["issuance"], card_ref)
347
+ except Exception:
348
+ # Saved issuer receipts can be inspected; no automatic re-purchase.
349
+ state["status"] = "issuance_unknown"
350
+ self.storage.save(reference, state)
351
+ await self._cleanup_browser(reference, state)
352
+ return self.safe(reference, state)
353
+ state["issuance_completed"] = True
354
+ state["status"] = "authorized"
355
+ self.storage.save(reference, state)
356
+ capsule = CardRuntimeSecrets(self.vault)
357
+ if not capsule.available(card_ref):
358
+ card = await refresh_saved_card(self.vault, card_ref)
359
+ if not capsule.available(card_ref):
360
+ if card.get("status") in TERMINAL or not card.get("refresh_available"):
361
+ state["status"] = "card_unavailable"
362
+ else:
363
+ state["status"] = "awaiting_card"
364
+ state["retry_after_seconds"] = card.get("retry_after_seconds")
365
+ self.storage.save(reference, state)
366
+ if state["status"] in FINAL_STATES:
367
+ await self._cleanup_browser(reference, state)
368
+ return self.safe(reference, state)
369
+ # Card removal and private use serialize on the card's own lock.
370
+ async with self.vault.async_record_lock(card_ref):
371
+ card = CardCatalog(self.vault).get(card_ref)
372
+ if card.get("status") in TERMINAL:
373
+ state["status"] = "card_unavailable"
374
+ self.storage.save(reference, state)
375
+ await self._cleanup_browser(reference, state)
376
+ return self.safe(reference, state)
377
+ if state.get("checkout"):
378
+ return await self._execute_checkout(reference, state, capsule)
379
+ url = _url(state["request"]["url"])
380
+ address = await resolve_public_destination(url)
381
+ if time.time() >= state["valid_until"]:
382
+ state["status"] = "expired"
383
+ self.storage.save(reference, state)
384
+ return self.safe(reference, state)
385
+ fields = capsule.load_for_executor(card_ref)
386
+ _render(state["request"].get("json", state["request"].get("form")), fields)
387
+ # Before any request bytes can leave, record the attempt durably.
388
+ state["status"] = "dispatching"
389
+ state.pop("retry_after_seconds", None)
390
+ state.pop("last_attempt_not_sent", None)
391
+ self.storage.save(reference, state)
392
+ try:
393
+ code = await asyncio.wait_for(send_private_request(
394
+ state["request"], fields, address=address, operation_id=reference,
395
+ ), timeout=40)
396
+ state["http_status"] = code
397
+ state["status"] = "request_succeeded" if 200 <= code < 300 else "request_rejected"
398
+ except (httpx.ConnectError, httpx.ConnectTimeout):
399
+ # Fresh client, no proxy, redirects or transport retries:
400
+ # connection establishment failed before HTTP bytes were sent.
401
+ # Keep the exact durable authorization for a later explicit
402
+ # continuation, without retrying inside this invocation.
403
+ state["status"] = "authorized"
404
+ state["last_attempt_not_sent"] = True
405
+ state["retry_after_seconds"] = 5
406
+ except asyncio.CancelledError:
407
+ state["status"] = "outcome_unknown"
408
+ self.storage.save(reference, state)
409
+ raise
410
+ except Exception:
411
+ # Cancellation/transport failures are uncertain outcomes.
412
+ # No remote exception text is stored or returned.
413
+ state["status"] = "outcome_unknown"
414
+ self.storage.save(reference, state)
415
+ finally:
416
+ fields.clear() # Best effort only; Python cannot promise zeroization.
417
+ state["last_attempt_at"] = int(time.time())
418
+ if state["status"] in FINAL_STATES:
419
+ state["finished_at"] = state["last_attempt_at"]
420
+ self.storage.save(reference, state)
421
+ return self.safe(reference, state)
422
+
423
+ async def _execute_checkout(self, reference: str, state: dict[str, Any], capsule: CardRuntimeSecrets) -> dict[str, Any]:
424
+ from agent_wallet.kernel_browser import KernelBrowser
425
+
426
+ browser = KernelBrowser(self.vault)
427
+ fields = capsule.load_for_executor(state["vault_reference"])
428
+ selected: list[str] = []
429
+ try:
430
+ selected = browser.select_fields(state["checkout"], fields)
431
+ await browser.preflight(state["checkout"], operation_id=reference)
432
+ if time.time() >= state["valid_until"]:
433
+ state["status"] = "expired"
434
+ else:
435
+ # Persist BEFORE any remote fill: input handlers can cause site effects.
436
+ state["status"] = "dispatching"
437
+ state.pop("retry_after_seconds", None)
438
+ self.storage.save(reference, state)
439
+ result = await browser.checkout(state["checkout"], selected, reference)
440
+ state.update(result)
441
+ except asyncio.CancelledError:
442
+ state["status"] = "outcome_unknown" if state["status"] == "dispatching" else "checkout_unavailable"
443
+ self.storage.save(reference, state)
444
+ raise
445
+ except Exception:
446
+ dispatched = state["status"] == "dispatching"
447
+ state["status"] = "outcome_unknown" if dispatched else "checkout_unavailable"
448
+ if dispatched:
449
+ state["checkout_diagnostics"] = {"phase": "transport", "reason": "executor_result_unavailable"}
450
+ finally:
451
+ selected.clear()
452
+ fields.clear()
453
+ await self._cleanup_browser(reference, state)
454
+ state["finished_at"] = int(time.time())
455
+ self.storage.save(reference, state)
456
+ return self.safe(reference, state)
@@ -0,0 +1 @@
1
+ """Plugin-friendly agent wallet backends."""