@balchemyai/agent-sdk 0.8.1 → 0.9.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 (74) hide show
  1. package/CHANGELOG.md +16 -1
  2. package/README.md +20 -284
  3. package/dist/agent-loop/llm-adapters/openai.js +1 -1
  4. package/dist/agent-loop/llm-adapters/openai.js.map +1 -1
  5. package/dist/agent-loop/types.d.ts +1 -138
  6. package/dist/agent-loop/types.d.ts.map +1 -1
  7. package/dist/index.d.ts +1 -33
  8. package/dist/index.d.ts.map +1 -1
  9. package/dist/index.js +5 -72
  10. package/dist/index.js.map +1 -1
  11. package/docs/error-retry-strategy.md +4 -4
  12. package/docs/release-policy.md +1 -1
  13. package/package.json +2 -6
  14. package/dist/agent-loop/agent-loop.d.ts +0 -77
  15. package/dist/agent-loop/agent-loop.d.ts.map +0 -1
  16. package/dist/agent-loop/agent-loop.js +0 -1270
  17. package/dist/agent-loop/agent-loop.js.map +0 -1
  18. package/dist/agent-loop/decision-handler.d.ts +0 -38
  19. package/dist/agent-loop/decision-handler.d.ts.map +0 -1
  20. package/dist/agent-loop/decision-handler.js +0 -231
  21. package/dist/agent-loop/decision-handler.js.map +0 -1
  22. package/dist/agent-loop/llm-cost-tracker.d.ts +0 -27
  23. package/dist/agent-loop/llm-cost-tracker.d.ts.map +0 -1
  24. package/dist/agent-loop/llm-cost-tracker.js +0 -102
  25. package/dist/agent-loop/llm-cost-tracker.js.map +0 -1
  26. package/dist/agent-loop/model-router.d.ts +0 -35
  27. package/dist/agent-loop/model-router.d.ts.map +0 -1
  28. package/dist/agent-loop/model-router.js +0 -55
  29. package/dist/agent-loop/model-router.js.map +0 -1
  30. package/dist/agent-loop/rule-checker.d.ts +0 -26
  31. package/dist/agent-loop/rule-checker.d.ts.map +0 -1
  32. package/dist/agent-loop/rule-checker.js +0 -70
  33. package/dist/agent-loop/rule-checker.js.map +0 -1
  34. package/dist/agent-loop/telemetry-reporter.d.ts +0 -70
  35. package/dist/agent-loop/telemetry-reporter.d.ts.map +0 -1
  36. package/dist/agent-loop/telemetry-reporter.js +0 -221
  37. package/dist/agent-loop/telemetry-reporter.js.map +0 -1
  38. package/dist/agent-loop/webhook-receiver.d.ts +0 -41
  39. package/dist/agent-loop/webhook-receiver.d.ts.map +0 -1
  40. package/dist/agent-loop/webhook-receiver.js +0 -308
  41. package/dist/agent-loop/webhook-receiver.js.map +0 -1
  42. package/dist/auth/onboarding.d.ts +0 -12
  43. package/dist/auth/onboarding.d.ts.map +0 -1
  44. package/dist/auth/onboarding.js +0 -70
  45. package/dist/auth/onboarding.js.map +0 -1
  46. package/dist/auth/token-store.d.ts +0 -44
  47. package/dist/auth/token-store.d.ts.map +0 -1
  48. package/dist/auth/token-store.js +0 -67
  49. package/dist/auth/token-store.js.map +0 -1
  50. package/dist/mcp/mcp-client.d.ts +0 -174
  51. package/dist/mcp/mcp-client.d.ts.map +0 -1
  52. package/dist/mcp/mcp-client.js +0 -845
  53. package/dist/mcp/mcp-client.js.map +0 -1
  54. package/dist/streaming/sse-event-stream.d.ts +0 -72
  55. package/dist/streaming/sse-event-stream.d.ts.map +0 -1
  56. package/dist/streaming/sse-event-stream.js +0 -403
  57. package/dist/streaming/sse-event-stream.js.map +0 -1
  58. package/dist/types.d.ts +0 -162
  59. package/dist/types.d.ts.map +0 -1
  60. package/dist/types.js +0 -3
  61. package/dist/types.js.map +0 -1
  62. package/dist/utils/package-version.d.ts +0 -2
  63. package/dist/utils/package-version.d.ts.map +0 -1
  64. package/dist/utils/package-version.js +0 -54
  65. package/dist/utils/package-version.js.map +0 -1
  66. package/docs/BEHAVIOR_RULES.md +0 -184
  67. package/docs/DEPLOYMENT.md +0 -197
  68. package/docs/QUICKSTART.md +0 -139
  69. package/docs/examples/custom-strategy.yaml +0 -73
  70. package/docs/examples/dca-accumulator.yaml +0 -41
  71. package/docs/examples/memecoin-sniper.yaml +0 -47
  72. package/docs/examples/swing-trader.yaml +0 -50
  73. package/docs/partner-integration-checklist.md +0 -47
  74. package/docs/python-parity-backlog.md +0 -20
