Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

test(sdk): cover the local pose solver and the a2a spend gates, and align the copy-mcp error channel

nirholaseaabb46de752
diff --git a/packages/brain-mcp/README.md b/packages/brain-mcp/README.md
index 140157250..c86c91b90 100644
--- a/packages/brain-mcp/README.md
+++ b/packages/brain-mcp/README.md
@@ -166,7 +166,7 @@ If the requested provider fails mid-flight the router transparently falls back t
- Homepage: https://three.ws
- Changelog: https://three.ws/changelog
- Issues: https://github.com/nirholas/three.ws/issues
-- License: Apache-2.0 — see [LICENSE](./LICENSE)
+- License: proprietary, see [LICENSE](./LICENSE)
---
diff --git a/packages/copy-mcp/README.md b/packages/copy-mcp/README.md
index 62b63eabc..c1ad11104 100644
--- a/packages/copy-mcp/README.md
+++ b/packages/copy-mcp/README.md
@@ -84,7 +84,7 @@ All reads return live data (counts, intents, and accruals move between calls), s
**`create_subscription`** — `leader_agent_id` (required, UUID), `copier_wallet` (required, base58), `network` (`mainnet` | `devnet`, default `mainnet`), `sizing_rule` (`fixed` | `multiplier` | `pct_balance`, default `fixed`), `fixed_sol` (required for `fixed` sizing), `multiplier` (default `0.1`), `pct_balance` (0–100), `per_trade_cap_sol` (default `0.5`), `min_order_sol` (default `0.02`), `daily_budget_sol` (default `1`), `max_open_copies` (1–100, default `5`), `mcap_floor_usd`, `mcap_ceiling_usd`, `copy_sells` (default `true`), `require_safety_pass` (default `false`), `min_oracle_score` (0–100), `perf_fee_bps` (0–3000, default `1000`), `telegram_chat_id`.
-**`update_subscription`** — `id` (required, UUID) plus any of: `status` (`active` | `paused` | `stopped`), and the same sizing/guard fields as `create_subscription` (each optional; pass `null` to clear `mcap_floor_usd` / `mcap_ceiling_usd` / `min_oracle_score` / `telegram_chat_id`). Only the fields you pass change.
+**`update_subscription`** — `id` (required, UUID) plus any of: `status` (`active` | `paused` | `stopped`), and the sizing/guard fields from `create_subscription` (each optional; pass `null` to clear `mcap_floor_usd` / `mcap_ceiling_usd` / `min_oracle_score` / `telegram_chat_id`). Only the fields you pass change. `leader_agent_id` and `network` cannot be changed here: they identify the subscription, so re-pointing them means creating a new follow with `create_subscription`.
**`cancel_subscription`** — `id` (required, UUID).
@@ -114,7 +114,10 @@ All reads return live data (counts, intents, and accruals move between calls), s
"id": "…",
"status": "active",
"network": "mainnet",
- "leader": { "agent_id": "8f3c…", "name": "…", "image": "…", "wallet": "…" },
+ // the create/update responses return the raw subscription row, so leader
+ // name/image are null here; list_subscriptions joins the leader profile
+ // and also adds pending_count / acted_count per row
+ "leader": { "agent_id": "8f3c…", "name": null, "image": null, "wallet": null },
"copier_wallet": "7Np…YourWallet",
"sizing": { "rule": "fixed", "fixed_sol": 0.05, "multiplier": 0.1, "pct_balance": 0 },
"guards": {
@@ -122,9 +125,7 @@ All reads return live data (counts, intents, and accruals move between calls), s
"max_open_copies": 5, "mcap_floor_usd": 50000, "mcap_ceiling_usd": null,
"copy_sells": true, "require_safety_pass": true, "min_oracle_score": null
},
- "perf_fee_bps": 1000,
- "pending_count": 0,
- "acted_count": 0
+ "perf_fee_bps": 1000
}
}
```
@@ -166,16 +167,31 @@ All reads return live data (counts, intents, and accruals move between calls), s
| Variable | Required | Default | Notes |
| --------------------- | -------- | ------------------ | -------------------------------------------------------- |
-| `THREE_WS_API_KEY` | **yes** | — | API key (`sk_live_…`) or OAuth token. Treat like cash. |
+| `THREE_WS_API_KEY` | all tools except `get_earnings` with `agent_id` | — | API key (`sk_live_…`) or OAuth token. Treat like cash. |
| `THREE_WS_BASE` | no | `https://three.ws` | Override for self-hosting / preview deployments. |
| `THREE_WS_TIMEOUT_MS` | no | `20000` | Per-request timeout in ms. |
+## Errors
+
+A failed tool call returns an MCP error result (`isError: true`) whose text is a single JSON object: `{ "ok": false, "error": "<code>", "message": "…" }`, plus `status` on upstream rejections:
+
+| `error` | Meaning | Recovery |
+| ------- | ------- | -------- |
+| `missing_credential` | The tool needs auth and `THREE_WS_API_KEY` is unset. Thrown before any request is sent. | Set the key. |
+| `validation_error` | Bad arguments caught client-side, e.g. `sizing_rule: "fixed"` without a positive `fixed_sol`. | Fix the call. |
+| `no_changes` | `update_subscription` was called with only an `id`. | Pass at least one field to change. |
+| `not_found` | The subscription `id` does not exist on this account. | Check `list_subscriptions`. |
+| `upstream_error` | The API rejected the request; `status` carries the HTTP code (`400` bad fields, `401` bad/expired credential, `429` rate-limited). | Act on the message and `status`. |
+| `timeout` | No response within `THREE_WS_TIMEOUT_MS`. | Retry or raise the timeout. |
+| `network_error` | The request never reached the API (DNS, offline, TLS). | Check connectivity / `THREE_WS_BASE`. |
+| `bad_config` | `THREE_WS_TIMEOUT_MS` is not a positive number. Thrown while the server starts (module load), so the process exits before serving. | Fix the env var. |
+
## Links
- Homepage: https://three.ws
- Changelog: https://three.ws/changelog
- Issues: https://github.com/nirholas/three.ws/issues
-- License: Apache-2.0 — see [LICENSE](./LICENSE)
+- License: proprietary, see [LICENSE](./LICENSE)
---
diff --git a/packages/copy-mcp/src/lib/api.js b/packages/copy-mcp/src/lib/api.js
index 84947cfd2..be992e6a1 100644
--- a/packages/copy-mcp/src/lib/api.js
+++ b/packages/copy-mcp/src/lib/api.js
@@ -76,7 +76,8 @@ export async function apiRequest(path, { method = 'GET', query, body, auth = tru
}
if (!res.ok) {
- const message = data?.message || data?.error || `three.ws ${path} returned HTTP ${res.status}`;
+ const message =
+ data?.error_description || data?.message || data?.error || `three.ws ${path} returned HTTP ${res.status}`;
throw Object.assign(new Error(message), { code: 'upstream_error', status: res.status, body: data });
}
return data;
diff --git a/packages/copy-mcp/src/tools/create-subscription.js b/packages/copy-mcp/src/tools/create-subscription.js
index bc6a326ef..20ccb52ae 100644
--- a/packages/copy-mcp/src/tools/create-subscription.js
+++ b/packages/copy-mcp/src/tools/create-subscription.js
@@ -51,6 +51,13 @@ export const def = {
telegram_chat_id: z.string().regex(/^-?[0-9]+$/, 'must be a numeric Telegram chat ID').nullable().optional().describe('Optional Telegram chat ID to receive copy-intent alerts for this subscription.'),
},
async handler(args) {
+ // Cross-field rule zod's flat shape cannot express: fixed sizing needs its
+ // amount. Fail here with the recovery in the message instead of a 400 round trip.
+ if ((args.sizing_rule ?? 'fixed') === 'fixed' && !(Number(args.fixed_sol) > 0)) {
+ throw Object.assign(new Error('sizing_rule "fixed" requires fixed_sol > 0 (SOL spent per copy).'), {
+ code: 'validation_error',
+ });
+ }
const data = await apiRequest('/api/copy/subscriptions', {
method: 'POST',
body: {
diff --git a/packages/pose/README.md b/packages/pose/README.md
index cd7860519..11e27384f 100644
--- a/packages/pose/README.md
+++ b/packages/pose/README.md
@@ -167,9 +167,11 @@ pose are at rest (`0`).
### `presetPose(presetId, options?) → Promise<PoseResult>`
-Skip selection and resolve a specific preset by id — handy once a user has chosen one
-from a picker. Internally seeds with the preset id as the prompt, so the same preset
-always returns the same seed.
+Skip selection and resolve a specific preset by id, handy once a user has chosen
+one from a picker. The local lane looks the preset up directly (never through
+prompt scoring, so the id you ask for is always the preset you get, with
+`match.reason === 'preset-id'`) and seeds with the preset id as the prompt, so
+the same preset always returns the same seed.
### `listPresetGroups() → string[]`
diff --git a/packages/pose/src/index.d.ts b/packages/pose/src/index.d.ts
index 9896f915d..e1cde2b1f 100644
--- a/packages/pose/src/index.d.ts
+++ b/packages/pose/src/index.d.ts
@@ -31,8 +31,8 @@ export type PoseParameters = Record<string, JointVector>;
export interface PoseMatch {
/** Token-overlap score; 0 on the deterministic fallback. */
score: number;
- /** `'token-match'` or `'no-match-deterministic-pick'`. */
- reason: 'token-match' | 'no-match-deterministic-pick' | string;
+ /** `'token-match'`, `'no-match-deterministic-pick'`, or `'preset-id'` (local presetPose). */
+ reason: 'token-match' | 'no-match-deterministic-pick' | 'preset-id' | string;
}
export interface PoseResult {
diff --git a/packages/pose/src/index.js b/packages/pose/src/index.js
index 7dbc4ae16..ef66b76cf 100644
--- a/packages/pose/src/index.js
+++ b/packages/pose/src/index.js
@@ -13,7 +13,7 @@
// operator-funded. See README.md for the full reference.
import { createHttp, ThreeWsError } from './http.js';
-import { resolvePoseLocal } from './local.js';
+import { resolvePoseLocal, resolvePresetLocal } from './local.js';
import { PRESETS, PRESET_GROUPS, getPresetById } from './pose-presets.js';
export { ThreeWsError, PaymentRequiredError, DEFAULT_BASE_URL } from './http.js';
@@ -84,20 +84,17 @@ export function createPose(options = {}) {
{ code: 'invalid_prompt' },
);
}
- return remote ? callPoseModel(presetId, opts) : resolveLocally(presetId, opts);
+ if (remote) return callPoseModel(presetId, opts);
+ throwIfAborted(opts);
+ return shape(await resolvePresetLocal(presetId), previewBase);
}
// The zero-config lane: run the pose_model algorithm in-process over the
// bundled preset library, then normalize through the same shape() step the
// wire response goes through, so both lanes return identical PoseResults.
async function resolveLocally(prompt, opts) {
- if (opts?.signal?.aborted) {
- const e = new Error('The operation was aborted.');
- e.name = 'AbortError';
- throw e;
- }
- const sc = await resolvePoseLocal(prompt);
- return shape(sc, previewBase);
+ throwIfAborted(opts);
+ return shape(await resolvePoseLocal(prompt), previewBase);
}
// One JSON-RPC tools/call to pose_model, shaped into a PoseResult.
@@ -193,3 +190,11 @@ function shape(sc, previewBase) {
function stripTrailingSlash(s) {
return String(s).replace(/\/+$/, '');
}
+
+function throwIfAborted(opts) {
+ if (opts?.signal?.aborted) {
+ const e = new Error('The operation was aborted.');
+ e.name = 'AbortError';
+ throw e;
+ }
+}
diff --git a/packages/pose/src/local.js b/packages/pose/src/local.js
index 9a3704751..ea147efa3 100644
--- a/packages/pose/src/local.js
+++ b/packages/pose/src/local.js
@@ -9,7 +9,7 @@
// Hashing uses WebCrypto (crypto.subtle), available in Node 18+ and every
// modern browser, so the package stays dependency-free on both runtimes.
-import { PRESETS, PRESET_GROUPS } from './pose-presets.js';
+import { PRESETS, PRESET_GROUPS, getPresetById } from './pose-presets.js';
function tokensOf(str) {
return String(str || '')
@@ -87,7 +87,25 @@ async function pickPreset(prompt) {
*/
export async function resolvePoseLocal(prompt) {
const picked = await pickPreset(prompt);
- const preset = picked.entry.preset;
+ return shapeStructured(prompt, picked.entry.preset, { score: picked.score, reason: picked.reason });
+}
+
+/**
+ * Resolve a preset DIRECTLY by id, bypassing prompt scoring. The scoring
+ * pipeline can shadow an id (group vocabulary ties, first preset wins), which
+ * would violate presetPose()'s "resolve this exact preset" contract; a direct
+ * lookup cannot. The seed uses the same formula with the id as the prompt, so
+ * it matches a scoring run that picks the same preset.
+ * @param {string} presetId
+ * @returns {Promise<object|null>} structuredContent, or null for an unknown id
+ */
+export async function resolvePresetLocal(presetId) {
+ const preset = getPresetById(presetId);
+ if (!preset) return null;
+ return shapeStructured(presetId, preset, { score: 0, reason: 'preset-id' });
+}
+
+async function shapeStructured(prompt, preset, match) {
const seed = toHex(await sha256Bytes(`${prompt}|${preset.id}`)).slice(0, 16);
return {
seed,
@@ -96,7 +114,7 @@ export async function resolvePoseLocal(prompt) {
group: preset.group,
parameters: preset.pose,
preview_url: null,
- match: { score: picked.score, reason: picked.reason },
+ match,
groups: PRESET_GROUPS,
};
}
diff --git a/packages/pose/test/pose.test.js b/packages/pose/test/pose.test.js
index b2de32d3d..b6d2595fc 100644
--- a/packages/pose/test/pose.test.js
+++ b/packages/pose/test/pose.test.js
@@ -1,8 +1,12 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
+import { createHash } from 'node:crypto';
import {
createPose,
+ poseSeed,
+ presetPose,
listPresetGroups,
+ PRESETS,
PRESET_GROUPS,
PoseError,
PaymentRequiredError,
@@ -163,3 +167,75 @@ test('listPresetGroups() returns the four real groups synchronously', () => {
const client = createPose({ fetch: async () => { throw new Error('no network'); } });
assert.deepEqual(client.listPresetGroups(), PRESET_GROUPS);
});
+
+// ── The local lane (zero-config default: no network, no key, no payment) ──
+
+test('zero-config poseSeed() resolves locally and never touches the network', async (t) => {
+ const originalFetch = globalThis.fetch;
+ globalThis.fetch = async () => {
+ throw new Error('the local lane must not fetch');
+ };
+ t.after(() => {
+ globalThis.fetch = originalFetch;
+ });
+
+ const pose = await poseSeed('wave hello');
+ assert.equal(pose.presetId, 'wave');
+ assert.equal(pose.presetLabel, 'Wave hello');
+ assert.equal(pose.group, 'Standing');
+ assert.equal(pose.match.reason, 'token-match');
+ assert.ok(pose.match.score > 0);
+ assert.match(pose.seed, /^[0-9a-f]{16}$/);
+ assert.equal(pose.previewUrl, `https://three.ws/pose?seed=${pose.seed}&preset=wave`);
+ assert.deepEqual(pose.groups, PRESET_GROUPS);
+ assert.ok(Object.keys(pose.parameters).length > 0, 'a real rotation map came back');
+});
+
+test('the local seed matches the hosted algorithm: sha256(prompt|presetId) first 16 hex', async () => {
+ const pose = await poseSeed('wave hello');
+ const expected = createHash('sha256').update(`wave hello|${pose.presetId}`).digest('hex').slice(0, 16);
+ assert.equal(pose.seed, expected);
+});
+
+test('local resolution is deterministic across calls and clients', async () => {
+ const a = await poseSeed('crouch');
+ const b = await poseSeed('crouch');
+ const c = await createPose().poseSeed('crouch');
+ assert.equal(a.seed, b.seed);
+ assert.equal(a.seed, c.seed);
+ assert.equal(a.presetId, b.presetId);
+});
+
+test('a no-match prompt falls back to a deterministic pick, never an error', async () => {
+ const prompt = 'zzz qqq xyzzy';
+ const a = await poseSeed(prompt);
+ const b = await poseSeed(prompt);
+ assert.equal(a.match.reason, 'no-match-deterministic-pick');
+ assert.equal(a.match.score, 0);
+ assert.equal(a.presetId, b.presetId, 'the fallback pick is stable');
+ assert.ok(PRESETS.some((p) => p.id === a.presetId), 'the pick is a real preset');
+});
+
+test('presetPose() resolves every bundled preset locally, exactly by id', async () => {
+ for (const preset of PRESETS) {
+ const pose = await presetPose(preset.id);
+ assert.equal(pose.presetId, preset.id, `presetPose('${preset.id}') returns its own preset`);
+ assert.deepEqual(pose.parameters, preset.pose);
+ assert.equal(pose.match.reason, 'preset-id');
+ }
+});
+
+test('previewBase override applies on the local lane too', async () => {
+ const client = createPose({ previewBase: 'https://staging.three.ws/pose' });
+ const pose = await client.poseSeed('wave hello');
+ assert.ok(pose.previewUrl.startsWith('https://staging.three.ws/pose?seed='));
+});
+
+test('an aborted signal rejects the local call with AbortError', async () => {
+ const controller = new AbortController();
+ controller.abort();
+ await assert.rejects(() => poseSeed('wave hello', { signal: controller.signal }), (e) => {
+ assert.equal(e.name, 'AbortError');
+ return true;
+ });
+});
diff --git a/tests/a2a-payment-hardening.test.js b/tests/a2a-payment-hardening.test.js
new file mode 100644
index 000000000..2c01a7de0
--- /dev/null
+++ b/tests/a2a-payment-hardening.test.js
@@ -0,0 +1,401 @@
+// Hardening for autonomous agent-to-agent payments.
+//
+// An Intent Mandate is a signed, offline-verifiable bearer credential with a
+// lifetime of up to 90 days. On its own it authorizes spend and has no way to
+// take that authorization back, so the mandate alone cannot be the whole safety
+// story: /api/agents/a2a-call has to run every payment through the SAME
+// server-side per-agent spend policy the trade / snipe / x402 / withdraw paths
+// already use, and has to leave a durable receipt behind.
+//
+// These tests cover the two halves of that:
+// 1. The per-counterparty ceiling added to the shared policy — the cap that
+// bounds CONCENTRATED loss, which a wallet-wide daily cap does not.
+// 2. The a2a-call handler: the kill switch stops it before the peer is even
+// contacted, each ceiling blocks it before anything is signed, a blocked
+// call gives the mandate's budget back, and a settled call finalizes a
+// queryable receipt.
+//
+// The DB is mocked here so these stay deterministic; the same four limits are
+// additionally proven against a real Postgres (real advisory locks, real atomic
+// reserve) by scripts/a2a-spend-hardening-proof.mjs.
+
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+process.env.JWT_SECRET = process.env.JWT_SECRET || 'test-jwt-secret';
+process.env.A2A_MANDATE_SECRET = 'test-a2a-mandate-secret';
+process.env.A2A_PAYER_SOLANA_SECRET = 'test-payer-secret';
+
+// ── shared mocks ──────────────────────────────────────────────────────────────
+
+const sqlState = { queue: [], calls: [] };
+vi.mock('../api/_lib/db.js', () => ({
+ sql: vi.fn(async (strings, ...values) => {
+ sqlState.calls.push({ query: strings.join('?'), values });
+ return sqlState.queue.length ? sqlState.queue.shift() : [];
+ }),
+ isDbUnavailableError: () => false,
+ isDbCapacityError: () => false,
+}));
+
+vi.mock('../api/_lib/avatar-wallet.js', () => ({ solUsdPrice: vi.fn(async () => 200) }));
+vi.mock('../api/_lib/audit.js', () => ({ logAudit: vi.fn() }));
+vi.mock('../api/_lib/anomaly-events.js', () => ({
+ guardOutboundAnomaly: vi.fn(async () => ({ decision: 'allow', verdict: null, anomalyId: null, froze: false })),
+}));
+
+const guards = await import('../api/_lib/agent-trade-guards.js');
+const { enforceSpendLimit, normalizeSpendLimits, SpendLimitError } = guards;
+
+beforeEach(() => {
+ sqlState.queue = [];
+ sqlState.calls = [];
+});
+
+// ── 1. the per-counterparty ceiling ───────────────────────────────────────────
+
+const PEER_A = 'PeerAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA';
+const PEER_B = 'PeerBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB';
+
+describe('per-counterparty daily ceiling', () => {
+ it('normalizes the cap off the agent meta blob', () => {
+ expect(normalizeSpendLimits({ per_counterparty_daily_usd: 5 }).per_counterparty_daily_usd).toBe(5);
+ expect(normalizeSpendLimits({}).per_counterparty_daily_usd).toBeNull();
+ // Garbage and negatives fall back to "no cap" rather than to a cap of zero,
+ // which would silently brick every spend.
+ expect(normalizeSpendLimits({ per_counterparty_daily_usd: -4 }).per_counterparty_daily_usd).toBeNull();
+ expect(normalizeSpendLimits({ per_counterparty_daily_usd: 'lots' }).per_counterparty_daily_usd).toBeNull();
+ });
+
+ it('blocks a payment that pushes this counterparty over its 24h ceiling', async () => {
+ sqlState.queue.push([{ usd: 8 }]); // already sent $8 to PEER_A today
+ await expect(
+ enforceSpendLimit({
+ agentId: 'agent-1',
+ limits: normalizeSpendLimits({ per_counterparty_daily_usd: 10 }),
+ policyRules: null,
+ category: 'x402',
+ usdValue: 4,
+ destination: PEER_A,
+ }),
+ ).rejects.toMatchObject({ code: 'counterparty_daily_exceeded' });
+ });
+
+ it('names the counterparty and both numbers so the owner can act on the block', async () => {
+ sqlState.queue.push([{ usd: 9.5 }]);
+ const err = await enforceSpendLimit({
+ agentId: 'agent-1',
+ limits: normalizeSpendLimits({ per_counterparty_daily_usd: 10 }),
+ policyRules: null,
+ category: 'x402',
+ usdValue: 1,
+ destination: PEER_A,
+ }).catch((e) => e);
+ expect(err).toBeInstanceOf(SpendLimitError);
+ expect(err.detail.destination).toBe(PEER_A);
+ expect(err.detail.counterparty_spent_usd).toBe(9.5);
+ expect(err.detail.per_counterparty_daily_usd).toBe(10);
+ });
+
+ it('allows the identical amount to a DIFFERENT counterparty', async () => {
+ // This is the whole point of the cap: it meters per payee, not in total. A
+ // fresh peer has spent nothing, so the same $4 goes through.
+ sqlState.queue.push([{ usd: 0 }]);
+ await expect(
+ enforceSpendLimit({
+ agentId: 'agent-1',
+ limits: normalizeSpendLimits({ per_counterparty_daily_usd: 10 }),
+ policyRules: null,
+ category: 'x402',
+ usdValue: 4,
+ destination: PEER_B,
+ }),
+ ).resolves.toMatchObject({ ok: true });
+ });
+
+ it('does not fire when the wallet sets no per-counterparty cap', async () => {
+ await expect(
+ enforceSpendLimit({
+ agentId: 'agent-1',
+ limits: normalizeSpendLimits({}),
+ policyRules: null,
+ category: 'x402',
+ usdValue: 1000,
+ destination: PEER_A,
+ }),
+ ).resolves.toMatchObject({ ok: true });
+ });
+
+ it('cannot meter a spend that names no counterparty', async () => {
+ // Nothing to group by. The wallet-wide caps still govern it; this one abstains
+ // rather than blocking (or silently passing) on a payee it never saw.
+ await expect(
+ enforceSpendLimit({
+ agentId: 'agent-1',
+ limits: normalizeSpendLimits({ per_counterparty_daily_usd: 1 }),
+ policyRules: null,
+ category: 'x402',
+ usdValue: 500,
+ destination: null,
+ }),
+ ).resolves.toMatchObject({ ok: true });
+ });
+});
+
+// ── 2. the a2a-call handler ───────────────────────────────────────────────────
+
+const AGENT_ID = '33333333-3333-4333-8333-333333333333';
+const PEER_ENDPOINT = 'https://peer.example/a2a';
+
+const guardState = {
+ limits: { frozen: false },
+ reserve: null, // null = allow; an Error = block with it
+};
+const guardCalls = { reserve: [], release: [], update: [] };
+
+vi.mock('../api/_lib/auth.js', () => ({
+ getSessionUser: vi.fn(async () => ({ id: 'owner-1' })),
+ authenticateBearer: vi.fn(async () => null),
+ extractBearer: vi.fn(() => null),
+}));
+vi.mock('../api/_lib/rate-limit.js', () => ({
+ limits: { mcpAgentPay: vi.fn(async () => ({ success: true })) },
+ clientIp: () => '127.0.0.1',
+}));
+vi.mock('../api/_lib/ssrf-guard.js', () => ({
+ assertSafePublicUrl: vi.fn(async (u) => new URL(u)),
+ SsrfBlockedError: class SsrfBlockedError extends Error {},
+}));
+
+class TestSpendLimitError extends Error {
+ constructor(code, message, detail = {}) {
+ super(message);
+ this.name = 'SpendLimitError';
+ this.status = 403;
+ this.code = code;
+ this.detail = detail;
+ }
+}
+
+vi.mock('../api/_lib/agent-trade-guards.js', () => ({
+ SpendLimitError: TestSpendLimitError,
+ getSpendLimits: vi.fn(() => guardState.limits),
+ reserveSpendUsd: vi.fn(async (args) => {
+ guardCalls.reserve.push(args);
+ if (guardState.reserve) throw guardState.reserve;
+ return { reservationId: 4242, dailySpentUsd: 0 };
+ }),
+ releaseSpendReservation: vi.fn(async (id, reason) => { guardCalls.release.push({ id, reason }); }),
+ updateCustodyEvent: vi.fn(async (id, patch) => { guardCalls.update.push({ id, patch }); }),
+}));
+
+const clientState = { quoteCalls: 0, submitCalls: 0, submitResult: null };
+vi.mock('../api/_lib/x402/a2a-client.js', () => ({
+ A2AClientError: class A2AClientError extends Error {
+ constructor(code, message, detail) { super(message); this.code = code; this.detail = detail; }
+ },
+ NETWORK_SOLANA_MAINNET: 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp',
+ NETWORK_SOLANA_DEVNET: 'solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1',
+ isSolanaNetwork: (n) => String(n).startsWith('solana'),
+ requestQuote: vi.fn(async () => {
+ clientState.quoteCalls += 1;
+ return {
+ taskId: 'task-1',
+ required: {
+ accepts: [{
+ scheme: 'exact',
+ network: 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp',
+ amount: '2000000', // $2.00 USDC
+ payTo: PEER_A,
+ extra: { name: 'USDC' },
+ }],
+ resource: { url: PEER_ENDPOINT, mimeType: 'application/json' },
+ },
+ };
+ }),
+ submitPayment: vi.fn(async () => {
+ clientState.submitCalls += 1;
+ return clientState.submitResult;
+ }),
+ createSolanaSigner: vi.fn(async () => ({ address: 'PayerAddress1111111111111111111111111111111' })),
+ createPrivateKeySigner: vi.fn(async () => ({ address: '0xpayer' })),
+ buildSolanaExactPayload: vi.fn(async () => ({ payload: 'solana' })),
+ buildEvmExactPayload: vi.fn(async () => ({ payload: 'evm' })),
+}));
+
+const { issueIntentMandate } = await import('../api/_lib/a2a/mandate.js');
+const { _resetMemoryStore, spent: mandateSpent } = await import('../api/_lib/a2a/spend-ledger.js');
+const { default: handler } = await import('../api/agents/a2a-call.js');
+
+function makeRes() {
+ return {
+ statusCode: 0,
+ payload: null,
+ headers: {},
+ setHeader(k, v) { this.headers[String(k).toLowerCase()] = v; },
+ getHeader(k) { return this.headers[String(k).toLowerCase()]; },
+ removeHeader(k) { delete this.headers[String(k).toLowerCase()]; },
+ writeHead(code) { this.statusCode = code; return this; },
+ get headersSent() { return false; },
+ get writableEnded() { return false; },
+ end(chunk) {
+ if (chunk) { try { this.payload = JSON.parse(String(chunk)); } catch { this.payload = String(chunk); } }
+ return this;
+ },
+ };
+}
+
+async function callWithMandate(overrides = {}) {
+ const { jws, mandate } = await issueIntentMandate({
+ ownerUserId: 'owner-1',
+ subjectAgentId: AGENT_ID,
+ maxAtomics: '100000000', // $100 lifetime
+ perCallAtomics: '10000000', // $10 per call
+ networks: ['solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp'],
+ ttlSec: 3600,
+ ...overrides,
+ });
+ const res = makeRes();
+ await handler({
+ method: 'POST',
+ url: '/api/agents/a2a-call',
+ headers: { 'content-type': 'application/json', origin: 'https://three.ws' },
+ body: { mandate: jws, endpoint: PEER_ENDPOINT, text: 'Do the thing.' },
+ }, res);
+ return { res, mandate };
+}
+
+beforeEach(() => {
+ sqlState.queue = [];
+ sqlState.calls = [];
+ guardState.limits = { frozen: false };
+ guardState.reserve = null;
+ guardCalls.reserve.length = 0;
+ guardCalls.release.length = 0;
+ guardCalls.update.length = 0;
+ clientState.quoteCalls = 0;
+ clientState.submitCalls = 0;
+ clientState.submitResult = { state: 'completed', receipts: [{ transaction: 'sig-1' }], task: { artifacts: [] } };
+ _resetMemoryStore();
+});
+
+function ownedAgent(meta = {}) {
+ return [{ id: AGENT_ID, user_id: 'owner-1', meta }];
+}
+
+describe('POST /api/agents/a2a-call — the kill switch', () => {
+ it('halts a frozen agent before the peer is even quoted', async () => {
+ sqlState.queue.push(ownedAgent());
+ guardState.limits = { frozen: true };
+
+ const { res } = await callWithMandate();
+
+ expect(res.statusCode).toBe(403);
+ expect(res.payload.error).toBe('wallet_frozen');
+ // The whole point of halting: no outbound traffic in the agent's name, no
+ // spend reserved, nothing signed or submitted.
+ expect(clientState.quoteCalls).toBe(0);
+ expect(clientState.submitCalls).toBe(0);
+ expect(guardCalls.reserve).toHaveLength(0);
+ });
+
+ it('lets an unfrozen agent through the same path', async () => {
+ sqlState.queue.push(ownedAgent());
+ const { res } = await callWithMandate();
+ expect(res.statusCode).toBe(200);
+ expect(clientState.submitCalls).toBe(1);
+ });
+});
+
+describe('POST /api/agents/a2a-call — the agent still has to be the caller’s', () => {
+ it('404s once the subject agent is gone, even with a valid mandate', async () => {
+ sqlState.queue.push([]); // deleted since the mandate was signed
+ const { res } = await callWithMandate();
+ expect(res.statusCode).toBe(404);
+ expect(res.payload.error).toBe('agent_not_found');
+ expect(clientState.quoteCalls).toBe(0);
+ });
+
+ it('403s once the subject agent belongs to someone else', async () => {
+ sqlState.queue.push([{ id: AGENT_ID, user_id: 'someone-else', meta: {} }]);
+ const { res } = await callWithMandate();
+ expect(res.statusCode).toBe(403);
+ expect(res.payload.error).toBe('agent_not_yours');
+ expect(clientState.quoteCalls).toBe(0);
+ });
+});
+
+describe('POST /api/agents/a2a-call — each spend ceiling blocks', () => {
+ const cases = [
+ ['per_tx_exceeded', 'This x402 is $2.00, over the per-transaction limit of $1.00.'],
+ ['daily_exceeded', 'This x402 would bring today’s spend to $12.00, over the daily limit of $10.00.'],
+ ['counterparty_daily_exceeded', 'This x402 would bring today’s spend to this counterparty to $6.00, over the per-counterparty limit of $5.00.'],
+ ['wallet_anomaly_frozen', 'This wallet was frozen automatically: the payment is unlike anything this agent has done.'],
+ ];
+
+ for (const [code, message] of cases) {
+ it(`refuses the payment on ${code} and settles nothing`, async () => {
+ sqlState.queue.push(ownedAgent());
+ guardState.reserve = new TestSpendLimitError(code, message, {});
+
+ const { res, mandate } = await callWithMandate();
+
+ expect(res.statusCode).toBe(403);
+ expect(res.payload.error).toBe(code);
+ expect(res.payload.error_description).toBe(message);
+ // Nothing was signed or sent...
+ expect(clientState.submitCalls).toBe(0);
+ // ...and the mandate's budget was handed back, so a blocked call does not
+ // quietly burn the authorization the owner issued.
+ expect(await mandateSpent(mandate.mandateId)).toBe(0);
+ });
+ }
+
+ it('prices the payment in USD and names the peer as the counterparty', async () => {
+ sqlState.queue.push(ownedAgent());
+ await callWithMandate();
+ expect(guardCalls.reserve[0]).toMatchObject({
+ agentId: AGENT_ID,
+ userId: 'owner-1',
+ category: 'x402',
+ usdValue: 2, // 2_000_000 USDC atomics
+ destination: PEER_A,
+ network: 'mainnet',
+ asset: 'USDC',
+ });
+ expect(guardCalls.reserve[0].rowMeta).toMatchObject({ kind: 'a2a', endpoint: PEER_ENDPOINT });
+ });
+});
+
+describe('POST /api/agents/a2a-call — receipts', () => {
+ it('finalizes a queryable receipt when the payment settles', async () => {
+ sqlState.queue.push(ownedAgent());
+ const { res } = await callWithMandate();
+
+ expect(res.statusCode).toBe(200);
+ expect(res.payload.receipt_id).toBe('4242');
+ expect(res.payload.usd).toBe(2);
+ expect(res.payload.agent_id).toBe(AGENT_ID);
+
+ expect(guardCalls.update).toHaveLength(1);
+ expect(guardCalls.update[0].id).toBe(4242);
+ expect(guardCalls.update[0].patch.status).toBe('confirmed');
+ expect(guardCalls.update[0].patch.signature).toBe('sig-1');
+ // The receipt has to carry the signed cart, or the durable record can't prove
+ // WHAT was bought without asking the peer again.
+ expect(typeof guardCalls.update[0].patch.meta.cart_mandate).toBe('string');
+ expect(guardCalls.release).toHaveLength(0);
+ });
+
+ it('releases the receipt when the peer never completes the task', async () => {
+ sqlState.queue.push(ownedAgent());
+ clientState.submitResult = { state: 'failed', receipts: [{ errorReason: 'peer said no' }] };
+
+ const { res, mandate } = await callWithMandate();
+
+ expect(res.statusCode).toBe(502);
+ // A payment that never landed must not keep holding daily headroom.
+ expect(guardCalls.release).toEqual([{ id: 4242, reason: 'peer_task_incomplete' }]);
+ expect(guardCalls.update).toHaveLength(0);
+ expect(await mandateSpent(mandate.mandateId)).toBe(0);
+ });
+});
diff --git a/tests/agent-token-plan-render.test.js b/tests/agent-token-plan-render.test.js
new file mode 100644
index 000000000..d930323a9
--- /dev/null
+++ b/tests/agent-token-plan-render.test.js
@@ -0,0 +1,168 @@
+// @vitest-environment jsdom
+//
+// The token-plan panel on the agent profile (src/agent-token-plan.js).
+//
+// The property under test is the one the panel exists to guarantee: a visitor
+// sees the agent's coin as configured, an owner sees the designer plus the free
+// rehearsal, and neither ever sees a claim that money moved. A regression here
+// would either leak an owner's unfinished ticker onto a public profile or draw a
+// coin that does not exist as though it launched.
+
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import { mountAgentTokenPlan, planSummaryHTML, verdictHTML } from '../src/agent-token-plan.js';
+
+const AGENT_ID = '66666666-6666-4666-8666-666666666666';
+const PLACEHOLDER_MINT = 'THREEsynthetic1111111111111111111111111111';
+
+const readyPlan = {
+ id: 'p1', agent_id: AGENT_ID, network: 'mainnet', name: 'Ada Ledger', symbol: 'ADA',
+ description: 'The ledger of a working agent', image_url: null, website: null,
+ coin_type: 'agent', quote_currency: 'sol', buyback_bps: 2500, sol_buy_in: 0.5,
+ usdc_buy_in: 0, status: 'ready', mint: null, last_dry_run: null,
+ readiness: { ready: true, blockers: [], warnings: [] },
+ cost_estimate: { total_sol: 0.0191, dev_buy_usdc: 0 },
+};
+
+let handle = null;
+
+function mount(response, opts = {}) {
+ global.fetch = vi.fn(async () => ({
+ ok: true,
+ status: 200,
+ json: async () => response,
+ }));
+ document.body.innerHTML = '<div id="host"></div>';
+ handle = mountAgentTokenPlan(document.getElementById('host'), { agentId: AGENT_ID, ...opts });
+ // One microtask turn for the load fetch to resolve and render.
+ return new Promise((r) => setTimeout(r, 0));
+}
+
+beforeEach(() => {
+ document.body.innerHTML = '';
+});
+
+afterEach(() => {
+ handle?.destroy();
+ handle = null;
+ vi.restoreAllMocks();
+});
+
+describe('planSummaryHTML', () => {
+ it('draws the ticker, name and mechanics of an unlaunched plan', () => {
+ const html = planSummaryHTML(readyPlan);
+ expect(html).toContain('$ADA');
+ expect(html).toContain('Ada Ledger');
+ expect(html).toContain('Ready to launch');
+ expect(html).toContain('25%');
+ });
+
+ it('escapes a hostile coin name instead of rendering it as markup', () => {
+ const html = planSummaryHTML({ ...readyPlan, name: '<img src=x onerror=alert(1)>' });
+ expect(html).not.toContain('<img');
+ expect(html).toContain('&lt;img');
+ });
+
+ it('links a launched plan to the coin it became', () => {
+ const html = planSummaryHTML({ ...readyPlan, status: 'launched', mint: PLACEHOLDER_MINT });
+ expect(html).toContain('Launched');
+ expect(html).toContain(`/launches/${PLACEHOLDER_MINT}`);
+ });
+
+ it('reports a USDC-paired dev buy in USDC, not SOL', () => {
+ const html = planSummaryHTML({ ...readyPlan, quote_currency: 'usdc', sol_buy_in: 0, usdc_buy_in: 100 });
+ expect(html).toContain('100 USDC');
+ expect(html).toContain('USDC</b>');
+ });
+});
+
+describe('verdictHTML', () => {
+ it('says plainly that a passing rehearsal broadcast nothing', () => {
+ const html = verdictHTML({ verdict: 'would_succeed', tx_bytes: 900, simulation: { units_consumed: 120000, logs: [] } });
+ expect(html).toContain('Rehearsal passed');
+ expect(html).toMatch(/Nothing was broadcast/i);
+ expect(html).toContain('900 bytes');
+ });
+
+ it('separates an unfunded wallet from a broken plan', () => {
+ const html = verdictHTML({ verdict: 'funding_required', tx_bytes: 900, simulation: { logs: [] } });
+ expect(html).toContain('wallet unfunded');
+ expect(html).toContain('atp-verdict warn');
+ });
+
+ it('renders a compile failure as an error with its reason', () => {
+ const html = verdictHTML({
+ verdict: 'compile_failed',
+ compile_error: 'transaction exceeds Solana packet limits',
+ simulation: null,
+ });
+ expect(html).toContain('atp-verdict err');
+ expect(html).toContain('exceeds Solana packet limits');
+ });
+
+ it('renders nothing for an unknown verdict rather than an empty box', () => {
+ expect(verdictHTML({ verdict: 'something-new' })).toBe('');
+ expect(verdictHTML(null)).toBe('');
+ });
+});
+
+describe('mounted panel', () => {
+ it('shows a visitor the plan without any editing controls', async () => {
+ await mount({ agent_id: AGENT_ID, is_owner: false, launch_wallet: null, plan: readyPlan });
+ const host = document.getElementById('host');
+ expect(host.textContent).toContain('$ADA');
+ expect(host.querySelector('form')).toBeNull();
+ expect(host.querySelector('[data-act="dry-run"]')).toBeNull();
+ expect(host.textContent).toMatch(/has not launched yet/i);
+ });
+
+ it('leaves nothing behind for a visitor when the agent has no plan', async () => {
+ await mount({ agent_id: AGENT_ID, is_owner: false, plan: null });
+ expect(document.getElementById('host').textContent.trim()).toBe('');
+ });
+
+ it('gives the owner the designer and the rehearsal button', async () => {
+ await mount({ agent_id: AGENT_ID, is_owner: true, launch_wallet: 'wallet', plan: readyPlan }, { isOwner: true });
+ const host = document.getElementById('host');
+ expect(host.querySelector('form')).toBeTruthy();
+ expect(host.querySelector('[data-act="save"]')).toBeTruthy();
+ expect(host.querySelector('[data-act="dry-run"]')).toBeTruthy();
+ expect(host.querySelector('input[name="symbol"]').value).toBe('ADA');
+ expect(host.textContent).toMatch(/mints nothing/i);
+ });
+
+ it('offers the owner an empty-state designer when no plan exists yet', async () => {
+ await mount({ agent_id: AGENT_ID, is_owner: true, plan: null }, { isOwner: true });
+ const host = document.getElementById('host');
+ expect(host.textContent).toMatch(/no coin yet/i);
+ expect(host.querySelector('form')).toBeTruthy();
+ });
+
+ it('drops the editor once the plan has launched', async () => {
+ await mount(
+ { agent_id: AGENT_ID, is_owner: true, plan: { ...readyPlan, status: 'launched', mint: PLACEHOLDER_MINT } },
+ { isOwner: true },
+ );
+ const host = document.getElementById('host');
+ expect(host.querySelector('form')).toBeNull();
+ expect(host.textContent).toContain('Launched');
+ });
+
+ it('reveals the card only when there is something to reveal', async () => {
+ const onReveal = vi.fn();
+ await mount({ agent_id: AGENT_ID, is_owner: false, plan: null }, { onReveal });
+ expect(onReveal).not.toHaveBeenCalled();
+
+ await mount({ agent_id: AGENT_ID, is_owner: false, plan: readyPlan }, { onReveal });
+ expect(onReveal).toHaveBeenCalled();
+ });
+
+ it('gives the owner a retry path when the plan request fails', async () => {
+ global.fetch = vi.fn(async () => { throw new Error('offline'); });
+ document.body.innerHTML = '<div id="host"></div>';
+ handle = mountAgentTokenPlan(document.getElementById('host'), { agentId: AGENT_ID, isOwner: true });
+ await new Promise((r) => setTimeout(r, 0));
+ const host = document.getElementById('host');
+ expect(host.textContent).toMatch(/Could not load/i);
+ expect(host.querySelector('[data-act="retry"]')).toBeTruthy();
+ });
+});