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.

mobile UX overhaul + chat failover + Helius RPC fallback + SDK update

nirholas48212dd080b3
diff --git a/api/_lib/balances.js b/api/_lib/balances.js
index 4f00baac8..2026230a7 100644
--- a/api/_lib/balances.js
+++ b/api/_lib/balances.js
@@ -27,30 +27,51 @@ async function fetchJson(url, opts = {}) {
return r.json();
}
-async function getSolanaBalances(address) {
- const rpcUrl = process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com';
+// Helius primary, public mainnet-beta fallback. Helius is required for `getAsset`
+// (DAS) — token metadata silently degrades when we fall back, but balances still
+// resolve, which is better than 503ing the whole portfolio when Helius is rate-
+// limited or out of credits.
+const PUBLIC_SOL_RPC = process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com';
+function heliusRpc() {
+ const key = process.env.HELIUS_API_KEY;
+ return key ? `https://mainnet.helius-rpc.com/?api-key=${key}` : null;
+}
- const solResp = await fetchJson(rpcUrl, {
+async function solRpc(body, { allowFallback = true } = {}) {
+ const helius = heliusRpc();
+ if (helius) {
+ try {
+ return await fetchJson(helius, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify(body),
+ });
+ } catch (err) {
+ if (!allowFallback) throw err;
+ console.warn('[balances] helius failed, falling back to public RPC:', err?.message);
+ }
+ }
+ return fetchJson(PUBLIC_SOL_RPC, {
method: 'POST',
headers: { 'content-type': 'application/json' },
- body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'getBalance', params: [address] }),
+ body: JSON.stringify(body),
});
+}
+
+async function getSolanaBalances(address) {
+ const solResp = await solRpc({ jsonrpc: '2.0', id: 1, method: 'getBalance', params: [address] });
const lamports = solResp.result?.value ?? 0;
const solAmount = lamports / 1e9;
- const tokenResp = await fetchJson(rpcUrl, {
- method: 'POST',
- headers: { 'content-type': 'application/json' },
- body: JSON.stringify({
- jsonrpc: '2.0',
- id: 2,
- method: 'getTokenAccountsByOwner',
- params: [
- address,
- { programId: 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA' },
- { encoding: 'jsonParsed' },
- ],
- }),
+ const tokenResp = await solRpc({
+ jsonrpc: '2.0',
+ id: 2,
+ method: 'getTokenAccountsByOwner',
+ params: [
+ address,
+ { programId: 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA' },
+ { encoding: 'jsonParsed' },
+ ],
});
const tokenAccounts = tokenResp.result?.value ?? [];
@@ -91,21 +112,25 @@ async function getSolanaBalances(address) {
// best-effort
}
- // DAS metadata is one RPC per mint; run them concurrently.
- const metaResults = await Promise.all(
- fungible.map((t) =>
- fetchJson(rpcUrl, {
- method: 'POST',
- headers: { 'content-type': 'application/json' },
- body: JSON.stringify({
- jsonrpc: '2.0',
- id: 'meta',
- method: 'getAsset',
- params: { id: t.mint },
- }),
- }).catch(() => null),
- ),
- );
+ // DAS metadata (getAsset) is Helius-only — skip entirely if no key, since
+ // public mainnet-beta returns "method not found" for every mint.
+ const helius = heliusRpc();
+ const metaResults = helius
+ ? await Promise.all(
+ fungible.map((t) =>
+ fetchJson(helius, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({
+ jsonrpc: '2.0',
+ id: 'meta',
+ method: 'getAsset',
+ params: { id: t.mint },
+ }),
+ }).catch(() => null),
+ ),
+ )
+ : fungible.map(() => null);
const tokens = fungible.map((t, i) => {
const priceInfo = cgTokenPrices[t.mint.toLowerCase()] || cgTokenPrices[t.mint] || {};
diff --git a/api/chat.js b/api/chat.js
index 0bb23748c..a60fd0a44 100644
--- a/api/chat.js
+++ b/api/chat.js
@@ -253,7 +253,7 @@ export default wrap(async (req, res) => {
anonymous = true;
}
- const route = pickProvider(body.provider, body.model);
+ let route = pickProvider(body.provider, body.model);
if (!route) {
return error(res, 503, 'chat_unavailable', 'no chat provider is configured');
}
@@ -282,19 +282,43 @@ export default wrap(async (req, res) => {
history.push({ role: 'user', content: body.message });
const started = Date.now();
+ // Provider/model failover chain. The first entry is the picked route; if it
+ // returns 429 (rate-limit) or 5xx (provider down) we cycle through a
+ // pre-built fallback list before surfacing an error.
+ const fallbackRoutes = buildFallbackChain(route);
+
let upstream;
- try {
- upstream = await fetch(route.url, {
- method: 'POST',
- headers: route.headers,
- body: JSON.stringify(route.buildPayload({ systemPrompt, history, maxTokens })),
- });
- } catch (err) {
- captureException(err, { route: 'chat', stage: 'fetch', provider: route.name });
- if (process.env.DEBUG === 'true') {
- console.warn(`[chat:${route.name}] upstream fetch failed:`, err.message);
+ let routeIdx = 0;
+ while (true) {
+ try {
+ upstream = await fetch(route.url, {
+ method: 'POST',
+ headers: route.headers,
+ body: JSON.stringify(route.buildPayload({ systemPrompt, history, maxTokens })),
+ });
+ } catch (err) {
+ captureException(err, { route: 'chat', stage: 'fetch', provider: route.name });
+ console.error(`[chat:${route.name}] upstream fetch failed:`, err.message);
+ // Network blip — try next route if available.
+ routeIdx++;
+ if (routeIdx < fallbackRoutes.length) {
+ route = fallbackRoutes[routeIdx];
+ continue;
+ }
+ return error(res, 502, 'upstream_unavailable', 'chat backend unreachable');
}
- return error(res, 502, 'upstream_unavailable', 'chat backend unreachable');
+
+ // Fall over on rate-limit (429) and transient gateway errors (502/503/504).
+ // Don't re-fetch on 4xx other than 429 — those are caller mistakes that
+ // the next provider would also reject.
+ if ((upstream.status === 429 || upstream.status >= 500) && routeIdx + 1 < fallbackRoutes.length) {
+ const text = await upstream.text().catch(() => '');
+ console.warn(`[chat:${route.name}] ${upstream.status} — falling over to ${fallbackRoutes[routeIdx + 1].name}/${fallbackRoutes[routeIdx + 1].model}: ${text.slice(0, 120)}`);
+ routeIdx++;
+ route = fallbackRoutes[routeIdx];
+ continue;
+ }
+ break;
}
if (!upstream.ok) {
@@ -306,7 +330,7 @@ export default wrap(async (req, res) => {
body: text.slice(0, 400),
});
// Always log — diagnosing prod 502s without provider context is hopeless.
- console.warn(`[chat:${route.name}]`, upstream.status, text.slice(0, 400));
+ console.error(`[chat:${route.name}]`, upstream.status, text.slice(0, 400));
// Surface the upstream reason in the response body. Strip any API-key
// fragments out of defence; the body is generally short JSON like
// {"error":{"type":"invalid_request_error","message":"..."}}.
@@ -392,6 +416,58 @@ function pickProvider(requested, model) {
return null;
}
+// Build an ordered failover list starting with the primary route. Cycles
+// through (a) sibling models on the same provider so a per-model rate-limit
+// doesn't kill the request, then (b) the next configured provider's default
+// model. Stops as soon as a provider has no API key. The primary is always
+// position 0 so the happy path is one entry.
+//
+// Why per-provider sibling models: OpenRouter's `:free` tier rate-limits per
+// model. Falling over from llama-3.3-70b:free → llama-3.1-8b:free → mistral-
+// 7b:free recovers from a single upstream burst without paying. Last resort
+// is paid Anthropic so the user still gets a response.
+const FALLBACK_SIBLINGS = {
+ openrouter: [
+ 'meta-llama/llama-3.3-70b-instruct:free',
+ 'meta-llama/llama-3.1-8b-instruct:free',
+ 'mistralai/mistral-7b-instruct:free',
+ ],
+ groq: ['llama-3.3-70b-versatile', 'llama-3.1-8b-instant'],
+ anthropic: ['claude-sonnet-4-6', 'claude-haiku-4-5-20251001'],
+ openai: ['gpt-4o-mini'],
+};
+
+function buildFallbackChain(primary) {
+ const chain = [primary];
+ const seen = new Set([`${primary.name}:${primary.model}`]);
+
+ // Sibling models on the same provider
+ const siblings = FALLBACK_SIBLINGS[primary.name] || [];
+ for (const m of siblings) {
+ const key = `${primary.name}:${m}`;
+ if (seen.has(key)) continue;
+ seen.add(key);
+ const cfg = PROVIDERS[primary.name];
+ const apiKey = process.env[cfg.envKey];
+ if (!apiKey) continue;
+ chain.push(makeRoute(primary.name, cfg, apiKey, m));
+ }
+
+ // Other providers, in declared order, picking the configured default model
+ for (const name of Object.keys(PROVIDERS)) {
+ if (name === primary.name) continue;
+ const cfg = PROVIDERS[name];
+ const apiKey = process.env[cfg.envKey];
+ if (!apiKey) continue;
+ const key = `${name}:${cfg.defaultModel}`;
+ if (seen.has(key)) continue;
+ seen.add(key);
+ chain.push(makeRoute(name, cfg, apiKey, cfg.defaultModel));
+ }
+
+ return chain;
+}
+
function makeRoute(name, cfg, apiKey, model) {
if (cfg.style === 'anthropic') {
return {
diff --git a/scripts/verify-widget-no-sw.mjs b/scripts/verify-widget-no-sw.mjs
new file mode 100644
index 000000000..02c309904
--- /dev/null
+++ b/scripts/verify-widget-no-sw.mjs
@@ -0,0 +1,61 @@
+// Post-build verification: confirm dist/widget.html (and other embed entries)
+// don't carry the VitePWA service-worker registration script. Without this
+// stripping, third-party iframes that load /widget would register a SW under
+// our origin and intercept requests across every other page on three.ws —
+// a privacy + correctness hazard for embedders.
+//
+// node scripts/verify-widget-no-sw.mjs
+//
+// Exits non-zero on the first leak. CI wires this after `vite build`.
+
+import { readFileSync, existsSync } from 'node:fs';
+import { join } from 'node:path';
+
+const DIST = join(process.cwd(), 'dist');
+
+// Source-relative names mirrored from the strip-sw plugin in vite.config.js.
+// Add new embed entries here and in the plugin's EMBED_ENTRIES Set together.
+const EMBED_ENTRIES = ['widget', 'embed', 'avatar-embed', 'agent-embed', 'a-embed'];
+
+const REGISTER_SW_RE = /id=["']vite-plugin-pwa:register-sw["']/;
+
+// Vite emits page HTMLs under one of:
+// dist/<name>.html
+// dist/pages/<name>.html (when source lives in /pages/)
+function candidatePaths(name) {
+ return [join(DIST, `${name}.html`), join(DIST, 'pages', `${name}.html`)];
+}
+
+const leaks = [];
+const checked = [];
+for (const entry of EMBED_ENTRIES) {
+ const paths = candidatePaths(entry);
+ let found = false;
+ for (const p of paths) {
+ if (!existsSync(p)) continue;
+ found = true;
+ const html = readFileSync(p, 'utf8');
+ checked.push(p);
+ if (REGISTER_SW_RE.test(html)) {
+ leaks.push(p);
+ console.error(`✗ SW registration script present in ${p}`);
+ } else {
+ console.log(`✓ ${p}`);
+ }
+ }
+ if (!found) {
+ console.warn(`! ${entry} not found in dist/ — skipped (may be unused or a Vercel-only static page).`);
+ }
+}
+
+if (leaks.length) {
+ console.error(`\n✗ ${leaks.length} embed page(s) still ship registerSW — fix the strip-sw transformIndexHtml plugin in vite.config.js.`);
+ process.exit(1);
+}
+
+if (!checked.length) {
+ console.error('✗ no embed pages found in dist/ — did `vite build` run?');
+ process.exit(2);
+}
+
+console.log(`\n✓ ${checked.length}/${checked.length} embed page(s) have no SW registration script.`);
diff --git a/sdk/CHANGELOG.md b/sdk/CHANGELOG.md
index 325670475..f6edd792b 100644
--- a/sdk/CHANGELOG.md
+++ b/sdk/CHANGELOG.md
@@ -1,6 +1,6 @@
# Changelog
-All notable changes to `@nirholas/agent-kit` are documented here.
+All notable changes to `@three-ws/sdk` are documented here.
The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
diff --git a/sdk/README.md b/sdk/README.md
index 1950f9c02..cdf528539 100644
--- a/sdk/README.md
+++ b/sdk/README.md
@@ -1,11 +1,11 @@
-# @nirholas/agent-kit
+# @three-ws/sdk
Ship an **ERC-8004 agent** with on-chain identity, a chat panel, and discoverable `.well-known` endpoints — in minutes.
## Install
```bash
-npm install @nirholas/agent-kit ethers
+npm install @three-ws/sdk ethers
```
`ethers@^6` is a peer dependency (only needed if you call `register()`).
@@ -13,8 +13,8 @@ npm install @nirholas/agent-kit ethers
## Quick start
```js
-import { AgentKit } from '@nirholas/agent-kit';
-import '@nirholas/agent-kit/styles';
+import { AgentKit } from '@three-ws/sdk';
+import '@three-ws/sdk/styles';
const agent = new AgentKit({
name: 'My Agent',
@@ -36,7 +36,7 @@ framework or plain HTML — the helper lazy-loads the published
from the three.ws CDN.
```js
-import { loadAvatar } from '@nirholas/agent-kit';
+import { loadAvatar } from '@three-ws/sdk';
const handle = await loadAvatar({
agentId: 'agt_abc123',
@@ -135,7 +135,7 @@ import {
aiPlugin,
IDENTITY_REGISTRY_ABI,
REGISTRY_DEPLOYMENTS,
-} from '@nirholas/agent-kit';
+} from '@three-ws/sdk';
```
## Configuring registry addresses
@@ -155,8 +155,8 @@ Grant, list, redeem, and revoke ERC-7710 scoped delegations via the `Permissions
`grant` and `revoke` require a browser wallet (MetaMask / any injected ethers v6 Signer).
```ts
-import { AgentKit } from '@nirholas/agent-kit';
-import { PermissionsClient } from '@nirholas/agent-kit/permissions';
+import { AgentKit } from '@three-ws/sdk';
+import { PermissionsClient } from '@three-ws/sdk/permissions';
const client = new PermissionsClient({ baseUrl: 'https://three.ws/' });
@@ -191,7 +191,7 @@ For advanced use (direct toolkit access with tree-shaking):
import {
encodeScopedDelegation,
isDelegationValid,
-} from '@nirholas/agent-kit/permissions/advanced';
+} from '@three-ws/sdk/permissions/advanced';
```
## License
diff --git a/sdk/agent-sdk/package.json b/sdk/agent-sdk/package.json
index 553173bf9..d3abe9d91 100644
--- a/sdk/agent-sdk/package.json
+++ b/sdk/agent-sdk/package.json
@@ -1,13 +1,28 @@
{
"name": "@3d-agent/sdk",
"version": "0.0.1",
- "description": "3D-Agent JavaScript SDK",
- "main": "dist/index.js",
- "module": "dist/index.mjs",
- "types": "dist/index.d.ts",
+ "description": "3D-Agent JavaScript SDK — minimal chat + embed helpers for the three.ws agent fabric.",
+ "type": "module",
+ "main": "./dist/index.cjs",
+ "module": "./dist/index.js",
+ "types": "./dist/index.d.ts",
+ "exports": {
+ ".": {
+ "types": "./dist/index.d.ts",
+ "import": "./dist/index.js",
+ "require": "./dist/index.cjs",
+ "default": "./dist/index.js"
+ }
+ },
+ "files": [
+ "dist",
+ "src",
+ "README.md"
+ ],
"scripts": {
- "build": "tsup src/index.ts --format cjs,esm --dts",
- "dev": "tsup src/index.ts --format cjs,esm --dts --watch",
+ "build": "tsup src/index.ts --format cjs,esm --dts --out-dir dist --clean",
+ "prepublishOnly": "npm run build",
+ "dev": "tsup src/index.ts --format cjs,esm --dts --out-dir dist --watch",
"test": "vitest"
},
"devDependencies": {
diff --git a/sdk/agent-sdk/src/index.ts b/sdk/agent-sdk/src/index.ts
index 533cbee13..fd0518596 100644
--- a/sdk/agent-sdk/src/index.ts
+++ b/sdk/agent-sdk/src/index.ts
@@ -1,85 +1,129 @@
+/**
+ * @3d-agent/sdk — minimal chat + embed SDK for the three.ws agent fabric.
+ *
+ * Defaults point at https://three.ws. Override via the `baseUrl` option on
+ * the constructor (or via the `THREE_WS_BASE_URL` env var for Node consumers).
+ */
+
+export interface AgentOptions {
+ /** API base URL. Defaults to https://three.ws or the THREE_WS_BASE_URL env. */
+ baseUrl?: string;
+}
+
+const DEFAULT_BASE_URL = 'https://three.ws';
+
+function resolveBaseUrl(opts?: AgentOptions): string {
+ if (opts?.baseUrl) return stripTrailingSlash(opts.baseUrl);
+ if (typeof process !== 'undefined' && process.env?.THREE_WS_BASE_URL) {
+ return stripTrailingSlash(process.env.THREE_WS_BASE_URL);
+ }
+ return DEFAULT_BASE_URL;
+}
+
+function stripTrailingSlash(s: string): string {
+ return s.endsWith('/') ? s.slice(0, -1) : s;
+}
+
export class Agent {
- private apiKey: string;
- private agentId: string;
+ private apiKey: string;
+ private agentId: string;
+ private baseUrl: string;
- constructor(apiKey: string, agentId: string) {
- this.apiKey = apiKey;
- this.agentId = agentId;
- }
+ constructor(apiKey: string, agentId: string, options?: AgentOptions) {
+ this.apiKey = apiKey;
+ this.agentId = agentId;
+ this.baseUrl = resolveBaseUrl(options);
+ }
- async chat(message: string, history: { role: 'user' | 'assistant', content: string }[] = []): Promise<AsyncIterable<any>> {
- const response = await fetch('https://three.ws/api/chat', {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- 'Authorization': `Bearer ${this.apiKey}`,
- },
- body: JSON.stringify({
- agentId: this.agentId,
- message,
- history,
- }),
- });
+ async chat(
+ message: string,
+ history: { role: 'user' | 'assistant'; content: string }[] = [],
+ ): Promise<AsyncIterable<any>> {
+ const response = await fetch(`${this.baseUrl}/api/chat`, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ Authorization: `Bearer ${this.apiKey}`,
+ },
+ body: JSON.stringify({
+ agentId: this.agentId,
+ message,
+ history,
+ }),
+ });
- if (!response.ok) {
- const errorText = await response.text();
- throw new Error(`Chat API request failed: ${response.status} ${errorText}`);
- }
+ if (!response.ok) {
+ const errorText = await response.text();
+ throw new Error(`Chat API request failed: ${response.status} ${errorText}`);
+ }
- if (!response.body) {
- throw new Error('No response body from chat API');
- }
+ if (!response.body) {
+ throw new Error('No response body from chat API');
+ }
- const reader = response.body.getReader();
- const decoder = new TextDecoder();
- let buffer = '';
+ const reader = response.body.getReader();
+ const decoder = new TextDecoder();
+ let buffer = '';
- return {
- [Symbol.asyncIterator]: () => ({
- async next() {
- while (true) {
- const { done, value } = await reader.read();
- if (done) {
- if (buffer.length > 0) {
- try {
- return { value: JSON.parse(buffer), done: false };
- } catch (e) {
- // ignore partial JSON at the end
- }
- }
- return { done: true, value: undefined };
- }
+ return {
+ [Symbol.asyncIterator]: () => ({
+ async next() {
+ while (true) {
+ const { done, value } = await reader.read();
+ if (done) {
+ if (buffer.length > 0) {
+ // Final fragment — server-sent-events streams sometimes
+ // terminate mid-buffer if the connection closes between
+ // events. We surface the parse error so consumers can
+ // log it instead of silently dropping the last chunk.
+ try {
+ return { value: JSON.parse(buffer), done: false };
+ } catch (err) {
+ console.warn(
+ '[3d-agent/sdk] dropped trailing chat fragment',
+ (err as Error)?.message,
+ );
+ }
+ }
+ return { done: true, value: undefined };
+ }
- buffer += decoder.decode(value, { stream: true });
- const lines = buffer.split('\n');
- buffer = lines.pop() || '';
+ buffer += decoder.decode(value, { stream: true });
+ const lines = buffer.split('\n');
+ buffer = lines.pop() || '';
- for (const line of lines) {
- if (line.startsWith('data: ')) {
- const json = line.slice(6);
- try {
- return { value: JSON.parse(json), done: false };
- } catch (e) {
- // ignore partial JSON
- }
- }
- }
- }
- }
- })
- };
- }
+ for (const line of lines) {
+ if (line.startsWith('data: ')) {
+ const json = line.slice(6);
+ try {
+ return { value: JSON.parse(json), done: false };
+ } catch (err) {
+ // Mid-stream parse error — log and continue to the
+ // next line rather than silently swallowing the
+ // failure (which used to mask malformed payloads).
+ console.warn(
+ '[3d-agent/sdk] skipped malformed SSE chunk',
+ (err as Error)?.message,
+ );
+ }
+ }
+ }
+ }
+ },
+ }),
+ };
+ }
- embed(element: HTMLElement) {
- const iframe = document.createElement('iframe');
- iframe.src = `https://three.ws/agent/${this.agentId}/embed`;
- iframe.width = '100%';
- iframe.height = '100%';
- iframe.style.border = 'none';
- element.appendChild(iframe);
- }
+ embed(element: HTMLElement) {
+ const iframe = document.createElement('iframe');
+ iframe.src = `${this.baseUrl}/agent/${this.agentId}/embed`;
+ iframe.width = '100%';
+ iframe.height = '100%';
+ iframe.style.border = 'none';
+ element.appendChild(iframe);
+ }
}
-export function createAgent(apiKey: string, agentId: string): Agent {
- return new Agent(apiKey, agentId);
+export function createAgent(apiKey: string, agentId: string, options?: AgentOptions): Agent {
+ return new Agent(apiKey, agentId, options);
}
diff --git a/sdk/example/index.html b/sdk/example/index.html
index 40e63ea8c..7c34e5a8e 100644
--- a/sdk/example/index.html
+++ b/sdk/example/index.html
@@ -3,7 +3,7 @@
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
- <title>@nirholas/agent-kit — demo</title>
+ <title>@three-ws/sdk — demo</title>
<link rel="stylesheet" href="../src/styles.css" />
<style>
* {
@@ -97,7 +97,7 @@
const agent = new AgentKit({
name: 'Demo Agent',
description:
- 'A demo of @nirholas/agent-kit — the fastest way to ship an ERC-8004 agent.',
+ 'A demo of @three-ws/sdk — the fastest way to ship an ERC-8004 agent.',
endpoint: 'https://demo.example.com',
image: 'https://demo.example.com/logo.png',
version: '0.1.0',
diff --git a/sdk/package.json b/sdk/package.json
index ebc4e841a..eda25652e 100644
--- a/sdk/package.json
+++ b/sdk/package.json
@@ -3,26 +3,39 @@
"version": "0.1.0",
"description": "Ship a cross-chain 3D AI agent with EVM + Solana identity, a chat panel, and discoverable .well-known endpoints.",
"type": "module",
- "main": "./dist/index.js",
- "module": "./dist/index.mjs",
+ "main": "./src/index.js",
+ "module": "./src/index.js",
"types": "./types/index.d.ts",
"exports": {
".": {
"types": "./types/index.d.ts",
- "import": "./dist/index.mjs",
- "require": "./dist/index.js",
- "default": "./dist/index.mjs"
+ "import": "./src/index.js",
+ "default": "./src/index.js"
},
"./permissions": {
"types": "./types/permissions.d.ts",
- "import": "./dist/index.mjs",
- "require": "./dist/index.js",
- "default": "./dist/index.mjs"
+ "import": "./src/permissions.js",
+ "default": "./src/permissions.js"
},
- "./styles": "./dist/styles.css"
+ "./permissions/advanced": {
+ "types": "./src/permissions/advanced.d.ts",
+ "import": "./src/permissions/advanced.js",
+ "default": "./src/permissions/advanced.js"
+ },
+ "./styles": "./src/styles.css",
+ "./solana": {
+ "types": "./types/solana.d.ts",
+ "import": "./src/solana.js",
+ "default": "./src/solana.js"
+ },
+ "./solana-attestations": {
+ "types": "./types/solana-attestations.d.ts",
+ "import": "./src/solana-attestations.js",
+ "default": "./src/solana-attestations.js"
+ }
},
"files": [
- "dist",
+ "src",
"types",
"README.md",
"LICENSE",
@@ -30,6 +43,7 @@
],
"scripts": {
"build": "node build.mjs",
+ "prepublishOnly": "node build.mjs",
"test": "node --test 'test/**/*.test.js'"
},
"publishConfig": {
diff --git a/sdk/src/erc7710/abi.js b/sdk/src/erc7710/abi.js
index 4786f133a..973dd5f71 100644
--- a/sdk/src/erc7710/abi.js
+++ b/sdk/src/erc7710/abi.js
@@ -1,47 +1,141 @@
/**
* ERC-7710 / MetaMask Delegation Toolkit ABIs and addresses.
*
- * Caveat enforcer addresses and DelegationManager deployments.
- * Source: https://github.com/MetaMask/delegation-framework
+ * Source of deployment addresses:
+ * https://github.com/MetaMask/delegation-framework/blob/main/documents/deployments
+ *
+ * Authoritative deployments are tracked in env vars so this SDK can be used
+ * against any chain the MetaMask delegation framework has been deployed to,
+ * including networks the SDK was written before. Set:
+ *
+ * THREE_WS_DELEGATION_MANAGER_<chainId>=0x…
+ * THREE_WS_ENFORCER_<NAME>_<chainId>=0x…
+ *
+ * where <chainId> is the EVM chain id and <NAME> is one of
+ * ALLOWED_TARGETS / ERC20_LIMIT / TIMESTAMP. The lookup helpers in this
+ * file read the env first and fall back to a built-in registry only for
+ * chains that explicitly have a real deployed address.
+ *
+ * Until a chain has either an env override or a registered address,
+ * `getDelegationManager(chainId)` throws — preventing the SDK from
+ * silently emitting transactions to the zero address.
*/
+import { encodeAbiParameters, parseAbiParameters } from 'viem';
+
export const DELEGATION_MANAGER_ABI = [
'function disableDelegation(bytes32 delegationHash) external',
'function isDelegationDisabled(bytes32 delegationHash) external view returns (bool)',
'event DisabledDelegation(bytes32 indexed delegationHash)',
];
-/** Known DelegationManager addresses keyed by chainId. */
-export const DELEGATION_MANAGER_DEPLOYMENTS = {
- 1: '0x0000000000000000000000000000000000000000', // Ethereum mainnet — update when deployed
- 11155111: '0x0000000000000000000000000000000000000000', // Sepolia — update when deployed
-};
+/**
+ * Known DelegationManager addresses keyed by chainId.
+ * No entry == not deployed; consumers must set an env override or pass an
+ * explicit address to the higher-level helpers.
+ *
+ * @type {Record<number, string>}
+ */
+export const DELEGATION_MANAGER_DEPLOYMENTS = Object.freeze({
+ // Intentionally empty until an upstream deployment is published. Set the
+ // `THREE_WS_DELEGATION_MANAGER_<chainId>` env to opt into a chain.
+});
/**
* Caveat enforcer contract addresses keyed by chainId.
- * Each enforcer restricts what a delegation can do.
+ * Same opt-in convention as DELEGATION_MANAGER_DEPLOYMENTS.
+ *
+ * @type {Record<string, Record<number, string>>}
*/
-export const CAVEAT_ENFORCERS = {
- AllowedTargetsEnforcer: {
- 1: '0x0000000000000000000000000000000000000000',
- 11155111: '0x0000000000000000000000000000000000000000',
- },
- ERC20LimitEnforcer: {
- 1: '0x0000000000000000000000000000000000000000',
- 11155111: '0x0000000000000000000000000000000000000000',
- },
- TimestampEnforcer: {
- 1: '0x0000000000000000000000000000000000000000',
- 11155111: '0x0000000000000000000000000000000000000000',
- },
-};
+export const CAVEAT_ENFORCERS = Object.freeze({
+ AllowedTargetsEnforcer: {},
+ ERC20LimitEnforcer: {},
+ TimestampEnforcer: {},
+});
+
+const ZERO_ADDRESS = '0x0000000000000000000000000000000000000000';
+
+function envAddress(key) {
+ if (typeof process === 'undefined' || !process.env) return null;
+ const raw = process.env[key];
+ if (!raw) return null;
+ const trimmed = raw.trim();
+ if (!/^0x[0-9a-fA-F]{40}$/.test(trimmed)) return null;
+ if (trimmed.toLowerCase() === ZERO_ADDRESS) return null;
+ return trimmed;
+}
/**
- * ABI-encode an array of caveat objects into bytes.
+ * Resolve the DelegationManager address for a chain. Throws if no real
+ * deployment is configured (so the SDK cannot accidentally send a tx to the
+ * zero address).
+ *
+ * @param {number} chainId
+ * @returns {string} 0x EVM address
+ */
+export function getDelegationManager(chainId) {
+ const env = envAddress(`THREE_WS_DELEGATION_MANAGER_${chainId}`);
+ if (env) return env;
+ const known = DELEGATION_MANAGER_DEPLOYMENTS[chainId];
+ if (known && known.toLowerCase() !== ZERO_ADDRESS) return known;
+ throw new Error(
+ `erc7710_not_configured: no DelegationManager deployment for chainId ${chainId}. ` +
+ `Set THREE_WS_DELEGATION_MANAGER_${chainId}=0x… to opt in.`,
+ );
+}
+
+/**
+ * Resolve a caveat enforcer address. Same gate as getDelegationManager.
+ *
+ * @param {'AllowedTargetsEnforcer'|'ERC20LimitEnforcer'|'TimestampEnforcer'} name
+ * @param {number} chainId
+ * @returns {string} 0x EVM address
+ */
+export function getCaveatEnforcer(name, chainId) {
+ const map = {
+ AllowedTargetsEnforcer: 'ALLOWED_TARGETS',
+ ERC20LimitEnforcer: 'ERC20_LIMIT',
+ TimestampEnforcer: 'TIMESTAMP',
+ };
+ const slug = map[name];
+ if (!slug) throw new Error(`unknown_enforcer: ${name}`);
+ const env = envAddress(`THREE_WS_ENFORCER_${slug}_${chainId}`);
+ if (env) return env;
+ const known = CAVEAT_ENFORCERS[name]?.[chainId];
+ if (known && known.toLowerCase() !== ZERO_ADDRESS) return known;
+ throw new Error(
+ `erc7710_not_configured: no ${name} deployment for chainId ${chainId}. ` +
+ `Set THREE_WS_ENFORCER_${slug}_${chainId}=0x… to opt in.`,
+ );
+}
+
+/**
+ * ABI-encode an array of caveat objects into bytes for the DelegationManager.
+ * Each caveat is `(address enforcer, bytes terms, bytes args)`.
+ *
* @param {Array<{enforcer: string, terms: string, args: string}>} caveats
* @returns {string} hex-encoded bytes
*/
export function encodeCaveats(caveats) {
- // Minimal placeholder — real implementation uses ethers ABI encoding.
- return '0x' + caveats.map((c) => c.enforcer.slice(2)).join('');
+ if (!Array.isArray(caveats)) {
+ throw new TypeError('encodeCaveats: expected an array of caveats');
+ }
+ const normalised = caveats.map((c, i) => {
+ if (!c || typeof c !== 'object') {
+ throw new TypeError(`encodeCaveats: caveat[${i}] is not an object`);
+ }
+ if (!/^0x[0-9a-fA-F]{40}$/.test(c.enforcer || '')) {
+ throw new TypeError(`encodeCaveats: caveat[${i}].enforcer must be a 0x EVM address`);
+ }
+ const terms = c.terms || '0x';
+ const args = c.args || '0x';
+ if (!/^0x[0-9a-fA-F]*$/.test(terms) || !/^0x[0-9a-fA-F]*$/.test(args)) {
+ throw new TypeError(`encodeCaveats: caveat[${i}].terms / .args must be 0x-hex`);
+ }
+ return { enforcer: c.enforcer, terms, args };
+ });
+ return encodeAbiParameters(
+ parseAbiParameters('(address enforcer, bytes terms, bytes args)[]'),
+ [normalised],
+ );
}
diff --git a/sdk/src/index.d.ts b/sdk/src/index.d.ts
index 7071ace06..4bccb6648 100644
--- a/sdk/src/index.d.ts
+++ b/sdk/src/index.d.ts
@@ -1,5 +1,5 @@
/**
- * @nirholas/agent-kit — TypeScript definitions
+ * @three-ws/sdk — TypeScript definitions
*/
// ---------------------------------------------------------------------------
diff --git a/sdk/src/index.js b/sdk/src/index.js
index 61e7de047..e20c14753 100644
--- a/sdk/src/index.js
+++ b/sdk/src/index.js
@@ -6,8 +6,8 @@
*
* Quick start:
*
- * import { AgentKit } from '@nirholas/agent-kit';
- * import '@nirholas/agent-kit/styles';
+ * import { AgentKit } from '@three-ws/sdk';
+ * import '@three-ws/sdk/styles';
*
* const agent = new AgentKit({
* name: 'My Agent',
diff --git a/sdk/src/permissions.d.ts b/sdk/src/permissions.d.ts
index 29fc19b23..21334998a 100644
--- a/sdk/src/permissions.d.ts
+++ b/sdk/src/permissions.d.ts
@@ -1,5 +1,5 @@
/**
- * @nirholas/agent-kit — Permissions module types
+ * @three-ws/sdk — Permissions module types
*/
import type { Signer } from 'ethers';
diff --git a/sdk/src/permissions.js b/sdk/src/permissions.js
index 83e096220..5fc04c71b 100644
--- a/sdk/src/permissions.js
+++ b/sdk/src/permissions.js
@@ -1,10 +1,10 @@
/**
- * @nirholas/agent-kit — Permissions module
+ * @three-ws/sdk — Permissions module
*
* ERC-7710 scoped delegation client for three.ws.
*
* Quick start:
- * import { PermissionsClient } from '@nirholas/agent-kit/permissions';
+ * import { PermissionsClient } from '@three-ws/sdk/permissions';
* const client = new PermissionsClient({ baseUrl: 'https://three.ws/' });
* const { delegations } = await client.getMetadata(agentId);
*/
diff --git a/sdk/src/permissions/advanced.d.ts b/sdk/src/permissions/advanced.d.ts
index 20175c308..0a35f98bc 100644
--- a/sdk/src/permissions/advanced.d.ts
+++ b/sdk/src/permissions/advanced.d.ts
@@ -1,5 +1,5 @@
/**
- * @nirholas/agent-kit/permissions/advanced — TypeScript definitions
+ * @three-ws/sdk/permissions/advanced — TypeScript definitions
*/
import type { Signer } from 'ethers';
diff --git a/sdk/src/permissions/advanced.js b/sdk/src/permissions/advanced.js
index 76daa1be3..376f0a1f5 100644
--- a/sdk/src/permissions/advanced.js
+++ b/sdk/src/permissions/advanced.js
@@ -1,5 +1,5 @@
/**
- * @nirholas/agent-kit/permissions/advanced
+ * @three-ws/sdk/permissions/advanced
*
* Re-exports low-level ERC-7710 delegation helpers from the toolkit for
* advanced consumers who need direct control over delegation encoding.
@@ -7,7 +7,7 @@
* Tree-shaking note: import from this sub-entry instead of the main package
* entry to avoid pulling in the full PermissionsClient:
*
- * import { encodeScopedDelegation } from '@nirholas/agent-kit/permissions/advanced';
+ * import { encodeScopedDelegation } from '@three-ws/sdk/permissions/advanced';
*/
export {
diff --git a/sdk/src/permissions/toolkit.js b/sdk/src/permissions/toolkit.js
index 2224b1023..0eb337f67 100644
--- a/sdk/src/permissions/toolkit.js
+++ b/sdk/src/permissions/toolkit.js
@@ -9,7 +9,7 @@
import { PermissionError } from '../permissions.js';
export { PermissionError };
-import { DELEGATION_MANAGER_ABI, DELEGATION_MANAGER_DEPLOYMENTS } from '../erc7710/abi.js';
+import { DELEGATION_MANAGER_ABI, getDelegationManager } from '../erc7710/abi.js';
/**
* Build an unsigned delegation envelope ready to be signed via `signDelegation`.
@@ -51,11 +51,15 @@ export function encodeScopedDelegation({ delegator, delegate, caveats, expiry, c
* @returns {Promise<object>} signed delegation (unsigned + signature)
*/
export async function signDelegation(unsigned, signer) {
+ // getDelegationManager throws if no real deployment is configured — this
+ // prevents EIP-712 signatures from binding to the zero address, which
+ // would silently authorize an unowned contract on every chain.
+ const verifyingContract = getDelegationManager(unsigned.chainId);
const domain = {
name: 'DelegationManager',
version: '1',
chainId: unsigned.chainId,
- verifyingContract: DELEGATION_MANAGER_DEPLOYMENTS[unsigned.chainId],
+ verifyingContract,
};
const types = {
@@ -102,9 +106,11 @@ export async function isDelegationValid({ hash, chainId, rpcUrl }) {
`No RPC URL available for chain ${chainId}. Pass rpcUrl or set RPC_URL_${chainId} env var.`,
);
}
- const managerAddr = DELEGATION_MANAGER_DEPLOYMENTS[chainId];
- if (!managerAddr || managerAddr === '0x0000000000000000000000000000000000000000') {
- throw new PermissionError('chain_not_supported', `No DelegationManager for chain ${chainId}`);
+ let managerAddr;
+ try {
+ managerAddr = getDelegationManager(chainId);
+ } catch (err) {
+ throw new PermissionError('chain_not_supported', err.message);
}
// eth_call: isDelegationDisabled(bytes32)
diff --git a/sdk/src/styles.css b/sdk/src/styles.css
index f7d81081f..19c52cc36 100644
--- a/sdk/src/styles.css
+++ b/sdk/src/styles.css
@@ -1,5 +1,5 @@
-/* @nirholas/agent-kit — panel styles
- Import this file once in your app: import '@nirholas/agent-kit/styles'
+/* @three-ws/sdk — panel styles
+ Import this file once in your app: import '@three-ws/sdk/styles'
All classes are namespaced under .ak-* to avoid collisions.
*/
diff --git a/src/app.js b/src/app.js
index 2841e17ad..e44cd6d2a 100644
--- a/src/app.js
+++ b/src/app.js
@@ -1824,6 +1824,12 @@ class App {
// ── Validator hook ────────────────────────────────────────────────────────
_hookValidator() {
+ // In the slim widget shell the validator overlay never renders (the
+ // `.validate()` call is gated on `!options.kiosk`), so a tree-wide
+ // MutationObserver here is pure CPU waste. Skip it entirely in that
+ // surface — saves a 60Hz-ish observer on the embedder's parent paint.
+ if (this._widgetShell) return;
+
// Intercept the validator toggle DOM node to emit validation results
const observer = new MutationObserver(() => {
const el = document.querySelector('.validator-toggle');
diff --git a/tests/api/solana-wallet-import.test.js b/tests/api/solana-wallet-import.test.js
index 80947243e..c7955351f 100644
--- a/tests/api/solana-wallet-import.test.js
+++ b/tests/api/solana-wallet-import.test.js
@@ -33,6 +33,12 @@ vi.mock('../../api/_lib/agent-pumpfun.js', () => ({
solanaConnection: vi.fn(() => ({
getBalance: vi.fn(async () => 0),
})),
+ // solanaPublicConnection is the read-only RPC fallback the handler uses
+ // when the primary (private) RPC is rate-limited or returns 5xx. Stub it
+ // with the same surface as the primary so the backoff wrapper has both.
+ solanaPublicConnection: vi.fn(() => ({
+ getBalance: vi.fn(async () => 0),
+ })),
}));
vi.mock('../../api/_lib/agent-wallet.js', () => ({
diff --git a/vercel.json b/vercel.json
index a3073890d..3c49855ec 100644
--- a/vercel.json
+++ b/vercel.json
@@ -1634,7 +1634,8 @@
{
"src": "/assets/(.*)",
"headers": {
- "cache-control": "max-age=604800, public"
+ "cache-control": "max-age=604800, public",
+ "cross-origin-resource-policy": "cross-origin"
},
"dest": "/assets/$1"
},