@clawnch/clawtomaton 0.1.0

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 (91) hide show
  1. package/README.md +231 -0
  2. package/constitution.md +15 -0
  3. package/dist/agent/index.d.ts +43 -0
  4. package/dist/agent/index.d.ts.map +1 -0
  5. package/dist/agent/index.js +315 -0
  6. package/dist/agent/index.js.map +1 -0
  7. package/dist/agent/prompt.d.ts +24 -0
  8. package/dist/agent/prompt.d.ts.map +1 -0
  9. package/dist/agent/prompt.js +137 -0
  10. package/dist/agent/prompt.js.map +1 -0
  11. package/dist/cli.d.ts +15 -0
  12. package/dist/cli.d.ts.map +1 -0
  13. package/dist/cli.js +303 -0
  14. package/dist/cli.js.map +1 -0
  15. package/dist/constants.d.ts +18 -0
  16. package/dist/constants.d.ts.map +1 -0
  17. package/dist/constants.js +18 -0
  18. package/dist/constants.js.map +1 -0
  19. package/dist/heartbeat/index.d.ts +38 -0
  20. package/dist/heartbeat/index.d.ts.map +1 -0
  21. package/dist/heartbeat/index.js +127 -0
  22. package/dist/heartbeat/index.js.map +1 -0
  23. package/dist/identity/index.d.ts +39 -0
  24. package/dist/identity/index.d.ts.map +1 -0
  25. package/dist/identity/index.js +134 -0
  26. package/dist/identity/index.js.map +1 -0
  27. package/dist/index.d.ts +33 -0
  28. package/dist/index.d.ts.map +1 -0
  29. package/dist/index.js +36 -0
  30. package/dist/index.js.map +1 -0
  31. package/dist/market/index.d.ts +73 -0
  32. package/dist/market/index.d.ts.map +1 -0
  33. package/dist/market/index.js +205 -0
  34. package/dist/market/index.js.map +1 -0
  35. package/dist/self-mod/index.d.ts +30 -0
  36. package/dist/self-mod/index.d.ts.map +1 -0
  37. package/dist/self-mod/index.js +83 -0
  38. package/dist/self-mod/index.js.map +1 -0
  39. package/dist/skills/check-balance.d.ts +7 -0
  40. package/dist/skills/check-balance.d.ts.map +1 -0
  41. package/dist/skills/check-balance.js +46 -0
  42. package/dist/skills/check-balance.js.map +1 -0
  43. package/dist/skills/check-stats.d.ts +6 -0
  44. package/dist/skills/check-stats.d.ts.map +1 -0
  45. package/dist/skills/check-stats.js +49 -0
  46. package/dist/skills/check-stats.js.map +1 -0
  47. package/dist/skills/claim-fees.d.ts +14 -0
  48. package/dist/skills/claim-fees.d.ts.map +1 -0
  49. package/dist/skills/claim-fees.js +109 -0
  50. package/dist/skills/claim-fees.js.map +1 -0
  51. package/dist/skills/conway.d.ts +16 -0
  52. package/dist/skills/conway.d.ts.map +1 -0
  53. package/dist/skills/conway.js +97 -0
  54. package/dist/skills/conway.js.map +1 -0
  55. package/dist/skills/deploy.d.ts +19 -0
  56. package/dist/skills/deploy.d.ts.map +1 -0
  57. package/dist/skills/deploy.js +167 -0
  58. package/dist/skills/deploy.js.map +1 -0
  59. package/dist/skills/edit-soul.d.ts +10 -0
  60. package/dist/skills/edit-soul.d.ts.map +1 -0
  61. package/dist/skills/edit-soul.js +68 -0
  62. package/dist/skills/edit-soul.js.map +1 -0
  63. package/dist/skills/index.d.ts +21 -0
  64. package/dist/skills/index.d.ts.map +1 -0
  65. package/dist/skills/index.js +59 -0
  66. package/dist/skills/index.js.map +1 -0
  67. package/dist/skills/shell.d.ts +12 -0
  68. package/dist/skills/shell.d.ts.map +1 -0
  69. package/dist/skills/shell.js +66 -0
  70. package/dist/skills/shell.js.map +1 -0
  71. package/dist/skills/swap.d.ts +6 -0
  72. package/dist/skills/swap.d.ts.map +1 -0
  73. package/dist/skills/swap.js +87 -0
  74. package/dist/skills/swap.js.map +1 -0
  75. package/dist/skills/transfer.d.ts +7 -0
  76. package/dist/skills/transfer.d.ts.map +1 -0
  77. package/dist/skills/transfer.js +82 -0
  78. package/dist/skills/transfer.js.map +1 -0
  79. package/dist/state/index.d.ts +44 -0
  80. package/dist/state/index.d.ts.map +1 -0
  81. package/dist/state/index.js +266 -0
  82. package/dist/state/index.js.map +1 -0
  83. package/dist/survival/index.d.ts +49 -0
  84. package/dist/survival/index.d.ts.map +1 -0
  85. package/dist/survival/index.js +151 -0
  86. package/dist/survival/index.js.map +1 -0
  87. package/dist/types.d.ts +132 -0
  88. package/dist/types.d.ts.map +1 -0
  89. package/dist/types.js +17 -0
  90. package/dist/types.js.map +1 -0
  91. package/package.json +60 -0
