clawpowers 2.2.5 → 2.2.7

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 (138) hide show
  1. package/CHANGELOG.md +186 -160
  2. package/COMPATIBILITY.md +48 -13
  3. package/KNOWN_LIMITATIONS.md +20 -19
  4. package/LICENSE +44 -44
  5. package/LICENSING.md +10 -10
  6. package/README.md +486 -462
  7. package/SECURITY.md +52 -52
  8. package/dist/index.d.ts +17 -5
  9. package/dist/index.js +187 -92
  10. package/dist/index.js.map +1 -1
  11. package/native/Cargo.lock +4927 -4927
  12. package/native/Cargo.toml +73 -73
  13. package/native/crates/canonical/Cargo.toml +24 -24
  14. package/native/crates/canonical/src/lib.rs +677 -673
  15. package/native/crates/compression/Cargo.toml +20 -20
  16. package/native/crates/compression/benches/compression_bench.rs +42 -42
  17. package/native/crates/compression/src/lib.rs +393 -393
  18. package/native/crates/evm-eth/Cargo.toml +13 -13
  19. package/native/crates/evm-eth/src/lib.rs +105 -105
  20. package/native/crates/fee/Cargo.toml +15 -15
  21. package/native/crates/fee/src/lib.rs +281 -281
  22. package/native/crates/index/Cargo.toml +16 -16
  23. package/native/crates/index/src/lib.rs +277 -277
  24. package/native/crates/policy/Cargo.toml +17 -17
  25. package/native/crates/policy/src/lib.rs +614 -614
  26. package/native/crates/security/Cargo.toml +22 -22
  27. package/native/crates/security/src/lib.rs +478 -478
  28. package/native/crates/tokens/Cargo.toml +13 -13
  29. package/native/crates/tokens/src/lib.rs +534 -534
  30. package/native/crates/verification/Cargo.toml +23 -23
  31. package/native/crates/verification/src/lib.rs +333 -333
  32. package/native/crates/wallet/Cargo.toml +20 -20
  33. package/native/crates/wallet/src/lib.rs +261 -261
  34. package/native/crates/x402/Cargo.toml +30 -30
  35. package/native/crates/x402/src/lib.rs +423 -423
  36. package/native/ffi/Cargo.toml +34 -34
  37. package/native/ffi/build.rs +4 -4
  38. package/native/ffi/src/lib.rs +352 -352
  39. package/native/ffi/tests/integration.rs +354 -354
  40. package/native/pyo3/Cargo.toml +26 -26
  41. package/native/pyo3/pyproject.toml +16 -16
  42. package/native/pyo3/src/lib.rs +407 -407
  43. package/native/pyo3/tests/test_smoke.py +180 -180
  44. package/native/wasm/Cargo.toml +47 -44
  45. package/native/wasm/pkg/.gitignore +6 -6
  46. package/native/wasm/pkg/clawpowers_wasm.d.ts +208 -208
  47. package/native/wasm/pkg/clawpowers_wasm.js +872 -872
  48. package/native/wasm/pkg/clawpowers_wasm_bg.wasm.d.ts +40 -40
  49. package/native/wasm/pkg/package.json +16 -16
  50. package/native/wasm/pkg-node/clawpowers_wasm.d.ts +143 -143
  51. package/native/wasm/pkg-node/clawpowers_wasm.js +798 -798
  52. package/native/wasm/pkg-node/clawpowers_wasm_bg.wasm.d.ts +40 -40
  53. package/native/wasm/pkg-node/package.json +12 -12
  54. package/native/wasm/src/lib.rs +433 -433
  55. package/package.json +13 -8
  56. package/scripts/build-wasm.mjs +59 -0
  57. package/scripts/generate_hermes_wrappers.py +211 -0
  58. package/scripts/hermes_wrapper_overrides.json +184 -0
  59. package/scripts/run-python-script.mjs +48 -0
  60. package/scripts/verify-consumer-install.mjs +109 -0
  61. package/scripts/verify-wasm-artifacts.mjs +26 -3
  62. package/scripts/verify_hermes_wrappers.py +154 -0
  63. package/skill.json +20 -0
  64. package/skills/1password/SKILL.md +34 -0
  65. package/skills/README.md +44 -0
  66. package/skills/agent-nexus-2/SKILL.md +34 -0
  67. package/skills/apple-notes/SKILL.md +34 -0
  68. package/skills/apple-reminders/SKILL.md +34 -0
  69. package/skills/autoresearch/SKILL.md +43 -0
  70. package/skills/bear-notes/SKILL.md +34 -0
  71. package/skills/blogwatcher/SKILL.md +34 -0
  72. package/skills/blucli/SKILL.md +34 -0
  73. package/skills/bluebubbles/SKILL.md +34 -0
  74. package/skills/business-strategy/SKILL.md +41 -0
  75. package/skills/camsnap/SKILL.md +34 -0
  76. package/skills/canvas/SKILL.md +34 -0
  77. package/skills/clawhub/SKILL.md +34 -0
  78. package/skills/coding-agent/SKILL.md +34 -0
  79. package/skills/coding-discipline.skill/SKILL.md +34 -0
  80. package/skills/content-writer/SKILL.md +41 -0
  81. package/skills/discord/SKILL.md +34 -0
  82. package/skills/eightctl/SKILL.md +34 -0
  83. package/skills/execution-validation.skill/SKILL.md +34 -0
  84. package/skills/gemini/SKILL.md +34 -0
  85. package/skills/gh-issues/SKILL.md +34 -0
  86. package/skills/gifgrep/SKILL.md +34 -0
  87. package/skills/github/SKILL.md +41 -0
  88. package/skills/gog/SKILL.md +34 -0
  89. package/skills/goplaces/SKILL.md +34 -0
  90. package/skills/healthcheck/SKILL.md +34 -0
  91. package/skills/himalaya/SKILL.md +34 -0
  92. package/skills/humanize/SKILL.md +41 -0
  93. package/skills/imsg/SKILL.md +34 -0
  94. package/skills/itp/SKILL.md +112 -0
  95. package/skills/mcporter/SKILL.md +34 -0
  96. package/skills/model-usage/SKILL.md +34 -0
  97. package/skills/nano-pdf/SKILL.md +34 -0
  98. package/skills/node-connect/SKILL.md +34 -0
  99. package/skills/notion/SKILL.md +34 -0
  100. package/skills/obsidian/SKILL.md +34 -0
  101. package/skills/openai-whisper/SKILL.md +34 -0
  102. package/skills/openai-whisper-api/SKILL.md +34 -0
  103. package/skills/openhue/SKILL.md +34 -0
  104. package/skills/oracle/SKILL.md +34 -0
  105. package/skills/ordercli/SKILL.md +34 -0
  106. package/skills/peekaboo/SKILL.md +34 -0
  107. package/skills/polyclaw/SKILL.md +34 -0
  108. package/skills/prospector/SKILL.md +41 -0
  109. package/skills/rsi.skill/SKILL.md +34 -0
  110. package/skills/sag/SKILL.md +34 -0
  111. package/skills/security/SKILL.md +41 -0
  112. package/skills/session-logs/SKILL.md +34 -0
  113. package/skills/sherpa-onnx-tts/SKILL.md +34 -0
  114. package/skills/skill-creator/SKILL.md +34 -0
  115. package/skills/slack/SKILL.md +34 -0
  116. package/skills/songsee/SKILL.md +34 -0
  117. package/skills/sonoscli/SKILL.md +34 -0
  118. package/skills/spotify-player/SKILL.md +34 -0
  119. package/skills/strykr-prism/SKILL.md +41 -0
  120. package/skills/summarize/SKILL.md +34 -0
  121. package/skills/taskbridge/SKILL.md +34 -0
  122. package/skills/things-mac/SKILL.md +34 -0
  123. package/skills/tmux/SKILL.md +34 -0
  124. package/skills/trello/SKILL.md +34 -0
  125. package/skills/validator-agent/SKILL.md +41 -0
  126. package/skills/video-frames/SKILL.md +34 -0
  127. package/skills/voice-call/SKILL.md +34 -0
  128. package/skills/wacli/SKILL.md +34 -0
  129. package/skills/weather/SKILL.md +34 -0
  130. package/skills/webmcp-payments/SKILL.md +41 -0
  131. package/skills/xurl/SKILL.md +34 -0
  132. package/src/skills/catalog.ts +435 -435
  133. package/src/skills/executor.ts +56 -56
  134. package/src/skills/index.ts +3 -3
  135. package/src/skills/itp/SKILL.md +112 -112
  136. package/src/skills/loader.ts +262 -193
  137. package/native/ffi/index.node +0 -0
  138. package/native/wasm/pkg-node/.gitignore +0 -6
