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.

feat: implement voice management endpoints and enhance agent voice handling

nirholas6cef3e8fe6dc
diff --git a/api/agents.js b/api/agents.js
index b4d9cfc29..0a74e721d 100644
--- a/api/agents.js
+++ b/api/agents.js
@@ -345,6 +345,10 @@ function decorate(row, isOwner = true) {
is_registered: Boolean(row.erc8004_agent_id) || !!onchain,
created_at: row.created_at,
};
+ // Voice clone fields are public (voice_id is needed by the runtime to select TTS).
+ base.voice_provider = row.voice_provider || 'browser';
+ base.voice_id = row.voice_id || null;
+
if (isOwner) {
base.wallet_address = row.wallet_address;
base.chain_id = row.chain_id;
diff --git a/api/agents/[id].js b/api/agents/[id].js
index ff45be640..840d11b4f 100644
--- a/api/agents/[id].js
+++ b/api/agents/[id].js
@@ -14,6 +14,7 @@
*
* /api/agents/:id/livekit-token — GET short-lived LiveKit room JWT
* /api/agents/:id/embed — POST text → 1024-dim embedding vector
+ * /api/agents/:id/voice — GET/DELETE voice status; POST /voice/clone to clone
* /api/agents/:id/pumpfun/* is routed directly to api/agents/pumpfun/[action].js
* by vercel.json — see the rewrite for that path family.
*/
@@ -81,6 +82,18 @@ export default wrap(async function handler(req, res) {
return mod.handleMemories(req, res, id, action);
}
+ if (sub === 'memory') {
+ if (action === 'pin') {
+ const mod = await import('./memory/pin.js');
+ return mod.default(req, res);
+ }
+ if (action && CID_RE.test(action)) {
+ const mod = await import('./memory/[cid].js');
+ return mod.default(req, res);
+ }
+ return error(res, 404, 'not_found', 'unknown memory sub-resource');
+ }
+
if (sub === 'livekit-token') {
const mod = await import('./livekit-token.js');
return mod.handleLiveKitToken(req, res, id);
@@ -91,5 +104,10 @@ export default wrap(async function handler(req, res) {
return mod.handleEmbed(req, res, id);
}
+ if (sub === 'voice') {
+ const mod = await import('./voice.js');
+ return mod.handleVoice(req, res, id, action);
+ }
+
return handleGetOne(req, res, id);
});
diff --git a/api/agents/[id]/_sub.js b/api/agents/[id]/_sub.js
index 27343f4b6..e1235795c 100644
--- a/api/agents/[id]/_sub.js
+++ b/api/agents/[id]/_sub.js
@@ -136,7 +136,7 @@ export const handleManifest = wrap(async (req, res, id) => {
if (!/^[0-9a-f-]{36}$/i.test(id)) return error(res, 400, 'invalid_request', 'agent id required');
- const [row] = await sql`select a.id, a.name, a.description, a.avatar_id, a.skills, a.meta, a.chain_id, a.erc8004_agent_id, a.erc8004_registry, a.registration_cid, a.created_at, av.id as avatar_db_id, av.storage_key, av.content_type from agent_identities a left join avatars av on av.id = a.avatar_id and av.deleted_at is null where a.id = ${id} and a.deleted_at is null limit 1`;
+ const [row] = await sql`select a.id, a.name, a.description, a.avatar_id, a.skills, a.meta, a.chain_id, a.erc8004_agent_id, a.erc8004_registry, a.registration_cid, a.created_at, a.voice_provider, a.voice_id, av.id as avatar_db_id, av.storage_key, av.content_type from agent_identities a left join avatars av on av.id = a.avatar_id and av.deleted_at is null where a.id = ${id} and a.deleted_at is null limit 1`;
if (!row) return error(res, 404, 'not_found', 'agent not found');
let bodyUri = '';
@@ -160,6 +160,9 @@ export const handleManifest = wrap(async (req, res, id) => {
skills: Array.isArray(row.skills) ? row.skills : [],
homeUrl: `${origin}/agent/${row.id}`,
registrations: row.chain_id && row.erc8004_agent_id ? [{ agentRegistry: `eip155:${row.chain_id}:${row.erc8004_registry}`, agentId: row.erc8004_agent_id }] : [],
+ voice: row.voice_id
+ ? { provider: row.voice_provider || 'elevenlabs', voice_id: row.voice_id }
+ : { provider: 'browser' },
createdAt: row.created_at,
};
diff --git a/api/agents/[id]/voice.js b/api/agents/[id]/voice.js
new file mode 100644
index 000000000..b516a8a78
--- /dev/null
+++ b/api/agents/[id]/voice.js
@@ -0,0 +1,188 @@
+// Voice clone management for an agent.
+//
+// GET /api/agents/:id/voice — current voice status
+// POST /api/agents/:id/voice/clone — clone voice from uploaded audio
+// DELETE /api/agents/:id/voice — remove cloned voice
+
+import { sql } from '../../_lib/db.js';
+import { getSessionUser, authenticateBearer, extractBearer } from '../../_lib/auth.js';
+import { cors, json, method, wrap, error } from '../../_lib/http.js';
+import { limits, clientIp } from '../../_lib/rate-limit.js';
+import { env } from '../../_lib/env.js';
+
+const MAX_AUDIO_BYTES = 10 * 1024 * 1024; // 10 MB
+const MIN_DURATION_SEC = 30;
+const ELEVEN_BASE = 'https://api.elevenlabs.io/v1';
+
+async function resolveAuth(req) {
+ const session = await getSessionUser(req);
+ if (session) return { userId: session.id };
+ const bearer = await authenticateBearer(extractBearer(req));
+ if (bearer) return { userId: bearer.userId };
+ return null;
+}
+
+function readRawBody(req) {
+ return new Promise((resolve, reject) => {
+ const chunks = [];
+ let total = 0;
+ req.on('data', (chunk) => {
+ total += chunk.length;
+ if (total > MAX_AUDIO_BYTES) {
+ reject(Object.assign(new Error('payload too large'), { status: 413 }));
+ req.destroy();
+ return;
+ }
+ chunks.push(chunk);
+ });
+ req.on('end', () => resolve(Buffer.concat(chunks)));
+ req.on('error', reject);
+ });
+}
+
+export const handleVoice = wrap(async (req, res, id, action) => {
+ if (cors(req, res, { methods: 'GET,POST,DELETE,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET', 'POST', 'DELETE'])) return;
+
+ const auth = await resolveAuth(req);
+ if (!auth) return error(res, 401, 'unauthorized', 'sign in required');
+
+ const [agent] =
+ await sql`SELECT id, user_id, name FROM agent_identities WHERE id = ${id} AND deleted_at IS NULL`;
+ if (!agent) return error(res, 404, 'not_found', 'agent not found');
+ if (agent.user_id !== auth.userId) return error(res, 403, 'forbidden', 'not your agent');
+
+ // ── GET — voice status ───────────────────────────────────────────────────
+
+ if (req.method === 'GET') {
+ const [row] =
+ await sql`SELECT voice_provider, voice_id, voice_cloned_at FROM agent_identities WHERE id = ${id}`;
+ return json(res, 200, {
+ voice_provider: row.voice_provider || 'browser',
+ voice_id: row.voice_id || null,
+ voice_cloned_at: row.voice_cloned_at || null,
+ });
+ }
+
+ // ── DELETE — remove cloned voice ─────────────────────────────────────────
+
+ if (req.method === 'DELETE') {
+ const [row] = await sql`SELECT voice_id FROM agent_identities WHERE id = ${id}`;
+ if (row?.voice_id) {
+ // Best-effort: free the quota slot on ElevenLabs.
+ const apiKey = env.ELEVENLABS_API_KEY;
+ if (apiKey) {
+ fetch(`${ELEVEN_BASE}/voices/${encodeURIComponent(row.voice_id)}`, {
+ method: 'DELETE',
+ headers: { 'xi-api-key': apiKey },
+ }).catch(() => {});
+ }
+ }
+ await sql`
+ UPDATE agent_identities
+ SET voice_provider = 'browser', voice_id = NULL, voice_cloned_at = NULL
+ WHERE id = ${id}
+ `;
+ return json(res, 200, { voice_provider: 'browser', voice_id: null });
+ }
+
+ // ── POST /clone ──────────────────────────────────────────────────────────
+
+ if (req.method === 'POST' && action === 'clone') {
+ const apiKey = env.ELEVENLABS_API_KEY;
+ if (!apiKey)
+ return error(res, 503, 'not_configured', 'voice cloning is not configured on this server');
+
+ // Rate limit: 3 clones per user per day.
+ const rl = await limits.voiceClone(auth.userId);
+ if (!rl.success)
+ return error(res, 429, 'rate_limited', 'voice clone limit reached (3 per day)');
+
+ // Client can send recording duration in seconds so we can reject short clips
+ // without decoding the audio.
+ const durationSec = Number(req.headers['x-recording-duration'] || '0');
+ if (durationSec > 0 && durationSec < MIN_DURATION_SEC) {
+ return error(
+ res,
+ 400,
+ 'audio_too_short',
+ `recording must be at least ${MIN_DURATION_SEC} seconds (got ${Math.round(durationSec)}s)`,
+ );
+ }
+
+ const ct = (req.headers['content-type'] || '').split(';')[0].trim();
+ if (!ct.startsWith('audio/')) {
+ return error(res, 415, 'unsupported_media_type', 'content-type must be audio/*');
+ }
+
+ let audioBuf;
+ try {
+ audioBuf = await readRawBody(req);
+ } catch (err) {
+ if (err.status === 413)
+ return error(res, 413, 'payload_too_large', 'audio file must be under 10 MB');
+ throw err;
+ }
+
+ if (audioBuf.length === 0) return error(res, 400, 'validation_error', 'audio body is empty');
+
+ // Fallback size check when no duration header. WebM/Opus at 64 kbps:
+ // 3 s ≈ 24 KB, 30 s ≈ 240 KB. 50 KB catches sub-6-second clips.
+ if (!durationSec && audioBuf.length < 50_000) {
+ return error(res, 400, 'audio_too_short', 'recording must be at least 30 seconds');
+ }
+
+ const url = new URL(req.url, 'http://x');
+ const voiceName = url.searchParams.get('name') || agent.name || 'Agent Voice';
+ const voiceDescription = url.searchParams.get('description') || '';
+
+ // Map MIME type to a filename extension ElevenLabs can identify.
+ const ext = ct.includes('webm')
+ ? 'audio.webm'
+ : ct.includes('mpeg') || ct.includes('mp3')
+ ? 'audio.mp3'
+ : ct.includes('wav')
+ ? 'audio.wav'
+ : ct.includes('mp4') || ct.includes('m4a')
+ ? 'audio.m4a'
+ : 'audio.webm';
+
+ const form = new FormData();
+ form.append('name', voiceName);
+ if (voiceDescription) form.append('description', voiceDescription);
+ form.append('files', new Blob([audioBuf], { type: ct }), ext);
+
+ let elevenResp;
+ try {
+ elevenResp = await fetch(`${ELEVEN_BASE}/voices/add`, {
+ method: 'POST',
+ headers: { 'xi-api-key': apiKey },
+ body: form,
+ });
+ } catch (err) {
+ console.error('[voice/clone] elevenlabs fetch failed', err);
+ return error(res, 502, 'upstream_error', 'voice cloning service unavailable');
+ }
+
+ if (!elevenResp.ok) {
+ const body = await elevenResp.text().catch(() => '');
+ console.error('[voice/clone] elevenlabs error', elevenResp.status, body);
+ if (elevenResp.status === 422)
+ return error(res, 400, 'audio_too_short', 'audio is too short or low quality for cloning');
+ return error(res, 502, 'upstream_error', 'voice cloning failed');
+ }
+
+ const { voice_id } = await elevenResp.json();
+ if (!voice_id) return error(res, 502, 'upstream_error', 'unexpected response from voice service');
+
+ await sql`
+ UPDATE agent_identities
+ SET voice_provider = 'elevenlabs', voice_id = ${voice_id}, voice_cloned_at = now()
+ WHERE id = ${id}
+ `;
+
+ return json(res, 201, { voice_id, name: voiceName });
+ }
+
+ return error(res, 404, 'not_found', 'unknown voice action');
+});
diff --git a/api/erc8004/register-confirm.js b/api/erc8004/register-confirm.js
new file mode 100644
index 000000000..f139970a1
--- /dev/null
+++ b/api/erc8004/register-confirm.js
@@ -0,0 +1,122 @@
+import { id as keccakId, AbiCoder, getAddress } from 'ethers';
+import { z } from 'zod';
+import { sql } from '../_lib/db.js';
+import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../_lib/auth.js';
+import { cors, json, method, wrap, error, readJson } from '../_lib/http.js';
+import { parse } from '../_lib/validate.js';
+import { CHAIN_BY_ID } from '../_lib/erc8004-chains.js';
+
+const REGISTERED_TOPIC = keccakId('Registered(uint256,string,address)');
+const ABI_CODER = AbiCoder.defaultAbiCoder();
+const TIMEOUT_MS = 10_000;
+
+const bodySchema = z.object({
+ chainId: z.number().int().positive(),
+ txHash: z.string().regex(/^0x[0-9a-fA-F]{64}$/),
+ agentId: z.union([z.string(), z.number()]).transform(String),
+ metadataUri: z.string().min(1),
+ ownerAddress: z.string().regex(/^0x[0-9a-fA-F]{40}$/),
+});
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const session = await getSessionUser(req);
+ const bearer = session ? null : await authenticateBearer(extractBearer(req));
+ if (!session && !bearer) return error(res, 401, 'unauthorized', 'sign in required');
+ if (bearer && !hasScope(bearer.scope, 'avatars:write'))
+ return error(res, 403, 'insufficient_scope', 'avatars:write scope required');
+
+ const body = parse(bodySchema, await readJson(req));
+ const chain = CHAIN_BY_ID[body.chainId];
+ if (!chain) return error(res, 400, 'bad_request', `unsupported chain ${body.chainId}`);
+
+ const receipt = await rpcCall(chain.rpcUrl, 'eth_getTransactionReceipt', [body.txHash]);
+ if (!receipt) return error(res, 422, 'tx_not_mined', 'transaction not yet mined');
+ if (receipt.status === '0x0') return error(res, 422, 'tx_failed', 'transaction reverted');
+
+ const log = (receipt.logs ?? []).find(
+ (l) =>
+ l.address?.toLowerCase() === chain.registry.toLowerCase() &&
+ l.topics?.[0] === REGISTERED_TOPIC,
+ );
+ if (!log) return error(res, 422, 'event_not_found', 'Registered event not found in receipt');
+
+ const onChainId = BigInt(log.topics[1]).toString();
+ const ownerHex = getAddress('0x' + log.topics[2].slice(-40)).toLowerCase();
+ const [agentUri] = ABI_CODER.decode(['string'], log.data);
+
+ if (onChainId !== body.agentId) return error(res, 422, 'mismatch', 'agentId mismatch');
+ if (ownerHex !== body.ownerAddress.toLowerCase())
+ return error(res, 422, 'mismatch', 'ownerAddress mismatch');
+
+ const metaUri = body.metadataUri || agentUri || null;
+
+ await sql`
+ INSERT INTO erc8004_agents_index
+ (chain_id, agent_id, owner, registry, agent_uri,
+ registered_block, registered_tx, registered_at, last_seen_at)
+ VALUES
+ (${body.chainId}, ${onChainId}, ${ownerHex}, ${chain.registry.toLowerCase()},
+ ${metaUri}, ${Number.parseInt(receipt.blockNumber, 16)}, ${body.txHash}, now(), now())
+ ON CONFLICT (chain_id, agent_id) DO NOTHING
+ `;
+
+ if (metaUri) await enrichMetadata(body.chainId, onChainId, metaUri).catch(() => {});
+
+ return json(res, 200, { success: true, agentId: onChainId, chainId: body.chainId });
+});
+
+async function rpcCall(url, methodName, params) {
+ const ac = new AbortController();
+ const t = setTimeout(() => ac.abort(), TIMEOUT_MS);
+ try {
+ const r = await fetch(url, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: methodName, params }),
+ signal: ac.signal,
+ });
+ if (!r.ok) throw new Error(`HTTP ${r.status}`);
+ const d = await r.json();
+ if (d.error) throw new Error(`RPC ${d.error.code}: ${d.error.message}`);
+ return d.result;
+ } finally {
+ clearTimeout(t);
+ }
+}
+
+function resolveGateway(uri) {
+ if (!uri) return '';
+ if (uri.startsWith('ipfs://')) return 'https://ipfs.io/ipfs/' + uri.slice(7);
+ if (uri.startsWith('ar://')) return 'https://arweave.net/' + uri.slice(5);
+ return uri.startsWith('http') ? uri : '';
+}
+
+async function enrichMetadata(chainId, agentId, uri) {
+ const url = resolveGateway(uri);
+ if (!url) return;
+ const r = await fetch(url, { signal: AbortSignal.timeout(TIMEOUT_MS) });
+ if (!r.ok) return;
+ const meta = await r.json();
+ const services = Array.isArray(meta.services) ? meta.services : [];
+ const avatarSvc = services.find(
+ (s) => String(s?.name || '').toLowerCase() === 'avatar' && s?.endpoint,
+ );
+ const glbUrl = avatarSvc ? resolveGateway(avatarSvc.endpoint) : null;
+ await sql`
+ UPDATE erc8004_agents_index SET
+ name = ${(meta.name || '').slice(0, 200) || null},
+ description = ${(meta.description || '').slice(0, 1000) || null},
+ image = ${resolveGateway(meta.image || '') || null},
+ glb_url = ${glbUrl},
+ services = ${JSON.stringify(services)}::jsonb,
+ has_3d = ${!!glbUrl},
+ active = ${meta.active !== false},
+ x402_support = ${!!(meta.x402Support || meta.x402)},
+ metadata_error = null,
+ last_metadata_at = now()
+ WHERE chain_id = ${chainId} AND agent_id = ${agentId}
+ `;
+}
diff --git a/solana-agent-sdk/jest.config.ts b/solana-agent-sdk/jest.config.ts
new file mode 100644
index 000000000..d93660c52
--- /dev/null
+++ b/solana-agent-sdk/jest.config.ts
@@ -0,0 +1,14 @@
+import type { Config } from "jest";
+
+const config: Config = {
+ preset: "ts-jest/presets/default-esm",
+ testEnvironment: "node",
+ extensionsToTreatAsEsm: [".ts"],
+ moduleNameMapper: { "^(\\.{1,2}/.*)\\.js$": "$1" },
+ transform: {
+ "^.+\\.ts$": ["ts-jest", { useESM: true, tsconfig: "./tsconfig.test.json" }],
+ },
+ testMatch: ["<rootDir>/tests/wallet/**/*.test.ts"],
+};
+
+export default config;
diff --git a/solana-agent-sdk/package.json b/solana-agent-sdk/package.json
index cb8a71781..caf98683f 100644
--- a/solana-agent-sdk/package.json
+++ b/solana-agent-sdk/package.json
@@ -37,7 +37,8 @@
"dev": "tsup --watch",
"typecheck": "tsc --noEmit",
"clean": "rm -rf dist",
- "prepublishOnly": "npm run typecheck && npm run build:prod"
+ "prepublishOnly": "npm run typecheck && npm run build:prod",
+ "test": "node --experimental-vm-modules node_modules/.bin/jest"
},
"dependencies": {
"@solana/spl-token": "^0.4.9",
diff --git a/solana-agent-sdk/src/actions/stake.ts b/solana-agent-sdk/src/actions/stake.ts
index eecdbb84a..e9c77fbb3 100644
--- a/solana-agent-sdk/src/actions/stake.ts
+++ b/solana-agent-sdk/src/actions/stake.ts
@@ -189,7 +189,7 @@ export async function getStakeAccounts(
{
address: pubkey.toBase58(),
lamports: account.lamports,
- state: "initialized" as const,
+ state: "initialized" as StakeAccountInfo["state"],
},
];
}
diff --git a/solana-agent-sdk/src/solana-agent-kit/actions.ts b/solana-agent-sdk/src/solana-agent-kit/actions.ts
index b2bcb740b..64c631978 100644
--- a/solana-agent-sdk/src/solana-agent-kit/actions.ts
+++ b/solana-agent-sdk/src/solana-agent-kit/actions.ts
@@ -274,7 +274,7 @@ export const stakeSolAction: Action = {
{
input: {
voteAccount: "Vote111111111111111111111111111111111111111",
- amount: 1,
+ amount: "1",
},
output: {
signature: "5K4b...txSig",
@@ -350,7 +350,7 @@ export const getStakeAccountsAction: Action = {
{
input: {},
output: {
- accounts: [
+ accounts: JSON.stringify([
{
address: "Ek5G...acct",
lamports: 1002282880,
@@ -358,7 +358,7 @@ export const getStakeAccountsAction: Action = {
voteAccount: "Vote111111111111111111111111111111111111111",
activationEpoch: 700,
},
- ],
+ ]),
},
explanation: "List all stake accounts for the agent wallet.",
},
diff --git a/solana-agent-sdk/src/solana-agent-kit/types.ts b/solana-agent-sdk/src/solana-agent-kit/types.ts
index cfd811b1d..3601e6027 100644
--- a/solana-agent-sdk/src/solana-agent-kit/types.ts
+++ b/solana-agent-sdk/src/solana-agent-kit/types.ts
@@ -14,8 +14,8 @@ export type ActionHandler = (
) => Promise<Record<string, unknown>>;
export interface ActionExample {
- input: Record<string, string>;
- output: Record<string, string>;
+ input: Record<string, unknown>;
+ output: Record<string, unknown>;
explanation: string;
}
diff --git a/solana-agent-sdk/tests/actions/ata.test.ts b/solana-agent-sdk/tests/actions/ata.test.ts
new file mode 100644
index 000000000..5ce19b316
--- /dev/null
+++ b/solana-agent-sdk/tests/actions/ata.test.ts
@@ -0,0 +1,95 @@
+import {
+ Keypair,
+ PublicKey,
+ type Connection,
+} from "@solana/web3.js";
+import {
+ getAssociatedTokenAddressSync,
+ TOKEN_PROGRAM_ID,
+ ASSOCIATED_TOKEN_PROGRAM_ID,
+} from "@solana/spl-token";
+import { getOrCreateAta } from "../../src/actions/ata.js";
+import { buildAndSend } from "../../src/tx/build.js";
+
+jest.mock("../../src/tx/build.js", () => ({ buildAndSend: jest.fn() }));
+
+const mockBuildAndSend = jest.mocked(buildAndSend);
+
+// Deterministic test keys
+const WALLET_PUBKEY = Keypair.fromSeed(new Uint8Array(32).fill(1)).publicKey;
+const CUSTOM_OWNER = Keypair.fromSeed(new Uint8Array(32).fill(2)).publicKey;
+const MINT_PUBKEY = Keypair.fromSeed(new Uint8Array(32).fill(3)).publicKey;
+
+const FAKE_ACCOUNT = { data: Buffer.alloc(0), executable: false, lamports: 1, owner: TOKEN_PROGRAM_ID } as any;
+
+const wallet = {
+ publicKey: WALLET_PUBKEY,
+ signTransaction: jest.fn(),
+ signAndSendTransaction: jest.fn(),
+};
+
+function makeConnection(ataExists: boolean) {
+ return {
+ getAccountInfo: jest.fn().mockResolvedValue(ataExists ? FAKE_ACCOUNT : null),
+ } as unknown as Connection;
+}
+
+beforeEach(() => {
+ jest.clearAllMocks();
+ mockBuildAndSend.mockResolvedValue("fakeSig");
+});
+
+describe("getOrCreateAta", () => {
+ it("returns { ata, signature: undefined } when ATA already exists", async () => {
+ const connection = makeConnection(true);
+ const result = await getOrCreateAta(wallet, connection, { mint: MINT_PUBKEY });
+
+ expect(result.signature).toBeUndefined();
+ expect(mockBuildAndSend).not.toHaveBeenCalled();
+
+ const expectedAta = getAssociatedTokenAddressSync(
+ MINT_PUBKEY, WALLET_PUBKEY, false, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID,
+ );
+ expect(result.ata.equals(expectedAta)).toBe(true);
+ });
+
+ it("calls buildAndSend and returns signature when ATA does not exist", async () => {
+ const connection = makeConnection(false);
+ const result = await getOrCreateAta(wallet, connection, { mint: MINT_PUBKEY });
+
+ expect(mockBuildAndSend).toHaveBeenCalledTimes(1);
+ expect(result.signature).toBe("fakeSig");
+ });
+
+ it("sends createAssociatedTokenAccountInstruction when ATA does not exist", async () => {
+ const connection = makeConnection(false);
+ await getOrCreateAta(wallet, connection, { mint: MINT_PUBKEY });
+
+ const [, , instructions] = mockBuildAndSend.mock.calls[0];
+ expect(instructions).toHaveLength(1);
+ expect(instructions[0].programId.equals(ASSOCIATED_TOKEN_PROGRAM_ID)).toBe(true);
+ });
+
+ it("uses wallet.publicKey as owner by default", async () => {
+ const connection = makeConnection(false);
+ const result = await getOrCreateAta(wallet, connection, { mint: MINT_PUBKEY });
+
+ const expectedAta = getAssociatedTokenAddressSync(
+ MINT_PUBKEY, WALLET_PUBKEY, false, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID,
+ );
+ expect(result.ata.equals(expectedAta)).toBe(true);
+ });
+
+ it("uses provided owner instead of wallet.publicKey", async () => {
+ const connection = makeConnection(false);
+ const result = await getOrCreateAta(wallet, connection, {
+ mint: MINT_PUBKEY,
+ owner: CUSTOM_OWNER,
+ });
+
+ const expectedAta = getAssociatedTokenAddressSync(
+ MINT_PUBKEY, CUSTOM_OWNER, false, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID,
+ );
+ expect(result.ata.equals(expectedAta)).toBe(true);
+ });
+});
diff --git a/solana-agent-sdk/tests/actions/swap.test.ts b/solana-agent-sdk/tests/actions/swap.test.ts
new file mode 100644
index 000000000..f58832cb4
--- /dev/null
+++ b/solana-agent-sdk/tests/actions/swap.test.ts
@@ -0,0 +1,169 @@
+import {
+ Keypair,
+ PublicKey,
+ TransactionMessage,
+ VersionedTransaction,
+ type Connection,
+} from "@solana/web3.js";
+import { jupiterSwap, getSwapQuote, SOL_MINT } from "../../src/actions/swap.js";
+import { SwapError } from "../../src/errors.js";
+import type { MetaAwareWallet, WalletProvider } from "../../src/wallet/types.js";
+
+// Deterministic test key
+const WALLET_PUBKEY = Keypair.fromSeed(new Uint8Array(32).fill(1)).publicKey;
+
+// Minimal valid VersionedTransaction for the mock Jupiter swap response
+const MOCK_TX_BASE64 = (() => {
+ const msg = new TransactionMessage({
+ payerKey: WALLET_PUBKEY,
+ recentBlockhash: "11111111111111111111111111111111",
+ instructions: [],
+ }).compileToV0Message();
+ return Buffer.from(new VersionedTransaction(msg).serialize()).toString("base64");
+})();
+
+const MOCK_QUOTE = {
+ inputMint: SOL_MINT,
+ outputMint: SOL_MINT,
+ inAmount: "1000000000",
+ outAmount: "990000000",
+ priceImpactPct: "0.01",
+};
+
+function makeWallet(publicKey = WALLET_PUBKEY): WalletProvider {
+ return {
+ publicKey,
+ signTransaction: jest.fn(),
+ signAndSendTransaction: jest.fn().mockResolvedValue("mockSwapSig"),
+ };
+}
+
+function makeMetaWallet(publicKey = WALLET_PUBKEY): MetaAwareWallet {
+ return {
+ ...makeWallet(publicKey),
+ setNextMeta: jest.fn(),
+ };
+}
+
+const connection = {} as unknown as Connection;
+
+let mockFetch: jest.Mock;
+
+beforeEach(() => {
+ mockFetch = jest.fn();
+ global.fetch = mockFetch;
+});
+
+afterEach(() => {
+ jest.clearAllMocks();
+});
+
+describe("getSwapQuote", () => {
+ it("constructs quote URL with inputMint, outputMint, amount, and slippageBps", async () => {
+ mockFetch.mockResolvedValue({ ok: true, json: async () => MOCK_QUOTE });
+
+ await getSwapQuote({
+ inputMint: SOL_MINT,
+ outputMint: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",
+ amount: 1_000_000_000n,
+ slippageBps: 100,
+ });
+
+ expect(mockFetch).toHaveBeenCalledTimes(1);
+ const url = new URL(mockFetch.mock.calls[0][0] as string);
+ expect(url.searchParams.get("inputMint")).toBe(SOL_MINT);
+ expect(url.searchParams.get("outputMint")).toBe("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v");
+ expect(url.searchParams.get("amount")).toBe("1000000000");
+ expect(url.searchParams.get("slippageBps")).toBe("100");
+ });
+
+ it("defaults slippageBps to 50 when not provided", async () => {
+ mockFetch.mockResolvedValue({ ok: true, json: async () => MOCK_QUOTE });
+
+ await getSwapQuote({ inputMint: SOL_MINT, outputMint: SOL_MINT, amount: 1n });
+
+ const url = new URL(mockFetch.mock.calls[0][0] as string);
+ expect(url.searchParams.get("slippageBps")).toBe("50");
+ });
+
+ it("throws SwapError when quote API returns non-200", async () => {
+ mockFetch.mockResolvedValue({ ok: false, text: async () => "rate limited" });
+
+ await expect(
+ getSwapQuote({ inputMint: SOL_MINT, outputMint: SOL_MINT, amount: 1n }),
+ ).rejects.toThrow(SwapError);
+ });
+});
+
+describe("jupiterSwap", () => {
+ it("sends correct POST body to swap endpoint", async () => {
+ mockFetch
+ .mockResolvedValueOnce({ ok: true, json: async () => MOCK_QUOTE })
+ .mockResolvedValueOnce({ ok: true, json: async () => ({ swapTransaction: MOCK_TX_BASE64 }) });
+
+ const w = makeWallet();
+ await jupiterSwap(w, connection, {
+ inputMint: SOL_MINT,
+ outputMint: SOL_MINT,
+ amount: 1_000_000_000n,
+ });
+
+ const [swapUrl, swapInit] = mockFetch.mock.calls[1] as [string, RequestInit];
+ expect(swapUrl).toContain("/swap");
+ const body = JSON.parse(swapInit.body as string);
+ expect(body.quoteResponse).toEqual(MOCK_QUOTE);
+ expect(body.userPublicKey).toBe(WALLET_PUBKEY.toBase58());
+ expect(body.dynamicComputeUnitLimit).toBe(true);
+ expect(body.prioritizationFeeLamports).toBe("auto");
+ });
+
+ it("throws SwapError when swap API returns non-200", async () => {
+ mockFetch
+ .mockResolvedValueOnce({ ok: true, json: async () => MOCK_QUOTE })
+ .mockResolvedValueOnce({ ok: false, text: async () => "swap failed" });
+
+ await expect(
+ jupiterSwap(makeWallet(), connection, {
+ inputMint: SOL_MINT,
+ outputMint: SOL_MINT,
+ amount: 1n,
+ }),
+ ).rejects.toThrow(SwapError);
+ });
+
+ it("calls setNextMeta on MetaAwareWallet with swap metadata", async () => {
+ mockFetch
+ .mockResolvedValueOnce({ ok: true, json: async () => MOCK_QUOTE })
+ .mockResolvedValueOnce({ ok: true, json: async () => ({ swapTransaction: MOCK_TX_BASE64 }) });
+
+ const w = makeMetaWallet();
+ await jupiterSwap(w, connection, {
+ inputMint: SOL_MINT,
+ outputMint: SOL_MINT,
+ amount: 1_000_000_000n,
+ inputSymbol: "SOL",
+ outputSymbol: "SOL",
+ });
+
+ expect(w.setNextMeta).toHaveBeenCalledTimes(1);
+ const meta = (w.setNextMeta as jest.Mock).mock.calls[0][0];
+ expect(meta.kind).toBe("swap");
+ expect(meta.amountIn).toBeDefined();
+ expect(meta.amountOut).toBeDefined();
+ });
+
+ it("does not throw when wallet does not implement setNextMeta", async () => {
+ mockFetch
+ .mockResolvedValueOnce({ ok: true, json: async () => MOCK_QUOTE })
+ .mockResolvedValueOnce({ ok: true, json: async () => ({ swapTransaction: MOCK_TX_BASE64 }) });
+
+ const w = makeWallet(); // no setNextMeta
+ await expect(
+ jupiterSwap(w, connection, {
+ inputMint: SOL_MINT,
+ outputMint: SOL_MINT,
+ amount: 1n,
+ }),
+ ).resolves.toBeDefined();
+ });
+});
diff --git a/solana-agent-sdk/tests/actions/transfer-sol.test.ts b/solana-agent-sdk/tests/actions/transfer-sol.test.ts
new file mode 100644
index 000000000..e7098a7b5
--- /dev/null
+++ b/solana-agent-sdk/tests/actions/transfer-sol.test.ts
@@ -0,0 +1,92 @@
+import {
+ Keypair,
+ LAMPORTS_PER_SOL,
+ PublicKey,
+ SystemInstruction,
+ SystemProgram,
+ type Connection,
+ type Transaction,
+ type VersionedTransaction,
+} from "@solana/web3.js";
+import { transferSol } from "../../src/actions/transfer-sol.js";
+import { buildAndSend } from "../../src/tx/build.js";
+import type { TxMetadata } from "../../src/wallet/types.js";
+
+jest.mock("../../src/tx/build.js", () => ({ buildAndSend: jest.fn() }));
+
+const mockBuildAndSend = jest.mocked(buildAndSend);
+
+// Deterministic test keys
+const WALLET_PUBKEY = Keypair.fromSeed(new Uint8Array(32).fill(1)).publicKey;
+const RECIPIENT_PUBKEY = Keypair.fromSeed(new Uint8Array(32).fill(2)).publicKey;
+
+const wallet = {
+ publicKey: WALLET_PUBKEY,
+ signTransaction: jest.fn(),
+ signAndSendTransaction: jest.fn(),
+};
+
+const connection = {} as unknown as Connection;
+
+beforeEach(() => {
+ jest.clearAllMocks();
+ mockBuildAndSend.mockResolvedValue("mockSig");
+});
+
+describe("transferSol", () => {
+ it("converts amount to correct lamports (0.5 SOL → 500_000_000)", async () => {
+ await transferSol(wallet, connection, { to: RECIPIENT_PUBKEY, amount: 0.5 });
+
+ const [, , instructions, opts] = mockBuildAndSend.mock.calls[0];
+ const ix = instructions[0];
+ const decoded = SystemInstruction.decodeTransfer(ix);
+ expect(Number(decoded.lamports)).toBe(0.5 * LAMPORTS_PER_SOL);
+ });
+
+ it("builds SystemProgram.transfer with correct pubkeys", async () => {
+ await transferSol(wallet, connection, { to: RECIPIENT_PUBKEY, amount: 1 });
+
+ const [, , instructions] = mockBuildAndSend.mock.calls[0];
+ const ix = instructions[0];
+ expect(ix.programId.equals(SystemProgram.programId)).toBe(true);
+
+ const decoded = SystemInstruction.decodeTransfer(ix);
+ expect(decoded.fromPubkey.equals(WALLET_PUBKEY)).toBe(true);
+ expect(decoded.toPubkey.equals(RECIPIENT_PUBKEY)).toBe(true);
+ });
+
+ it("auto-generates meta label containing amount and 'SOL'", async () => {
+ await transferSol(wallet, connection, { to: RECIPIENT_PUBKEY, amount: 2.5 });
+
+ const [, , , opts] = mockBuildAndSend.mock.calls[0];
+ expect(opts?.meta?.label).toContain("2.5");
+ expect(opts?.meta?.label).toContain("SOL");
+ });
+
+ it("auto-generated meta has kind 'transfer'", async () => {
+ await transferSol(wallet, connection, { to: RECIPIENT_PUBKEY, amount: 1 });
+
+ const [, , , opts] = mockBuildAndSend.mock.calls[0];
+ expect(opts?.meta?.kind).toBe("transfer");
+ });
+
+ it("accepts to as a base58 string", async () => {
+ const recipientStr = RECIPIENT_PUBKEY.toBase58();
+ await transferSol(wallet, connection, { to: recipientStr, amount: 1 });
+
+ const [, , instructions] = mockBuildAndSend.mock.calls[0];
+ const decoded = SystemInstruction.decodeTransfer(instructions[0]);
+ expect(decoded.toPubkey.equals(RECIPIENT_PUBKEY)).toBe(true);
+ });
+
+ it("uses provided opts.meta instead of auto-generating", async () => {
+ const customMeta: TxMetadata = {
+ label: "Custom label",
+ kind: "custom",
+ };
+ await transferSol(wallet, connection, { to: RECIPIENT_PUBKEY, amount: 1 }, { meta: customMeta });
+
+ const [, , , opts] = mockBuildAndSend.mock.calls[0];
+ expect(opts?.meta).toBe(customMeta);
+ });
+});
diff --git a/solana-agent-sdk/tests/actions/transfer-spl.test.ts b/solana-agent-sdk/tests/actions/transfer-spl.test.ts
new file mode 100644
index 000000000..111364bc2
--- /dev/null
+++ b/solana-agent-sdk/tests/actions/transfer-spl.test.ts
@@ -0,0 +1,147 @@
+import {
+ Keypair,
+ PublicKey,
+ type Connection,
+} from "@solana/web3.js";
+import {
+ getAssociatedTokenAddressSync,
+ getMint,
+ TOKEN_PROGRAM_ID,
+ ASSOCIATED_TOKEN_PROGRAM_ID,
+} from "@solana/spl-token";
+import { transferSpl } from "../../src/actions/transfer-spl.js";
+import { buildAndSend } from "../../src/tx/build.js";
+import { MissingTokenAccountError } from "../../src/errors.js";
+
+jest.mock("../../src/tx/build.js", () => ({ buildAndSend: jest.fn() }));
+
+jest.mock("@solana/spl-token", () => ({
+ ...jest.requireActual("@solana/spl-token"),
+ getMint: jest.fn(),
+}));
+
+const mockBuildAndSend = jest.mocked(buildAndSend);
+const mockGetMint = jest.mocked(getMint);
+
+// Deterministic test keys
+const WALLET_PUBKEY = Keypair.fromSeed(new Uint8Array(32).fill(1)).publicKey;
+const RECIPIENT_PUBKEY = Keypair.fromSeed(new Uint8Array(32).fill(2)).publicKey;
+const MINT_PUBKEY = Keypair.fromSeed(new Uint8Array(32).fill(3)).publicKey;
+
+const SENDER_ATA = getAssociatedTokenAddressSync(
+ MINT_PUBKEY, WALLET_PUBKEY, false, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID,
+);
+const RECEIVER_ATA = getAssociatedTokenAddressSync(
+ MINT_PUBKEY, RECIPIENT_PUBKEY, false, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID,
+);
+
+const DECIMALS = 6;
+const FAKE_ACCOUNT = { data: Buffer.alloc(0), executable: false, lamports: 1, owner: TOKEN_PROGRAM_ID } as any;
+
+function makeMockConnection(senderExists: boolean, receiverExists: boolean) {
+ return {
+ getAccountInfo: jest
+ .fn()
+ .mockImplementation(async (pubkey: PublicKey) => {
+ if (pubkey.equals(SENDER_ATA)) return senderExists ? FAKE_ACCOUNT : null;
+ if (pubkey.equals(RECEIVER_ATA)) return receiverExists ? FAKE_ACCOUNT : null;
+ return null;
+ }),
+ } as unknown as Connection;
+}
+
+beforeEach(() => {
+ jest.clearAllMocks();
+ mockBuildAndSend.mockResolvedValue("mockSig");
+ mockGetMint.mockResolvedValue({ decimals: DECIMALS, mintAuthority: null, supply: 0n, freezeAuthority: null, isInitialized: true } as any);
+});
+
+describe("transferSpl", () => {
+ it("adds createAssociatedTokenAccountInstruction when receiver ATA is missing", async () => {
+ const connection = makeMockConnection(true, false);
+ await transferSpl(wallet(WALLET_PUBKEY), connection, {
+ mint: MINT_PUBKEY,
+ to: RECIPIENT_PUBKEY,
+ amount: 1_000_000n,
+ });
+
+ const [, , instructions] = mockBuildAndSend.mock.calls[0];
+ expect(instructions).toHaveLength(2);
+ expect(instructions[0].programId.equals(ASSOCIATED_TOKEN_PROGRAM_ID)).toBe(true);
+ });
+
+ it("skips createAssociatedTokenAccountInstruction when receiver ATA exists", async () => {
+ const connection = makeMockConnection(true, true);
+ await transferSpl(wallet(WALLET_PUBKEY), connection, {
+ mint: MINT_PUBKEY,
+ to: RECIPIENT_PUBKEY,
+ amount: 1_000_000n,
+ });
+
+ const [, , instructions] = mockBuildAndSend.mock.calls[0];
+ expect(instructions).toHaveLength(1);
+ expect(instructions[0].programId.equals(TOKEN_PROGRAM_ID)).toBe(true);
+ });
+
+ it("throws MissingTokenAccountError when sender ATA is missing", async () => {
+ const connection = makeMockConnection(false, true);
+ await expect(
+ transferSpl(wallet(WALLET_PUBKEY), connection, {
+ mint: MINT_PUBKEY,
+ to: RECIPIENT_PUBKEY,
+ amount: 1_000_000n,
+ }),
+ ).rejects.toThrow(MissingTokenAccountError);
+ });
+
+ it("throws error message containing 'no token account' when sender ATA is missing", async () => {
+ const connection = makeMockConnection(false, true);
+ await expect(
+ transferSpl(wallet(WALLET_PUBKEY), connection, {
+ mint: MINT_PUBKEY,
+ to: RECIPIENT_PUBKEY,
+ amount: 1_000_000n,
+ }),
+ ).rejects.toThrow(/no token account/i);
+ });
+
+ it("builds TransferChecked instruction with correct keys", async () => {
+ const connection = makeMockConnection(true, true);
+ await transferSpl(wallet(WALLET_PUBKEY), connection, {
+ mint: MINT_PUBKEY,
+ to: RECIPIENT_PUBKEY,
+ amount: 1_000_000n,
+ });
+
+ const [, , instructions] = mockBuildAndSend.mock.calls[0];
+ const transferIx = instructions[0]; // only instruction (receiver exists)
+ // TransferChecked keys: source, mint, destination, authority
+ expect(transferIx.keys[0].pubkey.equals(SENDER_ATA)).toBe(true);
+ expect(transferIx.keys[1].pubkey.equals(MINT_PUBKEY)).toBe(true);
+ expect(transferIx.keys[2].pubkey.equals(RECEIVER_ATA)).toBe(true);
+ expect(transferIx.keys[3].pubkey.equals(WALLET_PUBKEY)).toBe(true);
+ });
+
+ it("computes uiAmount without BigInt precision loss for safe integers", async () => {
+ const connection = makeMockConnection(true, true);
+ // 1_500_000 base units at 6 decimals = 1.5
+ await transferSpl(wallet(WALLET_PUBKEY), connection, {
+ mint: MINT_PUBKEY,
+ to: RECIPIENT_PUBKEY,
+ amount: 1_500_000n,
+ symbol: "USDC",
+ });
+
+ const [, , , opts] = mockBuildAndSend.mock.calls[0];
+ expect(opts?.meta?.amountIn?.uiAmount).toBe("1.5");
+ });
+});
+
+// Helper to build a minimal WalletProvider mock
+function wallet(publicKey: PublicKey) {
+ return {
+ publicKey,
+ signTransaction: jest.fn(),
+ signAndSendTransaction: jest.fn(),
+ };
+}
diff --git a/solana-agent-sdk/tests/wallet/browser-client.test.ts b/solana-agent-sdk/tests/wallet/browser-client.test.ts
new file mode 100644
index 000000000..991a840a0
--- /dev/null
+++ b/solana-agent-sdk/tests/wallet/browser-client.test.ts
@@ -0,0 +1,153 @@
+import { Keypair, Transaction, VersionedTransaction } from "@solana/web3.js";
+import { BrowserWalletClient } from "../../src/wallet/browser-client.js";
+
+const baseUrl = "http://localhost:3000/api/wallet";
+
+// Flush all pending microtasks and macro-tasks in the queue.
+const flushPromises = () => new Promise<void>((resolve) => setImmediate(resolve));
+
+type MockEsInstance = {
+ onmessage: ((e: { data: string }) => void) | null;
+ onerror: (() => void) | null;
+ close: jest.Mock;
+};
+
+describe("BrowserWalletClient", () => {
+ let mockEs: MockEsInstance;
+
+ beforeEach(() => {
+ mockEs = { onmessage: null, onerror: null, close: jest.fn() };
+ (global as Record<string, unknown>)["EventSource"] = jest
+ .fn()
+ .mockImplementation(() => mockEs);
+ (global as Record<string, unknown>)["fetch"] = jest.fn().mockResolvedValue({
+ ok: true,
+ json: jest.fn().mockResolvedValue({ signature: "abc" }),
+ });
+ });
+
+ afterEach(() => {
+ jest.clearAllMocks();
+ jest.useRealTimers();
+ });
+
+ // Build a pending-tx payload with a real serialized Transaction.
+ function makePending() {
+ const kp = Keypair.generate();
+ const tx = new Transaction();
+ tx.recentBlockhash = "11111111111111111111111111111111";
+ tx.feePayer = kp.publicKey;
+ const b64 = Buffer.from(tx.serialize({ requireAllSignatures: false })).toString("base64");
+ const signer = jest.fn().mockImplementation(
+ async (decoded: Transaction | VersionedTransaction) => {
+ if (decoded instanceof Transaction) decoded.sign(kp);
+ return decoded;
+ },
+ );
+ return {
+ pending: { id: "tx-001", transaction: b64, versioned: false, createdAt: Date.now() },
+ signer,
+ };
+ }
+
+ it("connect() opens EventSource at baseUrl + '/stream'", () => {
+ const client = new BrowserWalletClient(baseUrl, jest.fn());
+ client.connect();
+ expect(
+ (global as Record<string, unknown>)["EventSource"] as jest.Mock,
+ ).toHaveBeenCalledWith(`${baseUrl}/stream`);
+ });
+
+ it("disconnect() closes the EventSource", () => {
+ const client = new BrowserWalletClient(baseUrl, jest.fn());
+ client.connect();
+ client.disconnect();
+ expect(mockEs.close).toHaveBeenCalled();
+ });
+
+ it("onmessage triggers the signer", async () => {
+ const { pending, signer } = makePending();
+ const client = new BrowserWalletClient(baseUrl, signer);
+ client.connect();
+
+ mockEs.onmessage!({ data: JSON.stringify(pending) });
+ await flushPromises();
+
+ expect(signer).toHaveBeenCalledTimes(1);
+ });
+
+ it("auto-signs without onApproval: signer is called immediately", async () => {
+ const { pending, signer } = makePending();
+ const client = new BrowserWalletClient(baseUrl, signer);
+ client.connect();
+
+ mockEs.onmessage!({ data: JSON.stringify(pending) });
+ await flushPromises();
+
+ expect(signer).toHaveBeenCalled();
+ });
+
+ it("onApproval blocks signing until approve() is called", async () => {
+ const { pending, signer } = makePending();
+ let doApprove!: () => void;
+ const client = new BrowserWalletClient(baseUrl, signer, {
+ onApproval: (_p, approve) => { doApprove = approve; },
+ });
+ client.connect();
+
+ mockEs.onmessage!({ data: JSON.stringify(pending) });
+ await flushPromises();
+ expect(signer).not.toHaveBeenCalled();
+
+ doApprove();
+ await flushPromises();
+ expect(signer).toHaveBeenCalled();
+ });
+
+ it("onApproval reject path: calls /reject/:id endpoint, signer not called", async () => {
+ const { pending, signer } = makePending();
+ let doReject!: () => void;
+ const client = new BrowserWalletClient(baseUrl, signer, {
+ onApproval: (_p, _approve, reject) => { doReject = reject; },
+ });
+ client.connect();
+
+ mockEs.onmessage!({ data: JSON.stringify(pending) });
+ doReject();
+ await flushPromises();
+
+ expect(
+ (global as Record<string, unknown>)["fetch"] as jest.Mock,
+ ).toHaveBeenCalledWith(`${baseUrl}/reject/${pending.id}`, { method: "POST" });
+ expect(signer).not.toHaveBeenCalled();
+ });
+
+ it("onConfirmed fires when the sign POST returns a signature", async () => {
+ const { pending, signer } = makePending();
+ const onConfirmed = jest.fn();
+ const client = new BrowserWalletClient(baseUrl, signer, { onConfirmed });
+ client.connect();
+
+ mockEs.onmessage!({ data: JSON.stringify(pending) });
+ await flushPromises();
+
+ expect(onConfirmed).toHaveBeenCalledWith(
+ expect.objectContaining({ id: pending.id }),
+ "abc",
+ );
+ });
+
+ it("reconnects on error: new EventSource created after reconnectMs", () => {
+ jest.useFakeTimers();
+ const client = new BrowserWalletClient(baseUrl, jest.fn(), { reconnectMs: 100 });
+ client.connect();
+
+ const EventSourceMock = (global as Record<string, unknown>)["EventSource"] as jest.Mock;
+ expect(EventSourceMock).toHaveBeenCalledTimes(1);
+
+ mockEs.onerror!();
+ jest.advanceTimersByTime(100);
+
+ expect(EventSourceMock).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/solana-agent-sdk/tests/wallet/browser-server.test.ts b/solana-agent-sdk/tests/wallet/browser-server.test.ts
new file mode 100644
index 000000000..c62d0394e
--- /dev/null
+++ b/solana-agent-sdk/tests/wallet/browser-server.test.ts
@@ -0,0 +1,130 @@
+import { Keypair, Transaction } from "@solana/web3.js";
+import { BrowserWalletProvider } from "../../src/wallet/browser-server.js";
+
+describe("BrowserWalletProvider", () => {
+ const keypair = Keypair.generate();
+
+ function makeSerializedTx(feePayer = keypair.publicKey): string {
+ const tx = new Transaction();
+ tx.recentBlockhash = "11111111111111111111111111111111";
+ tx.feePayer = feePayer;
+ return Buffer.from(tx.serialize({ requireAllSignatures: false })).toString("base64");
+ }
+
+ function makeTx(feePayer = keypair.publicKey): Transaction {
+ const tx = new Transaction();
+ tx.recentBlockhash = "11111111111111111111111111111111";
+ tx.feePayer = feePayer;
+ return tx;
+ }
+
+ afterEach(() => {
+ jest.useRealTimers();
+ });
+
+ it("constructor defaults: sessionId is a UUID, publicKey is set", () => {
+ const provider = new BrowserWalletProvider({ publicKey: keypair.publicKey });
+ expect(provider.sessionId).toMatch(
+ /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,
+ );
+ expect(provider.publicKey.toBase58()).toBe(keypair.publicKey.toBase58());
+ });
+
+ it("accepts a base58 string publicKey", () => {
+ const provider = new BrowserWalletProvider({ publicKey: keypair.publicKey.toBase58() });
+ expect(provider.publicKey.toBase58()).toBe(keypair.publicKey.toBase58());
+ });
+
+ it("setNextMeta attaches meta to the next pending tx", async () => {
+ const provider = new BrowserWalletProvider({ publicKey: keypair.publicKey });
+ const meta = { label: "Swap SOL → USDC", kind: "swap" as const };
+ provider.setNextMeta(meta);
+
+ const signPromise = provider.signTransaction(makeTx());
+ const [entry] = provider.getPending();
+ expect(entry?.meta).toEqual(meta);
+
+ provider.submitSigned(entry!.id, makeSerializedTx());
+ await signPromise;
+ });
+
+ it("signTransaction creates a pending entry", async () => {
+ const provider = new BrowserWalletProvider({ publicKey: keypair.publicKey });
+
+ const signPromise = provider.signTransaction(makeTx());
+ expect(provider.getPending()).toHaveLength(1);
+
+ const [entry] = provider.getPending();
+ provider.submitSigned(entry!.id, makeSerializedTx());
+ await signPromise;
+ });
+
+ it("pending entry has correct fields", async () => {
+ const provider = new BrowserWalletProvider({ publicKey: keypair.publicKey });
+
+ const signPromise = provider.signTransaction(makeTx());
+ const [entry] = provider.getPending();
+
+ expect(entry).toMatchObject({
+ id: expect.stringMatching(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/),
+ transaction: expect.any(String),
+ versioned: false,
+ createdAt: expect.any(Number),
+ });
+ expect(entry?.meta).toBeUndefined();
+
+ provider.submitSigned(entry!.id, makeSerializedTx());
+ await signPromise;
+ });
+
+ it("submitSigned resolves the signTransaction promise", async () => {
+ const provider = new BrowserWalletProvider({ publicKey: keypair.publicKey });
+
+ const signPromise = provider.signTransaction(makeTx());
+ const [entry] = provider.getPending();
+ provider.submitSigned(entry!.id, makeSerializedTx());
+
+ const result = await signPromise;
+ expect(result).toBeInstanceOf(Transaction);
+ });
+
+ it("submitRejected rejects the promise with 'rejected'", async () => {
+ const provider = new BrowserWalletProvider({ publicKey: keypair.publicKey });
+
+ const signPromise = provider.signTransaction(makeTx());
+ const [entry] = provider.getPending();
+ provider.submitRejected(entry!.id);
+
+ await expect(signPromise).rejects.toThrow(/rejected/i);
+ });
+
+ it("timeout rejects the promise with 'timed out' after timeoutMs", async () => {
+ jest.useFakeTimers();
+ const provider = new BrowserWalletProvider({ publicKey: keypair.publicKey, timeoutMs: 50 });
+
+ const signPromise = provider.signTransaction(makeTx());
+ jest.advanceTimersByTime(50);
+
+ await expect(signPromise).rejects.toThrow(/timed out/i);
+ });
+
+ it("nextMeta is consumed after one signTransaction call", async () => {
+ const provider = new BrowserWalletProvider({ publicKey: keypair.publicKey });
+ const meta = { label: "Send 1 SOL", kind: "transfer" as const };
+ provider.setNextMeta(meta);
+
+ // First call — meta should be present
+ const p1 = provider.signTransaction(makeTx());
+ const [e1] = provider.getPending();
+ expect(e1?.meta).toEqual(meta);
+ provider.submitSigned(e1!.id, makeSerializedTx());
+ await p1;
+
+ // Second call — meta should be cleared
+ const p2 = provider.signTransaction(makeTx());
+ const [e2] = provider.getPending();
+ expect(e2?.meta).toBeUndefined();
+ provider.submitSigned(e2!.id, makeSerializedTx());
+ await p2;
+ });
+});
diff --git a/solana-agent-sdk/tests/wallet/keypair.test.ts b/solana-agent-sdk/tests/wallet/keypair.test.ts
new file mode 100644
index 000000000..8bf1d8128
--- /dev/null
+++ b/solana-agent-sdk/tests/wallet/keypair.test.ts
@@ -0,0 +1,77 @@
+import {
+ Keypair,
+ Transaction,
+ VersionedTransaction,
+ TransactionMessage,
+ sendAndConfirmTransaction,
+} from "@solana/web3.js";
+import bs58 from "bs58";
+import { KeypairWalletProvider } from "../../src/wallet/keypair.js";
+
+jest.mock("@solana/web3.js", () => ({
+ ...jest.requireActual("@solana/web3.js"),
+ sendAndConfirmTransaction: jest.fn().mockResolvedValue("fakeSig"),
+}));
+
+describe("KeypairWalletProvider", () => {
+ const keypair = Keypair.generate();
+
+ it("base58 string constructor sets correct publicKey", () => {
+ const bs58Key = bs58.encode(keypair.secretKey);
+ const provider = new KeypairWalletProvider(bs58Key);
+ expect(provider.publicKey.toBase58()).toBe(keypair.publicKey.toBase58());
+ });
+
+ it("Uint8Array constructor sets correct publicKey", () => {
+ const provider = new KeypairWalletProvider(keypair.secretKey);
+ expect(provider.publicKey.toBase58()).toBe(keypair.publicKey.toBase58());
+ });
+
+ it("Array constructor sets correct publicKey", () => {
+ const provider = new KeypairWalletProvider(Array.from(keypair.secretKey));
+ expect(provider.publicKey.toBase58()).toBe(keypair.publicKey.toBase58());
+ });
+
+ it("signTransaction (legacy) produces a valid signature for the keypair", async () => {
+ const provider = new KeypairWalletProvider(keypair.secretKey);
+ const tx = new Transaction();
+ tx.recentBlockhash = "11111111111111111111111111111111";
+ tx.feePayer = keypair.publicKey;
+
+ const signed = await provider.signTransaction(tx);
+ const sig = signed.signature;
+ expect(sig).not.toBeNull();
+ expect(sig!.some((b) => b !== 0)).toBe(true);
+ });
+
+ it("signTransaction (versioned) produces non-empty signatures", async () => {
+ const provider = new KeypairWalletProvider(keypair.secretKey);
+ const message = new TransactionMessage({
+ payerKey: keypair.publicKey,
+ recentBlockhash: "11111111111111111111111111111111",
+ instructions: [],
+ }).compileToV0Message();
+ const vtx = new VersionedTransaction(message);
+
+ const signed = await provider.signTransaction(vtx);
+ expect(signed.signatures.length).toBeGreaterThan(0);
+ expect(signed.signatures[0]!.some((b) => b !== 0)).toBe(true);
+ });
+
+ it("signAndSendTransaction calls sendAndConfirmTransaction with the keypair", async () => {
+ const provider = new KeypairWalletProvider(keypair.secretKey);
+ const tx = new Transaction();
+ tx.recentBlockhash = "11111111111111111111111111111111";
+ tx.feePayer = keypair.publicKey;
+ const connection = {} as Parameters<typeof sendAndConfirmTransaction>[0];
+
+ const result = await provider.signAndSendTransaction(tx, connection);
+
+ expect(result).toBe("fakeSig");
+ expect(sendAndConfirmTransaction).toHaveBeenCalledWith(
+ connection,
+ tx,
+ expect.any(Array),
+ );
+ });
+});
diff --git a/solana-agent-sdk/tsconfig.test.json b/solana-agent-sdk/tsconfig.test.json
new file mode 100644
index 000000000..b62953dc4
--- /dev/null
+++ b/solana-agent-sdk/tsconfig.test.json
@@ -0,0 +1,10 @@
+{
+ "extends": "./tsconfig.json",
+ "compilerOptions": {
+ "rootDir": ".",
+ "noUnusedLocals": false,
+ "noUnusedParameters": false,
+ "noUncheckedIndexedAccess": false
+ },
+ "include": ["src/**/*", "tests/**/*"]
+}
diff --git a/solana-agent-sdk/tsup.config.ts b/solana-agent-sdk/tsup.config.ts
index 5e0e83c0d..7931d3b2f 100644
--- a/solana-agent-sdk/tsup.config.ts
+++ b/solana-agent-sdk/tsup.config.ts
@@ -9,7 +9,7 @@ export default defineConfig({
"src/solana-agent-kit/index.ts",
],
format: ["cjs", "esm"],
- dts: true,
+ dts: { compilerOptions: { noUnusedLocals: false, noUnusedParameters: false } },
clean: true,
sourcemap: true,
splitting: false,
diff --git a/src/agent-resolver.js b/src/agent-resolver.js
index 5215a3309..ddef32831 100644
--- a/src/agent-resolver.js
+++ b/src/agent-resolver.js
@@ -152,7 +152,17 @@ export async function resolveAgentById(
},
body: { uri: avatar.url, format: 'gltf-binary' },
brain: {},
- voice: { tts: { provider: 'browser' }, stt: { provider: 'browser' } },
+ voice: {
+ tts:
+ agent.voice_id && agent.voice_provider === 'elevenlabs'
+ ? {
+ provider: 'elevenlabs',
+ voiceId: agent.voice_id,
+ proxyURL: `${origin}/api/tts/eleven`,
+ }
+ : { provider: 'browser' },
+ stt: { provider: 'browser' },
+ },
skills,
memory: { mode: 'remote', namespace: agent.id },
tools: ['wave', 'lookAt', 'play_clip', 'setExpression', 'speak', 'remember'],
diff --git a/src/editor/voice-recorder.js b/src/editor/voice-recorder.js
new file mode 100644
index 000000000..907688365
--- /dev/null
+++ b/src/editor/voice-recorder.js
@@ -0,0 +1,378 @@
+// VoiceRecorder — inline editor section for recording and cloning an agent's voice.
+//
+// Usage:
+// const recorder = new VoiceRecorder(containerEl, { agentId: '...', agentName: '...' });
+// recorder.mount(); // renders into containerEl
+// recorder.destroy(); // removes listeners + DOM
+
+const MIN_DURATION = 30; // seconds — warn if below this
+const SAMPLE_TEXT = "Hello, I'm your agent. How can I help you today?";
+
+const CSS = `
+.vr-section {
+ font-family: system-ui, -apple-system, sans-serif;
+ color: #f9fafb;
+ background: rgba(17, 24, 39, 0.85);
+ border: 1px solid rgba(255,255,255,0.1);
+ border-radius: 12px;
+ padding: 16px 20px;
+ margin: 12px 0;
+}
+.vr-section h3 {
+ margin: 0 0 4px;
+ font-size: 14px;
+ font-weight: 600;
+ letter-spacing: 0.02em;
+}
+.vr-section .vr-sub {
+ margin: 0 0 14px;
+ font-size: 12px;
+ opacity: 0.55;
+}
+.vr-controls {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ flex-wrap: wrap;
+}
+.vr-btn {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ padding: 8px 16px;
+ border: 0;
+ border-radius: 8px;
+ font: 600 13px system-ui, sans-serif;
+ cursor: pointer;
+ transition: opacity 0.12s;
+}
+.vr-btn:disabled { opacity: 0.4; cursor: default; }
+.vr-btn:not(:disabled):hover { opacity: 0.85; }
+.vr-btn.primary { background: #3b82f6; color: #fff; }
+.vr-btn.danger { background: #ef4444; color: #fff; }
+.vr-btn.ghost { background: rgba(255,255,255,0.08); color: #f9fafb; border: 1px solid rgba(255,255,255,0.15); }
+.vr-timer {
+ font: 600 16px/1 'SF Mono', 'Fira Mono', monospace;
+ color: #f9fafb;
+ min-width: 52px;
+ display: none;
+}
+.vr-timer.active { display: block; }
+.vr-timer.warn { color: #f59e0b; }
+.vr-status {
+ font-size: 12px;
+ margin-top: 10px;
+ min-height: 18px;
+ display: flex;
+ align-items: center;
+ gap: 6px;
+}
+.vr-status .spin {
+ width: 12px; height: 12px;
+ border-radius: 50%;
+ border: 2px solid rgba(255,255,255,0.2);
+ border-top-color: #3b82f6;
+ animation: vr-spin 0.9s linear infinite;
+ flex-shrink: 0;
+}
+@keyframes vr-spin { to { transform: rotate(360deg); } }
+.vr-status.ok { color: #4ade80; }
+.vr-status.err { color: #f87171; }
+.vr-status.info { color: #94a3b8; }
+.vr-current {
+ font-size: 12px;
+ margin-top: 10px;
+ padding: 8px 12px;
+ background: rgba(59,130,246,0.12);
+ border: 1px solid rgba(59,130,246,0.3);
+ border-radius: 8px;
+ display: none;
+}
+.vr-current.visible { display: block; }
+.vr-current .label { opacity: 0.55; font-size: 11px; text-transform: uppercase; letter-spacing: 0.05em; }
+`;
+
+export class VoiceRecorder {
+ constructor(containerEl, { agentId, agentName = 'Agent' } = {}) {
+ this._container = containerEl;
+ this._agentId = agentId;
+ this._agentName = agentName;
+
+ this._recorder = null;
+ this._chunks = [];
+ this._recording = false;
+ this._startTime = 0;
+ this._timerRaf = null;
+
+ // Current cloned state (fetched on mount)
+ this._voiceId = null;
+ this._voiceProvider = 'browser';
+
+ // DOM refs (set after mount)
+ this._el = null;
+ this._btnRecord = null;
+ this._btnStop = null;
+ this._btnRemove = null;
+ this._btnPlay = null;
+ this._timerEl = null;
+ this._statusEl = null;
+ this._currentEl = null;
+ }
+
+ async mount() {
+ this._injectStyle();
+ this._el = document.createElement('div');
+ this._el.className = 'vr-section';
+ this._el.innerHTML = `
+ <h3>Voice Clone</h3>
+ <p class="vr-sub">Record 30–60 seconds of speech to give this agent a unique voice.</p>
+ <div class="vr-controls">
+ <button class="vr-btn primary" data-ref="record">Record</button>
+ <button class="vr-btn danger" data-ref="stop" disabled>Stop &amp; Clone</button>
+ <span class="vr-timer" data-ref="timer">0:00</span>
+ </div>
+ <div class="vr-current" data-ref="current">
+ <div class="label">Current voice</div>
+ <div data-ref="currentLabel"></div>
+ </div>
+ <div class="vr-status info" data-ref="status"></div>
+ `;
+ this._container.appendChild(this._el);
+
+ this._btnRecord = this._el.querySelector('[data-ref="record"]');
+ this._btnStop = this._el.querySelector('[data-ref="stop"]');
+ this._timerEl = this._el.querySelector('[data-ref="timer"]');
+ this._statusEl = this._el.querySelector('[data-ref="status"]');
+ this._currentEl = this._el.querySelector('[data-ref="current"]');
+ this._currentLabelEl = this._el.querySelector('[data-ref="currentLabel"]');
+
+ this._btnRecord.addEventListener('click', () => this._startRecording());
+ this._btnStop.addEventListener('click', () => this._stopAndClone());
+
+ await this._fetchStatus();
+ }
+
+ destroy() {
+ this._stopTimer();
+ if (this._recorder && this._recording) {
+ try { this._recorder.stop(); } catch {}
+ }
+ this._el?.remove();
+ this._el = null;
+ }
+
+ // ── Private ──────────────────────────────────────────────────────────────
+
+ _injectStyle() {
+ const id = 'vr-styles';
+ if (!document.getElementById(id)) {
+ const s = document.createElement('style');
+ s.id = id;
+ s.textContent = CSS;
+ document.head.appendChild(s);
+ }
+ }
+
+ async _fetchStatus() {
+ if (!this._agentId) return;
+ try {
+ const res = await fetch(`/api/agents/${this._agentId}/voice`, { credentials: 'include' });
+ if (!res.ok) return;
+ const data = await res.json();
+ this._voiceId = data.voice_id;
+ this._voiceProvider = data.voice_provider;
+ this._renderCurrentVoice();
+ } catch {}
+ }
+
+ _renderCurrentVoice() {
+ if (this._voiceId && this._voiceProvider === 'elevenlabs') {
+ this._currentEl.classList.add('visible');
+ this._currentLabelEl.innerHTML = `
+ Cloned voice (ElevenLabs)
+ <button class="vr-btn ghost" style="margin-left:8px;padding:4px 10px;font-size:11px" data-ref="play">Play sample</button>
+ <button class="vr-btn danger" style="margin-left:6px;padding:4px 10px;font-size:11px" data-ref="remove">Remove</button>
+ `;
+ this._currentLabelEl.querySelector('[data-ref="play"]')
+ ?.addEventListener('click', () => this._playSample());
+ this._currentLabelEl.querySelector('[data-ref="remove"]')
+ ?.addEventListener('click', () => this._removeVoice());
+ } else {
+ this._currentEl.classList.remove('visible');
+ }
+ }
+
+ async _startRecording() {
+ let stream;
+ try {
+ stream = await navigator.mediaDevices.getUserMedia({ audio: true });
+ } catch {
+ this._setStatus('err', 'Microphone access denied.');
+ return;
+ }
+
+ this._chunks = [];
+ const mimeType = MediaRecorder.isTypeSupported('audio/webm;codecs=opus')
+ ? 'audio/webm;codecs=opus'
+ : MediaRecorder.isTypeSupported('audio/webm')
+ ? 'audio/webm'
+ : '';
+
+ this._recorder = mimeType
+ ? new MediaRecorder(stream, { mimeType })
+ : new MediaRecorder(stream);
+
+ this._recorder.ondataavailable = (e) => {
+ if (e.data.size > 0) this._chunks.push(e.data);
+ };
+
+ this._recorder.start(250); // collect in 250ms chunks
+ this._recording = true;
+ this._startTime = Date.now();
+
+ this._btnRecord.disabled = true;
+ this._btnStop.disabled = false;
+ this._timerEl.classList.add('active');
+ this._setStatus('info', 'Recording… speak naturally for 30–60 seconds.');
+ this._startTimer();
+ }
+
+ _startTimer() {
+ const tick = () => {
+ if (!this._recording) return;
+ const elapsed = (Date.now() - this._startTime) / 1000;
+ const m = Math.floor(elapsed / 60);
+ const s = Math.floor(elapsed % 60);
+ this._timerEl.textContent = `${m}:${s.toString().padStart(2, '0')}`;
+ this._timerEl.classList.toggle('warn', elapsed < MIN_DURATION);
+ this._timerRaf = requestAnimationFrame(tick);
+ };
+ this._timerRaf = requestAnimationFrame(tick);
+ }
+
+ _stopTimer() {
+ if (this._timerRaf) {
+ cancelAnimationFrame(this._timerRaf);
+ this._timerRaf = null;
+ }
+ }
+
+ async _stopAndClone() {
+ if (!this._recorder || !this._recording) return;
+
+ const durationSec = (Date.now() - this._startTime) / 1000;
+ this._recording = false;
+ this._stopTimer();
+
+ await new Promise((resolve) => {
+ this._recorder.onstop = resolve;
+ this._recorder.stop();
+ // Stop microphone tracks
+ this._recorder.stream?.getTracks().forEach((t) => t.stop());
+ });
+
+ this._btnRecord.disabled = false;
+ this._btnStop.disabled = true;
+ this._timerEl.classList.remove('active', 'warn');
+
+ if (durationSec < MIN_DURATION) {
+ this._setStatus('err', `Recording too short (${Math.round(durationSec)}s). Please record at least 30 seconds.`);
+ return;
+ }
+
+ const mimeType = this._recorder.mimeType || 'audio/webm';
+ const blob = new Blob(this._chunks, { type: mimeType });
+
+ this._setStatus('spin', 'Cloning voice…');
+ this._btnRecord.disabled = true;
+
+ try {
+ const url =
+ `/api/agents/${this._agentId}/voice/clone` +
+ `?name=${encodeURIComponent(this._agentName + ' Voice')}`;
+
+ const res = await fetch(url, {
+ method: 'POST',
+ credentials: 'include',
+ headers: {
+ 'content-type': mimeType,
+ 'x-recording-duration': String(Math.round(durationSec)),
+ },
+ body: blob,
+ });
+
+ if (!res.ok) {
+ const err = await res.json().catch(() => ({}));
+ const msg = err.error_description || `Error ${res.status}`;
+ this._setStatus('err', msg);
+ this._btnRecord.disabled = false;
+ return;
+ }
+
+ const data = await res.json();
+ this._voiceId = data.voice_id;
+ this._voiceProvider = 'elevenlabs';
+ this._setStatus('ok', 'Voice cloned successfully.');
+ this._renderCurrentVoice();
+ } catch {
+ this._setStatus('err', 'Clone failed. Check your connection and try again.');
+ } finally {
+ this._btnRecord.disabled = false;
+ }
+ }
+
+ async _playSample() {
+ if (!this._voiceId) return;
+ this._setStatus('spin', 'Generating sample…');
+ try {
+ const res = await fetch('/api/tts/eleven', {
+ method: 'POST',
+ credentials: 'include',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ voiceId: this._voiceId, text: SAMPLE_TEXT }),
+ });
+ if (!res.ok) {
+ this._setStatus('err', 'Could not generate sample.');
+ return;
+ }
+ const blob = await res.blob();
+ const audio = new Audio(URL.createObjectURL(blob));
+ audio.onended = () => URL.revokeObjectURL(audio.src);
+ audio.play();
+ this._setStatus('ok', 'Playing sample…');
+ } catch {
+ this._setStatus('err', 'Playback failed.');
+ }
+ }
+
+ async _removeVoice() {
+ if (!confirm('Remove this agent\'s cloned voice? It will revert to browser TTS.')) return;
+ this._setStatus('spin', 'Removing voice…');
+ try {
+ const res = await fetch(`/api/agents/${this._agentId}/voice`, {
+ method: 'DELETE',
+ credentials: 'include',
+ });
+ if (!res.ok) {
+ this._setStatus('err', 'Could not remove voice.');
+ return;
+ }
+ this._voiceId = null;
+ this._voiceProvider = 'browser';
+ this._renderCurrentVoice();
+ this._setStatus('info', 'Voice removed. Agent will use browser TTS.');
+ } catch {
+ this._setStatus('err', 'Remove failed.');
+ }
+ }
+
+ _setStatus(type, text) {
+ if (!this._statusEl) return;
+ this._statusEl.className = `vr-status ${type}`;
+ if (type === 'spin') {
+ this._statusEl.innerHTML = `<span class="spin"></span>${text}`;
+ } else {
+ this._statusEl.textContent = text;
+ }
+ }
+}
diff --git a/tests/api/agent-memory.test.js b/tests/api/agent-memory.test.js
new file mode 100644
index 000000000..35567a8ef
--- /dev/null
+++ b/tests/api/agent-memory.test.js
@@ -0,0 +1,454 @@
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+
+// ── Mocks ─────────────────────────────────────────────────────────────────
+
+const sqlMock = vi.fn();
+vi.mock('../../api/_lib/db.js', () => ({ sql: sqlMock }));
+
+const getSessionUserMock = vi.fn();
+const authenticateBearerMock = vi.fn();
+const extractBearerMock = vi.fn();
+vi.mock('../../api/_lib/auth.js', () => ({
+ getSessionUser: (...a) => getSessionUserMock(...a),
+ authenticateBearer: (...a) => authenticateBearerMock(...a),
+ extractBearer: (...a) => extractBearerMock(...a),
+}));
+
+vi.mock('../../api/_lib/env.js', () => ({
+ env: {
+ APP_ORIGIN: 'http://localhost:3000',
+ ISSUER: 'http://test',
+ MCP_RESOURCE: 'http://test',
+ },
+}));
+
+const { default: handler } = await import('../../api/agent-memory.js');
+
+// ── Helpers ───────────────────────────────────────────────────────────────
+
+function mkReq({ method = 'GET', url = '/api/agent-memory', headers = {}, body = null } = {}) {
+ const req = {
+ method,
+ url,
+ headers: { ...headers },
+ on(event, cb) {
+ if (event === 'data' && body != null) {
+ const buf = Buffer.from(typeof body === 'string' ? body : JSON.stringify(body));
+ queueMicrotask(() => {
+ cb(buf);
+ this._endCb?.();
+ });
+ } else if (event === 'end') {
+ this._endCb = cb;
+ if (body == null) queueMicrotask(() => cb());
+ } else if (event === 'error') {
+ // no-op
+ }
+ },
+ destroy() {},
+ };
+ return req;
+}
+
+function mkRes() {
+ return {
+ statusCode: 200,
+ headers: {},
+ body: undefined,
+ writableEnded: false,
+ setHeader(k, v) {
+ this.headers[k.toLowerCase()] = v;
+ },
+ end(b) {
+ this.body = b;
+ this.writableEnded = true;
+ },
+ };
+}
+
+function parse(res) {
+ return res.body ? JSON.parse(res.body) : undefined;
+}
+
+// Queue sql results FIFO. Each sql`...` call consumes one.
+let sqlQueue = [];
+function queueSql(...results) {
+ sqlQueue.push(...results);
+}
+
+async function invoke(reqOpts) {
+ const req = mkReq(reqOpts);
+ const res = mkRes();
+ await handler(req, res);
+ return { res, status: res.statusCode, body: parse(res) };
+}
+
+// ── Reset ─────────────────────────────────────────────────────────────────
+
+beforeEach(() => {
+ sqlQueue = [];
+ sqlMock.mockReset();
+ sqlMock.mockImplementation(() => {
+ if (sqlQueue.length === 0) throw new Error('unexpected sql call — queue is empty');
+ return Promise.resolve(sqlQueue.shift());
+ });
+ getSessionUserMock.mockReset().mockResolvedValue(null);
+ authenticateBearerMock.mockReset().mockResolvedValue(null);
+ extractBearerMock.mockReset().mockReturnValue(null);
+});
+
+// ── Auth ──────────────────────────────────────────────────────────────────
+
+describe('auth', () => {
+ it('GET without session or bearer returns 401', async () => {
+ const { status, body } = await invoke({ method: 'GET', url: '/api/agent-memory?agentId=a1' });
+ expect(status).toBe(401);
+ expect(body.error).toBe('unauthorized');
+ });
+
+ it('POST without auth returns 401', async () => {
+ const { status } = await invoke({
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: { agentId: 'a1', entry: { content: 'x' } },
+ });
+ expect(status).toBe(401);
+ });
+
+ it('DELETE without auth returns 401', async () => {
+ const { status } = await invoke({ method: 'DELETE', url: '/api/agent-memory/mem-1' });
+ expect(status).toBe(401);
+ });
+
+ it('accepts bearer token when session is absent', async () => {
+ extractBearerMock.mockReturnValue('tok');
+ authenticateBearerMock.mockResolvedValue({ userId: 'u1' });
+ queueSql([{ user_id: 'u1' }], []); // ownership row, then memory rows
+
+ const { status, body } = await invoke({
+ method: 'GET',
+ url: '/api/agent-memory?agentId=a1',
+ });
+ expect(status).toBe(200);
+ expect(body.entries).toEqual([]);
+ });
+});
+
+// ── GET (list) ────────────────────────────────────────────────────────────
+
+describe('GET /api/agent-memory', () => {
+ beforeEach(() => {
+ getSessionUserMock.mockResolvedValue({ id: 'u1' });
+ });
+
+ it('returns entries for the authenticated agent owner', async () => {
+ const createdAt = new Date('2024-06-01T00:00:00Z');
+ queueSql(
+ [{ user_id: 'u1' }],
+ [
+ {
+ id: 'm1',
+ agent_id: 'a1',
+ type: 'project',
+ content: 'test note',
+ tags: ['alpha'],
+ context: { k: 1 },
+ salience: 0.8,
+ created_at: createdAt,
+ expires_at: null,
+ },
+ ],
+ );
+
+ const { status, body } = await invoke({
+ method: 'GET',
+ url: '/api/agent-memory?agentId=a1',
+ });
+
+ expect(status).toBe(200);
+ expect(body.entries).toHaveLength(1);
+ expect(body.entries[0]).toMatchObject({
+ id: 'm1',
+ agent_id: 'a1',
+ type: 'project',
+ content: 'test note',
+ tags: ['alpha'],
+ salience: 0.8,
+ createdAt: createdAt.getTime(),
+ expiresAt: null,
+ });
+ });
+
+ it('returns 400 when agentId is missing', async () => {
+ const { status, body } = await invoke({ method: 'GET', url: '/api/agent-memory' });
+ expect(status).toBe(400);
+ expect(body.error).toBe('validation_error');
+ });
+
+ it('returns 404 when agent does not exist', async () => {
+ queueSql([]); // no ownership row
+ const { status } = await invoke({ method: 'GET', url: '/api/agent-memory?agentId=nope' });
+ expect(status).toBe(404);
+ });
+
+ it('returns 403 when agent is owned by another user', async () => {
+ queueSql([{ user_id: 'other-user' }]);
+ const { status, body } = await invoke({
+ method: 'GET',
+ url: '/api/agent-memory?agentId=a1',
+ });
+ expect(status).toBe(403);
+ expect(body.error).toBe('forbidden');
+ });
+
+ it('handles null tags/context with safe defaults in response', async () => {
+ queueSql(
+ [{ user_id: 'u1' }],
+ [
+ {
+ id: 'm2',
+ agent_id: 'a1',
+ type: 'user',
+ content: '',
+ tags: null,
+ context: null,
+ salience: 0.5,
+ created_at: new Date(),
+ expires_at: null,
+ },
+ ],
+ );
+ const { body } = await invoke({ method: 'GET', url: '/api/agent-memory?agentId=a1' });
+ expect(body.entries[0].tags).toEqual([]);
+ expect(body.entries[0].context).toEqual({});
+ });
+});
+
+// ── POST (upsert) ─────────────────────────────────────────────────────────
+
+describe('POST /api/agent-memory', () => {
+ beforeEach(() => {
+ getSessionUserMock.mockResolvedValue({ id: 'u1' });
+ });
+
+ it('creates a new entry (no client id) and returns it with an id', async () => {
+ const createdAt = new Date();
+ queueSql(
+ [{ user_id: 'u1' }],
+ [
+ {
+ id: 'server-gen-id',
+ agent_id: 'a1',
+ type: 'project',
+ content: 'new memory',
+ tags: [],
+ context: {},
+ salience: 0.5,
+ created_at: createdAt,
+ expires_at: null,
+ },
+ ],
+ );
+
+ const { status, body } = await invoke({
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: { agentId: 'a1', entry: { content: 'new memory' } },
+ });
+
+ expect(status).toBe(201);
+ expect(body.entry.id).toBe('server-gen-id');
+ expect(body.entry.content).toBe('new memory');
+ });
+
+ it('returns 400 when agentId is missing', async () => {
+ const { status, body } = await invoke({
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: { entry: { content: 'x' } },
+ });
+ expect(status).toBe(400);
+ expect(body.error_description).toMatch(/agentId/);
+ });
+
+ it('returns 400 when entry is missing', async () => {
+ const { status, body } = await invoke({
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: { agentId: 'a1' },
+ });
+ expect(status).toBe(400);
+ expect(body.error_description).toMatch(/entry/);
+ });
+
+ it('returns 403 when agent belongs to another user', async () => {
+ queueSql([{ user_id: 'other' }]);
+ const { status } = await invoke({
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: { agentId: 'a1', entry: { content: 'steal' } },
+ });
+ expect(status).toBe(403);
+ });
+
+ it('upserts an entry when a client-supplied id is provided', async () => {
+ queueSql(
+ [{ user_id: 'u1' }],
+ [
+ {
+ id: 'client-id',
+ agent_id: 'a1',
+ type: 'user',
+ content: 'updated',
+ tags: [],
+ context: {},
+ salience: 0.9,
+ created_at: new Date(),
+ expires_at: null,
+ },
+ ],
+ );
+
+ const { status, body } = await invoke({
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: {
+ agentId: 'a1',
+ entry: { id: 'client-id', type: 'user', content: 'updated', salience: 0.9 },
+ },
+ });
+
+ expect(status).toBe(201);
+ expect(body.entry.id).toBe('client-id');
+ expect(body.entry.salience).toBe(0.9);
+ });
+
+ it('returns 409 when id collides with another agent\'s memory', async () => {
+ // ON CONFLICT WHERE guard fires — SQL returns no rows.
+ queueSql([{ user_id: 'u1' }], []);
+ const { status, body } = await invoke({
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: { agentId: 'a1', entry: { id: 'stolen-id', content: 'x' } },
+ });
+ expect(status).toBe(409);
+ expect(body.error).toBe('id_conflict');
+ });
+
+ it('normalizes unknown entry.type to "project"', async () => {
+ queueSql(
+ [{ user_id: 'u1' }],
+ [
+ {
+ id: 'm1',
+ agent_id: 'a1',
+ type: 'project',
+ content: 'x',
+ tags: [],
+ context: {},
+ salience: 0.5,
+ created_at: new Date(),
+ expires_at: null,
+ },
+ ],
+ );
+
+ const { status, body } = await invoke({
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: { agentId: 'a1', entry: { type: 'bogus-type', content: 'x' } },
+ });
+
+ expect(status).toBe(201);
+ expect(body.entry.type).toBe('project');
+ });
+
+ it('truncates content longer than 10,000 characters', async () => {
+ const huge = 'x'.repeat(20_000);
+ let capturedContent;
+
+ sqlMock.mockReset();
+ let call = 0;
+ sqlMock.mockImplementation((_strings, ...values) => {
+ call += 1;
+ if (call === 1) return Promise.resolve([{ user_id: 'u1' }]);
+ capturedContent = values.find((v) => typeof v === 'string' && v.length >= 10_000);
+ return Promise.resolve([
+ {
+ id: 'x',
+ agent_id: 'a1',
+ type: 'project',
+ content: capturedContent,
+ tags: [],
+ context: {},
+ salience: 0.5,
+ created_at: new Date(),
+ expires_at: null,
+ },
+ ]);
+ });
+
+ const { status } = await invoke({
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: { agentId: 'a1', entry: { content: huge } },
+ });
+
+ expect(status).toBe(201);
+ expect(capturedContent).toBeDefined();
+ expect(capturedContent.length).toBe(10_000);
+ });
+});
+
+// ── DELETE ────────────────────────────────────────────────────────────────
+
+describe('DELETE /api/agent-memory/:id', () => {
+ beforeEach(() => {
+ getSessionUserMock.mockResolvedValue({ id: 'u1' });
+ });
+
+ it('deletes the memory row and returns { ok: true }', async () => {
+ queueSql([{ id: 'mem-1', user_id: 'u1' }], []); // lookup, delete
+ const { status, body } = await invoke({
+ method: 'DELETE',
+ url: '/api/agent-memory/mem-1',
+ });
+ expect(status).toBe(200);
+ expect(body).toEqual({ ok: true });
+ });
+
+ it('returns 404 when the memory does not exist', async () => {
+ queueSql([]); // no row found
+ const { status } = await invoke({ method: 'DELETE', url: '/api/agent-memory/ghost' });
+ expect(status).toBe(404);
+ });
+
+ it('returns 403 when memory belongs to another user', async () => {
+ queueSql([{ id: 'mem-1', user_id: 'other' }]);
+ const { status, body } = await invoke({
+ method: 'DELETE',
+ url: '/api/agent-memory/mem-1',
+ });
+ expect(status).toBe(403);
+ expect(body.error).toBe('forbidden');
+ });
+});
+
+// ── Method routing ────────────────────────────────────────────────────────
+
+describe('method routing', () => {
+ it('PUT returns 405', async () => {
+ const { status } = await invoke({ method: 'PUT', url: '/api/agent-memory' });
+ expect(status).toBe(405);
+ });
+
+ it('OPTIONS returns 204 with CORS headers', async () => {
+ const { status, res } = await invoke({
+ method: 'OPTIONS',
+ headers: { origin: 'http://localhost:3000' },
+ });
+ expect(status).toBe(204);
+ expect(res.headers['access-control-allow-methods']).toMatch(/GET/);
+ expect(res.headers['access-control-allow-methods']).toMatch(/DELETE/);
+ });
+});
diff --git a/tests/src/agent-memory.test.js b/tests/src/agent-memory.test.js
new file mode 100644
index 000000000..0110e8481
--- /dev/null
+++ b/tests/src/agent-memory.test.js
@@ -0,0 +1,298 @@
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import { AgentMemory, MEMORY_TYPES } from '../../src/agent-memory.js';
+
+// ── Globals ───────────────────────────────────────────────────────────────
+
+const localStorageMock = (() => {
+ let store = {};
+ return {
+ getItem: vi.fn((key) => store[key] ?? null),
+ setItem: vi.fn((key, val) => {
+ store[key] = val;
+ }),
+ removeItem: vi.fn((key) => {
+ delete store[key];
+ }),
+ clear: vi.fn(() => {
+ store = {};
+ }),
+ _reset() {
+ store = {};
+ },
+ _store() {
+ return store;
+ },
+ };
+})();
+
+vi.stubGlobal('localStorage', localStorageMock);
+
+const fetchMock = vi.fn().mockResolvedValue({ ok: true, json: async () => ({}) });
+vi.stubGlobal('fetch', fetchMock);
+
+// ── Reset ─────────────────────────────────────────────────────────────────
+
+beforeEach(() => {
+ localStorageMock._reset();
+ localStorageMock.getItem.mockClear();
+ localStorageMock.setItem.mockClear();
+ fetchMock.mockClear();
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+});
+
+// ── Tests ─────────────────────────────────────────────────────────────────
+
+describe('AgentMemory.add()', () => {
+ it('stores entry in memory and returns a string id', () => {
+ const mem = new AgentMemory('agent-1');
+ const id = mem.add({ type: MEMORY_TYPES.USER, content: 'hello' });
+
+ expect(typeof id).toBe('string');
+ expect(id.length).toBeGreaterThan(0);
+
+ const results = mem.query();
+ expect(results).toHaveLength(1);
+ expect(results[0].id).toBe(id);
+ expect(results[0].content).toBe('hello');
+ });
+
+ it('persists entry to localStorage immediately', () => {
+ const mem = new AgentMemory('agent-1');
+ mem.add({ type: MEMORY_TYPES.USER, content: 'persist me' });
+
+ expect(localStorageMock.setItem).toHaveBeenCalled();
+
+ const lastCall = localStorageMock.setItem.mock.calls.at(-1);
+ const key = lastCall[0];
+ const stored = JSON.parse(lastCall[1]);
+
+ expect(key).toBe('agent_memory_agent-1');
+ expect(Array.isArray(stored)).toBe(true);
+ expect(stored[0].content).toBe('persist me');
+ });
+
+ it('schedules a backend sync when backendSync is enabled', () => {
+ const mem = new AgentMemory('agent-1', { backendSync: true });
+ // Constructor also fires _hydrateFromBackend — clear before the assertion.
+ fetchMock.mockClear();
+
+ mem.add({ type: MEMORY_TYPES.USER, content: 'sync me' });
+
+ expect(fetchMock).toHaveBeenCalledOnce();
+ const [url, opts] = fetchMock.mock.calls[0];
+ expect(url).toContain('agent-1');
+ expect(opts.method).toBe('POST');
+ });
+
+ it('does NOT call fetch when backendSync is false (default)', () => {
+ const mem = new AgentMemory('agent-1');
+ mem.add({ type: MEMORY_TYPES.USER, content: 'no sync' });
+
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+});
+
+describe('AgentMemory.query() — filtering', () => {
+ it('query({ type }) returns only entries of that type', () => {
+ const mem = new AgentMemory('agent-1');
+ mem.add({ type: MEMORY_TYPES.USER, content: 'user note' });
+ mem.add({ type: MEMORY_TYPES.PROJECT, content: 'project note' });
+ mem.add({ type: MEMORY_TYPES.REFERENCE, content: 'ref note' });
+
+ const results = mem.query({ type: MEMORY_TYPES.USER });
+ expect(results).toHaveLength(1);
+ expect(results[0].content).toBe('user note');
+ });
+
+ it('query({ tags }) returns only entries containing ALL specified tags', () => {
+ const mem = new AgentMemory('agent-1');
+ mem.add({ type: MEMORY_TYPES.USER, content: 'both tags', tags: ['foo', 'bar'] });
+ mem.add({ type: MEMORY_TYPES.USER, content: 'one tag', tags: ['foo'] });
+ mem.add({ type: MEMORY_TYPES.USER, content: 'no tags' });
+
+ const fooBar = mem.query({ tags: ['foo', 'bar'] });
+ expect(fooBar).toHaveLength(1);
+ expect(fooBar[0].content).toBe('both tags');
+
+ const fooOnly = mem.query({ tags: ['foo'] });
+ expect(fooOnly).toHaveLength(2);
+ });
+
+ it('query({ limit }) returns at most limit results', () => {
+ const mem = new AgentMemory('agent-1');
+ for (let i = 0; i < 10; i++) {
+ mem.add({ type: MEMORY_TYPES.PROJECT, content: `entry ${i}` });
+ }
+
+ expect(mem.query({ limit: 3 })).toHaveLength(3);
+ expect(mem.query({ limit: 1 })).toHaveLength(1);
+ });
+
+ it('query({ since }) excludes entries created before the timestamp', () => {
+ vi.useFakeTimers();
+ const mem = new AgentMemory('agent-1');
+
+ mem.add({ type: MEMORY_TYPES.PROJECT, content: 'old' });
+
+ vi.advanceTimersByTime(5000);
+ const cutoff = Date.now();
+
+ vi.advanceTimersByTime(1000);
+ mem.add({ type: MEMORY_TYPES.PROJECT, content: 'new' });
+
+ const results = mem.query({ since: cutoff });
+ expect(results).toHaveLength(1);
+ expect(results[0].content).toBe('new');
+ });
+
+ it('excludes expired entries (expiresAt in the past)', () => {
+ vi.useFakeTimers();
+ const now = Date.now();
+ const mem = new AgentMemory('agent-1');
+
+ mem.add({ type: MEMORY_TYPES.PROJECT, content: 'active' });
+ mem.add({
+ type: MEMORY_TYPES.PROJECT,
+ content: 'expired',
+ expiresAt: now - 1000,
+ });
+
+ const results = mem.query();
+ expect(results).toHaveLength(1);
+ expect(results[0].content).toBe('active');
+ });
+
+ it('includes entries whose expiresAt is in the future', () => {
+ vi.useFakeTimers();
+ const now = Date.now();
+ const mem = new AgentMemory('agent-1');
+
+ mem.add({
+ type: MEMORY_TYPES.PROJECT,
+ content: 'not yet expired',
+ expiresAt: now + 60_000,
+ });
+
+ expect(mem.query()).toHaveLength(1);
+ });
+});
+
+describe('AgentMemory.query() — scoring', () => {
+ it('sorts entries by salience × recency (highest score first)', () => {
+ vi.useFakeTimers();
+ const mem = new AgentMemory('agent-1');
+
+ // All added at the same time so recency is identical —
+ // sort order is determined purely by salience.
+ // feedback base = 0.8, reference base = 0.5.
+ mem.add({ type: MEMORY_TYPES.REFERENCE, content: 'low' });
+ mem.add({ type: MEMORY_TYPES.FEEDBACK, content: 'high' });
+ mem.add({ type: MEMORY_TYPES.USER, content: 'mid' });
+
+ const results = mem.query();
+ expect(results[0].content).toBe('high'); // feedback: 0.8
+ expect(results[1].content).toBe('mid'); // user: 0.7
+ expect(results[2].content).toBe('low'); // reference: 0.5
+ });
+
+ it('entry.important=true gives salience 1.0, appearing before all others', () => {
+ vi.useFakeTimers();
+ const mem = new AgentMemory('agent-1');
+
+ mem.add({ type: MEMORY_TYPES.FEEDBACK, content: 'high' });
+ mem.add({ type: MEMORY_TYPES.PROJECT, content: 'critical', important: true });
+
+ const results = mem.query();
+ expect(results[0].content).toBe('critical');
+ expect(results[0].salience).toBe(1.0);
+ });
+});
+
+describe('AgentMemory — localStorage hydration', () => {
+ it('loads existing entries from localStorage on construction', () => {
+ const existing = [
+ {
+ id: 'hydrated-1',
+ type: MEMORY_TYPES.USER,
+ content: 'remembered',
+ tags: [],
+ context: {},
+ salience: 0.7,
+ createdAt: Date.now(),
+ expiresAt: null,
+ },
+ ];
+ localStorageMock.getItem.mockReturnValueOnce(JSON.stringify(existing));
+
+ const mem = new AgentMemory('agent-1');
+ const results = mem.query();
+
+ expect(results).toHaveLength(1);
+ expect(results[0].id).toBe('hydrated-1');
+ expect(results[0].content).toBe('remembered');
+ });
+
+ it('starts with empty entries when localStorage has nothing', () => {
+ // default getItem mock returns null
+ const mem = new AgentMemory('agent-1');
+ expect(mem.query()).toHaveLength(0);
+ });
+
+ it('starts with empty entries when localStorage contains invalid JSON', () => {
+ localStorageMock.getItem.mockReturnValueOnce('not-valid-json{{{');
+ const mem = new AgentMemory('agent-1');
+ expect(mem.query()).toHaveLength(0);
+ });
+
+ it('uses the agentId-scoped storage key', () => {
+ new AgentMemory('my-special-agent');
+ expect(localStorageMock.getItem).toHaveBeenCalledWith('agent_memory_my-special-agent');
+ });
+});
+
+describe('AgentMemory.forget() / clear()', () => {
+ it('forget(id) removes the entry from query results', () => {
+ const mem = new AgentMemory('agent-1');
+ const id = mem.add({ type: MEMORY_TYPES.PROJECT, content: 'delete me' });
+ mem.add({ type: MEMORY_TYPES.PROJECT, content: 'keep me' });
+
+ mem.forget(id);
+ const results = mem.query();
+ expect(results).toHaveLength(1);
+ expect(results[0].content).toBe('keep me');
+ });
+
+ it('forget(id) persists the removal to localStorage', () => {
+ const mem = new AgentMemory('agent-1');
+ const id = mem.add({ type: MEMORY_TYPES.PROJECT, content: 'gone' });
+
+ localStorageMock.setItem.mockClear();
+ mem.forget(id);
+
+ expect(localStorageMock.setItem).toHaveBeenCalled();
+ const stored = JSON.parse(localStorageMock.setItem.mock.calls.at(-1)[1]);
+ expect(stored.find((e) => e.id === id)).toBeUndefined();
+ });
+
+ it('clear(type) removes only entries of that type', () => {
+ const mem = new AgentMemory('agent-1');
+ mem.add({ type: MEMORY_TYPES.USER, content: 'user' });
+ mem.add({ type: MEMORY_TYPES.PROJECT, content: 'project' });
+
+ mem.clear(MEMORY_TYPES.USER);
+ expect(mem.query()).toHaveLength(1);
+ expect(mem.query()[0].content).toBe('project');
+ });
+
+ it('clear() with no argument removes all entries', () => {
+ const mem = new AgentMemory('agent-1');
+ mem.add({ type: MEMORY_TYPES.USER, content: 'a' });
+ mem.add({ type: MEMORY_TYPES.PROJECT, content: 'b' });
+
+ mem.clear();
+ expect(mem.query()).toHaveLength(0);
+ });
+});
diff --git a/tests/src/agent-skills.test.js b/tests/src/agent-skills.test.js
new file mode 100644
index 000000000..e2555f2e0
--- /dev/null
+++ b/tests/src/agent-skills.test.js
@@ -0,0 +1,409 @@
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+
+// Mock pumpfun side-effect modules before AgentSkills is imported
+vi.mock('../../src/agent-skills-pumpfun.js', () => ({ registerPumpFunSkills: vi.fn() }));
+vi.mock('../../src/agent-skills-pumpfun-watch.js', () => ({ registerPumpFunWatchSkills: vi.fn() }));
+vi.mock('../../src/agent-skills-pumpfun-autonomous.js', () => ({
+ registerPumpFunAutonomousSkills: vi.fn(),
+}));
+vi.mock('../../src/agent-skills-pumpfun-compose.js', () => ({
+ registerPumpFunComposeSkills: vi.fn(),
+}));
+vi.mock('../../src/agent-skills-pumpfun-hooks.js', () => ({ attachPumpFunMemoryHooks: vi.fn() }));
+
+// Mock sandbox host so worker code doesn't run in Node
+vi.mock('../../src/skills/sandbox-host.js', () => ({
+ getHost: vi.fn(() => ({ invoke: vi.fn() })),
+}));
+
+import { AgentSkills } from '../../src/agent-skills.js';
+import { AgentProtocol, ACTION_TYPES } from '../../src/agent-protocol.js';
+import { SkillRegistry } from '../../src/skills/index.js';
+
+// ── helpers ───────────────────────────────────────────────────────────────────
+
+function makeResponse(data, { ok = true, status = 200, asText = false } = {}) {
+ return {
+ ok,
+ status,
+ json: () => Promise.resolve(data),
+ text: () => Promise.resolve(asText ? data : JSON.stringify(data)),
+ };
+}
+
+/**
+ * Build a fetch stub that returns responses keyed by URL suffix.
+ * Keys are matched via String.includes(); the first match wins.
+ */
+function makeFetch(routes = {}) {
+ return vi.fn(async (url) => {
+ const str = url.toString();
+ for (const [pattern, response] of Object.entries(routes)) {
+ if (str.includes(pattern)) return response;
+ }
+ return makeResponse(null, { ok: false, status: 404 });
+ });
+}
+
+function fixtureManifest(overrides = {}) {
+ return {
+ name: 'test-skill',
+ version: '1.0.0',
+ description: 'A test skill',
+ author: '0xowner',
+ sandboxPolicy: 'sandboxed',
+ ...overrides,
+ };
+}
+
+function fixtureRoutes(manifest = fixtureManifest(), { instructions = '', tools = [] } = {}) {
+ return {
+ 'manifest.json': makeResponse(manifest),
+ 'SKILL.md': makeResponse(instructions, { asText: true }),
+ 'tools.json': makeResponse({ tools }),
+ 'handlers.js': makeResponse('export default {}', { asText: true }),
+ };
+}
+
+// ── SkillRegistry – Installation & trust ─────────────────────────────────────
+
+describe('SkillRegistry.install – trust modes', () => {
+ it('any trust accepts a skill with any author', async () => {
+ const manifest = fixtureManifest({ author: '0xstranger' });
+ const registry = new SkillRegistry({
+ fetchFn: makeFetch(fixtureRoutes(manifest)),
+ trust: 'any',
+ });
+ const skill = await registry.install({ uri: 'https://example.com/skill/' });
+ expect(skill.name).toBe('test-skill');
+ });
+
+ it('owned-only rejects a skill whose author does not match ownerAddress', async () => {
+ const manifest = fixtureManifest({ author: '0xstranger' });
+ const registry = new SkillRegistry({
+ fetchFn: makeFetch(fixtureRoutes(manifest)),
+ trust: 'owned-only',
+ ownerAddress: '0xowner',
+ });
+ await expect(registry.install({ uri: 'https://example.com/skill/' })).rejects.toThrow(
+ /not trusted under owned-only/,
+ );
+ });
+
+ it('owned-only accepts a skill whose author matches ownerAddress (case-insensitive)', async () => {
+ const manifest = fixtureManifest({ author: '0xOwner' });
+ const registry = new SkillRegistry({
+ fetchFn: makeFetch(fixtureRoutes(manifest)),
+ trust: 'owned-only',
+ ownerAddress: '0xowner',
+ });
+ const skill = await registry.install({ uri: 'https://example.com/skill/' });
+ expect(skill.name).toBe('test-skill');
+ });
+
+ it('owned-only allows any skill when ownerAddress is not set', async () => {
+ const manifest = fixtureManifest({ author: '0xanyone' });
+ const registry = new SkillRegistry({
+ fetchFn: makeFetch(fixtureRoutes(manifest)),
+ trust: 'owned-only',
+ });
+ const skill = await registry.install({ uri: 'https://example.com/skill/' });
+ expect(skill.name).toBe('test-skill');
+ });
+
+ it('whitelist mode is a no-op and does not reject skills (enforcement is a hook)', async () => {
+ const registry = new SkillRegistry({
+ fetchFn: makeFetch(fixtureRoutes()),
+ trust: 'whitelist',
+ });
+ // No whitelist config → currently installs without error
+ const skill = await registry.install({ uri: 'https://example.com/skill/' });
+ expect(skill.name).toBe('test-skill');
+ });
+});
+
+describe('SkillRegistry.install – dependency loading', () => {
+ it('recursively installs each dependency URI listed in manifest.dependencies', async () => {
+ const depManifest = fixtureManifest({ name: 'dep-skill', dependencies: undefined });
+ const rootManifest = fixtureManifest({
+ dependencies: { 'https://cdn.example.com/dep/': '1.0.0' },
+ });
+
+ const fetchFn = makeFetch({
+ // root skill
+ 'example.com/skill/manifest.json': makeResponse(rootManifest),
+ 'example.com/skill/SKILL.md': makeResponse('', { asText: true }),
+ 'example.com/skill/tools.json': makeResponse({ tools: [] }),
+ 'example.com/skill/handlers.js': makeResponse('', { asText: true }),
+ // dependency
+ 'cdn.example.com/dep/manifest.json': makeResponse(depManifest),
+ 'cdn.example.com/dep/SKILL.md': makeResponse('', { asText: true }),
+ 'cdn.example.com/dep/tools.json': makeResponse({ tools: [] }),
+ 'cdn.example.com/dep/handlers.js': makeResponse('', { asText: true }),
+ });
+
+ const registry = new SkillRegistry({ fetchFn, trust: 'any' });
+ await registry.install({ uri: 'https://example.com/skill/' });
+
+ const names = registry.all().map((s) => s.name);
+ expect(names).toContain('dep-skill');
+ });
+
+ it('installing the same URI twice returns the cached skill and does not duplicate', async () => {
+ const fetchFn = makeFetch(fixtureRoutes());
+ const registry = new SkillRegistry({ fetchFn, trust: 'any' });
+
+ await registry.install({ uri: 'https://example.com/skill/' });
+ await registry.install({ uri: 'https://example.com/skill/' });
+
+ expect(registry.all()).toHaveLength(1);
+ // fetchFn called only for the first install (3 files; handlers.js is a 4th)
+ expect(fetchFn).toHaveBeenCalledTimes(4);
+ });
+});
+
+// ── SkillRegistry – Skill lookup ──────────────────────────────────────────────
+
+describe('SkillRegistry – skill lookup', () => {
+ let registry;
+ beforeEach(async () => {
+ registry = new SkillRegistry({ fetchFn: makeFetch(fixtureRoutes()), trust: 'any' });
+ await registry.install({ uri: 'https://example.com/skill/' });
+ });
+
+ it('installed skill is discoverable via all()', () => {
+ const found = registry.all().find((s) => s.name === 'test-skill');
+ expect(found).toBeDefined();
+ expect(found.name).toBe('test-skill');
+ });
+
+ it('uninstalled skill name returns undefined from all().find()', () => {
+ const found = registry.all().find((s) => s.name === 'nonexistent');
+ expect(found).toBeUndefined();
+ });
+
+ it('findSkillForTool returns null for an unknown tool', () => {
+ expect(registry.findSkillForTool('ghost-tool')).toBeNull();
+ });
+
+ it('findSkillForTool returns the skill that owns a registered tool', async () => {
+ const tools = [{ name: 'do-thing', description: 'does thing' }];
+ const reg2 = new SkillRegistry({
+ fetchFn: makeFetch(fixtureRoutes(fixtureManifest({ name: 'tool-skill' }), { tools })),
+ trust: 'any',
+ });
+ await reg2.install({ uri: 'https://cdn.example.com/tool-skill/' });
+ const skill = reg2.findSkillForTool('do-thing');
+ expect(skill).not.toBeNull();
+ expect(skill.name).toBe('tool-skill');
+ });
+});
+
+// ── SkillRegistry – Manifest loading ─────────────────────────────────────────
+
+describe('SkillRegistry – manifest loading', () => {
+ it('loads a skill from an https:// URL, normalizing the trailing slash', async () => {
+ const fetchFn = makeFetch(fixtureRoutes());
+ const registry = new SkillRegistry({ fetchFn, trust: 'any' });
+ // No trailing slash — should be added automatically
+ const skill = await registry.install({ uri: 'https://example.com/skill' });
+ expect(skill).toBeDefined();
+ expect(skill.uri).toBe('https://example.com/skill/');
+ });
+
+ it('resolves an ipfs:// URI to a dweb.link gateway URL before fetching', async () => {
+ // ipfs://QmTest → https://dweb.link/ipfs/QmTest/
+ const fetchFn = makeFetch({
+ 'dweb.link/ipfs/QmTest/manifest.json': makeResponse(fixtureManifest()),
+ 'dweb.link/ipfs/QmTest/SKILL.md': makeResponse('', { asText: true }),
+ 'dweb.link/ipfs/QmTest/tools.json': makeResponse({ tools: [] }),
+ 'dweb.link/ipfs/QmTest/handlers.js': makeResponse('', { asText: true }),
+ });
+ const registry = new SkillRegistry({ fetchFn, trust: 'any' });
+ const skill = await registry.install({ uri: 'ipfs://QmTest' });
+ expect(skill).toBeDefined();
+ expect(skill.uri).toContain('dweb.link/ipfs/QmTest');
+ });
+});
+
+// ── AgentSkills – Execution lifecycle ────────────────────────────────────────
+
+describe('AgentSkills.perform – execution lifecycle', () => {
+ let protocol, memory, skills;
+
+ beforeEach(() => {
+ protocol = new AgentProtocol();
+ memory = { add: vi.fn(() => 'mem-1'), query: vi.fn(() => []) };
+ skills = new AgentSkills(protocol, memory);
+ // Register a minimal custom skill for execution tests
+ skills.register({
+ name: 'echo',
+ description: 'echoes args',
+ handler: vi.fn(async (args) => ({ success: true, output: args.text ?? 'ok' })),
+ });
+ });
+
+ it('invokes the handler with (args, ctx)', async () => {
+ const handler = skills.get('echo').handler;
+ await skills.perform('echo', { text: 'hello' });
+ expect(handler).toHaveBeenCalledOnce();
+ const [args, ctx] = handler.mock.calls[0];
+ expect(args).toEqual({ text: 'hello' });
+ expect(ctx).toHaveProperty('protocol', protocol);
+ expect(ctx).toHaveProperty('memory', memory);
+ });
+
+ it('emits PERFORM_SKILL before the handler runs', async () => {
+ const events = [];
+ protocol.on(ACTION_TYPES.PERFORM_SKILL, (a) => events.push(a));
+ const handler = skills.get('echo').handler;
+ handler.mockImplementation(async () => {
+ expect(events).toHaveLength(1); // already emitted
+ return { success: true, output: 'ok' };
+ });
+ await skills.perform('echo', {});
+ expect(events[0].payload.skill).toBe('echo');
+ });
+
+ it('emits SKILL_DONE with the result on success', async () => {
+ const done = vi.fn();
+ protocol.on(ACTION_TYPES.SKILL_DONE, done);
+ await skills.perform('echo', { text: 'hi' });
+ expect(done).toHaveBeenCalledOnce();
+ expect(done.mock.calls[0][0].payload).toMatchObject({
+ skill: 'echo',
+ result: { success: true, output: 'hi' },
+ });
+ });
+
+ it('emits SKILL_ERROR and returns a failure result when the handler throws', async () => {
+ skills.register({
+ name: 'bad-skill',
+ description: 'always throws',
+ handler: async () => {
+ throw new Error('something went wrong');
+ },
+ });
+ const errEvents = vi.fn();
+ protocol.on(ACTION_TYPES.SKILL_ERROR, errEvents);
+
+ const result = await skills.perform('bad-skill', {});
+
+ expect(result.success).toBe(false);
+ expect(result.output).toContain('something went wrong');
+ expect(errEvents).toHaveBeenCalledOnce();
+ expect(errEvents.mock.calls[0][0].payload).toMatchObject({
+ skill: 'bad-skill',
+ error: 'something went wrong',
+ });
+ });
+
+ it('returns a failure result for an unknown skill without throwing', async () => {
+ const result = await skills.perform('no-such-skill', {});
+ expect(result.success).toBe(false);
+ expect(result.output).toContain('no-such-skill');
+ });
+
+ it('auto-speaks the result output when isBrowser is true', async () => {
+ const speaks = vi.fn();
+ protocol.on(ACTION_TYPES.SPEAK, speaks);
+ await skills.perform('echo', { text: 'greetings' }, { isBrowser: true });
+ expect(speaks).toHaveBeenCalledOnce();
+ expect(speaks.mock.calls[0][0].payload.text).toBe('greetings');
+ });
+
+ it('does not auto-speak when isBrowser is false', async () => {
+ const speaks = vi.fn();
+ protocol.on(ACTION_TYPES.SPEAK, speaks);
+ await skills.perform('echo', { text: 'greetings' }, { isBrowser: false });
+ expect(speaks).not.toHaveBeenCalled();
+ });
+});
+
+// ── AgentSkills – Built-in skill: remember ────────────────────────────────────
+
+describe('AgentSkills built-in – remember', () => {
+ let protocol, memory, skills;
+
+ beforeEach(() => {
+ protocol = new AgentProtocol();
+ memory = { add: vi.fn(() => 'mem-42'), query: vi.fn(() => []) };
+ skills = new AgentSkills(protocol, memory);
+ });
+
+ it('emits REMEMBER on the protocol when isBrowser is true', async () => {
+ const remembered = vi.fn();
+ protocol.on(ACTION_TYPES.REMEMBER, remembered);
+ await skills.perform('remember', { content: 'unit test ran' }, { isBrowser: true });
+ expect(remembered).toHaveBeenCalledOnce();
+ expect(remembered.mock.calls[0][0].payload.content).toBe('unit test ran');
+ });
+
+ it('does not emit REMEMBER when isBrowser is false', async () => {
+ const remembered = vi.fn();
+ protocol.on(ACTION_TYPES.REMEMBER, remembered);
+ await skills.perform('remember', { content: 'silent' }, { isBrowser: false });
+ expect(remembered).not.toHaveBeenCalled();
+ });
+
+ it('stores the memory entry via memory.add()', async () => {
+ await skills.perform('remember', { content: 'important fact' }, { isBrowser: false });
+ expect(memory.add).toHaveBeenCalledWith(
+ expect.objectContaining({ content: 'important fact' }),
+ );
+ });
+
+ it('returns failure when content is missing', async () => {
+ const result = await skills.perform('remember', {}, { isBrowser: false });
+ expect(result.success).toBe(false);
+ });
+});
+
+// ── AgentSkills – Registry API ────────────────────────────────────────────────
+
+describe('AgentSkills – registry API', () => {
+ let skills;
+
+ beforeEach(() => {
+ skills = new AgentSkills(new AgentProtocol(), {
+ add: vi.fn(),
+ query: vi.fn(() => []),
+ });
+ });
+
+ it('get(name) returns the skill def for a registered skill', () => {
+ const def = skills.get('greet');
+ expect(def).toBeDefined();
+ expect(def.name).toBe('greet');
+ expect(typeof def.handler).toBe('function');
+ });
+
+ it('get(name) returns undefined for an unregistered skill', () => {
+ expect(skills.get('not-here')).toBeUndefined();
+ });
+
+ it('list() includes all built-in skills', () => {
+ const names = skills.list().map((s) => s.name);
+ expect(names).toContain('greet');
+ expect(names).toContain('remember');
+ expect(names).toContain('help');
+ expect(names).toContain('think');
+ });
+
+ it('unregister removes the skill from the registry', () => {
+ skills.register({ name: 'temp', description: 'temp', handler: vi.fn() });
+ expect(skills.get('temp')).toBeDefined();
+ skills.unregister('temp');
+ expect(skills.get('temp')).toBeUndefined();
+ });
+
+ it('toMcpTools() returns only mcpExposed skills', () => {
+ const tools = skills.toMcpTools();
+ // All returned tools should come from MCP-exposed skills
+ const exposedNames = skills.list().filter((s) => s.mcpExposed).map((s) => s.name);
+ expect(tools.length).toBe(exposedNames.length);
+ // 'help' and 'think' are not MCP-exposed
+ expect(tools.map((t) => t.name)).not.toContain('skill_help');
+ expect(tools.map((t) => t.name)).not.toContain('skill_think');
+ });
+});
diff --git a/tests/src/runtime.test.js b/tests/src/runtime.test.js
new file mode 100644
index 000000000..89b1fa18e
--- /dev/null
+++ b/tests/src/runtime.test.js
@@ -0,0 +1,334 @@
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+import { Runtime } from '../../src/runtime/index.js';
+import { NullProvider } from '../../src/runtime/providers.js';
+import { BUILTIN_HANDLERS } from '../../src/runtime/tools.js';
+
+// Disable voice in all Runtime instances — avoids BrowserTTS/BrowserSTT in tests
+const NO_VOICE = { tts: { provider: 'none' }, stt: { provider: 'none' } };
+
+// ── Mock provider factory ─────────────────────────────────────────────────────
+
+function mockProvider(responses) {
+ let idx = 0;
+ return {
+ complete: vi.fn(() => {
+ const r = responses[idx < responses.length ? idx++ : responses.length - 1];
+ return Promise.resolve(r);
+ }),
+ formatAssistantWithToolCalls(text, toolCalls) {
+ const content = [];
+ if (text) content.push({ type: 'text', text });
+ for (const c of toolCalls)
+ content.push({ type: 'tool_use', id: c.id, name: c.name, input: c.input });
+ return { role: 'assistant', content };
+ },
+ formatToolResults(results) {
+ return {
+ role: 'user',
+ content: results.map((r) => ({
+ type: 'tool_result',
+ tool_use_id: r.id,
+ content: JSON.stringify(r.output),
+ is_error: !!r.isError,
+ })),
+ };
+ },
+ };
+}
+
+// Shorthand response shapes
+const textResp = (text) => ({ text, toolCalls: [], thinking: '', stopReason: 'end_turn' });
+const toolResp = (name, input = {}, id = 'call_1') => ({
+ text: '',
+ toolCalls: [{ id, name, input }],
+ thinking: '',
+ stopReason: 'tool_use',
+});
+
+// Build a Runtime with a mock provider and optional overrides
+function makeRuntime(provider, { viewer = null, memory = null, skills = null, manifest = {} } = {}) {
+ const rt = new Runtime({
+ manifest,
+ viewer,
+ memory,
+ skills,
+ providerConfig: { provider: 'none' },
+ voiceConfig: NO_VOICE,
+ });
+ rt.provider = provider;
+ return rt;
+}
+
+// Collect CustomEvent detail objects from a Runtime EventTarget
+function collect(runtime, eventName) {
+ const events = [];
+ runtime.addEventListener(eventName, (e) => events.push(e.detail));
+ return events;
+}
+
+// ── NullProvider ──────────────────────────────────────────────────────────────
+
+describe('NullProvider', () => {
+ it('complete() resolves immediately without making HTTP calls', async () => {
+ const fetchSpy = vi.spyOn(globalThis, 'fetch');
+ const p = new NullProvider();
+ const result = await p.complete({ system: '', messages: [], tools: [] });
+ expect(result.text).toBe('');
+ expect(result.toolCalls).toEqual([]);
+ expect(result.stopReason).toBe('end_turn');
+ expect(fetchSpy).not.toHaveBeenCalled();
+ fetchSpy.mockRestore();
+ });
+});
+
+// ── Text response flow ────────────────────────────────────────────────────────
+
+describe('Runtime — text response', () => {
+ it('calls provider.complete with user message and returns final text', async () => {
+ const provider = mockProvider([textResp('Hello world')]);
+ const rt = makeRuntime(provider);
+ const result = await rt.send('Hi');
+ expect(provider.complete).toHaveBeenCalledOnce();
+ expect(provider.complete.mock.calls[0][0].messages[0]).toMatchObject({
+ role: 'user',
+ content: 'Hi',
+ });
+ expect(result.text).toBe('Hello world');
+ });
+
+ it('emits brain:message for user turn then assistant turn', async () => {
+ const provider = mockProvider([textResp('Hello world')]);
+ const rt = makeRuntime(provider);
+ const events = collect(rt, 'brain:message');
+ await rt.send('Hi');
+ expect(events).toHaveLength(2);
+ expect(events[0]).toMatchObject({ role: 'user', content: 'Hi' });
+ expect(events[1]).toMatchObject({ role: 'assistant', content: 'Hello world' });
+ });
+
+ it('appends both turns to runtime.messages', async () => {
+ const provider = mockProvider([textResp('Reply')]);
+ const rt = makeRuntime(provider);
+ await rt.send('Hello');
+ expect(rt.messages).toHaveLength(2);
+ expect(rt.messages[0]).toMatchObject({ role: 'user', content: 'Hello' });
+ expect(rt.messages[1]).toMatchObject({ role: 'assistant', content: 'Reply' });
+ });
+});
+
+// ── Thinking ──────────────────────────────────────────────────────────────────
+
+describe('Runtime — thinking events', () => {
+ it('emits brain:thinking when provider returns thinking content', async () => {
+ const provider = mockProvider([
+ { text: 'Answer', toolCalls: [], thinking: 'Reasoning here', stopReason: 'end_turn' },
+ ]);
+ const rt = makeRuntime(provider);
+ const events = collect(rt, 'brain:thinking');
+ await rt.send('question');
+ expect(events).toHaveLength(1);
+ expect(events[0].content).toBe('Reasoning here');
+ });
+
+ it('does not emit brain:thinking when thinking is empty', async () => {
+ const provider = mockProvider([textResp('answer')]);
+ const rt = makeRuntime(provider);
+ const events = collect(rt, 'brain:thinking');
+ await rt.send('question');
+ expect(events).toHaveLength(0);
+ });
+});
+
+// ── Tool call dispatch ────────────────────────────────────────────────────────
+
+describe('Runtime — tool dispatch', () => {
+ it('calls the built-in handler when provider returns a tool call', async () => {
+ const provider = mockProvider([toolResp('lookAt', { target: 'user' }), textResp('Done')]);
+ const viewer = { lookAt: vi.fn() };
+ const rt = makeRuntime(provider, { viewer });
+ await rt.send('look at me');
+ expect(viewer.lookAt).toHaveBeenCalledWith('user');
+ });
+
+ it('emits skill:tool-called after each tool execution', async () => {
+ const provider = mockProvider([toolResp('lookAt', { target: 'camera' }), textResp('Done')]);
+ const rt = makeRuntime(provider, { viewer: { lookAt: vi.fn() } });
+ const events = collect(rt, 'skill:tool-called');
+ await rt.send('look');
+ expect(events).toHaveLength(1);
+ expect(events[0]).toMatchObject({ tool: 'lookAt', args: { target: 'camera' } });
+ });
+
+ it('sends tool results back to provider on the next complete() call', async () => {
+ const provider = mockProvider([
+ toolResp('lookAt', { target: 'user' }, 'call_abc'),
+ textResp('Done'),
+ ]);
+ const rt = makeRuntime(provider, { viewer: { lookAt: vi.fn() } });
+ await rt.send('look');
+ expect(provider.complete).toHaveBeenCalledTimes(2);
+ const secondMessages = provider.complete.mock.calls[1][0].messages;
+ const toolResultMsg = secondMessages.find(
+ (m) => m.role === 'user' && Array.isArray(m.content),
+ );
+ expect(toolResultMsg).toBeDefined();
+ expect(toolResultMsg.content[0].tool_use_id).toBe('call_abc');
+ });
+
+ it('skill-provided tool shadows built-in when skills.findSkillForTool returns a match', async () => {
+ const provider = mockProvider([toolResp('wave', {}), textResp('Done')]);
+ const skillInvoke = vi.fn().mockResolvedValue({ ok: true, from: 'skill' });
+ const skills = {
+ findSkillForTool: vi.fn().mockReturnValue({ invoke: skillInvoke }),
+ allTools: () => [],
+ systemPrompt: () => '',
+ };
+ const rt = makeRuntime(provider, { skills });
+ await rt.send('wave');
+ expect(skillInvoke).toHaveBeenCalledWith('wave', {}, expect.any(Object));
+ });
+});
+
+// ── MAX_TOOL_ITERATIONS guard ─────────────────────────────────────────────────
+
+describe('Runtime — MAX_TOOL_ITERATIONS', () => {
+ it('exits the loop after 8 iterations even if provider keeps returning tool calls', async () => {
+ const infiniteProvider = {
+ complete: vi.fn(() => Promise.resolve(toolResp('lookAt', { target: 'user' }))),
+ formatAssistantWithToolCalls(text, toolCalls) {
+ return {
+ role: 'assistant',
+ content: toolCalls.map((c) => ({
+ type: 'tool_use',
+ id: c.id,
+ name: c.name,
+ input: c.input,
+ })),
+ };
+ },
+ formatToolResults(results) {
+ return {
+ role: 'user',
+ content: results.map((r) => ({
+ type: 'tool_result',
+ tool_use_id: r.id,
+ content: JSON.stringify(r.output),
+ })),
+ };
+ },
+ };
+ const rt = makeRuntime(infiniteProvider, { viewer: { lookAt: vi.fn() } });
+ const result = await rt.send('go');
+ expect(infiniteProvider.complete).toHaveBeenCalledTimes(8);
+ expect(result.text).toBe('');
+ });
+});
+
+// ── Error handling ────────────────────────────────────────────────────────────
+
+describe('Runtime — tool error handling', () => {
+ it('records isError and continues loop without throwing when tool is unknown', async () => {
+ const provider = mockProvider([toolResp('nonexistent_tool', {}), textResp('Recovered')]);
+ const rt = makeRuntime(provider);
+ const toolEvents = collect(rt, 'skill:tool-called');
+ const result = await rt.send('do something');
+ expect(result.text).toBe('Recovered');
+ expect(toolEvents[0].result).toMatchObject({ error: expect.stringContaining('Unknown tool') });
+ });
+
+ it('records isError when tool handler throws and still reaches final response', async () => {
+ const provider = mockProvider([toolResp('lookAt', { target: 'user' }), textResp('OK')]);
+ const viewer = {
+ lookAt: vi.fn(() => {
+ throw new Error('viewer not ready');
+ }),
+ };
+ const rt = makeRuntime(provider, { viewer });
+ const toolEvents = collect(rt, 'skill:tool-called');
+ const result = await rt.send('look');
+ expect(result.text).toBe('OK');
+ expect(toolEvents[0].result).toMatchObject({ error: 'viewer not ready' });
+ });
+});
+
+// ── Busy guard ────────────────────────────────────────────────────────────────
+
+describe('Runtime — busy guard', () => {
+ it('throws if send() is called while a turn is in progress', async () => {
+ const provider = mockProvider([textResp('ok')]);
+ const rt = makeRuntime(provider);
+ const first = rt.send('first');
+ await expect(rt.send('second')).rejects.toThrow('Runtime busy');
+ await first;
+ });
+
+ it('clears busy flag after send() completes', async () => {
+ const provider = mockProvider([textResp('ok'), textResp('ok2')]);
+ const rt = makeRuntime(provider);
+ await rt.send('first');
+ await expect(rt.send('second')).resolves.toMatchObject({ text: 'ok2' });
+ });
+});
+
+// ── BUILTIN_HANDLERS ──────────────────────────────────────────────────────────
+
+describe('BUILTIN_HANDLERS.speak', () => {
+ it('calls ctx.speak with the text and returns ok', async () => {
+ const ctx = { speak: vi.fn().mockResolvedValue(undefined) };
+ const result = await BUILTIN_HANDLERS.speak({ text: 'Hello there' }, ctx);
+ expect(ctx.speak).toHaveBeenCalledWith('Hello there');
+ expect(result).toEqual({ ok: true });
+ });
+});
+
+describe('BUILTIN_HANDLERS.remember', () => {
+ it('writes to ctx.memory and returns ok with the saved key', async () => {
+ const ctx = { memory: { write: vi.fn() } };
+ const args = {
+ key: 'user_role',
+ name: 'User role',
+ description: 'What the user does',
+ type: 'user',
+ body: 'The user is a developer.',
+ };
+ const result = await BUILTIN_HANDLERS.remember(args, ctx);
+ expect(ctx.memory.write).toHaveBeenCalledWith('user_role', {
+ name: 'User role',
+ description: 'What the user does',
+ type: 'user',
+ body: 'The user is a developer.',
+ });
+ expect(result).toEqual({ ok: true, saved: 'user_role' });
+ });
+});
+
+describe('BUILTIN_HANDLERS.lookAt', () => {
+ it('calls ctx.viewer.lookAt with the target and returns ok', async () => {
+ const ctx = { viewer: { lookAt: vi.fn() } };
+ const result = await BUILTIN_HANDLERS.lookAt({ target: 'camera' }, ctx);
+ expect(ctx.viewer.lookAt).toHaveBeenCalledWith('camera');
+ expect(result).toEqual({ ok: true, target: 'camera' });
+ });
+
+ it('defaults target to "user" when not provided', async () => {
+ const ctx = { viewer: { lookAt: vi.fn() } };
+ const result = await BUILTIN_HANDLERS.lookAt({}, ctx);
+ expect(ctx.viewer.lookAt).toHaveBeenCalledWith('user');
+ expect(result.target).toBe('user');
+ });
+});
+
+describe('BUILTIN_HANDLERS.setExpression', () => {
+ it('calls ctx.viewer.setExpression with preset and intensity', async () => {
+ const ctx = { viewer: { setExpression: vi.fn() } };
+ const result = await BUILTIN_HANDLERS.setExpression({ preset: 'happy', intensity: 0.8 }, ctx);
+ expect(ctx.viewer.setExpression).toHaveBeenCalledWith('happy', 0.8);
+ expect(result).toEqual({ ok: true, preset: 'happy' });
+ });
+
+ it('defaults intensity to 1 when not provided', async () => {
+ const ctx = { viewer: { setExpression: vi.fn() } };
+ await BUILTIN_HANDLERS.setExpression({ preset: 'sad' }, ctx);
+ expect(ctx.viewer.setExpression).toHaveBeenCalledWith('sad', 1);
+ });
+});
diff --git a/vercel.json b/vercel.json
index ea9a493e0..1f21eff80 100644
--- a/vercel.json
+++ b/vercel.json
@@ -95,6 +95,8 @@
{ "src": "/api/agents/([^/]+)/usage", "dest": "/api/agents/[id]" },
{ "src": "/api/agents/([^/]+)/memories/([^/]+)", "dest": "/api/agents/[id]" },
{ "src": "/api/agents/([^/]+)/memories", "dest": "/api/agents/[id]" },
+ { "src": "/api/agents/([^/]+)/memory/pin", "dest": "/api/agents/[id]" },
+ { "src": "/api/agents/([^/]+)/memory/([^/]+)", "dest": "/api/agents/[id]" },
{ "src": "/api/agents/([^/]+)/livekit-token", "dest": "/api/agents/[id]" },
{ "src": "/api/agents/([^/]+)/embed", "dest": "/api/agents/[id]" },
{ "src": "/api/agents/pumpfun-feed", "dest": "/api/agents/pumpfun?_handler=feed" },