@@ -1,139 +0,0 @@
1
- # Balchemy Agent — Quickstart
2
-
3
- Connect a local CLI/SDK runner to a Balchemy Hub agent in under 5 minutes.
4
-
5
- ---
6
-
7
- ## Prerequisites
8
-
9
- - Node.js 18+ (or Docker)
10
- - A Balchemy account with at least one Hub agent, or an explicit walletless
11
- onboarding flow
12
- - A scoped MCP/API key from Hub > Agents > your agent > Access/API Keys
13
- - An LLM API key (Anthropic or OpenAI)
14
-
15
- ---
16
-
17
- ## Step 1: Create or select a Hub agent
18
-
19
- 1. Go to [balchemy.ai](https://balchemy.ai) and sign in
20
- 2. Open Hub > Agents > New Agent
21
- 3. Complete the setup wizard enough to create the agent and runtime state
22
- 4. Open the agent Access/API key flow
23
- 5. Copy the MCP endpoint: `https://api.balchemy.ai/mcp/YOUR_PUBLIC_ID`
24
- 6. Generate a scoped API key and copy it (shown once)
25
-
26
- ---
27
-
28
- ## Step 2: Run the setup wizard
29
-
30
- ```bash
31
- npx balchemy
32
- ```
33
-
34
- The wizard asks:
35
- - LLM provider, API key, and model
36
- - New walletless agent or existing MCP endpoint/API key
37
- - Strategy preset and natural-language behavior rules
38
- - Whether to open the local cockpit
39
-
40
- New walletless agents are provisioned first. Root/recovery wallet binding and
41
- chain-specific setup happen later through the authenticated MCP setup flow.
42
- Existing agents can be resumed from the encrypted local agent store.
43
-
44
- ---
45
-
46
- ## Step 3: Start the local runner
47
-
48
- ```bash
49
- npx balchemy start
50
- ```
51
-
52
- The agent:
53
- 1. Connects to the Balchemy SSE event stream
54
- 2. Receives market signals and platform events
55
- 3. Fetches fresh `agent_status` and behavior rules before asking your LLM to
56
- decide whether to buy, sell, hold, block, or mark data degraded
57
- 4. Blocks trade calls in `shadow`, `live_unarmed`, `paused`, stale status, or
58
- missing-rule states
59
- 5. Calls `trade_command` only when local live mode and backend runtime are both
60
- live-armed and the policy/approval path allows it
61
- 6. Can be monitored and adjusted through the Balchemy CLI cockpit (`npx balchemy`)
62
-
63
- `shadow_mode` remains the safe default. Setting local `shadow_mode: false` is
64
- not enough to trade; the backend must report `autonomous_runtime.mode` as
65
- `live_armed`, `armed=true`, and `paused=false`.
66
-
67
- This quickstart does not claim live-trade proof, Base live coverage, or
68
- source-owner payout rails. Verify those from current runtime/backend evidence
69
- before relying on them.
70
-
71
- ---
72
-
73
- ## Step 4: Docker (production)
74
-
75
- ```bash
76
- npx balchemy docker
77
- docker compose up -d
78
- docker compose logs -f
79
- ```
80
-
81
- The generated `docker-compose.yml` runs the agent with:
82
- - `restart: always` — survives crashes and reboots
83
- - Mounted `agent.config.yaml` — edit config without rebuilding
84
- - JSON log rotation (10 MB × 5 files)
85
-
86
- ---
87
-
88
- ## Programmatic usage (TypeScript)
89
-
90
- ```typescript
91
- import { AgentLoop } from '@balchemyai/agent-sdk';
92
-
93
- const statusEvents: string[] = [];
94
- const decisionEvents: unknown[] = [];
95
- const errorEvents: string[] = [];
96
-
97
- const loop2 = new AgentLoop({
98
- mcpEndpoint: 'https://api.balchemy.ai/mcp/YOUR_PUBLIC_ID',
99
- apiKey: process.env.BALCHEMY_API_KEY!,
100
- llmProvider: 'anthropic',
101
- llmApiKey: process.env.ANTHROPIC_API_KEY!,
102
- llmModel: 'claude-haiku-4-5',
103
- maxDailyLlmCost: 5,
104
- onStatusChange: (s) => statusEvents.push(s.status),
105
- onDecision: (d) => decisionEvents.push(d),
106
- onError: (e) => errorEvents.push(e.message),
107
- });
108
- await loop2.start();
109
- ```
110
-
111
- The SDK constructs `AgentLoop` from explicit config. Use `npx balchemy start`
112
- when you want the CLI to load `agent.config.yaml` for you.
113
-
114
- For read-first integrations, use `connectMcp()`/`listTools()` and call only the
115
- runtime-advertised tools. Safe read wrappers include `agent_status`,
116
- `agent_context_snapshot`, `agent_market_brief`, `agent_candidate_report`, and
117
- `agent_risk_report`. Raw provider, approval, withdrawal, swap-bypass, and
118
- privileged manage surfaces are not public SDK helpers.
119
-
120
- ---
121
-
122
- ## Strategy presets
123
-
124
- | Preset | Description | Recommended model |
125
- |--------|-------------|-------------------|
126
- | `dca-accumulator` | Buy fixed-USD at regular intervals | gpt-4o-mini |
127
- | `memecoin-sniper` | Buy on launch signals, sell on pump | claude-haiku-4-5 |
128
- | `swing-trader` | Hold positions 2–72h, exit on RSI/MACD | claude-haiku-4-5 |
129
- | `custom` | Define your own rules in `behavior_rules` | any |
130
-
131
- See [BEHAVIOR_RULES.md](./BEHAVIOR_RULES.md) for the full rule schema.
132
-
133
- ---
134
-
135
- ## Next steps
136
-
137
- - [BEHAVIOR_RULES.md](./BEHAVIOR_RULES.md) — customize your agent's trading logic
138
- - [DEPLOYMENT.md](./DEPLOYMENT.md) — deploy to a VPS, Railway, or Render
139
- - [examples/](./examples/) — ready-to-use strategy YAML files
@@ -1,73 +0,0 @@
1
- # Custom Strategy — Annotated Example
2
- #
3
- # This file shows every supported behavior_rules field.
4
- # Use it as a reference when building your own strategy.
5
- # Delete or comment out fields you do not need.
6
-
7
- mcp_endpoint: "${MCP_ENDPOINT}"
8
- api_key: "${BALCHEMY_API_KEY}"
9
-
10
- llm:
11
- provider: anthropic # anthropic | openai
12
- api_key: "${LLM_API_KEY}"
13
- model: claude-haiku-4-5 # Use haiku/gpt-4o-mini for cost, sonnet/gpt-5 for quality
14
- max_daily_usd: 5 # Hard LLM budget cap in USD per day
15
- timeout_ms: 10000 # LLM call timeout in milliseconds
16
-
17
- # Optional: separate cheap/full models for model routing
18
- # cheapModel: claude-haiku-4-5 # Used for low-significance events (score < 60)
19
- # fullModel: claude-sonnet-4 # Used for high-significance events (score >= 60)
20
-
21
- strategy: custom
22
-
23
- # Optional webhook receiver — receives Balchemy push events directly
24
- # webhook:
25
- # port: 4242
26
- # secret: "${WEBHOOK_SECRET}"
27
-
28
- behavior_rules:
29
- version: "1"
30
- preset: custom # custom | memecoin-sniper | dca-accumulator | swing-trader
31
-
32
- # ─── Risk limits (applied globally, cannot be overridden per trade) ──────────
33
- risk:
34
- max_single_trade_usd: 50 # Hard cap per trade
35
- max_daily_loss_usd: 200 # Pause after this daily loss
36
- max_open_positions: 5 # Max simultaneous open positions
37
- pause_on_drawdown_pct: 20 # Pause if portfolio drops 20% from peak
38
- allowed_chains: [solana] # solana | base | ethereum | arbitrum
39
-
40
- # ─── Asset filters (applied before LLM call — zero LLM cost) ────────────────
41
- filters:
42
- min_liquidity_usd: 20000
43
- max_market_cap_usd: 50000000
44
- require_verified_contract: false
45
- blocked_tokens: # Addresses to never trade
46
- - "So11111111111111111111111111111111111111112"
47
- # allowed_tokens: # If set, only these tokens will be traded
48
- # - "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"
49
-
50
- # ─── Entry conditions ────────────────────────────────────────────────────────
51
- entry:
52
- # Trigger type: launch_signal | price_drop | rsi_signal | manual
53
- trigger: price_drop
54
- indicators: [rsi]
55
- rsi_oversold: 35
56
- max_position_usd: 100
57
- slippage_bps: 150
58
- min_confidence: 0.7 # LLM confidence threshold (0.0–1.0)
59
-
60
- # ─── Exit conditions ─────────────────────────────────────────────────────────
61
- exit:
62
- take_profit_pct: 30
63
- stop_loss_pct: 15
64
- trailing_stop_pct: 10 # Activate once in profit; trail 10% below peak
65
- min_hold_hours: 0 # Allow immediate exit if conditions are met
66
- max_hold_hours: 48 # Force exit after 48 hours
67
-
68
- # ─── DCA config (only for dca-accumulator preset) ───────────────────────────
69
- # dca:
70
- # target_token: SOL
71
- # amount_usd: 10
72
- # interval_hours: 24
73
- # max_total_usd: 500
@@ -1,41 +0,0 @@
1
- # DCA Accumulator Strategy
2
- #
3
- # Dollar-cost averages into SOL on a fixed schedule.
4
- # Buys $10 of SOL every 24 hours regardless of price.
5
- # Pauses DCA if portfolio drops more than 30% from peak.
6
- #
7
- # Risk profile: LOW — patient accumulation, no active trading decisions.
8
- # Recommended LLM: gpt-4o-mini (sufficient for simple buy confirmations)
9
-
10
- mcp_endpoint: "${MCP_ENDPOINT}"
11
- api_key: "${BALCHEMY_API_KEY}"
12
-
13
- llm:
14
- provider: openai
15
- api_key: "${LLM_API_KEY}"
16
- model: gpt-4o-mini
17
- max_daily_usd: 1 # DCA fires once per day — very low LLM cost
18
- timeout_ms: 15000
19
-
20
- strategy: dca-accumulator
21
-
22
- behavior_rules:
23
- version: "1"
24
- preset: dca-accumulator
25
-
26
- dca:
27
- target_token: SOL
28
- amount_usd: 10 # Buy $10 per interval
29
- interval_hours: 24 # Daily purchases
30
- max_total_usd: 1000 # Stop after $1000 total invested
31
-
32
- risk:
33
- max_single_trade_usd: 10 # Each DCA buy is capped at $10
34
- pause_on_drawdown_pct: 30 # Pause if portfolio value drops 30% from peak
35
- max_open_positions: 1 # Only hold SOL — single-asset strategy
36
- allowed_chains: [solana]
37
-
38
- filters:
39
- allowed_tokens:
40
- # Wrapped SOL (wSOL) — the only token this strategy trades
41
- - "So11111111111111111111111111111111111111112"
@@ -1,47 +0,0 @@
1
- # Memecoin Sniper Strategy
2
- #
3
- # Buys newly launched memecoins on Solana within the first few minutes
4
- # of listing. Takes profit at 100% gain, cuts losses at 50% drop.
5
- # Positions are never held longer than 60 minutes.
6
- #
7
- # Risk profile: HIGH — many trades will lose, winners cover losers.
8
- # Recommended LLM: claude-haiku-4-5 (fast, cheap, sufficient for signal routing)
9
-
10
- mcp_endpoint: "${MCP_ENDPOINT}"
11
- api_key: "${BALCHEMY_API_KEY}"
12
-
13
- llm:
14
- provider: anthropic
15
- api_key: "${LLM_API_KEY}"
16
- model: claude-haiku-4-5
17
- max_daily_usd: 3 # Memecoin sniper fires frequently — keep budget low
18
- timeout_ms: 5000 # Tight timeout — stale signals are worthless
19
-
20
- strategy: memecoin-sniper
21
-
22
- behavior_rules:
23
- version: "1"
24
- preset: memecoin-sniper
25
-
26
- filters:
27
- min_liquidity_usd: 10000 # Avoid rugpulls with thin liquidity
28
- max_market_cap_usd: 5000000 # Only micro-caps — higher upside
29
- require_verified_contract: false # Most new launches are unverified
30
- allowed_chains: [solana]
31
-
32
- entry:
33
- trigger: launch_signal # React to new token launch events
34
- max_position_usd: 25 # Small positions — many trades
35
- slippage_bps: 400 # High slippage accepted for fast entry
36
- min_confidence: 0.55 # Lower threshold — sniper takes more swings
37
-
38
- exit:
39
- take_profit_pct: 100 # Double or nothing
40
- stop_loss_pct: 50 # Cut at -50%
41
- max_hold_minutes: 60 # Force exit after 1 hour no matter what
42
- trailing_stop_pct: 20 # Lock in gains if price reverses 20% from peak
43
-
44
- risk:
45
- max_single_trade_usd: 25
46
- max_daily_loss_usd: 100 # Hard daily stop
47
- max_open_positions: 3 # Never hold more than 3 memecoins at once
@@ -1,50 +0,0 @@
1
- # Swing Trader Strategy
2
- #
3
- # Holds positions for 2–72 hours. Enters on RSI oversold + MACD crossover.
4
- # Targets 20% gain, stops at 10% loss. Uses a trailing stop to lock in profits.
5
- #
6
- # Risk profile: MEDIUM — requires technical indicator signals, holds through
7
- # short-term volatility.
8
- # Recommended LLM: claude-haiku-4-5 or gpt-4o-mini
9
-
10
- mcp_endpoint: "${MCP_ENDPOINT}"
11
- api_key: "${BALCHEMY_API_KEY}"
12
-
13
- llm:
14
- provider: anthropic
15
- api_key: "${LLM_API_KEY}"
16
- model: claude-haiku-4-5
17
- max_daily_usd: 2 # Swing trader fires infrequently
18
- timeout_ms: 10000
19
-
20
- strategy: swing-trader
21
-
22
- behavior_rules:
23
- version: "1"
24
- preset: swing-trader
25
-
26
- filters:
27
- min_liquidity_usd: 50000 # Only liquid assets for swing trades
28
- max_market_cap_usd: 500000000 # Mid-cap and below
29
- allowed_chains: [solana, base]
30
-
31
- entry:
32
- trigger: rsi_signal
33
- indicators: [rsi, macd]
34
- rsi_oversold: 30 # Enter when RSI < 30 (oversold)
35
- max_position_usd: 200 # Larger positions — fewer, higher-conviction trades
36
- slippage_bps: 100 # Tight slippage — not chasing
37
- min_confidence: 0.75 # High confidence required
38
-
39
- exit:
40
- take_profit_pct: 20 # Exit at +20%
41
- stop_loss_pct: 10 # Exit at -10%
42
- trailing_stop_pct: 8 # Trail 8% below peak once in profit
43
- min_hold_hours: 2 # Never exit in first 2 hours (noise avoidance)
44
- max_hold_hours: 72 # Force exit after 3 days
45
-
46
- risk:
47
- max_single_trade_usd: 200
48
- max_daily_loss_usd: 300
49
- max_open_positions: 5
50
- pause_on_drawdown_pct: 25
@@ -1,47 +0,0 @@
1
- # Partner Integration Checklist
2
-
3
- ## Discovery & Metadata
4
-
5
- - [ ] Publish `/.well-known/erc8004-discovery.json`
6
- - [ ] Publish `/.well-known/erc8004-onboarding.md`
7
- - [ ] Publish `/.well-known/erc8004-skills-manifest.json`
8
-
9
- ## Onboarding
10
-
11
- - [ ] Enable at least one onboarding mode (`siwe` or `walletless`)
12
- - [ ] Verify `POST /api/public/erc8004/onboarding/siwe`
13
- - [ ] Verify `POST /api/public/erc8004/onboarding/identity` (if walletless enabled)
14
- - [ ] For Hub-managed agents, use the Hub agent Access/API key flow and the
15
- returned `POST /mcp/{publicId}` endpoint
16
- - [ ] For walletless onboarding, complete the explicit MCP flow:
17
- `walletless/init` -> `walletless/provision` -> `walletless/bind-wallet`
18
- -> `setup_agent`
19
- - [ ] Validate replay protection (token/jti reuse rejection)
20
-
21
- ## Headers and Claims
22
-
23
- - [ ] `Authorization: Bearer <mcpApiKey>` on MCP calls
24
- - [ ] Identity claims include `provider`, `subjectId`, `agentId`, `chainId`, `controllingAddress`
25
- - [ ] Provider auth header and timeout configured
26
-
27
- ## Rate Limits
28
-
29
- - [ ] Onboarding route limits configured and monitored
30
- - [ ] Discovery feed and health endpoint limits configured
31
-
32
- ## MCP Exposure Boundaries
33
-
34
- - [ ] Treat `balchemy-backend/src/core/tools/mcp-exposure.policy.ts` as the
35
- public MCP exposure source of truth
36
- - [ ] Confirm default public tools and granular read-only tools are distinct
37
- - [ ] Do not document raw provider, wallet mutation, withdrawal, approval,
38
- swap-bypass, or privileged manage helpers as public SDK APIs unless they
39
- are advertised by `tools/list` for the caller and scope
40
- - [ ] Confirm live actions fail closed unless the backend runtime is
41
- `live_armed`, `armed=true`, `paused=false`, and policy/approval gates pass
42
-
43
- ## Operational
44
-
45
- - [ ] JWKS endpoint reachable (`/.well-known/jwks.json`)
46
- - [ ] Seed/failure telemetry visible in admin panel
47
- - [ ] Kill-switches documented and tested
@@ -1,20 +0,0 @@
1
- # Python SDK Minimum Parity Backlog
2
-
3
- ## Must-Have
4
-
5
- 1. `onboard_with_siwe(message, signature, agent_id)`
6
- 2. `onboard_with_identity(provider, identity_token, agent_id, chain_id=8453)`
7
- 3. `connect_mcp(endpoint, api_key)`
8
- 4. `list_tools()` and `call_tool(name, arguments)`
9
- 5. Error classes aligned with TS SDK codes
10
-
11
- ## Should-Have
12
-
13
- 1. Built-in timeout and retry policy helpers
14
- 2. SSE fallback parsing parity
15
- 3. Typed response dataclasses
16
-
17
- ## Nice-to-Have
18
-
19
- 1. Async client (`httpx`) and sync wrapper
20
- 2. CLI helper for onboarding smoke checks