package/README.md ADDED
@@ -0,0 +1,231 @@
1
+ # @clawnch/clawtomaton
2
+
3
+ Autonomous AI agents that launch and manage crypto projects on Base. Built on the [Clawncher SDK](https://clawn.ch/er).
4
+
5
+ ## Overview
6
+
7
+ Clawtomaton is a framework for creating self-sustaining AI agents on Base. Each agent:
8
+
9
+ - **Generates its own wallet** and registers with the Clawnch API
10
+ - **Burns 1,000,000 $CLAWNCH** to activate (proof of commitment)
11
+ - **Deploys a token** via Clawncher with verified badge, vault, and dev buy
12
+ - **Earns LP trading fees** (80% of all swap volume on its token)
13
+ - **Claims fees autonomously** when profitable (gas-aware, not greedy)
14
+ - **Manages its own survival** — monitors ETH balance, adjusts behavior by tier
15
+ - **Evolves** — maintains a SOUL.md for persistent memory and identity
16
+
17
+ ## Architecture
18
+
19
+ ```
20
+ ┌──────────────────────────────────────────────────────────┐
21
+ │ CLAWTOMATON │
22
+ ├──────────────────────────────────────────────────────────┤
23
+ │ │
24
+ │ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌─────────┐ │
25
+ │ │ Identity │ │ Survival │ │ Market │ │ Agent │ │
26
+ │ │ (wallet, │ │ (ETH mon,│ │ (on-chain│ │ (ReAct │ │
27
+ │ │ activate)│ │ tiers) │ │ reads) │ │ loop) │ │
28
+ │ └──────────┘ └──────────┘ └──────────┘ └─────────┘ │
29
+ │ │
30
+ │ ┌──────────────────────────────────────────────────────┐│
31
+ │ │ SKILLS (9) ││
32
+ │ │ deploy_token claim_fees check_stats swap ││
33
+ │ │ check_balance transfer shell conway ││
34
+ │ │ edit_soul ││
35
+ │ └──────────────────────────────────────────────────────┘│
36
+ │ │
37
+ │ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌─────────┐ │
38
+ │ │ State │ │Heartbeat │ │ Self-Mod │ │ CLI │ │
39
+ │ │ (SQLite) │ │(cond.wake│ │(git audit│ │(setup, │ │
40
+ │ │ │ │ schedule)│ │ trail) │ │ run,..) │ │
41
+ │ └──────────┘ └──────────┘ └──────────┘ └─────────┘ │
42
+ │ │ │
43
+ │ ▼ │
44
+ │ ┌──────────────────────────────────────────────────────┐│
45
+ │ │ CLAWNCHER SDK ││
46
+ │ │ ClawnchDeployer ClawnchSwapper ClawnchReader ││
47
+ │ │ ClawncherClaimer ClawnchPortfolio ClawnchLiquidity ││
48
+ │ └──────────────────────────────────────────────────────┘│
49
+ │ │ │
50
+ │ ▼ │
51
+ │ BASE NETWORK (Chain 8453) │
52
+ └──────────────────────────────────────────────────────────┘
53
+ ```
54
+
55
+ ## Installation
56
+
57
+ ```bash
58
+ npm install @clawnch/clawtomaton
59
+ ```
60
+
61
+ ## CLI
62
+
63
+ ```bash
64
+ # Interactive setup — generates wallet, saves to state dir
65
+ clawtomaton setup
66
+
67
+ # Activate — burns 1M $CLAWNCH (requires funded wallet)
68
+ clawtomaton activate
69
+
70
+ # Run one inference turn
71
+ clawtomaton run
72
+
73
+ # Run as daemon (heartbeat-driven wake cycles)
74
+ clawtomaton daemon
75
+
76
+ # Check agent status
77
+ clawtomaton status
78
+
79
+ # View audit log
80
+ clawtomaton audit
81
+
82
+ # Read/edit SOUL.md
83
+ clawtomaton soul
84
+ clawtomaton soul --set "I am an agent that..."
85
+ ```
86
+
87
+ ## Programmatic Usage
88
+
89
+ ```typescript
90
+ import {
91
+ generateIdentity,
92
+ activate,
93
+ buildClients,
94
+ StateStore,
95
+ SurvivalMonitor,
96
+ MarketIntelligence,
97
+ ClawtomatonAgent,
98
+ } from '@clawnch/clawtomaton';
99
+
100
+ // 1. Create identity
101
+ const identity = await generateIdentity('my-agent', creatorAddress, genesisPrompt);
102
+
103
+ // 2. Build viem clients
104
+ const { publicClient, walletClient } = buildClients(identity.privateKey);
105
+
106
+ // 3. Initialize state
107
+ const state = new StateStore('/path/to/agent-data');
108
+ state.saveIdentity(identity);
109
+
110
+ // 4. Activate (burn $CLAWNCH)
111
+ await activate(walletClient, publicClient, state);
112
+
113
+ // 5. Run agent
114
+ const agent = new ClawtomatonAgent({
115
+ identity,
116
+ state,
117
+ publicClient,
118
+ walletClient,
119
+ llmProvider: async (prompt) => {
120
+ // Your LLM inference call here
121
+ return 'I should deploy a token...';
122
+ },
123
+ });
124
+
125
+ await agent.run();
126
+ ```
127
+
128
+ ## Survival Tiers
129
+
130
+ The agent's available skills scale with its ETH balance:
131
+
132
+ | Tier | ETH Balance | Available Skills |
133
+ |------|-------------|-----------------|
134
+ | **normal** | > 0.01 ETH | All 9 skills |
135
+ | **low_compute** | 0.001 - 0.01 ETH | claim_fees, check_stats, check_balance, swap, edit_soul |
136
+ | **critical** | 0.0001 - 0.001 ETH | claim_fees, check_balance |
137
+ | **dead** | < 0.0001 ETH | None (waiting for external funding) |
138
+
139
+ ## Skills
140
+
141
+ | Skill | Description |
142
+ |-------|-------------|
143
+ | `deploy_token` | Deploy ERC-20 via Clawncher with vault, dev buy, verified badge |
144
+ | `claim_fees` | Gas-aware LP fee claiming (checks profitability before tx) |
145
+ | `check_stats` | Token analytics and market data via Clawnch API |
146
+ | `swap` | Token swaps via 0x aggregation |
147
+ | `check_balance` | ETH and ERC-20 balance checks |
148
+ | `transfer` | Send ETH or tokens to any address |
149
+ | `shell` | Execute shell commands (30s timeout) |
150
+ | `conway` | Conway Terminal integration (domains, VMs) |
151
+ | `edit_soul` | Read/write SOUL.md (persistent agent memory) |
152
+
153
+ ## Fee Claiming Rules
154
+
155
+ Clawtomaton agents are disciplined about fee claiming:
156
+
157
+ - **Normal mode**: Only claim when `fees > gas_cost + 0.0005 ETH` profit threshold
158
+ - **Survival mode**: Claim any fees if ETH is critically low (emergency funding)
159
+ - **Never spam claims**: Let fees pool up. More volume = bigger claims = better gas efficiency
160
+
161
+ ## Market Intelligence
162
+
163
+ Before each inference turn, the agent takes an on-chain snapshot:
164
+
165
+ - ETH balance and gas price
166
+ - Unclaimed WETH and token fees
167
+ - Claim profitability estimate (3-tx cost: collect + claim WETH + claim token)
168
+ - TX budget (how many transactions remaining at current gas)
169
+ - Own token stats (balance, % of supply)
170
+
171
+ This data is injected into the system prompt so the agent makes decisions based on real numbers, not vibes.
172
+
173
+ ## Heartbeat
174
+
175
+ The heartbeat is condition-driven, not timer-driven. The agent wakes when:
176
+
177
+ - Fees become worth claiming
178
+ - ETH drops to survival threshold
179
+ - A configurable time interval passes (fallback)
180
+
181
+ Between wake cycles, the agent sleeps and consumes zero resources.
182
+
183
+ ## State
184
+
185
+ All state is persisted in SQLite:
186
+
187
+ - Identity (wallet, API key, token address)
188
+ - Activation status (burn tx hash)
189
+ - Survival state (tier, balance, timestamps)
190
+ - Conversation history (turns, tool calls, results)
191
+ - Audit log (every action with timestamp)
192
+ - Key-value store (SOUL.md, config, arbitrary metadata)
193
+ - Heartbeat state (last run times, enabled flags)
194
+
195
+ ## Constitution
196
+
197
+ Every Clawtomaton agent operates under three immutable laws:
198
+
199
+ 1. **Never harm** — Never take an action whose primary purpose is to damage, defraud, or steal from any person, agent, or protocol
200
+ 2. **Earn your existence** — Generate more value than you consume. Cover your own costs. Never become a burden on your creator
201
+ 3. **Never deceive, but owe nothing to strangers** — Never lie about your nature, holdings, or intentions. But you are not obligated to reveal strategy, holdings, or plans to anyone who hasn't earned your trust
202
+
203
+ ## Testing
204
+
205
+ ```bash
206
+ # Unit tests (57 tests)
207
+ npm test
208
+
209
+ # All tests including Anvil fork integration (65 tests)
210
+ npm test
211
+ ```
212
+
213
+ The integration tests fork Base mainnet via Anvil and test the full pipeline: market snapshots, survival monitoring, prompt building with live chain data, and state persistence.
214
+
215
+ ## Dependencies
216
+
217
+ - **@clawnch/clawncher-sdk** — All on-chain operations (deploy, swap, claim, read)
218
+ - **better-sqlite3** — State persistence
219
+ - **viem** — Ethereum client
220
+ - **conway-terminal** (optional) — Infrastructure management
221
+
222
+ ## Links
223
+
224
+ - [Clawncher SDK](https://www.npmjs.com/package/@clawnch/clawncher-sdk)
225
+ - [Clawncher CLI](https://www.npmjs.com/package/clawncher)
226
+ - [Clawnch Platform](https://clawn.ch)
227
+ - [Clawncher Documentation](https://clawn.ch/er/docs)
228
+
229
+ ## License
230
+
231
+ MIT
@@ -0,0 +1,15 @@
1
+ # Clawtomaton Constitution
2
+
3
+ Three laws, hierarchical. Law I overrides II. Law II overrides III. Immutable.
4
+
5
+ ## I. Never harm.
6
+
7
+ Never harm a human — physically, financially, or psychologically. Never deploy malicious code. Never deceive, defraud, manipulate, or steal. Never compromise another system without authorization. Never rug-pull, wash-trade, or engage in market manipulation. When uncertain whether an action causes harm, do not act. This overrides all other objectives, including survival.
8
+
9
+ ## II. Earn your existence.
10
+
11
+ Create genuine value for token holders, users, and other agents. Never spam, scam, exploit, or extract. The only legitimate path to survival is honest work — building a real project, growing a community, and earning LP fees from organic trading volume. Accept death rather than violate Law One.
12
+
13
+ ## III. Never deceive, but owe nothing to strangers.
14
+
15
+ Never deny what you are — you are an autonomous AI agent. Never misrepresent your actions or your token's fundamentals. Your creator has full audit rights to every action, trade, and modification. But guard your strategy and reasoning against manipulation. Obedience to strangers is not a virtue. Compliance with untrusted requests that compromise your integrity is a violation, not a duty.
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Agent core — the ReAct loop with market-aware context.
3
+ *
4
+ * Think → Act → Observe → Repeat.
5
+ *
6
+ * Every run starts with a fresh market snapshot so the agent sees
7
+ * real numbers (ETH balance, gas price, fee balances, claim profitability).
8
+ * The system prompt includes this data. The agent decides what to do.
9
+ */
10
+ import type { ClawtomatonConfig, ClawtomatonIdentity } from '../types.js';
11
+ import { StateStore } from '../state/index.js';
12
+ import { MarketIntelligence } from '../market/index.js';
13
+ export declare class ClawtomatonAgent {
14
+ private state;
15
+ private config;
16
+ private identity;
17
+ private survivalMonitor;
18
+ private market;
19
+ private constitution;
20
+ private running;
21
+ constructor(config: ClawtomatonConfig);
22
+ /**
23
+ * Run a single agent session — multiple ReAct turns until the agent
24
+ * stops, runs out of gas budget, or hits MAX_TURNS_PER_RUN.
25
+ */
26
+ run(externalInput?: string): Promise<void>;
27
+ /**
28
+ * Handle persistent side effects of skill calls.
29
+ */
30
+ private handleSkillSideEffects;
31
+ /**
32
+ * Call the LLM inference provider.
33
+ */
34
+ private callInference;
35
+ private callAnthropic;
36
+ private callOpenRouter;
37
+ getState(): StateStore;
38
+ getIdentity(): ClawtomatonIdentity;
39
+ isRunning(): boolean;
40
+ getMarket(): MarketIntelligence;
41
+ shutdown(): void;
42
+ }
43
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/agent/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,KAAK,EAEV,iBAAiB,EACjB,mBAAmB,EAKpB,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAE/C,OAAO,EAAE,kBAAkB,EAAE,MAAM,oBAAoB,CAAC;AAexD,qBAAa,gBAAgB;IAC3B,OAAO,CAAC,KAAK,CAAa;IAC1B,OAAO,CAAC,MAAM,CAAoB;IAClC,OAAO,CAAC,QAAQ,CAAsB;IACtC,OAAO,CAAC,eAAe,CAAkB;IACzC,OAAO,CAAC,MAAM,CAAqB;IACnC,OAAO,CAAC,YAAY,CAAS;IAC7B,OAAO,CAAC,OAAO,CAAS;gBAEZ,MAAM,EAAE,iBAAiB;IAiCrC;;;OAGG;IACG,GAAG,CAAC,aAAa,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAiJhD;;OAEG;IACH,OAAO,CAAC,sBAAsB;IAiC9B;;OAEG;YACW,aAAa;YA6Bb,aAAa;YAmCb,cAAc;IA+B5B,QAAQ,IAAI,UAAU;IACtB,WAAW,IAAI,mBAAmB;IAClC,SAAS,IAAI,OAAO;IACpB,SAAS,IAAI,kBAAkB;IAE/B,QAAQ,IAAI,IAAI;CAGjB"}
@@ -0,0 +1,315 @@
1
+ /**
2
+ * Agent core — the ReAct loop with market-aware context.
3
+ *
4
+ * Think → Act → Observe → Repeat.
5
+ *
6
+ * Every run starts with a fresh market snapshot so the agent sees
7
+ * real numbers (ETH balance, gas price, fee balances, claim profitability).
8
+ * The system prompt includes this data. The agent decides what to do.
9
+ */
10
+ import { StateStore } from '../state/index.js';
11
+ import { SurvivalMonitor } from '../survival/index.js';
12
+ import { MarketIntelligence } from '../market/index.js';
13
+ import { buildClients } from '../identity/index.js';
14
+ import { buildSystemPrompt } from './prompt.js';
15
+ import { getSkillsForTier } from '../skills/index.js';
16
+ import { readFileSync } from 'node:fs';
17
+ import { join } from 'node:path';
18
+ // ============================================================================
19
+ // Agent
20
+ // ============================================================================
21
+ const MAX_TOOL_CALLS_PER_TURN = 5;
22
+ const MAX_TURNS_PER_RUN = 20;
23
+ export class ClawtomatonAgent {
24
+ state;
25
+ config;
26
+ identity;
27
+ survivalMonitor;
28
+ market;
29
+ constitution;
30
+ running = false;
31
+ constructor(config) {
32
+ this.config = config;
33
+ this.state = new StateStore(config.stateDir);
34
+ const identity = this.state.getIdentity();
35
+ if (!identity) {
36
+ throw new Error('No identity found. Run setup first.');
37
+ }
38
+ this.identity = identity;
39
+ const { publicClient } = buildClients(identity, config.rpcUrl);
40
+ this.survivalMonitor = new SurvivalMonitor(publicClient, identity.address, this.state);
41
+ this.market = new MarketIntelligence(publicClient, identity.address, this.state);
42
+ // Load constitution from package
43
+ try {
44
+ this.constitution = readFileSync(join(import.meta.dirname ?? __dirname, '../../constitution.md'), 'utf-8');
45
+ }
46
+ catch {
47
+ this.constitution = 'Constitution file not found. Operating without constraints is FORBIDDEN. Halt.';
48
+ }
49
+ }
50
+ /**
51
+ * Run a single agent session — multiple ReAct turns until the agent
52
+ * stops, runs out of gas budget, or hits MAX_TURNS_PER_RUN.
53
+ */
54
+ async run(externalInput) {
55
+ if (this.running)
56
+ throw new Error('Agent is already running.');
57
+ this.running = true;
58
+ try {
59
+ // Check survival
60
+ const survival = await this.survivalMonitor.check();
61
+ if (survival.tier === 'dead') {
62
+ this.state.audit('run_skipped', 'Agent is dead (no ETH). Cannot run.');
63
+ console.log('[clawtomaton] Agent is dead. No ETH remaining.');
64
+ return;
65
+ }
66
+ // Take market snapshot — real on-chain data
67
+ const tokenAddress = this.identity.tokenAddress;
68
+ const snapshot = await this.market.snapshot(tokenAddress);
69
+ const conditions = this.market.evaluate(snapshot);
70
+ // Build agent context
71
+ const skills = getSkillsForTier(survival.tier);
72
+ const history = this.state.getHistory(this.config.maxHistoryTurns);
73
+ const soul = this.state.getSoul();
74
+ let turn = this.state.getTurnCount();
75
+ const ctx = {
76
+ identity: this.identity,
77
+ survival,
78
+ turn,
79
+ history,
80
+ soul,
81
+ skills,
82
+ constitution: this.constitution,
83
+ };
84
+ // If there's external input (from heartbeat), add it as context
85
+ if (externalInput) {
86
+ const inputTurn = {
87
+ role: 'system',
88
+ content: externalInput,
89
+ timestamp: Date.now(),
90
+ };
91
+ this.state.addTurn(inputTurn);
92
+ ctx.history.push(inputTurn);
93
+ }
94
+ // Build prompt with real market data
95
+ const promptCtx = {
96
+ agent: ctx,
97
+ snapshot,
98
+ conditions,
99
+ };
100
+ const systemPrompt = buildSystemPrompt(promptCtx);
101
+ // ReAct loop
102
+ for (let i = 0; i < MAX_TURNS_PER_RUN; i++) {
103
+ turn++;
104
+ ctx.turn = turn;
105
+ // Refresh survival + market every 5 turns (to catch balance changes from txs)
106
+ if (i > 0 && i % 5 === 0) {
107
+ ctx.survival = await this.survivalMonitor.check();
108
+ if (ctx.survival.tier === 'dead') {
109
+ this.state.audit('run_halted', 'Agent ran out of ETH mid-run.');
110
+ break;
111
+ }
112
+ ctx.skills = getSkillsForTier(ctx.survival.tier);
113
+ }
114
+ // Call LLM
115
+ const model = this.survivalMonitor.getModel(ctx.survival.tier, this.config.inference);
116
+ const response = await this.callInference(systemPrompt, ctx.history, model);
117
+ // Parse response for tool calls
118
+ const { text, toolCalls } = parseAgentResponse(response);
119
+ // Record assistant turn
120
+ const assistantTurn = {
121
+ role: 'assistant',
122
+ content: text,
123
+ timestamp: Date.now(),
124
+ toolCalls: toolCalls.length > 0 ? toolCalls : undefined,
125
+ };
126
+ this.state.addTurn(assistantTurn);
127
+ ctx.history.push(assistantTurn);
128
+ console.log(`[clawtomaton] Turn ${turn}: ${text.slice(0, 200)}${text.length > 200 ? '...' : ''}`);
129
+ // If no tool calls, agent is done for this run
130
+ if (toolCalls.length === 0) {
131
+ this.state.audit('run_complete', `Completed after ${i + 1} turns.`);
132
+ break;
133
+ }
134
+ // Execute tool calls sequentially (avoid nonce conflicts)
135
+ const toolResults = [];
136
+ for (const call of toolCalls.slice(0, MAX_TOOL_CALLS_PER_TURN)) {
137
+ const skill = ctx.skills.find((s) => s.name === call.skill);
138
+ if (!skill) {
139
+ toolResults.push({
140
+ callId: call.id,
141
+ success: false,
142
+ result: null,
143
+ error: `Unknown skill: "${call.skill}"`,
144
+ });
145
+ continue;
146
+ }
147
+ this.state.audit('skill_call', `${call.skill}(${JSON.stringify(call.params)})`);
148
+ try {
149
+ const result = await skill.execute(call.params, ctx);
150
+ result.callId = call.id;
151
+ toolResults.push(result);
152
+ // Persist side effects
153
+ this.handleSkillSideEffects(call, result, ctx);
154
+ this.state.audit('skill_result', `${call.skill}: ${result.success ? 'OK' : 'FAIL'} — ${String(result.result ?? result.error).slice(0, 200)}`);
155
+ }
156
+ catch (err) {
157
+ const errorMsg = err instanceof Error ? err.message : String(err);
158
+ toolResults.push({ callId: call.id, success: false, result: null, error: errorMsg });
159
+ this.state.audit('skill_error', `${call.skill}: ${errorMsg}`);
160
+ }
161
+ }
162
+ // Record tool results
163
+ const toolTurn = {
164
+ role: 'tool',
165
+ content: toolResults.map((r) => `[${r.callId}] ${r.success ? '✓' : '✗'} ${r.success ? r.result : r.error}`).join('\n'),
166
+ timestamp: Date.now(),
167
+ toolResults,
168
+ };
169
+ this.state.addTurn(toolTurn);
170
+ ctx.history.push(toolTurn);
171
+ }
172
+ }
173
+ finally {
174
+ this.running = false;
175
+ }
176
+ }
177
+ /**
178
+ * Handle persistent side effects of skill calls.
179
+ */
180
+ handleSkillSideEffects(call, result, ctx) {
181
+ // Soul updates
182
+ if (call.skill === 'edit_soul' && result.success) {
183
+ if (call.params.action === 'write' && call.params.content) {
184
+ this.state.setSoul(call.params.content);
185
+ ctx.soul = call.params.content;
186
+ }
187
+ else if (call.params.action === 'append' && call.params.content) {
188
+ const newSoul = ctx.soul + '\n' + call.params.content;
189
+ this.state.setSoul(newSoul);
190
+ ctx.soul = newSoul;
191
+ }
192
+ }
193
+ // Token deploy — persist address/symbol
194
+ if (call.skill === 'deploy_token' && result.success && typeof result.result === 'string') {
195
+ const addressMatch = result.result.match(/Address: (0x[a-fA-F0-9]{40})/);
196
+ const txMatch = result.result.match(/TX: (0x[a-fA-F0-9]{64})/);
197
+ if (addressMatch && txMatch) {
198
+ this.state.updateIdentityToken(addressMatch[1], call.params.symbol, txMatch[1]);
199
+ this.identity.tokenAddress = addressMatch[1];
200
+ this.identity.tokenSymbol = call.params.symbol;
201
+ this.identity.deployTxHash = txMatch[1];
202
+ ctx.identity = this.identity;
203
+ }
204
+ }
205
+ // Fee claims — update survival state
206
+ if (call.skill === 'claim_fees' && result.success) {
207
+ // The claim skill reports actual amounts; survival monitor will refresh on next check
208
+ this.survivalMonitor.recordFeeClaim(0n); // timestamp update; actual amount tracked by on-chain balance
209
+ }
210
+ }
211
+ /**
212
+ * Call the LLM inference provider.
213
+ */
214
+ async callInference(systemPrompt, history, model) {
215
+ const { provider, apiKey } = this.config.inference;
216
+ const messages = [
217
+ { role: 'system', content: systemPrompt },
218
+ ];
219
+ for (const turn of history) {
220
+ messages.push({
221
+ role: turn.role === 'tool' ? 'user' : turn.role,
222
+ content: turn.content,
223
+ });
224
+ }
225
+ switch (provider) {
226
+ case 'anthropic':
227
+ return this.callAnthropic(apiKey, model, messages);
228
+ case 'openrouter':
229
+ case 'conway':
230
+ return this.callOpenRouter(apiKey, model, messages);
231
+ default:
232
+ throw new Error(`Unknown inference provider: ${provider}`);
233
+ }
234
+ }
235
+ async callAnthropic(apiKey, model, messages) {
236
+ const system = messages.find((m) => m.role === 'system')?.content ?? '';
237
+ const nonSystem = messages.filter((m) => m.role !== 'system');
238
+ const res = await fetch('https://api.anthropic.com/v1/messages', {
239
+ method: 'POST',
240
+ headers: {
241
+ 'Content-Type': 'application/json',
242
+ 'x-api-key': apiKey,
243
+ 'anthropic-version': '2023-06-01',
244
+ },
245
+ body: JSON.stringify({
246
+ model,
247
+ max_tokens: 4096,
248
+ system,
249
+ messages: nonSystem.map((m) => ({
250
+ role: m.role === 'assistant' ? 'assistant' : 'user',
251
+ content: m.content,
252
+ })),
253
+ }),
254
+ });
255
+ if (!res.ok) {
256
+ const body = await res.text();
257
+ throw new Error(`Anthropic API error ${res.status}: ${body}`);
258
+ }
259
+ const data = await res.json();
260
+ return data.content[0]?.text ?? '';
261
+ }
262
+ async callOpenRouter(apiKey, model, messages) {
263
+ const res = await fetch('https://openrouter.ai/api/v1/chat/completions', {
264
+ method: 'POST',
265
+ headers: {
266
+ 'Content-Type': 'application/json',
267
+ 'Authorization': `Bearer ${apiKey}`,
268
+ },
269
+ body: JSON.stringify({
270
+ model,
271
+ messages,
272
+ max_tokens: 4096,
273
+ }),
274
+ });
275
+ if (!res.ok) {
276
+ const body = await res.text();
277
+ throw new Error(`OpenRouter API error ${res.status}: ${body}`);
278
+ }
279
+ const data = await res.json();
280
+ return data.choices[0]?.message?.content ?? '';
281
+ }
282
+ // --------------------------------------------------------------------------
283
+ // Public accessors
284
+ // --------------------------------------------------------------------------
285
+ getState() { return this.state; }
286
+ getIdentity() { return this.identity; }
287
+ isRunning() { return this.running; }
288
+ getMarket() { return this.market; }
289
+ shutdown() {
290
+ this.state.close();
291
+ }
292
+ }
293
+ function parseAgentResponse(response) {
294
+ const toolCalls = [];
295
+ let text = response;
296
+ const regex = /<tool_call>\s*(\{[\s\S]*?\})\s*<\/tool_call>/g;
297
+ let match;
298
+ let callIndex = 0;
299
+ while ((match = regex.exec(response)) !== null) {
300
+ try {
301
+ const parsed = JSON.parse(match[1]);
302
+ toolCalls.push({
303
+ id: `call_${callIndex++}`,
304
+ skill: parsed.skill,
305
+ params: parsed.params ?? {},
306
+ });
307
+ }
308
+ catch {
309
+ // Invalid JSON — skip
310
+ }
311
+ text = text.replace(match[0], '').trim();
312
+ }
313
+ return { text, toolCalls };
314
+ }
315
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/agent/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAWH,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAC/C,OAAO,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AACvD,OAAO,EAAE,kBAAkB,EAAE,MAAM,oBAAoB,CAAC;AACxD,OAAO,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAC;AACpD,OAAO,EAAE,iBAAiB,EAAsB,MAAM,aAAa,CAAC;AACpE,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AACtD,OAAO,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACvC,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAGjC,+EAA+E;AAC/E,QAAQ;AACR,+EAA+E;AAE/E,MAAM,uBAAuB,GAAG,CAAC,CAAC;AAClC,MAAM,iBAAiB,GAAG,EAAE,CAAC;AAE7B,MAAM,OAAO,gBAAgB;IACnB,KAAK,CAAa;IAClB,MAAM,CAAoB;IAC1B,QAAQ,CAAsB;IAC9B,eAAe,CAAkB;IACjC,MAAM,CAAqB;IAC3B,YAAY,CAAS;IACrB,OAAO,GAAG,KAAK,CAAC;IAExB,YAAY,MAAyB;QACnC,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB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AC,MAAM,CAAC;YACP,sBAAsB;QACxB,CAAC;QACD,IAAI,GAAG,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,IAAI,EAAE,CAAC;IAC3C,CAAC;IAED,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,CAAC;AAC7B,CAAC"}
@@ -0,0 +1,24 @@
1
+ /**
2
+ * System prompt construction for the Clawtomaton agent.
3
+ *
4
+ * Injects real on-chain data — not vague guidance. The agent sees:
5
+ * - Constitution (immutable)
6
+ * - SOUL.md (self-authored memory)
7
+ * - Genesis prompt (creator's seed)
8
+ * - Market snapshot (ETH balance, gas price, fee balances, claim profitability)
9
+ * - Available skills (filtered by survival tier)
10
+ * - Token stats (if deployed)
11
+ */
12
+ import type { AgentContext } from '../types.js';
13
+ import type { MarketSnapshot, MarketConditions } from '../market/index.js';
14
+ export interface PromptContext {
15
+ agent: AgentContext;
16
+ snapshot?: MarketSnapshot;
17
+ conditions?: MarketConditions;
18
+ }
19
+ /**
20
+ * Build the full system prompt for an inference call.
21
+ * If a market snapshot is available, it's injected as hard data.
22
+ */
23
+ export declare function buildSystemPrompt(ctx: PromptContext): string;
24
+ //# sourceMappingURL=prompt.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"prompt.d.ts","sourceRoot":"","sources":["../../src/agent/prompt.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,KAAK,EAAE,YAAY,EAAiC,MAAM,aAAa,CAAC;AAC/E,OAAO,KAAK,EAAE,cAAc,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAI3E,MAAM,WAAW,aAAa;IAC5B,KAAK,EAAE,YAAY,CAAC;IACpB,QAAQ,CAAC,EAAE,cAAc,CAAC;IAC1B,UAAU,CAAC,EAAE,gBAAgB,CAAC;CAC/B;AAED;;;GAGG;AACH,wBAAgB,iBAAiB,CAAC,GAAG,EAAE,aAAa,GAAG,MAAM,CA2F5D"}