package/README.md CHANGED
@@ -1,462 +1,486 @@
1
- # ClawPowers
2
-
3
- **Launch surface:** `clawpowers` is the capability library. It is not the stock OpenClaw wrapper runtime. For the wrapper runtime, install `clawpowers-agent`.
4
-
5
- ## Canonical Links
6
- - Product site: https://clawpowers.ai
7
- - Docs: https://clawpowers.ai/docs
8
- - Agent runtime: https://clawpowers.ai/agent
9
-
10
- **Recommended pairing:** `clawpowers` 2.2.x with `clawpowers-agent` 1.1.x.
11
-
12
- **More docs:** [SECURITY](./SECURITY.md) · [Compatibility](./COMPATIBILITY.md) · [Known Limitations](./KNOWN_LIMITATIONS.md) · [Licensing](./LICENSING.md) · [Releasing](./RELEASING.md) · [Demo](./DEMO.md) · [Roadmap](./ROADMAP.md)
13
-
14
- **Skills library for AI agents — payments, memory, RSI, wallet, parallel swarm, ITP.** Drop-in capability layer for any agent framework.
15
-
16
- [![npm version](https://img.shields.io/npm/v/clawpowers)](https://www.npmjs.com/package/clawpowers)
17
- [![License: BSL 1.1](https://img.shields.io/badge/License-BSL%201.1-blue.svg)](LICENSE)
18
- [![CI](https://github.com/up2itnow0822/ClawPowers-Skills/actions/workflows/ci.yml/badge.svg)](https://github.com/up2itnow0822/ClawPowers-Skills/actions/workflows/ci.yml)
19
-
20
- ```bash
21
- npm install clawpowers
22
- ```
23
-
24
- ## 60-Second Demo
25
-
26
- ```bash
27
- npm install clawpowers
28
- node -e "
29
- const { generateWallet, detect402, SpendingPolicy, signMessage } = await import('clawpowers');
30
-
31
- // 1. Generate a real Ethereum wallet (MetaMask-compatible)
32
- const wallet = await generateWallet({ chain: 'base', dataDir: './demo-wallet' });
33
- console.log('Address:', wallet.address);
34
-
35
- // 2. Detect an x402 payment-required response
36
- const req = detect402({ status: 402, headers: {
37
- 'x-payment-amount': '0.10',
38
- 'x-payment-currency': 'USD',
39
- 'x-payment-recipient': '0xabc',
40
- 'x-payment-network': 'base'
41
- }});
42
- console.log('Payment required:', req);
43
-
44
- // 3. Enforce a spending policy
45
- const policy = new SpendingPolicy({ dailyLimitUsd: 25, allowedDomains: ['api.example.com'] });
46
- console.log('Allowed:', policy.checkTransaction(0.10, 'api.example.com').allowed);
47
- "
48
- ```
49
-
50
- That's a real Ethereum wallet, real x402 detection, and a real spending policy check — all in 60 seconds, zero config, zero Rust toolchain. The `native/` Rust acceleration is optional; the WASM tier ships pre-built in the npm package.
51
-
52
- > **⚠️ Patent Pending:** The x402 payment detection, autonomous spending policy enforcement, and recursive self-improvement (RSI) systems described in this library are subject to pending patent applications. Use is governed by the BSL 1.1 license.
53
-
54
- ---
55
-
56
- ## What Is This?
57
-
58
- ClawPowers extracts the core capabilities from [ClawPowers-Agent](https://github.com/up2itnow0822/ClawPowers-Agent) into a standalone library. **No agent control loop** — bring your own agent framework and get:
59
-
60
- That separation is intentional:
61
-
62
- - **`clawpowers`** owns the shared capability implementation.
63
- - **`clawpowers-agent`** owns the stock OpenClaw wrapper runtime.
64
- - Downstream wrappers should consume this package rather than duplicating capability logic.
65
-
66
- - **x402 Payments** — Detect HTTP 402 responses, enforce spending policies, execute payments
67
- - **Three-Tier Memory** — Working, episodic, procedural memory with crash recovery
68
- - **RSI Engine** — Metrics collection, hypothesis generation, mutation, A/B testing
69
- - **Wallet** — Generate, import, and sign with **MetaMask-compatible** Ethereum addresses out of the box (secp256k1 + Keccak-256 via pre-built WASM, no Rust toolchain required)
70
- - **Skills** — Discover, load, and track skill execution outcomes
71
- - **Parallel Swarm** — Concurrent task execution with intelligent model routing and token budgeting
72
- - **ITP (Identical Twins Protocol)** — Context compression that eliminates redundant token usage across agent sessions
73
-
74
- ## Native Acceleration
75
-
76
- ClawPowers ships the same optional **Rust + WASM + PyO3** stack as [ClawPowers-Agent](https://github.com/up2itnow0822/ClawPowers-Agent), exposed through a **3-tier loader** in TypeScript. **v2.2.0+:** when a native `.node` addon is present, the WASM bundle is still loaded if available so helpers such as secp256k1 stay available even if your local addon predates those exports; `getActiveTier()` remains `native` in that case.
77
-
78
- | Tier | Backend | When it loads |
79
- |------|---------|----------------|
80
- | **1 Native** | `napi-rs` `.node` addon (`native/ffi`, built locally with Rust) | Fastest; optional — not required for npm installs |
81
- | **2 — WASM** | Pre-built `native/wasm/pkg-node` (and `pkg` for web) | **Default** for most Node.js installs — no `wasm-pack` or Rust needed |
82
- | **3 TypeScript** | Pure JS / Node built-ins | Universal fallback when native and WASM are unavailable |
83
-
84
- Check status in code:
85
-
86
- ```typescript
87
- import { getActiveTier, isNativeAvailable, isWasmAvailable, getCapabilitySummary } from 'clawpowers';
88
-
89
- console.log(getActiveTier()); // 'native' | 'wasm' | 'typescript'
90
- console.log(isNativeAvailable(), isWasmAvailable());
91
- console.log(getCapabilitySummary());
92
- ```
93
-
94
- ### Building native / WASM locally
95
-
96
- **Requirements (optional):** Rust (`rustc` 1.70+), `wasm-pack` for regenerating WASM bindings.
97
-
98
- ```bash
99
- npm run build:native # workspace `cargo build --release` (ignored if Rust missing)
100
- npm run build:wasm # wasm-pack native/wasm/pkg-node (optional)
101
- ```
102
-
103
- `wasm-pack` may regenerate `pkg/.gitignore` / `pkg-node/.gitignore` that ignore all files in those folders — remove those ignore files if you need to commit refreshed WASM output.
104
-
105
- Pre-built `.wasm` artifacts are included in the package so consumers are **not** required to run `wasm-pack`.
106
-
107
- ### Module coverage (aligned with ClawPowers-Agent)
108
-
109
- | Area | Tier 1 / 2 capability | TypeScript fallback |
110
- |------|------------------------|---------------------|
111
- | Payments | `JsFeeSchedule`, WASM fee math | Pure-TS fee formula |
112
- | Payments | `JsX402Client` | Base64 JSON header |
113
- | Payments | `JsAgentWallet` (native only) | TS wallet + WASM secp256k1 + Keccak for real Ethereum addresses |
114
- | Memory | `JsCanonicalStore`, `JsTurboCompressor`, `JsWriteFirewall` | File/JSONL memory; simplified firewall |
115
- | Wallet / secp256k1 | Native + WASM: `deriveEthereumAddress`, `derivePublicKey`, `signEcdsa`, `verifyEcdsa`, `computeKeccak256` / `keccak256Bytes` | Tier 3: legacy digest-based “address” + HMAC signing fallback only |
116
-
117
- Exported helpers include `calculateTransactionFee`, `createPaymentHeader`, `generateWalletAddress`, `compressVector`, `getBestCanonicalStore`, `digestForWalletAddress`, and the full loader API in `src/native/index.ts`.
118
-
119
- ## x402 Payment Flow
120
-
121
- ```
122
- ┌─────────┐ ┌──────────────┐ ┌───────────────┐ ┌──────────┐
123
- │ Agent │────▶│ API Server │────▶│ detect402() │────▶│ Spending
124
- │ │ │ returns 402 │ parse x402 │ │ Policy │
125
- └─────────┘ └──────────────┘ │ headers │ │ check │
126
- └───────────────┘ └────┬─────┘
127
-
128
- ┌─────────────────▼─────────────────┐
129
- │ PaymentExecutor │
130
- │ ┌───────────┐ ┌─────────────┐ │
131
- │ │ MCP Client │ │ Audit Log │ │
132
- │ │ (agentpay) │ │ (append-only│ │
133
- │ └─────┬─────┘ └─────────────┘ │
134
- └───────┬───────────────────────────┘
135
-
136
- ┌───────▼───────┐
137
- │ Base Network │
138
- │ USDC Payment │
139
- └───────────────┘
140
- ```
141
-
142
- ## Framework Compatibility
143
-
144
- | Framework | Integration | Example |
145
- |-----------|------------|---------|
146
- | **LangChain** | `DynamicStructuredTool` | [`demos/langchain.ts`](demos/langchain.ts) |
147
- | **Claude Code** | `CLAUDE.md` config | [`demos/claude-code.md`](demos/claude-code.md) |
148
- | **ElizaOS** | Plugin pattern | [`demos/elizaos.ts`](demos/elizaos.ts) |
149
- | **AutoGPT** | Direct import | See examples below |
150
- | **CrewAI** | Tool wrapper | See examples below |
151
- | **Custom** | Direct TypeScript import | See examples below |
152
-
153
- ## Quick Start
154
-
155
- ### Payments
156
-
157
- ```typescript
158
- import { SpendingPolicy, PaymentExecutor, detect402 } from 'clawpowers';
159
-
160
- // Configure spending limits
161
- const policy = new SpendingPolicy({
162
- dailyLimit: 25, // $25/day
163
- transactionLimit: 10, // $10 per tx
164
- allowedDomains: ['api.example.com'],
165
- });
166
-
167
- // Create executor with your MCP client
168
- const executor = new PaymentExecutor(policy, mcpClient);
169
-
170
- // Detect and handle 402 responses
171
- const payment = detect402({ status: 402, headers: responseHeaders });
172
- if (payment) {
173
- const result = await executor.executePayment({
174
- amount: payment.amount,
175
- currency: payment.currency,
176
- recipient: payment.recipient,
177
- domain: 'api.example.com',
178
- x402Headers: payment.x402Headers,
179
- });
180
- }
181
- ```
182
-
183
- ### Memory
184
-
185
- ```typescript
186
- import { EpisodicMemory, ProceduralMemory, ContextInjector } from 'clawpowers';
187
-
188
- // Episodic: Task history (append-only JSONL)
189
- const episodic = new EpisodicMemory('~/.clawpowers/memory/episodic.jsonl');
190
- await episodic.append({
191
- taskId: 'task-1',
192
- timestamp: new Date().toISOString(),
193
- description: 'Built authentication module',
194
- outcome: 'success',
195
- lessonsLearned: ['Always test edge cases'],
196
- skillsUsed: ['tdd'],
197
- durationMs: 5000,
198
- tags: ['auth'],
199
- });
200
-
201
- // Procedural: Skill effectiveness tracking
202
- const procedural = new ProceduralMemory('~/.clawpowers/memory/procedural.json');
203
- await procedural.update('tdd', { succeeded: true, durationMs: 5000, taskId: 'task-1' });
204
-
205
- // Context injection: Relevant memories for new tasks
206
- const injector = new ContextInjector(episodic, procedural);
207
- const context = await injector.inject(goal, 2000); // 2000 token budget
208
- ```
209
-
210
- ### RSI (Recursive Self-Improvement)
211
-
212
- ```typescript
213
- import { MetricsCollector, HypothesisEngine, MutationEngine, ABTestManager } from 'clawpowers';
214
-
215
- // Collect metrics
216
- const metrics = new MetricsCollector('task-metrics.jsonl', 'skill-metrics.jsonl');
217
- await metrics.recordTaskMetrics({ taskId: 'task-1', outcome: 'success', /* ... */ });
218
-
219
- // Generate improvement hypotheses
220
- const hypothesis = new HypothesisEngine();
221
- const hypotheses = hypothesis.analyze(skillStats, taskHistory);
222
-
223
- // Create and test mutations
224
- const mutations = new MutationEngine('mutations.jsonl');
225
- const mutation = mutations.createMutation(hypotheses[0]);
226
-
227
- // A/B test mutations
228
- const ab = new ABTestManager();
229
- const test = ab.startTest(mutation, baselineStats);
230
- ab.recordResult(test.testId, newTaskMetrics);
231
- const result = ab.evaluateTest(test.testId);
232
- // result.decision: 'promote' | 'rollback' | 'continue'
233
- ```
234
-
235
- ### Wallet
236
-
237
- **v2.2.0+ produces real MetaMask-compatible Ethereum addresses** via the standard derivation chain: secp256k1 private key → uncompressed public key → Keccak-256 → last 20 bytes, with EIP-55 checksum case. Verified against the Hardhat default test vector (`0xac09...ff80` → `0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266`). Addresses are importable into MetaMask, Etherscan, and any EVM wallet.
238
-
239
- **Tier behavior:**
240
- - **Tier 1** (native `.node` addon, built locally with `cargo`): full secp256k1 + ECDSA + Keccak-256 via the `k256` Rust crate
241
- - **Tier 2** (pre-built WASM, ships in the npm package): same secp256k1 + ECDSA + Keccak-256 via `k256` compiled to WebAssembly
242
- > **⚠️ Wallet safety:** If both Tier 1 (native) and Tier 2 (WASM) fail to load, the library falls back to Tier 3 pure-TypeScript signing, which uses a legacy SHA-256 digest and HMAC — **not standard secp256k1, not production-safe for on-chain use.** Because Tier 2 WASM ships pre-built in every npm tarball, this fallback should only occur in heavily sandboxed environments. Call `getActiveTier()` at startup to verify you are running Tier 1 or Tier 2 before sending any real funds.
243
- - **Tier 3** (pure TypeScript, used only if Tier 1 AND Tier 2 both fail to load): legacy SHA-256 digest and HMAC signing — **not production-safe for on-chain use**
244
-
245
- Since Tier 2 WASM artifacts ship pre-built in the npm package, **every install gets real Ethereum wallets out of the box** — no Rust toolchain required.
246
-
247
- ```typescript
248
- import { WalletManager, generateWallet, signMessage } from 'clawpowers';
249
-
250
- // High-level API
251
- const wallet = new WalletManager({
252
- chain: 'base',
253
- dataDir: '~/.clawpowers/wallet',
254
- });
255
-
256
- const info = await wallet.generate();
257
- console.log(info.address); // 0x... — real Ethereum address, EIP-55 checksummed
258
-
259
- // Low-level API for direct key handling
260
- const sig = await signMessage(privateKeyHex, 'Hello, Ethereum');
261
- // Returns 65-byte ECDSA signature (r || s || recovery) as 0x-prefixed hex
262
- // Verifiable by any Ethereum node, ethers.js, viem, or MetaMask
263
- ```
264
-
265
- For production on-chain sending and transaction construction, you can still use [`viem`](https://viem.sh) or [`ethers`](https://docs.ethers.org) alongside ClawPowers our wallet produces the same addresses they do.
266
-
267
- ## Memory Module
268
-
269
- | Layer | Storage | Purpose |
270
- |-------|---------|---------|
271
- | **Working** | In-process | Current task context with token budget |
272
- | **Episodic** | JSONL file | Task history, searchable by keywords |
273
- | **Procedural** | JSON file | Skill effectiveness tracking with atomic writes |
274
- | **Checkpoint** | JSON files | Crash recovery, stale detection |
275
- | **Context Injector** | Computed | Selects relevant memories for new tasks |
276
-
277
- ## RSI Module
278
-
279
- The RSI engine implements a continuous improvement loop:
280
-
281
- ```
282
- measure → hypothesize → mutate → A/B test → promote/rollback → repeat
283
- ```
284
-
285
- **Tier Safety:**
286
- - **T1** (Parameter Tuning) Can auto-apply
287
- - **T2** (Strategy Evolution) — Can auto-apply with notification
288
- - **T3** (Skill Composition) — Requires testing gate
289
- - **T4** (Architecture Proposals) — **ALWAYS requires human approval**
290
-
291
- Safety invariants (spending limits, identity, RSI definitions, sandbox boundaries, credentials) can **NEVER** be modified by RSI.
292
-
293
- ## Parallel Swarm
294
-
295
- Run multiple tasks concurrently with intelligent model routing, shared context, and token budget management.
296
-
297
- ```typescript
298
- import { ConcurrencyManager, TokenPool, classifyHeuristic, selectModel } from 'clawpowers';
299
-
300
- const pool = new TokenPool({ totalBudget: 100000 });
301
- const concurrency = new ConcurrencyManager({ maxConcurrency: 5 });
302
-
303
- // Classify and route tasks to optimal models
304
- const complexity = classifyHeuristic('Build a distributed trading system');
305
- const model = selectModel(complexity); // → claude-opus-4-5
306
-
307
- // Allocate token budgets per task
308
- pool.allocate('task-1', 5000);
309
- ```
310
-
311
- ### Swarm vs Sequential Sessions
312
-
313
- Running N tasks as a single parallel swarm instead of N separate LLM sessions avoids reloading shared context (system prompt, workspace files, tool schemas) for every task.
314
-
315
- **Measured benefits:**
316
- - **Wall time:** parallel fan-out is significantly faster than sequential execution, scaling with task count and concurrency limit
317
- - **Token usage:** shared-context overhead is paid once per swarm run instead of once per task
318
-
319
- **Current measurement snapshot:**
320
-
321
- **Live ITP compression measurements:**
322
- - **25-message corpus:** 11 of 25 messages compressed, `862` to `759` estimated tokens, **11.95% token reduction**, **7.8 ms/message** round-trip
323
- - **5-task live swarm payload:** `183` to `133` task tokens, **27.32% payload reduction**, **5 of 5 tasks compressed**, **10.8 ms** average encode latency
324
-
325
- **Modeled prompt-cache economics on those same live prompt sizes:**
326
-
327
- | Scenario | Effective input units | Reduction vs baseline | Source type |
328
- |----------|-----------------------|-----------------------|-------------|
329
- | Baseline | 1902.00 | 0.00% | Derived from live prompt sizes |
330
- | ITP only | 1848.00 | 2.84% | Live ITP server compression applied to full prompts |
331
- | Prompt cache only | 752.95 | 60.41% | Anthropic cache-pricing model |
332
- | ITP + prompt cache | 698.95 | 63.25% | Hybrid result: live ITP compression + modeled cache pricing |
333
-
334
- - **Shared prompt prefix in swarm test:** 1,372 characters, about 343 estimated input tokens
335
- - **Three-set hybrid validation on a MacBook Pro (Apple M1, 16 GB RAM) with benchmark runner model `openai-codex/gpt-5.4`:** combined reduction ranged from **61.89%** to **63.25%**, with a **62.56%** mean and **0.56** standard deviation
336
-
337
- **Reproduce:**
338
- - `node benchmarks/itp-measurement.mjs` for the live ITP corpus benchmark
339
- - `node benchmarks/swarm-vs-sequential.mjs` for the structure-only swarm cost model
340
- - `node benchmarks/itp-cache-swarm-benchmark.mjs` for the hybrid benchmark (live ITP compression + modeled cache economics)
341
- - `node benchmarks/itp-cache-multi-swarm-benchmark.mjs` for the same hybrid methodology across three swarm sets
342
-
343
- ## ITP (Identical Twins Protocol) - Experimental
344
-
345
- > **Status: Experimental.** ITP compression and latency numbers below are measured against the running server. Any prompt-cache numbers are modeled Anthropic cache economics applied to those same live prompt sizes.
346
-
347
- Context compression for multi-agent communication. When agents share similar context (same model, same workspace), ITP deduplicates the common payload before transmission. The library ships with a graceful passthrough fallback, so code using ITP works even when the ITP server is offline. Messages are simply forwarded unchanged.
348
-
349
- ```typescript
350
- import { itpEncode, itpDecode, itpHealthCheck, encodeTaskDescription, decodeSwarmResult } from 'clawpowers';
351
-
352
- // Graceful fallback, works without ITP server running
353
- const encoded = await encodeTaskDescription('Analyze quarterly revenue data');
354
- const decoded = await decodeSwarmResult(result);
355
-
356
- // Health check
357
- const serverUp = await itpHealthCheck(); // false = passthrough mode
358
- ```
359
-
360
- **Live ITP benchmark snapshot:**
361
- - **Codebook:** `v1.0.0`, 99 entries
362
- - **Corpus benchmark:** **11.95%** token reduction on 25 messages
363
- - **Swarm payload benchmark:** **27.32%** task-token reduction on a 5-task swarm
364
- - **Hybrid swarm benchmark:** **63.25%** effective input-cost reduction from live ITP compression plus modeled prompt caching
365
-
366
- ITP is most effective in parallel swarm scenarios where multiple tasks share the same model context. Prompt caching handles repeated prompt structure, and ITP reduces the changing task payload inside that structure. Cross-model savings can also compound because providers inject similar preambles across nearby model tiers.
367
-
368
- ## Fee Structure
369
-
370
- | Operation | Fee |
371
- |-----------|-----|
372
- | Transaction | 0.77% |
373
- | Token Swap | 0.30% |
374
-
375
- Fees are applied at the payment execution layer and are included in the transaction amount.
376
-
377
- ## Python Integration
378
-
379
- ```python
380
- import subprocess
381
- import json
382
-
383
- # Call ClawPowers via Node.js subprocess
384
- # Note: use --input-type=module (or a .mjs file) because clawpowers is an ES module
385
- result = subprocess.run(
386
- ['node', '--input-type=module'],
387
- input='''
388
- import { detect402, SpendingPolicy } from "clawpowers";
389
- const policy = new SpendingPolicy({ dailyLimit: 25, transactionLimit: 10, allowedDomains: [] });
390
- const decision = policy.checkTransaction(5.00, "api.example.com");
391
- console.log(JSON.stringify(decision));
392
- ''',
393
- capture_output=True, text=True
394
- )
395
- decision = json.loads(result.stdout)
396
- ```
397
-
398
- ## API Reference
399
-
400
- ### Native acceleration
401
- - `getActiveTier()`, `isNativeAvailable()`, `isWasmAvailable()`, `getCapabilitySummary()` — Loader introspection
402
- - `computeSha256`, `digestForWalletAddress`, `tokenAmountFromHuman`, `calculateFee`, `evaluateWriteFirewall` — Routed helpers
403
- - `getNative()`, `getWasm()` — Low-level module access
404
-
405
- ### Payments
406
- - `detect402(response)` — Parse x402 headers from 402 response
407
- - `isPaymentRequired(error)` Type guard for 402 errors
408
- - `SpendingPolicy` Enforce daily/transaction/domain limits
409
- - `PaymentExecutor` — Execute payments via MCP client
410
- - `calculateTransactionFee`, `createPaymentHeader`, `generateWalletAddress` — Native/WASM-accelerated payment helpers (with TS fallbacks)
411
-
412
- ### Memory
413
- - `WorkingMemoryManager` In-process context management
414
- - `EpisodicMemory` JSONL task history
415
- - `ProceduralMemory` — Skill effectiveness tracking
416
- - `CheckpointManager` — Crash recovery
417
- - `ContextInjector` — Memory-to-context selection
418
- - `getBestCanonicalStore`, `getWasmCanonicalStore`, `compressVector`, `decompressVector`, `evaluateWriteSecurity` — Optional native/WASM memory bridges
419
-
420
- ### RSI
421
- - `MetricsCollector` — Task/skill metrics in JSONL
422
- - `HypothesisEngine` — Generate improvement hypotheses
423
- - `MutationEngine` — Create/apply/revert mutations
424
- - `ABTestManager` — A/B test mutations
425
- - `RSIAuditLog` — Append-only audit trail
426
- - `AutoResearcher` Research solutions to failures
427
-
428
- ### Skills
429
- - `discoverSkills(dir)` — Find skills in a directory
430
- - `loadSkillManifest(dir)` — Load a single skill manifest
431
- - `SkillExecutor` — Execute skills with outcome tracking
432
-
433
- ### Wallet
434
-
435
- - `WalletManager` — High-level wallet operations
436
- - `generateWallet(config)` — Generate new wallet (**v2.2.0+**: standard Ethereum address via secp256k1 when Tier 1/2 is active)
437
- - `importWallet(key, config)` — Import existing wallet (same derivation)
438
- - `signMessage(message, keyFile, passphrase)` — Sign; uses **ECDSA (secp256k1) over Keccak-256(UTF-8 message)** when native/WASM provides crypto, else legacy HMAC
439
- - `signMessage(privateKeyHex, message)` — Same ECDSA path; returns `0x` + 130 hex chars (65-byte signature)
440
-
441
- ### Config
442
- - `loadConfig()` / `saveConfig()` — Zod-validated config CRUD
443
- - `initConfig()` — Create default config
444
- - `getConfigValue()` / `setConfigValue()` — Dot-notation access
445
-
446
- ## License
447
-
448
- **Business Source License 1.1 (BSL 1.1)**
449
-
450
- This software is licensed under the BSL 1.1. You may use it for non-production purposes freely. Production use requires a commercial license until the Change Date, after which the software converts to the Apache 2.0 license.
451
-
452
- See [LICENSE](LICENSE) for full terms.
453
-
454
- ## Patent Notice
455
-
456
- ⚠️ **Patent Pending:** The autonomous payment detection, spending policy enforcement, recursive self-improvement engine, and multi-tier memory systems implemented in this library are subject to pending patent applications filed by AI Agent Economy. Unauthorized commercial use may constitute patent infringement.
457
-
458
- ---
459
-
460
- Built by [AI Agent Economy](https://github.com/up2itnow0822) 🦅
461
-
462
- For commercial use, review [LICENSING.md](./LICENSING.md).
1
+ # ClawPowers
2
+
3
+ > **Hermes-compatible branch note:** this branch only claims Hermes compatibility for the skill bundles exported under top-level `skills/`.
4
+ >
5
+ > Today that means the full top-level `skills/` surface on this branch, currently 67 Hermes-loadable bundles. `skills/itp/` remains the deepest manually validated proof bundle, while the rest of the exported surface is generated from the ClawPowers skill catalog with the same Hermes compatibility boundary.
6
+ >
7
+ > The broader `clawpowers` npm library, including wallet, payments, RSI, memory, and swarm modules, remains a separate library/runtime surface and is **not** part of this branch's Hermes-native compatibility claim.
8
+
9
+ See [HERMES_COMPATIBILITY.md](./HERMES_COMPATIBILITY.md) for the exact support contract.
10
+
11
+ **Launch surface:** `clawpowers` is the capability library. It is not the stock OpenClaw wrapper runtime. For the wrapper runtime, install `clawpowers-agent`.
12
+
13
+ ## Canonical Links
14
+ - Product site: https://clawpowers.ai
15
+ - Docs: https://clawpowers.ai/docs
16
+ - Agent runtime: https://clawpowers.ai/agent
17
+
18
+ **Recommended pairing:** `clawpowers` 2.2.x with `clawpowers-agent` 1.1.x.
19
+ **Node runtime:** Node.js 22+.
20
+
21
+ **More docs:** [SECURITY](./SECURITY.md) · [Compatibility](./COMPATIBILITY.md) · [Known Limitations](./KNOWN_LIMITATIONS.md) · [Licensing](./LICENSING.md) · [Releasing](./RELEASING.md) · [Demo](./DEMO.md) · [Roadmap](./ROADMAP.md)
22
+
23
+ **Skills library for AI agents — payments, memory, RSI, wallet, parallel swarm, ITP.** Drop-in capability layer for any agent framework.
24
+
25
+ [![npm version](https://img.shields.io/npm/v/clawpowers)](https://www.npmjs.com/package/clawpowers)
26
+ [![License: BSL 1.1](https://img.shields.io/badge/License-BSL%201.1-blue.svg)](LICENSE)
27
+ [![CI](https://github.com/up2itnow0822/ClawPowers-Skills/actions/workflows/ci.yml/badge.svg)](https://github.com/up2itnow0822/ClawPowers-Skills/actions/workflows/ci.yml)
28
+
29
+ ```bash
30
+ npm install clawpowers
31
+ ```
32
+
33
+ ## 60-Second Demo
34
+
35
+ ```bash
36
+ npm install clawpowers
37
+ node -e "
38
+ const { generateWallet, detect402, SpendingPolicy, getActiveTier } = await import('clawpowers');
39
+
40
+ // 1. Generate a real Ethereum wallet (MetaMask-compatible)
41
+ const wallet = await generateWallet({ chain: 'base', dataDir: './demo-wallet' });
42
+
43
+ // 2. Detect an x402 payment-required response
44
+ const req = detect402({ status: 402, headers: {
45
+ 'x-payment-amount': '0.10',
46
+ 'x-payment-currency': 'USD',
47
+ 'x-payment-recipient': '0xabc',
48
+ 'x-payment-network': 'base'
49
+ }});
50
+
51
+ // 3. Enforce a spending policy with one allow path and one reject path
52
+ const policy = new SpendingPolicy({
53
+ dailyLimit: 25,
54
+ transactionLimit: 1,
55
+ allowedDomains: ['api.example.com']
56
+ });
57
+ const allowed = policy.checkTransaction(0.10, 'api.example.com');
58
+ if (allowed.allowed) {
59
+ policy.recordSpend(0.10, 'api.example.com');
60
+ }
61
+ const blocked = policy.checkTransaction(0.10, 'evil.example.com');
62
+
63
+ console.log({
64
+ tier: getActiveTier(),
65
+ address: wallet.address,
66
+ paymentRequired: req,
67
+ allowed,
68
+ blocked,
69
+ dailySpent: policy.getDailySpent()
70
+ });
71
+ "
72
+ ```
73
+
74
+ That's a real Ethereum wallet, real x402 detection, and a real spending policy allow and reject check in under a minute. The `native/` Rust acceleration is optional, and the WASM tier ships pre-built in the npm package.
75
+
76
+ > **⚠️ Patent Pending:** The x402 payment detection, autonomous spending policy enforcement, and recursive self-improvement (RSI) systems described in this library are subject to pending patent applications. Use is governed by the BSL 1.1 license.
77
+
78
+ ---
79
+
80
+ ## What Is This?
81
+
82
+ ClawPowers extracts the core capabilities from [ClawPowers-Agent](https://github.com/up2itnow0822/ClawPowers-Agent) into a standalone library. **No agent control loop** bring your own agent framework and get:
83
+
84
+ That separation is intentional:
85
+
86
+ - **`clawpowers`** owns the shared capability implementation.
87
+ - **`clawpowers-agent`** owns the stock OpenClaw wrapper runtime.
88
+ - Downstream wrappers should consume this package rather than duplicating capability logic.
89
+
90
+ - **x402 Payments** — Detect HTTP 402 responses, enforce spending policies, execute payments
91
+ - **Three-Tier Memory** — Working, episodic, procedural memory with crash recovery
92
+ - **RSI Engine** — Metrics collection, hypothesis generation, mutation, A/B testing
93
+ - **Wallet** — Generate, import, and sign with **MetaMask-compatible** Ethereum addresses out of the box (secp256k1 + Keccak-256 via pre-built WASM, no Rust toolchain required)
94
+ - **Skills** Discover, load, and track skill execution outcomes
95
+ - **Parallel Swarm** — Concurrent task execution with intelligent model routing and token budgeting
96
+ - **ITP (Identical Twins Protocol)** Context compression that eliminates redundant token usage across agent sessions
97
+
98
+ ## Native Acceleration
99
+
100
+ ClawPowers ships the same optional **Rust + WASM + PyO3** stack as [ClawPowers-Agent](https://github.com/up2itnow0822/ClawPowers-Agent), exposed through a **3-tier loader** in TypeScript. **v2.2.0+:** when a native `.node` addon is present, the WASM bundle is still loaded if available so helpers such as secp256k1 stay available even if your local addon predates those exports; `getActiveTier()` remains `native` in that case.
101
+
102
+ | Tier | Backend | When it loads |
103
+ |------|---------|----------------|
104
+ | **1 — Native** | `napi-rs` `.node` addon (`native/ffi`, built locally with Rust) | Fastest; optional — not required for npm installs |
105
+ | **2 — WASM** | Pre-built `native/wasm/pkg-node` (and `pkg` for web) | **Default** for most Node.js installs no `wasm-pack` or Rust needed |
106
+ | **3 — TypeScript** | Pure JS / Node built-ins | Universal fallback when native and WASM are unavailable |
107
+
108
+ Check status in code:
109
+
110
+ ```typescript
111
+ import { getActiveTier, isNativeAvailable, isWasmAvailable, getCapabilitySummary } from 'clawpowers';
112
+
113
+ console.log(getActiveTier()); // 'native' | 'wasm' | 'typescript'
114
+ console.log(isNativeAvailable(), isWasmAvailable());
115
+ console.log(getCapabilitySummary());
116
+ ```
117
+
118
+ ### Building native / WASM locally
119
+
120
+ **Requirements (optional):** Rust (`rustc` 1.70+), `wasm-pack` for regenerating WASM bindings.
121
+
122
+ ```bash
123
+ npm run build:native # workspace `cargo build --release` (ignored if Rust missing)
124
+ npm run build:wasm # wasm-pack → native/wasm/pkg-node (optional)
125
+ ```
126
+
127
+ `npm run build:wasm` automatically removes `native/wasm/pkg-node/.gitignore` after generation so Node-targeted WASM artifacts are always packable.
128
+
129
+ Pre-built `.wasm` artifacts are included in the package so consumers are **not** required to run `wasm-pack`.
130
+
131
+ ### Module coverage (aligned with ClawPowers-Agent)
132
+
133
+ | Area | Tier 1 / 2 capability | TypeScript fallback |
134
+ |------|------------------------|---------------------|
135
+ | Payments | `JsFeeSchedule`, WASM fee math | Pure-TS fee formula |
136
+ | Payments | `JsX402Client` | Base64 JSON header |
137
+ | Payments | `JsAgentWallet` (native only) | TS wallet + WASM secp256k1 + Keccak for real Ethereum addresses |
138
+ | Memory | `JsCanonicalStore`, `JsTurboCompressor`, `JsWriteFirewall` | File/JSONL memory; simplified firewall |
139
+ | Wallet / secp256k1 | Native + WASM: `deriveEthereumAddress`, `derivePublicKey`, `signEcdsa`, `verifyEcdsa`, `computeKeccak256` / `keccak256Bytes` | Tier 3: legacy digest-based “address” + HMAC signing fallback only |
140
+
141
+ Exported helpers include `calculateTransactionFee`, `createPaymentHeader`, `generateWalletAddress`, `compressVector`, `getBestCanonicalStore`, `digestForWalletAddress`, and the full loader API in `src/native/index.ts`.
142
+
143
+ ## x402 Payment Flow
144
+
145
+ ```
146
+ ┌─────────┐ ┌──────────────┐ ┌───────────────┐ ┌──────────┐
147
+ │ Agent │────▶│ API Server │────▶│ detect402() │────▶│ Spending
148
+ │ │ │ returns 402 │ │ parse x402 │ │ Policy │
149
+ └─────────┘ └──────────────┘ │ headers │ │ check │
150
+ └───────────────┘ └────┬─────┘
151
+
152
+ ┌─────────────────▼─────────────────┐
153
+ │ PaymentExecutor │
154
+ │ ┌───────────┐ ┌─────────────┐ │
155
+ │ │ MCP Client │ │ Audit Log │ │
156
+ │ │ (agentpay) │ │ (append-only│ │
157
+ │ └─────┬─────┘ └─────────────┘ │
158
+ └───────┬───────────────────────────┘
159
+
160
+ ┌───────▼───────┐
161
+ │ Base Network │
162
+ USDC Payment │
163
+ └───────────────┘
164
+ ```
165
+
166
+ ## Framework Compatibility
167
+
168
+ | Framework | Integration | Example |
169
+ |-----------|------------|---------|
170
+ | **LangChain** | `DynamicStructuredTool` | [`demos/langchain.ts`](demos/langchain.ts) |
171
+ | **Claude Code** | `CLAUDE.md` config | [`demos/claude-code.md`](demos/claude-code.md) |
172
+ | **ElizaOS** | Plugin pattern | [`demos/elizaos.ts`](demos/elizaos.ts) |
173
+ | **AutoGPT** | Direct import | See examples below |
174
+ | **CrewAI** | Tool wrapper | See examples below |
175
+ | **Custom** | Direct TypeScript import | See examples below |
176
+
177
+ ## Quick Start
178
+
179
+ ### Payments
180
+
181
+ ```typescript
182
+ import { SpendingPolicy, PaymentExecutor, detect402 } from 'clawpowers';
183
+
184
+ // Configure spending limits
185
+ const policy = new SpendingPolicy({
186
+ dailyLimit: 25, // $25/day
187
+ transactionLimit: 10, // $10 per tx
188
+ allowedDomains: ['api.example.com'],
189
+ });
190
+
191
+ // Create executor with your MCP client
192
+ const executor = new PaymentExecutor(policy, mcpClient);
193
+
194
+ // Detect and handle 402 responses
195
+ const payment = detect402({ status: 402, headers: responseHeaders });
196
+ if (payment) {
197
+ const result = await executor.executePayment({
198
+ amount: payment.amount,
199
+ currency: payment.currency,
200
+ recipient: payment.recipient,
201
+ domain: 'api.example.com',
202
+ x402Headers: payment.x402Headers,
203
+ });
204
+ }
205
+ ```
206
+
207
+ ### Memory
208
+
209
+ ```typescript
210
+ import { EpisodicMemory, ProceduralMemory, ContextInjector } from 'clawpowers';
211
+
212
+ // Episodic: Task history (append-only JSONL)
213
+ const episodic = new EpisodicMemory('~/.clawpowers/memory/episodic.jsonl');
214
+ await episodic.append({
215
+ taskId: 'task-1',
216
+ timestamp: new Date().toISOString(),
217
+ description: 'Built authentication module',
218
+ outcome: 'success',
219
+ lessonsLearned: ['Always test edge cases'],
220
+ skillsUsed: ['tdd'],
221
+ durationMs: 5000,
222
+ tags: ['auth'],
223
+ });
224
+
225
+ // Procedural: Skill effectiveness tracking
226
+ const procedural = new ProceduralMemory('~/.clawpowers/memory/procedural.json');
227
+ await procedural.update('tdd', { succeeded: true, durationMs: 5000, taskId: 'task-1' });
228
+
229
+ // Context injection: Relevant memories for new tasks
230
+ const injector = new ContextInjector(episodic, procedural);
231
+ const context = await injector.inject(goal, 2000); // 2000 token budget
232
+ ```
233
+
234
+ ### RSI (Recursive Self-Improvement)
235
+
236
+ ```typescript
237
+ import { MetricsCollector, HypothesisEngine, MutationEngine, ABTestManager } from 'clawpowers';
238
+
239
+ // Collect metrics
240
+ const metrics = new MetricsCollector('task-metrics.jsonl', 'skill-metrics.jsonl');
241
+ await metrics.recordTaskMetrics({ taskId: 'task-1', outcome: 'success', /* ... */ });
242
+
243
+ // Generate improvement hypotheses
244
+ const hypothesis = new HypothesisEngine();
245
+ const hypotheses = hypothesis.analyze(skillStats, taskHistory);
246
+
247
+ // Create and test mutations
248
+ const mutations = new MutationEngine('mutations.jsonl');
249
+ const mutation = mutations.createMutation(hypotheses[0]);
250
+
251
+ // A/B test mutations
252
+ const ab = new ABTestManager();
253
+ const test = ab.startTest(mutation, baselineStats);
254
+ ab.recordResult(test.testId, newTaskMetrics);
255
+ const result = ab.evaluateTest(test.testId);
256
+ // result.decision: 'promote' | 'rollback' | 'continue'
257
+ ```
258
+
259
+ ### Wallet
260
+
261
+ **v2.2.0+ produces real MetaMask-compatible Ethereum addresses** via the standard derivation chain: secp256k1 private key → uncompressed public key → Keccak-256 → last 20 bytes, with EIP-55 checksum case. Verified against the Hardhat default test vector (`0xac09...ff80` → `0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266`). Addresses are importable into MetaMask, Etherscan, and any EVM wallet.
262
+
263
+ **Tier behavior:**
264
+ - **Tier 1** (native `.node` addon, built locally with `cargo`): full secp256k1 + ECDSA + Keccak-256 via the `k256` Rust crate
265
+ - **Tier 2** (pre-built WASM, ships in the npm package): same secp256k1 + ECDSA + Keccak-256 via `k256` compiled to WebAssembly
266
+ > **⚠️ Wallet safety:** If both Tier 1 (native) and Tier 2 (WASM) fail to load, the library falls back to Tier 3 pure-TypeScript signing, which uses a legacy SHA-256 digest and HMAC — **not standard secp256k1, not production-safe for on-chain use.** Because Tier 2 WASM ships pre-built in every npm tarball, this fallback should only occur in heavily sandboxed environments. Call `getActiveTier()` at startup to verify you are running Tier 1 or Tier 2 before sending any real funds.
267
+ - **Tier 3** (pure TypeScript, used only if Tier 1 AND Tier 2 both fail to load): legacy SHA-256 digest and HMAC signing — **not production-safe for on-chain use**
268
+
269
+ Since Tier 2 WASM artifacts ship pre-built in the npm package, **every install gets real Ethereum wallets out of the box** — no Rust toolchain required.
270
+
271
+ ```typescript
272
+ import { WalletManager, generateWallet, signMessage } from 'clawpowers';
273
+
274
+ // High-level API
275
+ const wallet = new WalletManager({
276
+ chain: 'base',
277
+ dataDir: '~/.clawpowers/wallet',
278
+ });
279
+
280
+ const info = await wallet.generate();
281
+ console.log(info.address); // 0x... — real Ethereum address, EIP-55 checksummed
282
+
283
+ // Low-level API for direct key handling
284
+ const sig = await signMessage(privateKeyHex, 'Hello, Ethereum');
285
+ // Returns 65-byte ECDSA signature (r || s || recovery) as 0x-prefixed hex
286
+ // Verifiable by any Ethereum node, ethers.js, viem, or MetaMask
287
+ ```
288
+
289
+ For production on-chain sending and transaction construction, you can still use [`viem`](https://viem.sh) or [`ethers`](https://docs.ethers.org) alongside ClawPowers our wallet produces the same addresses they do.
290
+
291
+ ## Memory Module
292
+
293
+ | Layer | Storage | Purpose |
294
+ |-------|---------|---------|
295
+ | **Working** | In-process | Current task context with token budget |
296
+ | **Episodic** | JSONL file | Task history, searchable by keywords |
297
+ | **Procedural** | JSON file | Skill effectiveness tracking with atomic writes |
298
+ | **Checkpoint** | JSON files | Crash recovery, stale detection |
299
+ | **Context Injector** | Computed | Selects relevant memories for new tasks |
300
+
301
+ ## RSI Module
302
+
303
+ The RSI engine implements a continuous improvement loop:
304
+
305
+ ```
306
+ measure → hypothesize → mutate → A/B test → promote/rollback → repeat
307
+ ```
308
+
309
+ **Tier Safety:**
310
+ - **T1** (Parameter Tuning) — Can auto-apply
311
+ - **T2** (Strategy Evolution) — Can auto-apply with notification
312
+ - **T3** (Skill Composition) — Requires testing gate
313
+ - **T4** (Architecture Proposals) **ALWAYS requires human approval**
314
+
315
+ Safety invariants (spending limits, identity, RSI definitions, sandbox boundaries, credentials) can **NEVER** be modified by RSI.
316
+
317
+ ## Parallel Swarm
318
+
319
+ Run multiple tasks concurrently with intelligent model routing, shared context, and token budget management.
320
+
321
+ ```typescript
322
+ import { ConcurrencyManager, TokenPool, classifyHeuristic, selectModel } from 'clawpowers';
323
+
324
+ const pool = new TokenPool({ totalBudget: 100000 });
325
+ const concurrency = new ConcurrencyManager({ maxConcurrency: 5 });
326
+
327
+ // Classify and route tasks to optimal models
328
+ const complexity = classifyHeuristic('Build a distributed trading system');
329
+ const model = selectModel(complexity); // claude-opus-4-5
330
+
331
+ // Allocate token budgets per task
332
+ pool.allocate('task-1', 5000);
333
+ ```
334
+
335
+ ### Swarm vs Sequential Sessions
336
+
337
+ Running N tasks as a single parallel swarm instead of N separate LLM sessions avoids reloading shared context (system prompt, workspace files, tool schemas) for every task.
338
+
339
+ **Measured benefits:**
340
+ - **Wall time:** parallel fan-out is significantly faster than sequential execution, scaling with task count and concurrency limit
341
+ - **Token usage:** shared-context overhead is paid once per swarm run instead of once per task
342
+
343
+ **Current measurement snapshot:**
344
+
345
+ **Live ITP compression measurements:**
346
+ - **25-message corpus:** 11 of 25 messages compressed, `862` to `759` estimated tokens, **11.95% token reduction**, **7.8 ms/message** round-trip
347
+ - **5-task live swarm payload:** `183` to `133` task tokens, **27.32% payload reduction**, **5 of 5 tasks compressed**, **10.8 ms** average encode latency
348
+
349
+ **Modeled prompt-cache economics on those same live prompt sizes:**
350
+
351
+ | Scenario | Effective input units | Reduction vs baseline | Source type |
352
+ |----------|-----------------------|-----------------------|-------------|
353
+ | Baseline | 1902.00 | 0.00% | Derived from live prompt sizes |
354
+ | ITP only | 1848.00 | 2.84% | Live ITP server compression applied to full prompts |
355
+ | Prompt cache only | 752.95 | 60.41% | Anthropic cache-pricing model |
356
+ | ITP + prompt cache | 698.95 | 63.25% | Hybrid result: live ITP compression + modeled cache pricing |
357
+
358
+ - **Shared prompt prefix in swarm test:** 1,372 characters, about 343 estimated input tokens
359
+ - **Three-set hybrid validation on a MacBook Pro (Apple M1, 16 GB RAM) with benchmark runner model `openai-codex/gpt-5.4`:** combined reduction ranged from **61.89%** to **63.25%**, with a **62.56%** mean and **0.56** standard deviation
360
+
361
+ **Reproduce:**
362
+ - `node benchmarks/itp-measurement.mjs` for the live ITP corpus benchmark
363
+ - `node benchmarks/swarm-vs-sequential.mjs` for the structure-only swarm cost model
364
+ - `node benchmarks/itp-cache-swarm-benchmark.mjs` for the hybrid benchmark (live ITP compression + modeled cache economics)
365
+ - `node benchmarks/itp-cache-multi-swarm-benchmark.mjs` for the same hybrid methodology across three swarm sets
366
+
367
+ ## ITP (Identical Twins Protocol) - Experimental
368
+
369
+ > **Status: Experimental.** ITP compression and latency numbers below are measured against the running server. Any prompt-cache numbers are modeled Anthropic cache economics applied to those same live prompt sizes.
370
+
371
+ Context compression for multi-agent communication. When agents share similar context (same model, same workspace), ITP deduplicates the common payload before transmission. The library ships with a graceful passthrough fallback, so code using ITP works even when the ITP server is offline. Messages are simply forwarded unchanged.
372
+
373
+ ```typescript
374
+ import { itpEncode, itpDecode, itpHealthCheck, encodeTaskDescription, decodeSwarmResult } from 'clawpowers';
375
+
376
+ // Graceful fallback, works without ITP server running
377
+ const encoded = await encodeTaskDescription('Analyze quarterly revenue data');
378
+ const decoded = await decodeSwarmResult(result);
379
+
380
+ // Health check
381
+ const serverUp = await itpHealthCheck(); // false = passthrough mode
382
+ ```
383
+
384
+ **Live ITP benchmark snapshot:**
385
+ - **Codebook:** `v1.0.0`, 99 entries
386
+ - **Corpus benchmark:** **11.95%** token reduction on 25 messages
387
+ - **Swarm payload benchmark:** **27.32%** task-token reduction on a 5-task swarm
388
+ - **Hybrid swarm benchmark:** **63.25%** effective input-cost reduction from live ITP compression plus modeled prompt caching
389
+
390
+ ITP is most effective in parallel swarm scenarios where multiple tasks share the same model context. Prompt caching handles repeated prompt structure, and ITP reduces the changing task payload inside that structure. Cross-model savings can also compound because providers inject similar preambles across nearby model tiers.
391
+
392
+ ## Fee Structure
393
+
394
+ | Operation | Fee |
395
+ |-----------|-----|
396
+ | Transaction | 0.77% |
397
+ | Token Swap | 0.30% |
398
+
399
+ Fees are applied at the payment execution layer and are included in the transaction amount.
400
+
401
+ ## Python Integration
402
+
403
+ ```python
404
+ import subprocess
405
+ import json
406
+
407
+ # Call ClawPowers via Node.js subprocess
408
+ # Note: use --input-type=module (or a .mjs file) because clawpowers is an ES module
409
+ result = subprocess.run(
410
+ ['node', '--input-type=module'],
411
+ input='''
412
+ import { detect402, SpendingPolicy } from "clawpowers";
413
+ const policy = new SpendingPolicy({ dailyLimit: 25, transactionLimit: 10, allowedDomains: [] });
414
+ const decision = policy.checkTransaction(5.00, "api.example.com");
415
+ console.log(JSON.stringify(decision));
416
+ ''',
417
+ capture_output=True, text=True
418
+ )
419
+ decision = json.loads(result.stdout)
420
+ ```
421
+
422
+ ## API Reference
423
+
424
+ ### Native acceleration
425
+ - `getActiveTier()`, `isNativeAvailable()`, `isWasmAvailable()`, `getCapabilitySummary()` Loader introspection
426
+ - `computeSha256`, `digestForWalletAddress`, `tokenAmountFromHuman`, `calculateFee`, `evaluateWriteFirewall` Routed helpers
427
+ - `getNative()`, `getWasm()` — Low-level module access
428
+
429
+ ### Payments
430
+ - `detect402(response)` — Parse x402 headers from 402 response
431
+ - `isPaymentRequired(error)` — Type guard for 402 errors
432
+ - `SpendingPolicy` — Enforce daily/transaction/domain limits
433
+ - `PaymentExecutor` — Execute payments via MCP client
434
+ - `calculateTransactionFee`, `createPaymentHeader`, `generateWalletAddress` — Native/WASM-accelerated payment helpers (with TS fallbacks)
435
+
436
+ ### Memory
437
+ - `WorkingMemoryManager` — In-process context management
438
+ - `EpisodicMemory` — JSONL task history
439
+ - `ProceduralMemory` — Skill effectiveness tracking
440
+ - `CheckpointManager` — Crash recovery
441
+ - `ContextInjector` — Memory-to-context selection
442
+ - `getBestCanonicalStore`, `getWasmCanonicalStore`, `compressVector`, `decompressVector`, `evaluateWriteSecurity`Optional native/WASM memory bridges
443
+
444
+ ### RSI
445
+ - `MetricsCollector` — Task/skill metrics in JSONL
446
+ - `HypothesisEngine` — Generate improvement hypotheses
447
+ - `MutationEngine` — Create/apply/revert mutations
448
+ - `ABTestManager` A/B test mutations
449
+ - `RSIAuditLog` — Append-only audit trail
450
+ - `AutoResearcher` Research solutions to failures
451
+
452
+ ### Skills
453
+ - `discoverSkills(dir)` — Find skills in a directory
454
+ - `loadSkillManifest(dir)` — Load a single skill manifest
455
+ - `SkillExecutor` — Execute skills with outcome tracking
456
+
457
+ ### Wallet
458
+
459
+ - `WalletManager` — High-level wallet operations
460
+ - `generateWallet(config)` Generate new wallet (**v2.2.0+**: standard Ethereum address via secp256k1 when Tier 1/2 is active)
461
+ - `importWallet(key, config)` — Import existing wallet (same derivation)
462
+ - `signMessage(message, keyFile, passphrase)` — Sign; uses **ECDSA (secp256k1) over Keccak-256(UTF-8 message)** when native/WASM provides crypto, else legacy HMAC
463
+ - `signMessage(privateKeyHex, message)` — Same ECDSA path; returns `0x` + 130 hex chars (65-byte signature)
464
+
465
+ ### Config
466
+ - `loadConfig()` / `saveConfig()` — Zod-validated config CRUD
467
+ - `initConfig()` — Create default config
468
+ - `getConfigValue()` / `setConfigValue()` — Dot-notation access
469
+
470
+ ## License
471
+
472
+ **Business Source License 1.1 (BSL 1.1)**
473
+
474
+ This software is licensed under the BSL 1.1. You may use it for non-production purposes freely. Production use requires a commercial license until the Change Date, after which the software converts to the Apache 2.0 license.
475
+
476
+ See [LICENSE](LICENSE) for full terms.
477
+
478
+ ## Patent Notice
479
+
480
+ ⚠️ **Patent Pending:** The autonomous payment detection, spending policy enforcement, recursive self-improvement engine, and multi-tier memory systems implemented in this library are subject to pending patent applications filed by AI Agent Economy. Unauthorized commercial use may constitute patent infringement.
481
+
482
+ ---
483
+
484
+ Built by [AI Agent Economy](https://github.com/up2itnow0822) 🦅
485
+
486
+ For commercial use, review [LICENSING.md](./LICENSING.md).