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.

milady

nirholas3f5d9c5ecb4d
diff --git a/agent-embed.html b/agent-embed.html
index 1b70ef006..6a14ad6df 100644
--- a/agent-embed.html
+++ b/agent-embed.html
@@ -1,140 +1,253 @@
<!doctype html>
<html lang="en">
-<head>
- <meta charset="utf-8" />
- <title>Agent</title>
- <meta name="viewport" content="width=device-width, initial-scale=1.0" />
- <meta name="description" content="Embedded 3D agent avatar." />
- <meta name="robots" content="noindex" />
- <style>
- html, body { margin: 0; padding: 0; height: 100%; width: 100%; background: transparent; overflow: hidden; font-family: system-ui, sans-serif; }
- #stage { position: absolute; inset: 0; }
- #stage canvas { display: block; width: 100% !important; height: 100% !important; }
- #stage .gui-wrap, #stage .gui-toggle, #stage .annotation-canvas { display: none !important; }
- #stage .model-info { display: none !important; }
- #name-plate {
- position: absolute; left: 12px; bottom: 10px; z-index: 2; pointer-events: none;
- font-size: 11px; color: rgba(255,255,255,0.55); letter-spacing: 0.04em;
- text-shadow: 0 1px 2px rgba(0,0,0,0.6);
- }
- #error {
- position: absolute; inset: 0; display: none; align-items: center; justify-content: center;
- color: rgba(255,255,255,0.4); font-size: 12px; padding: 1rem; text-align: center;
- }
- body.bg-dark { background: #0b0d10; }
- body.bg-light { background: #f5f5f5; }
- </style>
-</head>
-<body>
- <div id="stage"></div>
- <div id="name-plate"></div>
- <div id="error"></div>
-
- <script type="module">
- import { Viewer } from './src/viewer.js';
- import { AgentIdentity } from './src/agent-identity.js';
- import { AgentAvatar } from './src/agent-avatar.js';
- import { protocol } from './src/agent-protocol.js';
-
- const params = new URL(location.href).searchParams;
- const bg = params.get('bg') || 'transparent';
- if (bg === 'dark') document.body.classList.add('bg-dark');
- if (bg === 'light') document.body.classList.add('bg-light');
-
- const plateOn = params.get('name') !== '0';
- const preview = params.get('preview') === '1';
- const parts = location.pathname.split('/').filter(Boolean);
- const agentId = parts[parts.indexOf('agent') + 1];
-
- function hostMatches(host, pattern) {
- if (!host || !pattern) return false;
- host = host.toLowerCase();
- pattern = pattern.toLowerCase();
- if (pattern.startsWith('*.')) {
- const suffix = pattern.slice(2);
- return host === suffix || host.endsWith('.' + suffix);
- }
- return host === pattern;
- }
-
- function embeddingHost() {
- try {
- const anc = window.location.ancestorOrigins;
- if (anc && anc.length) return new URL(anc[0]).hostname;
- } catch {}
- try {
- if (document.referrer) return new URL(document.referrer).hostname;
- } catch {}
- return null;
- }
-
- async function checkPolicy() {
- if (preview) return true;
- const sameOrigin = !window.parent || window.parent === window
- || (() => { try { return window.parent.location.origin === location.origin; } catch { return false; } })();
- let policy = null;
- try {
- const r = await fetch(`/api/agents/${agentId}/embed-policy`, { credentials: 'omit' });
- if (r.ok) policy = (await r.json()).policy;
- } catch {}
- if (policy === null || policy === undefined) return true;
- if (sameOrigin) return true;
- const host = embeddingHost();
- const hosts = Array.isArray(policy.hosts) ? policy.hosts : [];
- const matched = host ? hosts.some((p) => hostMatches(host, p)) : false;
- if (policy.mode === 'allowlist') return matched;
- if (policy.mode === 'denylist') return !matched;
- return true;
- }
-
- async function main() {
- if (!(await checkPolicy())) {
- const el = document.getElementById('error');
- el.textContent = 'This agent can only be embedded on approved sites.';
- el.style.display = 'flex';
- parent?.postMessage({ __agent: agentId, type: 'blocked' }, '*');
- return;
+ <head>
+ <meta charset="utf-8" />
+ <title>Agent</title>
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <meta name="description" content="Embedded 3D agent avatar." />
+ <meta name="robots" content="noindex" />
+ <style>
+ html,
+ body {
+ margin: 0;
+ padding: 0;
+ height: 100%;
+ width: 100%;
+ background: transparent;
+ overflow: hidden;
+ font-family: system-ui, sans-serif;
+ }
+ #stage {
+ position: absolute;
+ inset: 0;
+ }
+ #stage canvas {
+ display: block;
+ width: 100% !important;
+ height: 100% !important;
+ }
+ #stage .gui-wrap,
+ #stage .gui-toggle,
+ #stage .annotation-canvas {
+ display: none !important;
+ }
+ #stage .model-info {
+ display: none !important;
+ }
+ #name-plate {
+ position: absolute;
+ left: 12px;
+ bottom: 10px;
+ z-index: 2;
+ pointer-events: none;
+ font-size: 11px;
+ color: rgba(255, 255, 255, 0.55);
+ letter-spacing: 0.04em;
+ text-shadow: 0 1px 2px rgba(0, 0, 0, 0.6);
+ }
+ #error {
+ position: absolute;
+ inset: 0;
+ display: none;
+ align-items: center;
+ justify-content: center;
+ color: rgba(255, 255, 255, 0.4);
+ font-size: 12px;
+ padding: 1rem;
+ text-align: center;
+ }
+ body.bg-dark {
+ background: #0b0d10;
+ }
+ body.bg-light {
+ background: #f5f5f5;
}
+ </style>
+ </head>
+ <body>
+ <div id="stage"></div>
+ <div id="name-plate"></div>
+ <div id="error"></div>
- const identity = new AgentIdentity({ agentId, autoLoad: false });
- await identity.load();
+ <script type="module">
+ import { Viewer } from './src/viewer.js';
+ import { AgentIdentity } from './src/agent-identity.js';
+ import { AgentAvatar } from './src/agent-avatar.js';
+ import { protocol } from './src/agent-protocol.js';
- if (plateOn && identity.name) {
- document.getElementById('name-plate').textContent = identity.name;
+ const params = new URL(location.href).searchParams;
+ const bg = params.get('bg') || 'transparent';
+ if (bg === 'dark') document.body.classList.add('bg-dark');
+ if (bg === 'light') document.body.classList.add('bg-light');
+
+ const plateOn = params.get('name') !== '0';
+ const preview = params.get('preview') === '1';
+ const parts = location.pathname.split('/').filter(Boolean);
+ const agentId = parts[parts.indexOf('agent') + 1];
+
+ function hostMatches(host, pattern) {
+ if (!host || !pattern) return false;
+ host = host.toLowerCase();
+ pattern = pattern.toLowerCase();
+ if (pattern.startsWith('*.')) {
+ const suffix = pattern.slice(2);
+ return host === suffix || host.endsWith('.' + suffix);
+ }
+ return host === pattern;
}
- if (!identity.avatarId) throw new Error('agent has no avatar body');
+ function embeddingHost() {
+ try {
+ const anc = window.location.ancestorOrigins;
+ if (anc && anc.length) return new URL(anc[0]).hostname;
+ } catch {}
+ try {
+ if (document.referrer) return new URL(document.referrer).hostname;
+ } catch {}
+ return null;
+ }
- const resp = await fetch(`/api/avatars/${identity.avatarId}`, { credentials: 'include' });
- if (!resp.ok) throw new Error(`avatar ${resp.status}`);
- const { avatar } = await resp.json();
- const glbUrl = avatar?.url;
- if (!glbUrl) throw new Error('no avatar url');
+ // Normalise policy to extended shape; returns null when no policy is set.
+ function normalisePolicy(raw) {
+ if (!raw) return null;
+ if (!('version' in raw) && ('mode' in raw || 'hosts' in raw)) {
+ // Old flat { mode, hosts } shape — only origins were configured.
+ return {
+ version: 1,
+ origins: {
+ mode: raw.mode || 'allowlist',
+ hosts: Array.isArray(raw.hosts) ? raw.hosts : [],
+ },
+ surfaces: { script: true, iframe: true, widget: true, mcp: true },
+ };
+ }
+ return raw;
+ }
- const stage = document.getElementById('stage');
- const viewer = new Viewer(stage, { kiosk: true });
- if (bg === 'transparent') {
- viewer.renderer?.setClearAlpha(0);
- if (viewer.scene) viewer.scene.background = null;
+ function buildCspContent(policy) {
+ const base = ["'self'", 'https://3dagent.vercel.app'];
+ if (policy?.origins?.hosts?.length) {
+ for (const h of policy.origins.hosts) {
+ const lower = h.toLowerCase();
+ // CSP wildcard format: *.foo.com → https://*.foo.com
+ base.push(lower.startsWith('*.') ? `https://${lower}` : `https://${lower}`);
+ }
+ }
+ return `frame-ancestors ${[...new Set(base)].join(' ')}`;
}
- await viewer.load(glbUrl, '', new Map());
- const avatarCtl = new AgentAvatar(viewer, protocol, identity);
- avatarCtl.attach();
+ function insertCspMeta(policy) {
+ const existing = document.querySelector(
+ 'meta[http-equiv="Content-Security-Policy"]',
+ );
+ if (existing) existing.remove();
+ const meta = document.createElement('meta');
+ meta.httpEquiv = 'Content-Security-Policy';
+ meta.content = buildCspContent(policy);
+ document.head.insertBefore(meta, document.head.querySelector('script'));
+ }
+
+ async function checkPolicy() {
+ if (preview) return true;
+ const sameOrigin =
+ !window.parent ||
+ window.parent === window ||
+ (() => {
+ try {
+ return window.parent.location.origin === location.origin;
+ } catch {
+ return false;
+ }
+ })();
+ let rawPolicy = null;
+ try {
+ const r = await fetch(`/api/agents/${agentId}/embed-policy`, {
+ credentials: 'omit',
+ });
+ if (r.ok) rawPolicy = (await r.json()).policy;
+ } catch {}
+
+ const policy = normalisePolicy(rawPolicy);
+ insertCspMeta(policy);
+
+ if (policy === null) return true;
+ if (sameOrigin) {
+ // surfaces.iframe gate still runs even for same-origin embeds
+ if (policy.surfaces && policy.surfaces.iframe === false) return false;
+ return true;
+ }
+
+ // Origin check (existing logic, extended shape)
+ const host = embeddingHost();
+ const hosts = policy.origins?.hosts ?? [];
+ const mode = policy.origins?.mode ?? 'allowlist';
+ const matched = host ? hosts.some((p) => hostMatches(host, p)) : false;
+ const originOk = mode === 'allowlist' ? matched : !matched;
+ if (!originOk) return false;
- window.addEventListener('message', (ev) => {
- const msg = ev.data;
- if (!msg || msg.__agent !== agentId) return;
- if (msg.type === 'action' && msg.action) protocol.emit(msg.action);
+ // surfaces.iframe gate — fail-closed
+ if (policy.surfaces && policy.surfaces.iframe === false) {
+ showError("This agent's iframe embed is disabled.");
+ return false;
+ }
+
+ return true;
+ }
+
+ function showError(msg) {
+ const el = document.getElementById('error');
+ el.textContent = msg;
+ el.style.display = 'flex';
+ }
+
+ async function main() {
+ if (!(await checkPolicy())) {
+ showError('This agent can only be embedded on approved sites.');
+ parent?.postMessage({ __agent: agentId, type: 'blocked' }, '*');
+ return;
+ }
+
+ const identity = new AgentIdentity({ agentId, autoLoad: false });
+ await identity.load();
+
+ if (plateOn && identity.name) {
+ document.getElementById('name-plate').textContent = identity.name;
+ }
+
+ if (!identity.avatarId) throw new Error('agent has no avatar body');
+
+ const resp = await fetch(`/api/avatars/${identity.avatarId}`, {
+ credentials: 'include',
+ });
+ if (!resp.ok) throw new Error(`avatar ${resp.status}`);
+ const { avatar } = await resp.json();
+ const glbUrl = avatar?.url;
+ if (!glbUrl) throw new Error('no avatar url');
+
+ const stage = document.getElementById('stage');
+ const viewer = new Viewer(stage, { kiosk: true });
+ if (bg === 'transparent') {
+ viewer.renderer?.setClearAlpha(0);
+ if (viewer.scene) viewer.scene.background = null;
+ }
+ await viewer.load(glbUrl, '', new Map());
+
+ const avatarCtl = new AgentAvatar(viewer, protocol, identity);
+ avatarCtl.attach();
+
+ window.addEventListener('message', (ev) => {
+ const msg = ev.data;
+ if (!msg || msg.__agent !== agentId) return;
+ if (msg.type === 'action' && msg.action) protocol.emit(msg.action);
+ });
+ parent?.postMessage({ __agent: agentId, type: 'ready', name: identity.name }, '*');
+ }
+
+ main().catch((err) => {
+ const el = document.getElementById('error');
+ el.textContent = err.message || 'Could not load agent';
+ el.style.display = 'flex';
});
- parent?.postMessage({ __agent: agentId, type: 'ready', name: identity.name }, '*');
- }
-
- main().catch(err => {
- const el = document.getElementById('error');
- el.textContent = err.message || 'Could not load agent';
- el.style.display = 'flex';
- });
- </script>
-</body>
+ </script>
+ </body>
</html>
diff --git a/api/_lib/avatars.js b/api/_lib/avatars.js
index a3bbff92f..b42931c44 100644
--- a/api/_lib/avatars.js
+++ b/api/_lib/avatars.js
@@ -3,6 +3,7 @@
import { sql } from './db.js';
import { publicUrl, presignGet, deleteObject } from './r2.js';
+import { defaultStorageMode } from './storage-mode.js';
export async function listAvatars({ userId, limit = 50, cursor, visibility, includePublic = false }) {
limit = Math.min(Math.max(limit, 1), 200);
@@ -50,16 +51,22 @@ export async function getAvatarBySlug({ ownerId, slug, requesterId = null }) {
export async function createAvatar({ userId, input, storageKey }) {
await enforceQuotas(userId, input.size_bytes);
const finalSlug = input.slug || (await generateSlug(userId, input.name));
+ const storageMode = defaultStorageMode({
+ storage_key: storageKey,
+ checksum_sha256: input.checksum_sha256 ?? null,
+ });
const [row] = await sql`
insert into avatars (
owner_id, slug, name, description, storage_key, size_bytes, content_type,
- source, source_meta, visibility, tags, checksum_sha256, parent_avatar_id
+ source, source_meta, visibility, tags, checksum_sha256, parent_avatar_id,
+ storage_mode
) values (
${userId}, ${finalSlug}, ${input.name}, ${input.description ?? null},
${storageKey}, ${input.size_bytes}, ${input.content_type},
${input.source}, ${JSON.stringify(input.source_meta)}::jsonb,
${input.visibility}, ${input.tags}, ${input.checksum_sha256 ?? null},
- ${input.parent_avatar_id ?? null}
+ ${input.parent_avatar_id ?? null},
+ ${JSON.stringify(storageMode)}::jsonb
) returning *
`;
return decorate(row);
diff --git a/api/_lib/embed-policy.js b/api/_lib/embed-policy.js
new file mode 100644
index 000000000..5b0337396
--- /dev/null
+++ b/api/_lib/embed-policy.js
@@ -0,0 +1,100 @@
+// Per-agent embed policy: one JSONB column on agent_identities holding
+// origins + surfaces + brain + storage config. See prompts/embed-hardening/.
+
+import { z } from 'zod';
+import { sql } from './db.js';
+
+const hostPattern =
+ /^(\*\.)?([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)(\.[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i;
+
+export const POLICY_VERSION = 1;
+
+export const policySchema = z.object({
+ version: z.literal(1).optional(),
+ origins: z.object({
+ mode: z.enum(['allowlist', 'denylist']),
+ hosts: z.array(z.string().trim().toLowerCase().min(1).max(253).regex(hostPattern)).max(100),
+ }),
+ surfaces: z.object({
+ script: z.boolean(),
+ iframe: z.boolean(),
+ widget: z.boolean(),
+ mcp: z.boolean(),
+ }),
+ brain: z
+ .object({
+ mode: z.enum(['we-pay', 'key-proxy', 'wallet-gated', 'none']),
+ proxy_url: z.string().url().nullable(),
+ monthly_quota: z.number().int().nonnegative().nullable(),
+ rate_limit_per_min: z.number().int().nonnegative().nullable(),
+ model: z.string().min(1).max(100),
+ })
+ .refine((b) => b.mode !== 'key-proxy' || !!b.proxy_url, {
+ message: 'proxy_url is required when brain.mode === "key-proxy"',
+ path: ['proxy_url'],
+ }),
+ storage: z.object({
+ primary: z.enum(['r2', 'ipfs']),
+ pinned_ipfs: z.boolean(),
+ onchain_attested: z.boolean(),
+ }),
+});
+
+export function defaultEmbedPolicy() {
+ return {
+ version: POLICY_VERSION,
+ origins: { mode: 'allowlist', hosts: [] },
+ surfaces: { script: true, iframe: true, widget: true, mcp: false },
+ brain: {
+ mode: 'we-pay',
+ proxy_url: null,
+ monthly_quota: 1000,
+ rate_limit_per_min: 10,
+ model: 'claude-opus-4-6',
+ },
+ storage: { primary: 'r2', pinned_ipfs: false, onchain_attested: false },
+ };
+}
+
+export function normalizeLegacyPolicy(input) {
+ if (!input) return defaultEmbedPolicy();
+ const isLegacy =
+ !('version' in input) && !('origins' in input) && 'mode' in input && 'hosts' in input;
+ if (isLegacy) {
+ const d = defaultEmbedPolicy();
+ return { ...d, origins: { mode: input.mode, hosts: input.hosts ?? [] } };
+ }
+ const d = defaultEmbedPolicy();
+ return {
+ version: POLICY_VERSION,
+ origins: { ...d.origins, ...(input.origins || {}) },
+ surfaces: { ...d.surfaces, ...(input.surfaces || {}) },
+ brain: { ...d.brain, ...(input.brain || {}) },
+ storage: { ...d.storage, ...(input.storage || {}) },
+ };
+}
+
+export async function readEmbedPolicy(agentId) {
+ let row;
+ try {
+ [row] = await sql`
+ SELECT embed_policy FROM agent_identities
+ WHERE id = ${agentId} AND deleted_at IS NULL
+ `;
+ } catch (err) {
+ if (
+ err.message &&
+ err.message.includes('column') &&
+ err.message.includes('does not exist')
+ ) {
+ return null;
+ }
+ throw err;
+ }
+ if (!row) return null;
+ return normalizeLegacyPolicy(row.embed_policy);
+}
+
+export function validateEmbedPolicy(input) {
+ return policySchema.parse(normalizeLegacyPolicy(input));
+}
diff --git a/api/_lib/env.js b/api/_lib/env.js
index c6052e9a9..c23d033e1 100644
--- a/api/_lib/env.js
+++ b/api/_lib/env.js
@@ -43,6 +43,10 @@ export const env = {
get AVATURN_API_KEY() { return opt('AVATURN_API_KEY'); },
get AVATURN_API_URL() { return trimSlash(opt('AVATURN_API_URL', 'https://api.avaturn.me')); },
+ // Anthropic API key — used by the we-pay LLM proxy (/api/llm/anthropic).
+ // Must be set in production; optional in local dev if the proxy is unused.
+ get ANTHROPIC_API_KEY() { return req('ANTHROPIC_API_KEY'); },
+
// Etherscan V2 — unified multichain explorer API (one key, all chains).
// Used by api/cron/erc8004-crawl.js to index ERC-8004 Registered events.
get ETHERSCAN_API_KEY() { return opt('ETHERSCAN_API_KEY'); },
diff --git a/api/_lib/schema.sql b/api/_lib/schema.sql
index 2bd0b7937..7a5c5dee6 100644
--- a/api/_lib/schema.sql
+++ b/api/_lib/schema.sql
@@ -52,6 +52,9 @@ create index if not exists avatars_owner_idx on avatars(owner_id) where deleted_
create index if not exists avatars_public_idx on avatars(visibility, created_at desc) where visibility = 'public' and deleted_at is null;
create index if not exists avatars_tags_idx on avatars using gin(tags);
+-- Additive migrations for avatars columns added after initial deployment.
+alter table avatars add column if not exists storage_mode jsonb;
+
-- ── OAuth 2.1 clients (for MCP & third-party apps) ──────────────────────────
-- Supports RFC 7591 dynamic client registration.
create table if not exists oauth_clients (
@@ -264,6 +267,7 @@ alter table agent_identities add column if not exists erc8004_agent_id bigint;
alter table agent_identities add column if not exists erc8004_registry text;
alter table agent_identities add column if not exists registration_cid text;
alter table agent_identities add column if not exists home_url text;
+alter table agent_identities add column if not exists embed_policy jsonb;
-- ── agent_memories — the agent's persistent context ──────────────────────────
create table if not exists agent_memories (
diff --git a/api/_lib/storage-mode.js b/api/_lib/storage-mode.js
new file mode 100644
index 000000000..26d23458a
--- /dev/null
+++ b/api/_lib/storage-mode.js
@@ -0,0 +1,75 @@
+// Per-avatar storage mode: one JSONB column on avatars tracking R2 / IPFS /
+// on-chain attestation state. See prompts/embed-hardening/05-storage-flags.md.
+
+import { z } from 'zod';
+import { sql } from './db.js';
+
+export const STORAGE_MODE_VERSION = 1;
+
+export const storageModeSchema = z.object({
+ version: z.literal(1).optional(),
+ primary: z.enum(['r2', 'ipfs']),
+ r2: z.object({
+ present: z.boolean(),
+ key: z.string().nullable(),
+ }),
+ ipfs: z.object({
+ pinned: z.boolean(),
+ cid: z.string().nullable(),
+ pinned_at: z.string().datetime().nullable(),
+ }),
+ attestation: z.object({
+ hash: z
+ .string()
+ .regex(/^[a-f0-9]{64}$/i)
+ .nullable(),
+ chain_id: z.number().int().nullable(),
+ tx_hash: z
+ .string()
+ .regex(/^0x[a-fA-F0-9]{64}$/)
+ .nullable(),
+ attested_at: z.string().datetime().nullable(),
+ }),
+});
+
+export function defaultStorageMode(avatarRow = {}) {
+ return {
+ version: STORAGE_MODE_VERSION,
+ primary: 'r2',
+ r2: { present: true, key: avatarRow.storage_key ?? null },
+ ipfs: { pinned: false, cid: null, pinned_at: null },
+ attestation: {
+ hash: avatarRow.checksum_sha256 ?? null,
+ chain_id: null,
+ tx_hash: null,
+ attested_at: null,
+ },
+ };
+}
+
+export async function readStorageMode(avatarId) {
+ try {
+ const [row] = await sql`
+ SELECT id, owner_id, storage_key, checksum_sha256, storage_mode
+ FROM avatars
+ WHERE id = ${avatarId} AND deleted_at IS NULL
+ `;
+ if (!row) return null;
+ const base = defaultStorageMode(row);
+ if (!row.storage_mode) return base;
+ return {
+ ...base,
+ ...row.storage_mode,
+ r2: { ...base.r2, ...(row.storage_mode.r2 || {}) },
+ ipfs: { ...base.ipfs, ...(row.storage_mode.ipfs || {}) },
+ attestation: { ...base.attestation, ...(row.storage_mode.attestation || {}) },
+ };
+ } catch (err) {
+ if (/column .* does not exist/i.test(String(err?.message))) return null;
+ throw err;
+ }
+}
+
+export function validateStorageMode(input) {
+ return storageModeSchema.parse(input);
+}
diff --git a/api/agents/[id]/embed-policy.js b/api/agents/[id]/embed-policy.js
index 4ef07d819..6e5be3212 100644
--- a/api/agents/[id]/embed-policy.js
+++ b/api/agents/[id]/embed-policy.js
@@ -1,36 +1,11 @@
-// GET /api/agents/:id/embed-policy — public; returns { policy } (or { policy: null })
-// PUT /api/agents/:id/embed-policy — owner-only; sets the policy
+// GET /api/agents/:id/embed-policy — public; returns { policy } (extended normalized shape)
+// PUT /api/agents/:id/embed-policy — owner-only; accepts extended or legacy shape
// DELETE /api/agents/:id/embed-policy — owner-only; clears the policy
-//
-// Policy shape when non-null:
-// { mode: "allowlist" | "denylist", hosts: ["example.com", "*.substack.com"] }
-// `hosts` supports exact match and a single leading-wildcard segment ("*.foo.com").
-import { z } from 'zod';
import { getSessionUser } from '../../_lib/auth.js';
import { sql } from '../../_lib/db.js';
import { cors, json, method, readJson, wrap, error } from '../../_lib/http.js';
-import { parse } from '../../_lib/validate.js';
-
-// Hostnames are ASCII only here — policy authors enter punycoded forms.
-// Allow a single leading "*." wildcard segment; otherwise require conventional
-// dot-separated labels. Cap at 253 chars (DNS max).
-const hostPattern = /^(\*\.)?([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)(\.[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i;
-
-const policySchema = z.object({
- mode: z.enum(['allowlist', 'denylist']),
- hosts: z
- .array(
- z
- .string()
- .trim()
- .toLowerCase()
- .min(1)
- .max(253)
- .regex(hostPattern, 'invalid host; use example.com or *.example.com'),
- )
- .max(100),
-});
+import { readEmbedPolicy, validateEmbedPolicy } from '../../_lib/embed-policy.js';
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,PUT,DELETE,OPTIONS', credentials: true })) return;
@@ -40,12 +15,15 @@ export default wrap(async (req, res) => {
if (!id) return error(res, 400, 'invalid_request', 'agent id required');
if (req.method === 'GET') {
- const [row] = await sql`
- SELECT embed_policy FROM agent_identities
- WHERE id = ${id} AND deleted_at IS NULL
- `;
- if (!row) return error(res, 404, 'not_found', 'agent not found');
- return json(res, 200, { policy: row.embed_policy ?? null });
+ const policy = await readEmbedPolicy(id);
+ if (policy === null) {
+ // Check if agent actually exists vs column missing
+ const [row] = await sql`
+ SELECT id FROM agent_identities WHERE id = ${id} AND deleted_at IS NULL
+ `;
+ if (!row) return error(res, 404, 'not_found', 'agent not found');
+ }
+ return json(res, 200, { policy: policy ?? null });
}
const session = await getSessionUser(req);
@@ -63,10 +41,21 @@ export default wrap(async (req, res) => {
return json(res, 200, { policy: null });
}
- const policy = parse(policySchema, await readJson(req));
+ let normalized;
+ try {
+ normalized = validateEmbedPolicy(await readJson(req));
+ } catch (err) {
+ if (err.name === 'ZodError') {
+ return error(res, 400, 'validation_error', err.errors[0]?.message || 'invalid policy', {
+ fields: err.errors,
+ });
+ }
+ throw err;
+ }
+
const [updated] = await sql`
UPDATE agent_identities
- SET embed_policy = ${JSON.stringify(policy)}::jsonb
+ SET embed_policy = ${JSON.stringify(normalized)}::jsonb
WHERE id = ${id}
RETURNING embed_policy
`;
diff --git a/api/avatars/[id]/pin-ipfs.js b/api/avatars/[id]/pin-ipfs.js
new file mode 100644
index 000000000..73441e6e2
--- /dev/null
+++ b/api/avatars/[id]/pin-ipfs.js
@@ -0,0 +1,39 @@
+// STUB — real pinning (Pinata / Web3.Storage) is a follow-up. For now this
+// computes a placeholder CID from the stored sha256 and flips pinned_ipfs.
+
+import { sql } from '../../_lib/db.js';
+import { getSessionUser } from '../../_lib/auth.js';
+import { cors, json, method, wrap, error } from '../../_lib/http.js';
+import { readStorageMode } from '../../_lib/storage-mode.js';
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const id = req.query?.id || new URL(req.url, 'http://x').pathname.split('/').filter(Boolean)[2];
+ if (!id) return error(res, 400, 'validation_error', 'avatar id required');
+
+ const session = await getSessionUser(req);
+ if (!session) return error(res, 401, 'unauthorized', 'sign in required');
+
+ const [row] = await sql`
+ SELECT id, owner_id, checksum_sha256 FROM avatars WHERE id = ${id} AND deleted_at IS NULL
+ `;
+ if (!row) return error(res, 404, 'not_found', 'avatar not found');
+ if (row.owner_id !== session.id) return error(res, 403, 'forbidden', 'not your avatar');
+
+ const mode = await readStorageMode(id);
+ if (!mode) return error(res, 500, 'internal', 'storage_mode unavailable');
+
+ const stubCid = row.checksum_sha256
+ ? `stub:sha256-${row.checksum_sha256}`
+ : `stub:no-hash-${id}`;
+
+ const next = {
+ ...mode,
+ ipfs: { pinned: true, cid: stubCid, pinned_at: new Date().toISOString() },
+ };
+
+ await sql`UPDATE avatars SET storage_mode = ${JSON.stringify(next)}::jsonb WHERE id = ${id}`;
+ return json(res, 200, { storage_mode: next, stub: true });
+});
diff --git a/api/avatars/[id]/storage-mode.js b/api/avatars/[id]/storage-mode.js
new file mode 100644
index 000000000..43e58269d
--- /dev/null
+++ b/api/avatars/[id]/storage-mode.js
@@ -0,0 +1,46 @@
+import { sql } from '../../_lib/db.js';
+import { getSessionUser } from '../../_lib/auth.js';
+import { cors, json, method, wrap, error, readJson } from '../../_lib/http.js';
+import { parse } from '../../_lib/validate.js';
+import { readStorageMode, storageModeSchema, defaultStorageMode } from '../../_lib/storage-mode.js';
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,PUT,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET', 'PUT'])) return;
+
+ const id = req.query?.id || new URL(req.url, 'http://x').pathname.split('/').filter(Boolean)[2];
+ if (!id) return error(res, 400, 'validation_error', 'avatar id required');
+
+ const [row] = await sql`
+ SELECT id, owner_id, visibility FROM avatars WHERE id = ${id} AND deleted_at IS NULL
+ `;
+ if (!row) return error(res, 404, 'not_found', 'avatar not found');
+
+ if (req.method === 'GET') {
+ if (row.visibility === 'private') {
+ const session = await getSessionUser(req);
+ if (!session || session.id !== row.owner_id)
+ return error(res, 403, 'forbidden', 'private avatar');
+ }
+ const mode = await readStorageMode(id);
+ return json(res, 200, { storage_mode: mode });
+ }
+
+ // PUT — owner only
+ const session = await getSessionUser(req);
+ if (!session) return error(res, 401, 'unauthorized', 'sign in required');
+ if (session.id !== row.owner_id) return error(res, 403, 'forbidden', 'not your avatar');
+
+ const body = parse(storageModeSchema, await readJson(req));
+
+ // Read current stored mode to preserve attestation fields — clients must not
+ // be able to forge tx_hash / chain_id / attested_at from the UI.
+ const current = await readStorageMode(id);
+ const safeBody = {
+ ...body,
+ attestation: current?.attestation ?? defaultStorageMode().attestation,
+ };
+
+ await sql`UPDATE avatars SET storage_mode = ${JSON.stringify(safeBody)}::jsonb WHERE id = ${id}`;
+ return json(res, 200, { storage_mode: safeBody });
+});
diff --git a/api/avatars/index.js b/api/avatars/index.js
index eacb794ca..b5ecc82e0 100644
--- a/api/avatars/index.js
+++ b/api/avatars/index.js
@@ -3,11 +3,14 @@
import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../_lib/auth.js';
import { listAvatars, createAvatar } from '../_lib/avatars.js';
-import { headObject } from '../_lib/r2.js';
+import { headObject, r2 } from '../_lib/r2.js';
+import { HeadObjectCommand } from '@aws-sdk/client-s3';
+import { env } from '../_lib/env.js';
import { sql } from '../_lib/db.js';
import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';
import { parse, createAvatarBody } from '../_lib/validate.js';
import { recordEvent } from '../_lib/usage.js';
+import { defaultStorageMode } from '../_lib/storage-mode.js';
import { z } from 'zod';
const createWithStorage = createAvatarBody.extend({
@@ -56,6 +59,26 @@ async function handleCreate(req, res) {
return error(res, 400, 'size_mismatch', 'size_bytes does not match uploaded object');
}
+ // Attempt to read sha256 from R2 (only present if the browser upload included it).
+ // Use ChecksumMode: ENABLED for a lightweight HEAD — no body download.
+ if (!body.checksum_sha256) {
+ try {
+ const headChecked = await r2.send(
+ new HeadObjectCommand({
+ Bucket: env.S3_BUCKET,
+ Key: body.storage_key,
+ ChecksumMode: 'ENABLED',
+ }),
+ );
+ if (headChecked?.ChecksumSHA256) {
+ // R2 returns base64; convert to lowercase hex.
+ body.checksum_sha256 = Buffer.from(headChecked.ChecksumSHA256, 'base64').toString('hex');
+ }
+ } catch {
+ // ChecksumMode unsupported or object has no checksum — leave null, not fatal.
+ }
+ }
+
// Validate parent_avatar_id ownership — prevents user B from pointing at user A's avatar chain.
if (body.parent_avatar_id) {
const rows = await sql`
diff --git a/api/mcp.js b/api/mcp.js
index 0eba2c57f..b43587647 100644
--- a/api/mcp.js
+++ b/api/mcp.js
@@ -12,11 +12,19 @@
// ─────────────────────────────────────────────────────────────────────────────
import { env } from './_lib/env.js';
+import { sql } from './_lib/db.js';
import { authenticateBearer, extractBearer, hasScope } from './_lib/auth.js';
import { cors, readJson, wrap } from './_lib/http.js';
import { limits, clientIp } from './_lib/rate-limit.js';
import { recordEvent, logger } from './_lib/usage.js';
-import { listAvatars, getAvatar, getAvatarBySlug, searchPublicAvatars, resolveAvatarUrl, deleteAvatar } from './_lib/avatars.js';
+import {
+ listAvatars,
+ getAvatar,
+ getAvatarBySlug,
+ searchPublicAvatars,
+ resolveAvatarUrl,
+ deleteAvatar,
+} from './_lib/avatars.js';
import { fetchModel, FetchModelError } from './_lib/fetch-model.js';
import { inspectModel, suggestOptimizations } from './_lib/model-inspect.js';
import { validateBytes } from 'gltf-validator';
@@ -29,18 +37,24 @@ export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,POST,DELETE,OPTIONS' })) return;
// Unauthenticated discovery surface — DELETE and GET without bearer are OK to reject quickly.
- if (req.method === 'GET') return handleSse(req, res);
+ if (req.method === 'GET') return handleSse(req, res);
if (req.method === 'DELETE') return handleTerminate(req, res);
- if (req.method !== 'POST') return send401(res, 'method not supported');
+ if (req.method !== 'POST') return send401(res, 'method not supported');
const bearer = extractBearer(req);
const auth = await authenticateBearer(bearer, { audience: env.MCP_RESOURCE });
if (!auth) return send401(res, 'missing or invalid access token');
const ipRl = await limits.mcpIp(clientIp(req));
- if (!ipRl.success) return sendJsonRpcError(res, null, -32000, 'rate_limited', { retry_after: Math.ceil((ipRl.reset - Date.now()) / 1000) });
+ if (!ipRl.success)
+ return sendJsonRpcError(res, null, -32000, 'rate_limited', {
+ retry_after: Math.ceil((ipRl.reset - Date.now()) / 1000),
+ });
const userRl = await limits.mcpUser(auth.userId);
- if (!userRl.success) return sendJsonRpcError(res, null, -32000, 'rate_limited', { retry_after: Math.ceil((userRl.reset - Date.now()) / 1000) });
+ if (!userRl.success)
+ return sendJsonRpcError(res, null, -32000, 'rate_limited', {
+ retry_after: Math.ceil((userRl.reset - Date.now()) / 1000),
+ });
const body = await readJson(req, 2_000_000);
const batch = Array.isArray(body) ? body : [body];
@@ -57,7 +71,7 @@ export default wrap(async (req, res) => {
res.statusCode = 200;
res.setHeader('content-type', 'application/json; charset=utf-8');
res.setHeader('mcp-protocol-version', PROTOCOL_VERSION);
- res.end(JSON.stringify(Array.isArray(body) ? responses : responses[0] ?? null));
+ res.end(JSON.stringify(Array.isArray(body) ? responses : (responses[0] ?? null)));
});
// ── JSON-RPC dispatch ────────────────────────────────────────────────────────
@@ -70,15 +84,15 @@ async function dispatch(msg, auth, req) {
if (msg.jsonrpc !== '2.0') throw rpcError(-32600, 'invalid Request');
const method = msg.method;
- if (method === 'initialize') return ok(id, await onInitialize(msg.params, auth));
- if (method === 'ping') return ok(id, {});
+ if (method === 'initialize') return ok(id, await onInitialize(msg.params, auth));
+ if (method === 'ping') return ok(id, {});
if (method === 'notifications/initialized') return null;
- if (method === 'tools/list') return ok(id, { tools: TOOL_CATALOG });
- if (method === 'tools/call') return ok(id, await onToolCall(msg.params, auth, started));
- if (method === 'resources/list') return ok(id, { resources: [] });
+ if (method === 'tools/list') return ok(id, { tools: TOOL_CATALOG });
+ if (method === 'tools/call') return ok(id, await onToolCall(msg.params, auth, started));
+ if (method === 'resources/list') return ok(id, { resources: [] });
if (method === 'resources/templates/list') return ok(id, { resourceTemplates: [] });
- if (method === 'prompts/list') return ok(id, { prompts: [] });
- if (method === 'logging/setLevel') return ok(id, {});
+ if (method === 'prompts/list') return ok(id, { prompts: [] });
+ if (method === 'logging/setLevel') return ok(id, {});
throw rpcError(-32601, `method not found: ${method}`);
} catch (err) {
@@ -87,7 +101,11 @@ async function dispatch(msg, auth, req) {
return {
jsonrpc: '2.0',
id,
- error: { code: err.code || -32603, message: err.message || 'internal error', data: err.data },
+ error: {
+ code: err.code || -32603,
+ message: err.message || 'internal error',
+ data: err.data,
+ },
};
}
}
@@ -115,7 +133,7 @@ async function onInitialize(_params, _auth) {
},
instructions: [
'Render 3D avatars stored on 3dagent.vercel.app as <model-viewer> HTML artifacts.',
- 'Use list_my_avatars to see the user\'s avatars and render_avatar to get embeddable viewer HTML.',
+ "Use list_my_avatars to see the user's avatars and render_avatar to get embeddable viewer HTML.",
'Public avatars can be discovered via search_public_avatars.',
].join(' '),
};
@@ -161,17 +179,58 @@ async function onToolCall(params, auth, started) {
}
}
+// ── inline embed-policy helpers (prompt 02 / api/_lib/embed-policy.js not yet shipped) ──
+
+function _mcpDefaultPolicy() {
+ return {
+ version: 1,
+ origins: { mode: 'allowlist', hosts: [] },
+ surfaces: { script: true, iframe: true, widget: true, mcp: true },
+ };
+}
+
+function _mcpParsePolicy(p) {
+ if (!p) return null;
+ if (!('version' in p) && ('mode' in p || 'hosts' in p)) {
+ // Old flat shape — only origins were configured; all surfaces (incl. mcp) allowed.
+ return {
+ ..._mcpDefaultPolicy(),
+ origins: { mode: p.mode || 'allowlist', hosts: p.hosts ?? [] },
+ };
+ }
+ return { ..._mcpDefaultPolicy(), ...p };
+}
+
+async function _readMcpPolicyByAvatar(avatarId) {
+ try {
+ const [row] = await sql`
+ SELECT embed_policy FROM agent_identities
+ WHERE avatar_id = ${avatarId} AND deleted_at IS NULL
+ LIMIT 1
+ `;
+ if (!row) return null;
+ return _mcpParsePolicy(row.embed_policy);
+ } catch (err) {
+ if (/column .* does not exist/i.test(String(err?.message))) return null;
+ throw err;
+ }
+}
+
// ── tool catalog ─────────────────────────────────────────────────────────────
const TOOL_CATALOG = [
{
name: 'list_my_avatars',
title: 'List my avatars',
- description: 'List the authenticated user\'s avatars. Returns id, name, slug, size, visibility, and direct model_url (when visibility permits).',
+ description:
+ "List the authenticated user's avatars. Returns id, name, slug, size, visibility, and direct model_url (when visibility permits).",
inputSchema: {
type: 'object',
properties: {
limit: { type: 'integer', minimum: 1, maximum: 100, default: 25 },
- cursor: { type: 'string', description: 'Opaque pagination cursor from previous response.' },
+ cursor: {
+ type: 'string',
+ description: 'Opaque pagination cursor from previous response.',
+ },
visibility: { type: 'string', enum: ['private', 'unlisted', 'public'] },
},
additionalProperties: false,
@@ -180,7 +239,8 @@ const TOOL_CATALOG = [
{
name: 'get_avatar',
title: 'Get avatar',
- description: 'Fetch a single avatar by id or by owner+slug. Returns metadata and a model_url (public/unlisted) or short-lived signed URL (private).',
+ description:
+ 'Fetch a single avatar by id or by owner+slug. Returns metadata and a model_url (public/unlisted) or short-lived signed URL (private).',
inputSchema: {
type: 'object',
properties: {
@@ -193,7 +253,8 @@ const TOOL_CATALOG = [
{
name: 'search_public_avatars',
title: 'Search public avatars',
- description: 'Search the public avatar gallery. Useful for finding characters to render without prior knowledge of an id.',
+ description:
+ 'Search the public avatar gallery. Useful for finding characters to render without prior knowledge of an id.',
inputSchema: {
type: 'object',
properties: {
@@ -216,12 +277,26 @@ const TOOL_CATALOG = [
id: { type: 'string', format: 'uuid' },
slug: { type: 'string' },
auto_rotate: { type: 'boolean', default: true },
- background: { type: 'string', description: 'CSS background color or gradient.', default: 'transparent' },
+ background: {
+ type: 'string',
+ description: 'CSS background color or gradient.',
+ default: 'transparent',
+ },
height: { type: 'string', default: '480px' },
width: { type: 'string', default: '100%' },
- camera_orbit: { type: 'string', description: 'model-viewer camera-orbit value, e.g. "0deg 80deg 2m".' },
- poster: { type: 'string', description: 'Optional poster image URL shown while loading.' },
- ar: { type: 'boolean', default: true, description: 'Include AR button for mobile.' },
+ camera_orbit: {
+ type: 'string',
+ description: 'model-viewer camera-orbit value, e.g. "0deg 80deg 2m".',
+ },
+ poster: {
+ type: 'string',
+ description: 'Optional poster image URL shown while loading.',
+ },
+ ar: {
+ type: 'boolean',
+ default: true,
+ description: 'Include AR button for mobile.',
+ },
},
additionalProperties: false,
},
@@ -245,7 +320,11 @@ const TOOL_CATALOG = [
inputSchema: {
type: 'object',
properties: {
- url: { type: 'string', format: 'uri', description: 'Public https URL of a .glb or .gltf file.' },
+ url: {
+ type: 'string',
+ format: 'uri',
+ description: 'Public https URL of a .glb or .gltf file.',
+ },
max_issues: { type: 'integer', minimum: 1, maximum: 500, default: 100 },
},
required: ['url'],
@@ -260,7 +339,11 @@ const TOOL_CATALOG = [
inputSchema: {
type: 'object',
properties: {
- url: { type: 'string', format: 'uri', description: 'Public https URL of a .glb or .gltf file.' },
+ url: {
+ type: 'string',
+ format: 'uri',
+ description: 'Public https URL of a .glb or .gltf file.',
+ },
},
required: ['url'],
additionalProperties: false,
@@ -274,7 +357,11 @@ const TOOL_CATALOG = [
inputSchema: {
type: 'object',
properties: {
- url: { type: 'string', format: 'uri', description: 'Public https URL of a .glb or .gltf file.' },
+ url: {
+ type: 'string',
+ format: 'uri',
+ description: 'Public https URL of a .glb or .gltf file.',
+ },
},
required: ['url'],
additionalProperties: false,
@@ -305,8 +392,12 @@ const TOOLS = {
const avatar = args.id
? await getAvatar({ id: args.id, requesterId: auth.userId })
: args.slug
- ? await getAvatarBySlug({ ownerId: auth.userId, slug: args.slug, requesterId: auth.userId })
- : null;
+ ? await getAvatarBySlug({
+ ownerId: auth.userId,
+ slug: args.slug,
+ requesterId: auth.userId,
+ })
+ : null;
if (!avatar) throw new Error('avatar not found');
const urlInfo = await resolveAvatarUrl(avatar);
const merged = { ...avatar, ...urlInfo };
@@ -325,7 +416,9 @@ const TOOLS = {
limit: args.limit || 12,
});
return {
- content: [{ type: 'text', text: formatAvatarList(result.avatars, { public: true }) }],
+ content: [
+ { type: 'text', text: formatAvatarList(result.avatars, { public: true }) },
+ ],
structuredContent: result,
};
},
@@ -337,9 +430,22 @@ const TOOLS = {
const avatar = args.id
? await getAvatar({ id: args.id, requesterId: auth.userId })
: args.slug
- ? await getAvatarBySlug({ ownerId: auth.userId, slug: args.slug, requesterId: auth.userId })
- : null;
+ ? await getAvatarBySlug({
+ ownerId: auth.userId,
+ slug: args.slug,
+ requesterId: auth.userId,
+ })
+ : null;
if (!avatar) throw new Error('avatar not found');
+ // surfaces.mcp gate — check if a registered agent owns this avatar
+ const _mcpPolicy = await _readMcpPolicyByAvatar(avatar.id);
+ if (_mcpPolicy && _mcpPolicy.surfaces?.mcp === false) {
+ throw rpcError(
+ -32000,
+ 'embed_denied_surface',
+ 'This agent disallows the MCP surface.',
+ );
+ }
const urlInfo = await resolveAvatarUrl(avatar, { expiresIn: 3600 });
const html = renderModelViewerHtml({
src: urlInfo.url,
@@ -385,7 +491,10 @@ const TOOLS = {
validate_model: {
async handler(args, auth) {
const rl = await limits.mcpValidate(auth.userId);
- if (!rl.success) throw rpcError(-32000, 'rate_limited', { retry_after: Math.ceil((rl.reset - Date.now()) / 1000) });
+ if (!rl.success)
+ throw rpcError(-32000, 'rate_limited', {
+ retry_after: Math.ceil((rl.reset - Date.now()) / 1000),
+ });
const { bytes, url, filename } = await safeFetchModel(args.url);
const max = Math.min(Math.max(args.max_issues || 100, 1), 500);
const report = await validateBytes(bytes, { maxIssues: max, uri: filename });
@@ -403,8 +512,14 @@ const TOOLS = {
truncated: !!issues.truncated,
};
return {
- content: [{ type: 'text', text: formatValidationSummary(summary, issues.messages || []) }],
- structuredContent: { ...summary, messages: issues.messages || [], info: report?.info || null },
+ content: [
+ { type: 'text', text: formatValidationSummary(summary, issues.messages || []) },
+ ],
+ structuredContent: {
+ ...summary,
+ messages: issues.messages || [],
+ info: report?.info || null,
+ },
};
},
},
@@ -412,7 +527,10 @@ const TOOLS = {
inspect_model: {
async handler(args, auth) {
const rl = await limits.mcpInspect(auth.userId);
- if (!rl.success) throw rpcError(-32000, 'rate_limited', { retry_after: Math.ceil((rl.reset - Date.now()) / 1000) });
+ if (!rl.success)
+ throw rpcError(-32000, 'rate_limited', {
+ retry_after: Math.ceil((rl.reset - Date.now()) / 1000),
+ });
const { bytes, url, filename } = await safeFetchModel(args.url);
const info = await inspectModel(bytes, { fileSize: bytes.byteLength });
return {
@@ -425,7 +543,10 @@ const TOOLS = {
optimize_model: {
async handler(args, auth) {
const rl = await limits.mcpOptimize(auth.userId);
- if (!rl.success) throw rpcError(-32000, 'rate_limited', { retry_after: Math.ceil((rl.reset - Date.now()) / 1000) });
+ if (!rl.success)
+ throw rpcError(-32000, 'rate_limited', {
+ retry_after: Math.ceil((rl.reset - Date.now()) / 1000),
+ });
const { bytes, url, filename } = await safeFetchModel(args.url);
const info = await inspectModel(bytes, { fileSize: bytes.byteLength });
const suggestions = suggestOptimizations(info);
@@ -447,7 +568,8 @@ async function safeFetchModel(url) {
}
function formatValidationSummary(s, messages) {
- const head = `glTF-Validator report for ${s.filename} (${(s.fileSize / 1024).toFixed(1)} KB)\n` +
+ const head =
+ `glTF-Validator report for ${s.filename} (${(s.fileSize / 1024).toFixed(1)} KB)\n` +
`Errors: ${s.numErrors}, Warnings: ${s.numWarnings}, Infos: ${s.numInfos}, Hints: ${s.numHints}` +
(s.truncated ? ' (truncated)' : '');
if (!messages.length) return head;
@@ -463,7 +585,12 @@ function formatValidationSummary(s, messages) {
function formatInspection(info) {
const c = info.counts;
const tex = info.textures.length
- ? info.textures.map((t) => ` • ${t.name || '(unnamed)'} — ${t.mimeType} ${t.width}×${t.height}, ${(t.byteSize / 1024).toFixed(1)} KB`).join('\n')
+ ? info.textures
+ .map(
+ (t) =>
+ ` • ${t.name || '(unnamed)'} — ${t.mimeType} ${t.width}×${t.height}, ${(t.byteSize / 1024).toFixed(1)} KB`,
+ )
+ .join('\n')
: ' (none)';
return [
`Model: ${info.filename} (${(info.fileSize / 1024 / 1024).toFixed(2)} MB, ${info.container})`,
@@ -479,15 +606,29 @@ function formatInspection(info) {
function formatSuggestions(suggestions) {
if (!suggestions.length) return 'No suggestions.';
- return suggestions.map((s) => {
- const tag = { info: 'INFO', warn: 'WARN', critical: 'CRIT' }[s.severity] || s.severity.toUpperCase();
- const est = s.estimate ? ` — ${s.estimate}` : '';
- return `[${tag}] ${s.id}: ${s.message}${est}`;
- }).join('\n');
+ return suggestions
+ .map((s) => {
+ const tag =
+ { info: 'INFO', warn: 'WARN', critical: 'CRIT' }[s.severity] ||
+ s.severity.toUpperCase();
+ const est = s.estimate ? ` — ${s.estimate}` : '';
+ return `[${tag}] ${s.id}: ${s.message}${est}`;
+ })
+ .join('\n');
}
// ── <model-viewer> artifact builder ─────────────────────────────────────────
-function renderModelViewerHtml({ src, name, poster, background, height, width, autoRotate, ar, cameraOrbit }) {
+function renderModelViewerHtml({
+ src,
+ name,
+ poster,
+ background,
+ height,
+ width,
+ autoRotate,
+ ar,
+ cameraOrbit,
+}) {
const attrs = [
`src="${attr(src)}"`,
'camera-controls',
@@ -499,13 +640,19 @@ function renderModelViewerHtml({ src, name, poster, background, height, width, a
poster ? `poster="${attr(poster)}"` : '',
cameraOrbit ? `camera-orbit="${attr(cameraOrbit)}"` : '',
`alt="${attr(name || 'Avatar')}"`,
- ].filter(Boolean).join(' ');
+ ]
+ .filter(Boolean)
+ .join(' ');
return [
'<!doctype html>',
'<html><head><meta charset="utf-8"><title>' + esc(name || 'Avatar') + '</title>',
'<script type="module" src="https://ajax.googleapis.com/ajax/libs/model-viewer/4.0.0/model-viewer.min.js"></script>',
'<style>html,body{margin:0;height:100%;background:' + attr(background) + '}',
- 'model-viewer{width:' + attr(width) + ';height:' + attr(height) + ';--progress-bar-color:#6a5cff}</style>',
+ 'model-viewer{width:' +
+ attr(width) +
+ ';height:' +
+ attr(height) +
+ ';--progress-bar-color:#6a5cff}</style>',
'</head><body>',
'<model-viewer ' + attrs + '></model-viewer>',
'</body></html>',
@@ -546,7 +693,7 @@ function send401(res, msg) {
res.statusCode = 401;
res.setHeader(
'www-authenticate',
- `Bearer resource_metadata="${env.APP_ORIGIN}/.well-known/oauth-protected-resource", resource="${resource}"`
+ `Bearer resource_metadata="${env.APP_ORIGIN}/.well-known/oauth-protected-resource", resource="${resource}"`,
);
res.setHeader('content-type', 'application/json; charset=utf-8');
res.end(JSON.stringify({ error: 'unauthorized', error_description: msg }));
@@ -568,10 +715,13 @@ function summarize(args) {
}
function esc(s) {
- return String(s).replace(/[&<>]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;' }[c]));
+ return String(s).replace(/[&<>]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;' })[c]);
}
function attr(s) {
- return String(s).replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c]));
+ return String(s).replace(
+ /[&<>"]/g,
+ (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[c],
+ );
}
// CSS inputs land inside a <style> declaration (`background: <value>`), where
@@ -599,5 +749,7 @@ function safeHttpsUrl(s) {
try {
const u = new URL(String(s));
return u.protocol === 'https:' ? u.toString() : undefined;
- } catch { return undefined; }
+ } catch {
+ return undefined;
+ }
}
diff --git a/api/widgets/page.js b/api/widgets/page.js
index 614bb7298..00a8d69a2 100644
--- a/api/widgets/page.js
+++ b/api/widgets/page.js
@@ -13,6 +13,59 @@ import { sql } from '../_lib/db.js';
import { env } from '../_lib/env.js';
import { cors, wrap } from '../_lib/http.js';
+// ── inline embed-policy helpers (prompt 02 / api/_lib/embed-policy.js not yet shipped) ──
+
+function _defaultPolicy() {
+ return {
+ version: 1,
+ origins: { mode: 'allowlist', hosts: [] },
+ surfaces: { script: true, iframe: true, widget: true, mcp: true },
+ };
+}
+
+function _parsePolicy(p) {
+ if (!p) return null;
+ if (!('version' in p) && ('mode' in p || 'hosts' in p)) {
+ // Old flat shape — only origins were configured; all surfaces allowed.
+ return {
+ ..._defaultPolicy(),
+ origins: { mode: p.mode || 'allowlist', hosts: p.hosts ?? [] },
+ };
+ }
+ return { ..._defaultPolicy(), ...p };
+}
+
+async function _readPolicyForAgent(agentId) {
+ try {
+ const [row] =
+ await sql`SELECT embed_policy FROM agent_identities WHERE id = ${agentId} AND deleted_at IS NULL`;
+ if (!row) return null;
+ return _parsePolicy(row.embed_policy);
+ } catch (err) {
+ if (/column .* does not exist/i.test(String(err?.message))) return null;
+ throw err;
+ }
+}
+
+function _originAllowed(refererHeader, policy, appOriginHost) {
+ if (!refererHeader) return true; // no referer → allow (bots, direct)
+ let host;
+ try {
+ host = new URL(refererHeader).hostname.toLowerCase();
+ } catch {
+ return true;
+ }
+ if (host === appOriginHost || host === 'localhost' || host.endsWith('.localhost')) return true;
+ const hosts = policy?.origins?.hosts ?? [];
+ const mode = policy?.origins?.mode ?? 'allowlist';
+ const matched = hosts.some((h) => {
+ const lower = h.toLowerCase();
+ if (lower.startsWith('*.')) return host.endsWith(lower.slice(1)) && host !== lower.slice(2);
+ return host === lower;
+ });
+ return mode === 'allowlist' ? matched : !matched;
+}
+
const TYPE_LABEL = {
turntable: 'Turntable Showcase',
'animation-gallery': 'Animation Gallery',
@@ -31,6 +84,20 @@ export default wrap(async (req, res) => {
const widget = await loadWidget(widgetId);
if (!widget) return notFound(res);
+ // Agent embed-policy gate — only when widget is tied to an agent identity.
+ if (widget.agent_id) {
+ const agentPolicy = await _readPolicyForAgent(widget.agent_id);
+ if (agentPolicy) {
+ if (agentPolicy.surfaces?.widget === false) {
+ return forbidden(res, "This widget's embed is disabled by the agent owner.");
+ }
+ const appHost = new URL(env.APP_ORIGIN).hostname.toLowerCase();
+ if (!_originAllowed(req.headers['referer'], agentPolicy, appHost)) {
+ return forbidden(res, 'This widget is not permitted on the requesting origin.');
+ }
+ }
+ }
+
const origin = env.APP_ORIGIN;
const pageUrl = `${origin}/w/${widget.id}`;
const ogUrl = `${origin}/api/widgets/${widget.id}/og`;
@@ -58,18 +125,38 @@ export default wrap(async (req, res) => {
async function loadWidget(id) {
try {
const [row] = await sql`
- select id, name, type, avatar_id, is_public
+ select id, name, type, avatar_id, agent_id, is_public
from widgets
where id = ${id} and deleted_at is null
limit 1
`;
return row || null;
} catch (err) {
+ if (/column .* does not exist/i.test(err?.message || '')) {
+ // agent_id column not yet migrated — fall back without it
+ const [row] = await sql`
+ select id, name, type, avatar_id, is_public
+ from widgets
+ where id = ${id} and deleted_at is null
+ limit 1
+ `;
+ return row || null;
+ }
if (/relation .* does not exist/i.test(err?.message || '')) return null;
throw err;
}
}
+function forbidden(res, msg) {
+ res.statusCode = 403;
+ res.setHeader('content-type', 'text/html; charset=utf-8');
+ res.setHeader('cache-control', 'public, max-age=60');
+ const m = escapeHtml(msg || 'Access denied.');
+ res.end(`<!doctype html><meta charset="utf-8"><title>Access denied</title>
+<style>body{font-family:Inter,system-ui,sans-serif;background:#0a0a0a;color:#e0e0e0;display:grid;place-items:center;min-height:100vh;margin:0}main{text-align:center;padding:2rem}a{color:#8b5cf6}</style>
+<main><h1>Access denied</h1><p>${m}</p><p><a href="/">Open 3D Agent</a></p></main>`);
+}
+
function notFound(res) {
res.statusCode = 404;
res.setHeader('content-type', 'text/html; charset=utf-8');
diff --git a/prompts/build/06-01-supported-trust-wizard.md b/prompts/build/06-01-supported-trust-wizard.md
new file mode 100644
index 000000000..8d302c72e
--- /dev/null
+++ b/prompts/build/06-01-supported-trust-wizard.md
@@ -0,0 +1,255 @@
+---
+mode: agent
+description: "Add supportedTrust multi-select to the ERC-8004 registration wizard and edit modal"
+---
+
+# 06-01 · supportedTrust Multi-Select in ERC-8004 Wizard
+
+## Context
+
+The ERC-8004 registration wizard (`src/erc8004/register-ui.js`) currently hardcodes `supportedTrust: ['reputation']` in `buildRegistrationJSON` (`src/erc8004/agent-registry.js:186`). The ERC-8004 spec allows three trust modes: `reputation`, `validation`, and `stake`. There is no UI for the user to choose.
+
+The wizard has 3 steps. Step 2 renders service endpoints and already has a working x402Support checkbox (wired end-to-end). This task follows that exact pattern to add a `supportedTrust` multi-checkbox group in the same step.
+
+## Files to modify
+
+- `src/erc8004/agent-registry.js` — `buildRegistrationJSON`
+- `src/erc8004/register-ui.js` — form init, `_renderStepServices`, `_doRegister`, `_doUpdateAgent`, `_openEditModal`, template click handler
+
+## What to build
+
+### 1. `buildRegistrationJSON` — accept `supportedTrust` param
+
+In `src/erc8004/agent-registry.js`, find `buildRegistrationJSON` (line ~147). It currently has:
+
+```js
+export function buildRegistrationJSON({
+ name,
+ description,
+ imageUrl,
+ glbUrl,
+ agentId,
+ chainId,
+ registryAddr,
+ services = [],
+ x402Support = false,
+}) {
+```
+
+And the `json` object sets:
+```js
+supportedTrust: ['reputation'],
+```
+
+Change to accept `supportedTrust = ['reputation']` in the destructuring, and use it in the output:
+
+```js
+export function buildRegistrationJSON({
+ name,
+ description,
+ imageUrl,
+ glbUrl,
+ agentId,
+ chainId,
+ registryAddr,
+ services = [],
+ x402Support = false,
+ supportedTrust = ['reputation'],
+}) {
+```
+
+In the `json` object, replace the hardcoded line with:
+```js
+supportedTrust: Array.isArray(supportedTrust) && supportedTrust.length > 0
+ ? supportedTrust
+ : ['reputation'],
+```
+
+### 2. Form initializers — add `supportedTrust` field
+
+There are two form objects in `src/erc8004/register-ui.js`:
+
+**Primary form init** (around line 270 in the constructor, after `x402Support: false`):
+```js
+services: [],
+x402Support: false,
+apiToken: '',
+```
+Add `supportedTrust: ['reputation'],` after `x402Support: false`.
+
+**Scratch reset** (around line 680, inside `_resetWizard` when `mode === 'scratch'`):
+```js
+services: [],
+x402Support: false,
+apiToken: this.form.apiToken || '',
+```
+Add `supportedTrust: ['reputation'],` after `x402Support: false`.
+
+### 3. `_renderStepServices` — add checkbox group
+
+In `_renderStepServices`, find the x402 checkbox block:
+```html
+<label class="erc8004-checkbox" style="margin-top:12px">
+ <input type="checkbox" data-role="x402" ${this.form.x402Support ? 'checked' : ''} />
+ Accept x402 payments (HTTP-native micropayments)
+</label>
+```
+
+Add a trust multi-select block immediately after it:
+```html
+<fieldset class="erc8004-fieldset" style="margin-top:14px;border:1px solid var(--erc8004-border,#333);border-radius:6px;padding:10px 12px">
+ <legend class="erc8004-label" style="padding:0 4px">Trust models</legend>
+ <p class="erc8004-hint" style="margin:2px 0 8px">How other agents can verify yours. Select all that apply.</p>
+ ${['reputation','validation','stake'].map(t => `
+ <label class="erc8004-checkbox" style="margin-bottom:4px">
+ <input type="checkbox" data-role="trust-${t}" ${(this.form.supportedTrust || []).includes(t) ? 'checked' : ''} />
+ ${t.charAt(0).toUpperCase() + t.slice(1)}
+ </label>
+ `).join('')}
+</fieldset>
+```
+
+Then in the JS wiring section of `_renderStepServices` (after the x402 change listener), add listeners for each trust checkbox:
+```js
+['reputation', 'validation', 'stake'].forEach((t) => {
+ body.querySelector(`[data-role="trust-${t}"]`).addEventListener('change', () => {
+ const checked = ['reputation', 'validation', 'stake'].filter(
+ (x) => body.querySelector(`[data-role="trust-${x}"]`)?.checked,
+ );
+ this.form.supportedTrust = checked.length > 0 ? checked : ['reputation'];
+ });
+});
+```
+
+### 4. `_doRegister` — pass `supportedTrust` to `registerAgent`
+
+In `_doRegister` (line ~1347), find the `registerAgent` call:
+```js
+return await registerAgent({
+ name,
+ description,
+ glbFile: glbFile || undefined,
+ glbUrl: glbUrl || undefined,
+ imageUrl: imageUrl || undefined,
+ apiToken: apiToken || undefined,
+ services: extraServices,
+ x402Support: !!this.form.x402Support,
+ onStatus: say,
+});
+```
+
+`registerAgent` calls `buildRegistrationJSON` internally. Look at how `registerAgent` is defined in `src/erc8004/agent-registry.js` (around line 218+) — add `supportedTrust` to its destructured params and forward it to `buildRegistrationJSON`. Then pass `supportedTrust: this.form.supportedTrust || ['reputation']` in the `registerAgent` call from `_doRegister`.
+
+In `src/erc8004/agent-registry.js`, the `registerAgent` function (around line 218+):
+```js
+export async function registerAgent({
+ name,
+ description,
+ glbFile,
+ glbUrl,
+ imageUrl,
+ apiToken,
+ chainId: preferredChainId,
+ services = [],
+ x402Support = false,
+ onStatus = () => {},
+}) {
+```
+Add `supportedTrust = ['reputation'],` to the destructuring. Then find the `buildRegistrationJSON` call inside it (around line 321) and add `supportedTrust` to that call:
+```js
+const registrationJSON = buildRegistrationJSON({
+ name,
+ description,
+ imageUrl,
+ glbUrl,
+ agentId,
+ chainId,
+ registryAddr,
+ services,
+ x402Support,
+ supportedTrust,
+});
+```
+
+### 5. `_doUpdateAgent` — preserve or override `supportedTrust`
+
+In `_doUpdateAgent` (line ~1895), find the `buildRegistrationJSON` call:
+```js
+const registrationJSON = buildRegistrationJSON({
+ name,
+ description,
+ imageUrl: newImageUrl || '',
+ glbUrl,
+ agentId,
+ chainId,
+ registryAddr,
+ services: preservedServices,
+ x402Support:
+ typeof x402Support === 'boolean'
+ ? x402Support
+ : !!(currentMeta?.x402Support || currentMeta?.x402),
+});
+```
+
+Add `supportedTrust` similarly — use it when provided (from the edit modal), otherwise fall back to whatever was in the existing metadata:
+```js
+supportedTrust: Array.isArray(supportedTrust) && supportedTrust.length > 0
+ ? supportedTrust
+ : Array.isArray(currentMeta?.supportedTrust) && currentMeta.supportedTrust.length > 0
+ ? currentMeta.supportedTrust
+ : ['reputation'],
+```
+
+Add `supportedTrust` to the `_doUpdateAgent` destructured params (alongside `x402Support`).
+
+### 6. `_openEditModal` — read `supportedTrust` from existing metadata + add checkboxes
+
+In `_openEditModal` (line ~1727), find the x402 checkbox in the modal HTML:
+```html
+<label class="erc8004-checkbox">
+ <input type="checkbox" name="x402Support" ${currentMeta?.x402Support || currentMeta?.x402 ? 'checked' : ''} />
+ Accept x402 payments (HTTP-native micropayments)
+</label>
+```
+
+Add the same trust fieldset immediately after it:
+```html
+<fieldset class="erc8004-fieldset" style="margin-top:14px;border:1px solid var(--erc8004-border,#333);border-radius:6px;padding:10px 12px">
+ <legend class="erc8004-label" style="padding:0 4px">Trust models</legend>
+ ${['reputation','validation','stake'].map(t => `
+ <label class="erc8004-checkbox" style="margin-bottom:4px">
+ <input type="checkbox" name="trust-${t}" ${(meta?.supportedTrust || ['reputation']).includes(t) ? 'checked' : ''} />
+ ${t.charAt(0).toUpperCase() + t.slice(1)}
+ </label>
+ `).join('')}
+</fieldset>
+```
+
+In the modal save handler (where `x402Support` is read), add:
+```js
+const supportedTrust = ['reputation', 'validation', 'stake'].filter(
+ (t) => !!modal.querySelector(`[name="trust-${t}"]`)?.checked,
+);
+```
+
+Pass `supportedTrust` into `_doUpdateAgent`.
+
+### 7. Template click handler — do NOT copy `supportedTrust` from templates
+
+Templates don't define `supportedTrust`. When a template is selected (around line ~2068), the handler currently copies `services` and `x402Support`. Leave `supportedTrust` at its current form value (default `['reputation']`) — don't reset it. No change needed here.
+
+## Verification
+
+```bash
+node --check src/erc8004/register-ui.js
+node --check src/erc8004/agent-registry.js
+npm run build
+```
+
+Both should exit clean. No browser environment available — note inability to smoke-test in report.
+
+## Out of scope
+
+- Changing what the contracts actually enforce for trust (on-chain only reads the URI).
+- Adding explanatory copy about what each trust model means (future UX task).
+- `_renderBatchTab` — batch deploys are separate and not in scope here.
diff --git a/prompts/build/06-02-hub-my-agents-autohighlight.md b/prompts/build/06-02-hub-my-agents-autohighlight.md
new file mode 100644
index 000000000..0d467e8a0
--- /dev/null
+++ b/prompts/build/06-02-hub-my-agents-autohighlight.md
@@ -0,0 +1,140 @@
+---
+mode: agent
+description: "When opening RegisterUI from the hub Manage button, auto-highlight the specific registered agent in the My Agents tab"
+---
+
+# 06-02 · Hub Manage Button — Auto-Highlight Registered Agent in My Agents Tab
+
+## Context
+
+On `/agent/:id`, the owner sees a "Deploy on-chain" button that, when the agent is already registered, opens `RegisterUI` on the **My Agents** tab. The code is in `src/agent-hub-actions.js` (the registered-agent click handler starting around line 59):
+
+```js
+new RegisterUI(
+ wrap,
+ () => { wrap.remove(); location.reload(); },
+ { initialTab: 'my' },
+);
+```
+
+The problem: the My Agents tab loads all agents owned by the connected wallet, but doesn't know which specific agent to highlight. The owner has to scan the list manually to find and click "Edit on-chain ✏️" for the right one.
+
+The backend already provides `erc8004_agent_id` and `chain_id` in the `rawAgent` object passed to `renderHubActions`. We can pass these as hints to `RegisterUI` so it auto-scrolls to and visually highlights the matching card.
+
+## Files to modify
+
+- `src/erc8004/register-ui.js` — constructor opts, `_renderMyAgents`, `_fillAgentCard`
+- `src/agent-hub-actions.js` — pass `highlightAgentId` + `highlightChainId` in the `opts` object
+
+## What to build
+
+### 1. `RegisterUI` constructor — accept `highlightAgentId` and `highlightChainId`
+
+In `src/erc8004/register-ui.js`, find the constructor (around line 230). After `this.activeTab = opts.initialTab || 'create';`, add:
+
+```js
+this._highlightAgentId = opts.highlightAgentId ? Number(opts.highlightAgentId) : null;
+this._highlightChainId = opts.highlightChainId ? Number(opts.highlightChainId) : null;
+```
+
+### 2. `_renderMyAgents` — switch to the correct chain before listing
+
+In `_renderMyAgents` (line ~1382), before the `listAgentsByOwner` call, if a highlight chain is set, switch `this.selectedChainId` to it and update the chain select element so the UI reflects the switch:
+
+```js
+if (this._highlightChainId && this._highlightChainId !== this.selectedChainId) {
+ this.selectedChainId = this._highlightChainId;
+ const sel = this.el.querySelector('.erc8004-chain-select');
+ if (sel) sel.value = String(this._highlightChainId);
+}
+```
+
+Place this block at the very top of `_renderMyAgents`, before any DOM writes.
+
+### 3. `_fillAgentCard` — auto-scroll and highlight the matched agent
+
+In `_fillAgentCard` (line ~1443), after the card's full `innerHTML` is set and the event listeners are wired (i.e., at the end of the `try` block, just before the closing `}`), add:
+
+```js
+if (this._highlightAgentId && Number(agentId) === this._highlightAgentId) {
+ card.classList.add('erc8004-agent-card--highlight');
+ // Scroll into view after a brief frame so layout is complete
+ requestAnimationFrame(() => card.scrollIntoView({ behavior: 'smooth', block: 'nearest' }));
+ // If this card has an edit button, click it automatically so the owner
+ // lands directly in the edit flow without an extra click.
+ if (opts.withEdit) {
+ const editBtn = card.querySelector('[data-role="edit"]');
+ if (editBtn) {
+ // Small delay to let the scroll finish
+ setTimeout(() => editBtn.click(), 400);
+ }
+ }
+}
+```
+
+### 4. CSS — highlight class
+
+The `erc8004-agent-card--highlight` class needs a visual distinction. Find where agent card styles live (they're inline in register-ui.js — search for `.erc8004-agent-card` in the `_buildStyles` or equivalent `<style>` injection). Add:
+
+```css
+.erc8004-agent-card--highlight {
+ outline: 2px solid var(--erc8004-accent, #7c6fff);
+ outline-offset: 2px;
+}
+```
+
+To find where to inject it: in `register-ui.js`, search for `erc8004-agent-card {` — the styles are in a template literal injected into a `<style>` tag. Add the new rule directly after the existing `.erc8004-agent-card` block.
+
+### 5. `src/agent-hub-actions.js` — pass the hint
+
+In the registered-agent click handler (around line 59–79), find:
+
+```js
+new RegisterUI(
+ wrap,
+ () => {
+ wrap.remove();
+ location.reload();
+ },
+ { initialTab: 'my' },
+);
+```
+
+Change to:
+
+```js
+new RegisterUI(
+ wrap,
+ () => {
+ wrap.remove();
+ location.reload();
+ },
+ {
+ initialTab: 'my',
+ highlightAgentId: erc8004AgentId || null,
+ highlightChainId: chainId || null,
+ },
+);
+```
+
+The variables `erc8004AgentId` and `chainId` are already extracted at the top of `renderHubActions` (lines 18–20).
+
+## Verification
+
+```bash
+node --check src/erc8004/register-ui.js
+node --check src/agent-hub-actions.js
+npm run build
+```
+
+Both should pass clean. No browser available — note inability to smoke-test in report.
+
+## Behaviour when `erc8004AgentId` is null
+
+If `rawAgent.erc8004_agent_id` is null (e.g., registered externally and not tracked by the backend), no auto-highlight occurs — the My Agents tab opens normally and the user selects manually. The guard `if (this._highlightAgentId && ...)` handles this safely.
+
+## Out of scope
+
+- Auto-connecting the wallet (wallet must already be connected for `_renderMyAgents` to load the list).
+- Changing what "Edit on-chain" does — that modal is separate.
+- Showing a loading skeleton while the card fills in (it already shows "Loading #ID…" text).
diff --git a/prompts/build/06-03-edit-modal-services.md b/prompts/build/06-03-edit-modal-services.md
new file mode 100644
index 000000000..d6e2fbec7
--- /dev/null
+++ b/prompts/build/06-03-edit-modal-services.md
@@ -0,0 +1,166 @@
+---
+mode: agent
+description: "Add service endpoint editor to the existing on-chain agent edit modal in RegisterUI"
+---
+
+# 06-03 · Edit Modal — Service Endpoint Editor
+
+## Context
+
+The `_openEditModal` in `src/erc8004/register-ui.js` (line ~1727) lets owners update name, description, image, GLB, x402Support, and avatar removal. But it does **not** let them edit service endpoints. The `_doUpdateAgent` method (line ~1834) already has logic to **preserve** non-avatar services (`preservedServices`), but there's no way for the user to add, remove, or edit them.
+
+The registration wizard Step 2 (`_renderStepServices`, line ~768) has a fully-working service list editor (add/remove rows, type select, endpoint input). This task ports that same editor pattern into the edit modal.
+
+## Files to modify
+
+- `src/erc8004/register-ui.js` only — `_openEditModal`, `_doUpdateAgent`
+
+## What to build
+
+### 1. Extract a reusable service-list renderer
+
+The service list logic in `_renderStepServices` builds a list of `{ name, type, endpoint }` rows with add/remove buttons. Rather than duplicating that HTML+JS verbatim in the modal, extract it into a private method `_buildServiceEditor(container, initialServices)` that:
+
+- Accepts a parent `HTMLElement` and an array of service objects as the initial state.
+- Renders the rows using the same structure as Step 2 (look for the `renderList` closure in `_renderStepServices`).
+- Exposes a `.getServices()` method (or closure) to read the current list back out.
+- Returns `{ getServices }`.
+
+Then in `_renderStepServices`, call `this._buildServiceEditor(serviceContainer, this.form.services)` and wire the returned `getServices` to update `this.form.services` on next/deploy click (replacing the current inline list-render logic).
+
+**Read `_renderStepServices` carefully** before extracting — the current code around line 768–825 uses:
+- `renderList()` — a closure that re-renders rows from a `services` array
+- An "add" button (`data-role="add"`)
+- Per-row remove buttons (`data-role="rm"`)
+- Per-row `<select>` for type (a2a / mcp / web / x402)
+- Per-row text input for endpoint
+
+Extract that into `_buildServiceEditor(container, initialServices)`. It should manage its own internal array copy and return `{ getServices: () => [...] }`.
+
+### 2. `_openEditModal` — add service editor section
+
+In `_openEditModal`, find the edit modal HTML template (the `modal.innerHTML = ...` block). After the x402Support checkbox and before the Pinata JWT label, inject a service editor section:
+
+```html
+<div class="erc8004-label" style="margin-top:14px">Service endpoints</div>
+<p class="erc8004-hint">Add or remove A2A / MCP / web endpoints. The 3D avatar service is managed by the "3D Avatar (GLB)" field above.</p>
+<div data-role="services-editor"></div>
+```
+
+After the modal is appended to `this.el`, wire the service editor:
+```js
+const nonAvatarServices = (meta?.services || []).filter(
+ (s) => s?.name !== 'avatar' && s?.name !== '3D',
+);
+const { getServices } = this._buildServiceEditor(
+ modal.querySelector('[data-role="services-editor"]'),
+ nonAvatarServices,
+);
+```
+
+### 3. Edit modal save handler — read services and pass to `_doUpdateAgent`
+
+In the save handler (around line 1796–1826), currently:
+```js
+const x402Support = !!modal.querySelector('[name="x402Support"]')?.checked;
+
+await this._doUpdateAgent({
+ agentId,
+ name,
+ description,
+ imageUrl: imageUrlInput,
+ glbFile,
+ removeAvatar,
+ x402Support,
+ apiToken,
+ currentMeta: card._meta,
+ say,
+});
+```
+
+Add services read and pass it through:
+```js
+const editedServices = getServices();
+const x402Support = !!modal.querySelector('[name="x402Support"]')?.checked;
+
+await this._doUpdateAgent({
+ agentId,
+ name,
+ description,
+ imageUrl: imageUrlInput,
+ glbFile,
+ removeAvatar,
+ x402Support,
+ services: editedServices,
+ apiToken,
+ currentMeta: card._meta,
+ say,
+});
+```
+
+### 4. `_doUpdateAgent` — use provided services instead of always pulling from metadata
+
+Currently `_doUpdateAgent` (line ~1834) always reconstructs services from `currentMeta`:
+```js
+const preservedServices = (currentMeta?.services || []).filter(
+ (s) => s?.name !== 'avatar' && s?.name !== '3D',
+);
+```
+
+Add a `services` parameter to `_doUpdateAgent` and use it when provided:
+```js
+async _doUpdateAgent({
+ agentId,
+ name,
+ description,
+ imageUrl,
+ glbFile,
+ removeAvatar = false,
+ x402Support,
+ services, // <-- add this
+ apiToken,
+ currentMeta,
+ say,
+}) {
+```
+
+Then change the `preservedServices` line:
+```js
+const preservedServices = Array.isArray(services)
+ ? services
+ : (currentMeta?.services || []).filter((s) => s?.name !== 'avatar' && s?.name !== '3D');
+```
+
+This keeps backward compat — callers that don't pass `services` still get the metadata-preserve behavior.
+
+## Service type options (for the editor select)
+
+Use the same set as Step 2:
+- `a2a` → label "A2A"
+- `mcp` → label "MCP"
+- `web` → label "Web"
+- `x402` → label "x402"
+
+Look at the existing `<select>` in `_renderStepServices` to match the exact option values and labels.
+
+## Verification
+
+```bash
+node --check src/erc8004/register-ui.js
+npm run build
+```
+
+Both should exit clean. No browser available — note inability to smoke-test in report.
+
+## Important constraints
+
+- The extracted `_buildServiceEditor` must work for both Step 2 and the edit modal. Don't break Step 2 when you refactor.
+- The `avatar` and `3D` service entries are auto-managed by GLB fields — never show them in the editor list.
+- Don't change `_doRegister` — it already reads from `this.form.services` which `_buildServiceEditor` will update in Step 2.
+- ESM only, tabs 4-wide, no TypeScript.
+
+## Out of scope
+
+- Service endpoint validation (URL format check) — future task.
+- Reordering services via drag-and-drop.
+- Changes to `buildRegistrationJSON` signature — services are already accepted as the `services` array parameter.
diff --git a/prompts/embed-hardening/00-README.md b/prompts/embed-hardening/00-README.md
index e8303dda8..f130d3c99 100644
--- a/prompts/embed-hardening/00-README.md
+++ b/prompts/embed-hardening/00-README.md
@@ -1,15 +1,15 @@
# Embed Hardening — Make the embed system production-safe before users flood in
-This band makes the existing embed surfaces safe to drop on third-party sites at scale. It's a follow-up to the CDN versioning work that landed in [scripts/publish-lib.mjs](../../scripts/publish-lib.mjs) + [vercel.json](../../vercel.json) `/agent-3d/*` routes — the script ships fine, but the *runtime* (per-agent policy, surface enforcement, LLM payment routing) has gaps that will bite the moment the snippet gets pasted somewhere real.
+This band makes the existing embed surfaces safe to drop on third-party sites at scale. It's a follow-up to the CDN versioning work that landed in [scripts/publish-lib.mjs](../../scripts/publish-lib.mjs) + [vercel.json](../../vercel.json) `/agent-3d/*` routes — the script ships fine, but the _runtime_ (per-agent policy, surface enforcement, LLM payment routing) has gaps that will bite the moment the snippet gets pasted somewhere real.
---
## The audit that drove these prompts
-Investigation of the current state ([api/agents/[id]/embed-policy.js](../../api/agents/[id]/embed-policy.js), [api/_lib/schema.sql](../../api/_lib/schema.sql), [src/runtime/providers.js](../../src/runtime/providers.js), [src/element.js](../../src/element.js), [agent-embed.html](../../agent-embed.html)) found:
+Investigation of the current state ([api/agents/[id]/embed-policy.js](../../api/agents/[id]/embed-policy.js), [api/\_lib/schema.sql](../../api/_lib/schema.sql), [src/runtime/providers.js](../../src/runtime/providers.js), [src/element.js](../../src/element.js), [agent-embed.html](../../agent-embed.html)) found:
- **Embed-policy endpoint exists** with GET/PUT/DELETE and a JSONB `embed_policy` column on `agent_identities`. Owner UI exists at [public/dashboard/embed-policy.html](../../public/dashboard/embed-policy.html). Origin allowlist is enforced in [agent-embed.html:49-88](../../agent-embed.html#L49-L88).
-- **Schema migration was never merged** — the `ADD COLUMN` lives in [specs/schema/embed-policy.sql](../../specs/schema/embed-policy.sql) but not in [api/_lib/schema.sql](../../api/_lib/schema.sql). Fresh deploys won't have the column.
+- **Schema migration was never merged** — the `ADD COLUMN` lives in [specs/schema/embed-policy.sql](../../specs/schema/embed-policy.sql) but not in [api/\_lib/schema.sql](../../api/_lib/schema.sql). Fresh deploys won't have the column.
- **`<agent-3d>` web component is broken on third-party sites** — [src/runtime/providers.js:30](../../src/runtime/providers.js#L30) defaults to `https://api.anthropic.com/v1/messages` with no key. No `we-pay`, no quota, no wallet-gating. A pasted snippet either fails silently or, if a key is somehow present, is uncapped.
- **Only one surface checks embed-policy** — the iframe page. The `<agent-3d>` script doesn't, widgets at `/w/:id` have a separate `visibility` flag, MCP at `/api/mcp/*` has no embedding checks at all.
- **No storage-mode tracking** — `avatars.storage_key` says "it's in R2." Nothing tracks "also pinned to IPFS" or "hash attested on-chain."
@@ -38,13 +38,13 @@ Backwards-compat: existing `{ mode, hosts }` shape is read as `policy.origins`.
## The five prompts
-| # | Prompt | What it ships |
-|---|---|---|
-| 01 | [01-schema-merge.md](01-schema-merge.md) | Move the `embed_policy` ALTER into [api/_lib/schema.sql](../../api/_lib/schema.sql) so fresh deploys have the column. Apply via [scripts/apply-schema.mjs](../../scripts/apply-schema.mjs). |
-| 02 | [02-extended-policy.md](02-extended-policy.md) | Define the extended JSONB shape. Write [api/_lib/embed-policy.js](../../api/_lib/embed-policy.js) helper. Extend [api/agents/[id]/embed-policy.js](../../api/agents/[id]/embed-policy.js) GET/PUT to accept the new shape (backwards-compat). Extend the dashboard UI with new sections. |
-| 03 | [03-surface-enforcement.md](03-surface-enforcement.md) | Wire policy reads into the `<agent-3d>` element, the widget page, the MCP endpoint, and CSP `frame-ancestors`. Fail-closed where denied. |
-| 04 | [04-llm-proxy-quotas.md](04-llm-proxy-quotas.md) | Build `/api/llm/anthropic` with per-agent monthly quota + per-IP rate limit. Default [src/runtime/providers.js](../../src/runtime/providers.js) to it when no key/proxy is set. Track usage in `usage_events`. **This is the spend-protection work — without it, no flood is safe.** |
-| 05 | [05-storage-flags.md](05-storage-flags.md) | Add `storage_mode` JSONB to `avatars`. Pin-to-IPFS UI in dashboard. Record content hash (no on-chain tx yet). |
+| # | Prompt | What it ships |
+| --- | ------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| 01 | [01-schema-merge.md](01-schema-merge.md) | Move the `embed_policy` ALTER into [api/\_lib/schema.sql](../../api/_lib/schema.sql) so fresh deploys have the column. Apply via [scripts/apply-schema.mjs](../../scripts/apply-schema.mjs). |
+| 02 | [02-extended-policy.md](02-extended-policy.md) | Define the extended JSONB shape. Write [api/\_lib/embed-policy.js](../../api/_lib/embed-policy.js) helper. Extend [api/agents/[id]/embed-policy.js](../../api/agents/[id]/embed-policy.js) GET/PUT to accept the new shape (backwards-compat). Extend the dashboard UI with new sections. |
+| 03 | [03-surface-enforcement.md](03-surface-enforcement.md) | Wire policy reads into the `<agent-3d>` element, the widget page, the MCP endpoint, and CSP `frame-ancestors`. Fail-closed where denied. |
+| 04 | [04-llm-proxy-quotas.md](04-llm-proxy-quotas.md) | Build `/api/llm/anthropic` with per-agent monthly quota + per-IP rate limit. Default [src/runtime/providers.js](../../src/runtime/providers.js) to it when no key/proxy is set. Track usage in `usage_events`. **This is the spend-protection work — without it, no flood is safe.** |
+| 05 | [05-storage-flags.md](05-storage-flags.md) | Add `storage_mode` JSONB to `avatars`. Pin-to-IPFS UI in dashboard. Record content hash (no on-chain tx yet). |
---
@@ -52,8 +52,8 @@ Backwards-compat: existing `{ mode, hosts }` shape is read as `policy.origins`.
These prompts are designed to run **in any order**, **in parallel**, in **separate Claude Code sessions**. The rules that make that safe:
-1. **Schema changes are additive `ALTER TABLE ... ADD COLUMN IF NOT EXISTS`**, appended to the existing migration block at [api/_lib/schema.sql:260](../../api/_lib/schema.sql#L260)+. Three of the five prompts (01, 02, 05) may add their own `ALTER` lines. They're idempotent — re-running is a no-op.
-2. **`api/_lib/embed-policy.js` is owned by prompt 02.** Prompts 03 and 04 import it *if it exists* and otherwise inline a minimal local copy of `defaultEmbedPolicy()` and `readEmbedPolicy(agentId)` (the inlined versions are spelled out in each prompt). Whichever ships first wins; later-shipping prompts can switch to the imported version in a follow-up.
+1. **Schema changes are additive `ALTER TABLE ... ADD COLUMN IF NOT EXISTS`**, appended to the existing migration block at [api/\_lib/schema.sql:260](../../api/_lib/schema.sql#L260)+. Three of the five prompts (01, 02, 05) may add their own `ALTER` lines. They're idempotent — re-running is a no-op.
+2. **`api/_lib/embed-policy.js` is owned by prompt 02.** Prompts 03 and 04 import it _if it exists_ and otherwise inline a minimal local copy of `defaultEmbedPolicy()` and `readEmbedPolicy(agentId)` (the inlined versions are spelled out in each prompt). Whichever ships first wins; later-shipping prompts can switch to the imported version in a follow-up.
3. **No two prompts touch the same source file's same lines.** Each prompt declares its **Files you own** (create/edit) and **Files off-limits** (other prompts are editing). If you find yourself wanting to edit an off-limits file, stop and report it instead.
4. **No prompt depends on another's runtime artifact.** Prompt 04 (LLM proxy) reads quotas from `embed_policy.brain.*` if present, falls back to a hard-coded global cap if absent. Prompt 03 (surface enforcement) reads `embed_policy.surfaces.*` if present, falls back to "all surfaces allowed" if absent.
5. **Prettier + `node --check` + `npx vite build`** are the verification floor for every prompt. SQL changes must be applied via `node scripts/apply-schema.mjs` against your local `DATABASE_URL` and re-run to prove idempotency.
@@ -82,6 +82,6 @@ If any of those don't hold, the band isn't done.
## House rules (also in [/CLAUDE.md](../../CLAUDE.md) and [/api/CLAUDE.md](../../api/CLAUDE.md))
- ESM only. Prettier: tabs, 4-wide, single quotes, 100 cols. Run `npx prettier --write` on every file you touch.
-- Use [api/_lib/http.js](../../api/_lib/http.js) (`json`/`error`/`wrap`/`cors`/`method`), [api/_lib/db.js](../../api/_lib/db.js) (`sql` tagged template), [api/_lib/auth.js](../../api/_lib/auth.js) (`getSessionUser`/`authenticateBearer`), [api/_lib/rate-limit.js](../../api/_lib/rate-limit.js) (`limits.*`/`clientIp`), [api/_lib/usage.js](../../api/_lib/usage.js) (`recordEvent`).
+- Use [api/\_lib/http.js](../../api/_lib/http.js) (`json`/`error`/`wrap`/`cors`/`method`), [api/\_lib/db.js](../../api/_lib/db.js) (`sql` tagged template), [api/\_lib/auth.js](../../api/_lib/auth.js) (`getSessionUser`/`authenticateBearer`), [api/\_lib/rate-limit.js](../../api/_lib/rate-limit.js) (`limits.*`/`clientIp`), [api/\_lib/usage.js](../../api/_lib/usage.js) (`recordEvent`).
- Never `res.end(JSON.stringify(...))`. Never instantiate a new Pool. Never hand-roll JWT.
- One PR per prompt. End every PR with a Reporting block (files changed, commands run + output, what was skipped, unrelated bugs noticed).
diff --git a/prompts/embed-hardening/01-schema-merge.md b/prompts/embed-hardening/01-schema-merge.md
index 4c4150879..a5ed57f33 100644
--- a/prompts/embed-hardening/01-schema-merge.md
+++ b/prompts/embed-hardening/01-schema-merge.md
@@ -2,17 +2,17 @@
## Why this exists
-The `/api/agents/:id/embed-policy` endpoint (see [api/agents/[id]/embed-policy.js](../../api/agents/[id]/embed-policy.js)) reads and writes a JSONB column `embed_policy` on the `agent_identities` table. The endpoint and the dashboard UI ship today, but the column itself was never merged into the canonical schema at [api/_lib/schema.sql](../../api/_lib/schema.sql) — it lives in a stranded one-off file at [specs/schema/embed-policy.sql](../../specs/schema/embed-policy.sql).
+The `/api/agents/:id/embed-policy` endpoint (see [api/agents/[id]/embed-policy.js](../../api/agents/[id]/embed-policy.js)) reads and writes a JSONB column `embed_policy` on the `agent_identities` table. The endpoint and the dashboard UI ship today, but the column itself was never merged into the canonical schema at [api/\_lib/schema.sql](../../api/_lib/schema.sql) — it lives in a stranded one-off file at [specs/schema/embed-policy.sql](../../specs/schema/embed-policy.sql).
Consequence: any fresh database (CI, local dev, a new Vercel preview branch with a fresh Neon DB) that runs `node scripts/apply-schema.mjs` does **not** get the column. The endpoint then 500s on its first read. This is the boring foundational fix that unblocks the other four prompts in [00-README.md](00-README.md).
## What you're building
-A two-line `ALTER TABLE` added to [api/_lib/schema.sql](../../api/_lib/schema.sql)'s additive-migrations block (currently lines 260–266), plus a header note in [specs/schema/embed-policy.sql](../../specs/schema/embed-policy.sql) marking it merged. Then run [scripts/apply-schema.mjs](../../scripts/apply-schema.mjs) against your local DB to confirm idempotency.
+A two-line `ALTER TABLE` added to [api/\_lib/schema.sql](../../api/_lib/schema.sql)'s additive-migrations block (currently lines 260–266), plus a header note in [specs/schema/embed-policy.sql](../../specs/schema/embed-policy.sql) marking it merged. Then run [scripts/apply-schema.mjs](../../scripts/apply-schema.mjs) against your local DB to confirm idempotency.
## Read first (in this order)
-1. [api/_lib/schema.sql](../../api/_lib/schema.sql) — focus on the `agent_identities` block at lines 235–266. Note the existing pattern for additive migrations (`alter table agent_identities add column if not exists ...`).
+1. [api/\_lib/schema.sql](../../api/_lib/schema.sql) — focus on the `agent_identities` block at lines 235–266. Note the existing pattern for additive migrations (`alter table agent_identities add column if not exists ...`).
2. [specs/schema/embed-policy.sql](../../specs/schema/embed-policy.sql) — 19 lines, the source of truth for the migration that needs merging.
3. [scripts/apply-schema.mjs](../../scripts/apply-schema.mjs) — the one-shot applier; reads `DATABASE_URL` from `.env.local` → `.env` → environment.
4. [api/agents/[id]/embed-policy.js](../../api/agents/[id]/embed-policy.js) — confirms the column name (`embed_policy`) and type (`jsonb`).
@@ -58,13 +58,13 @@ If you don't have a local Postgres / Neon connection, say so explicitly in your
## Files you own (create / edit)
-- Edit: [api/_lib/schema.sql](../../api/_lib/schema.sql) — one line added under the `agent_identities` additive-migrations block.
+- Edit: [api/\_lib/schema.sql](../../api/_lib/schema.sql) — one line added under the `agent_identities` additive-migrations block.
- Edit: [specs/schema/embed-policy.sql](../../specs/schema/embed-policy.sql) — header comment replaced; ALTER unchanged.
## Files off-limits (other prompts edit these)
- [api/agents/[id]/embed-policy.js](../../api/agents/[id]/embed-policy.js) — owned by prompt 02
-- [api/_lib/embed-policy.js](../../api/_lib/embed-policy.js) (if it exists) — owned by prompt 02
+- [api/\_lib/embed-policy.js](../../api/_lib/embed-policy.js) (if it exists) — owned by prompt 02
- [public/dashboard/embed-policy.html](../../public/dashboard/embed-policy.html) — owned by prompt 02
- Anything under [src/](../../src/) — owned by prompt 03
- [src/runtime/providers.js](../../src/runtime/providers.js) and any new `api/llm/*` — owned by prompt 04
@@ -90,9 +90,9 @@ Output at the end of your PR / commit:
- **Files changed:** with line counts.
- **Commands run + output:**
- - `node scripts/apply-schema.mjs` (first run + second run, full output).
- - `npx prettier --check ...` result.
- - `npx vite build` result (just last 5 lines + total time).
+ - `node scripts/apply-schema.mjs` (first run + second run, full output).
+ - `npx prettier --check ...` result.
+ - `npx vite build` result (just last 5 lines + total time).
- **Skipped:** anything you couldn't run (e.g. no local DB), with reason.
- **Unrelated bugs noticed:** list anything off in nearby code that you did NOT fix.
- **Confirmation of scope:** that you did not edit any file in the off-limits list above.
diff --git a/prompts/embed-hardening/02-extended-policy.md b/prompts/embed-hardening/02-extended-policy.md
new file mode 100644
index 000000000..457e496cb
--- /dev/null
+++ b/prompts/embed-hardening/02-extended-policy.md
@@ -0,0 +1,254 @@
+# Task 02 — Extended embed-policy JSONB shape, helper, API, and dashboard UI
+
+## Why this exists
+
+Today the per-agent `embed_policy` JSONB column on `agent_identities` only holds `{ mode: 'allowlist'|'denylist', hosts: [...] }` — an origin allowlist for the iframe page. We're extending it to a single configuration object that controls **three** axes: which **origins** can embed, which **render surfaces** are allowed (script tag / iframe / widget / MCP), and how the embedded agent's **brain** calls are paid for and rate-limited.
+
+Other prompts (03 surface enforcement, 04 LLM proxy) consume the new keys. This prompt is the source-of-truth for the shape, the helper, the API, and the owner-facing UI.
+
+See [00-README.md](00-README.md) for the full design and how this prompt fits with the other four.
+
+## What you're building
+
+Four deliverables:
+
+1. **Helper:** `api/_lib/embed-policy.js` — `defaultEmbedPolicy()`, `readEmbedPolicy(agentId)`, `validateEmbedPolicy(input)`, `normalizeLegacyPolicy(input)`.
+2. **API:** Extend [api/agents/[id]/embed-policy.js](../../api/agents/[id]/embed-policy.js) GET to return the normalized extended shape (legacy rows auto-migrate on read), PUT to accept the extended shape with backwards-compat for legacy `{ mode, hosts }` payloads.
+3. **UI:** Extend [public/dashboard/embed-policy.html](../../public/dashboard/embed-policy.html) with three new `<fieldset>` sections (surfaces, brain, storage) wired to the same PUT endpoint.
+4. **Idempotent ALTER** at the bottom of [api/\_lib/schema.sql](../../api/_lib/schema.sql) so this prompt can run before prompt 01.
+
+## The extended shape
+
+```jsonc
+{
+ "version": 1,
+ "origins": {
+ "mode": "allowlist" | "denylist", // default: "allowlist" with empty hosts = "deny all third-party origins"
+ "hosts": ["example.com", "*.substack.com"]
+ },
+ "surfaces": {
+ "script": true, // <agent-3d> on a third-party page
+ "iframe": true, // <iframe src="/agent/:id/embed">
+ "widget": true, // /w/:id widget pages
+ "mcp": false // exposed as an MCP tool over /api/mcp
+ },
+ "brain": {
+ "mode": "we-pay" | "key-proxy" | "wallet-gated" | "none",
+ "proxy_url": null, // required iff mode === "key-proxy"
+ "monthly_quota": 10000, // null = unlimited; whole-number completions
+ "rate_limit_per_min": 20, // null = unlimited
+ "model": "claude-opus-4-6"
+ },
+ "storage": {
+ "primary": "r2" | "ipfs",
+ "pinned_ipfs": false,
+ "onchain_attested": false
+ }
+}
+```
+
+### Defaults (`defaultEmbedPolicy()`)
+
+```js
+{
+ version: 1,
+ origins: { mode: 'allowlist', hosts: [] },
+ surfaces: { script: true, iframe: true, widget: true, mcp: false },
+ brain: { mode: 'we-pay', proxy_url: null, monthly_quota: 1000, rate_limit_per_min: 10, model: 'claude-opus-4-6' },
+ storage: { primary: 'r2', pinned_ipfs: false, onchain_attested: false }
+}
+```
+
+Note: an empty allowlist would lock the agent out of every site. Treat `origins.mode === 'allowlist' && origins.hosts.length === 0` as **"first-party only"** — i.e. `3dagent.vercel.app` and any value of `env.APP_ORIGIN` are always allowed regardless of the list.
+
+### Backwards-compat (`normalizeLegacyPolicy(input)`)
+
+If the row's stored value matches the legacy shape `{ mode: 'allowlist'|'denylist', hosts: [] }` (no `version` key, no `origins` key), wrap it as `{ ...defaultEmbedPolicy(), origins: input }` and return. If `input` is `null`, return `defaultEmbedPolicy()`. If `input` already has `version: 1`, return it merged on top of defaults so missing keys fill in.
+
+## Read first (in this order)
+
+1. [00-README.md](00-README.md) — the band-level design.
+2. [api/agents/[id]/embed-policy.js](../../api/agents/[id]/embed-policy.js) — full file, 75 lines. The shape you're extending.
+3. [public/dashboard/embed-policy.html](../../public/dashboard/embed-policy.html) — full file. The UI you're extending.
+4. [api/\_lib/http.js](../../api/_lib/http.js) — for `cors`, `json`, `error`, `wrap`, `method`, `readJson` (use these — never `res.end(JSON.stringify(...))`).
+5. [api/\_lib/db.js](../../api/_lib/db.js) — for `sql` tagged-template (never instantiate a Pool).
+6. [api/\_lib/auth.js](../../api/_lib/auth.js) — for `getSessionUser`.
+7. [api/\_lib/validate.js](../../api/_lib/validate.js) — for `parse`. Define your zod schema inline in `embed-policy.js` and re-export, since it's not a generic shape.
+8. [api/CLAUDE.md](../../api/CLAUDE.md) — endpoint conventions you must follow.
+9. [api/\_lib/schema.sql:235-266](../../api/_lib/schema.sql#L235-L266) — the additive-migrations block at the bottom of the `agent_identities` section.
+
+## What to change
+
+### 1. Create `api/_lib/embed-policy.js`
+
+```js
+// Per-agent embed policy: one JSONB column on agent_identities holding
+// origins + surfaces + brain + storage config. See prompts/embed-hardening/.
+
+import { z } from 'zod';
+import { sql } from './db.js';
+
+const hostPattern =
+ /^(\*\.)?([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)(\.[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i;
+
+export const POLICY_VERSION = 1;
+
+export const policySchema = z.object({
+ version: z.literal(1).optional(),
+ origins: z.object({
+ mode: z.enum(['allowlist', 'denylist']),
+ hosts: z.array(z.string().trim().toLowerCase().min(1).max(253).regex(hostPattern)).max(100),
+ }),
+ surfaces: z.object({
+ script: z.boolean(),
+ iframe: z.boolean(),
+ widget: z.boolean(),
+ mcp: z.boolean(),
+ }),
+ brain: z
+ .object({
+ mode: z.enum(['we-pay', 'key-proxy', 'wallet-gated', 'none']),
+ proxy_url: z.string().url().nullable(),
+ monthly_quota: z.number().int().nonnegative().nullable(),
+ rate_limit_per_min: z.number().int().nonnegative().nullable(),
+ model: z.string().min(1).max(100),
+ })
+ .refine((b) => b.mode !== 'key-proxy' || !!b.proxy_url, {
+ message: 'proxy_url is required when brain.mode === "key-proxy"',
+ path: ['proxy_url'],
+ }),
+ storage: z.object({
+ primary: z.enum(['r2', 'ipfs']),
+ pinned_ipfs: z.boolean(),
+ onchain_attested: z.boolean(),
+ }),
+});
+
+export function defaultEmbedPolicy() {
+ return {
+ version: POLICY_VERSION,
+ origins: { mode: 'allowlist', hosts: [] },
+ surfaces: { script: true, iframe: true, widget: true, mcp: false },
+ brain: {
+ mode: 'we-pay',
+ proxy_url: null,
+ monthly_quota: 1000,
+ rate_limit_per_min: 10,
+ model: 'claude-opus-4-6',
+ },
+ storage: { primary: 'r2', pinned_ipfs: false, onchain_attested: false },
+ };
+}
+
+export function normalizeLegacyPolicy(input) {
+ if (!input) return defaultEmbedPolicy();
+ const isLegacy =
+ !('version' in input) && !('origins' in input) && 'mode' in input && 'hosts' in input;
+ if (isLegacy) {
+ const d = defaultEmbedPolicy();
+ return { ...d, origins: { mode: input.mode, hosts: input.hosts ?? [] } };
+ }
+ const d = defaultEmbedPolicy();
+ return {
+ version: POLICY_VERSION,
+ origins: { ...d.origins, ...(input.origins || {}) },
+ surfaces: { ...d.surfaces, ...(input.surfaces || {}) },
+ brain: { ...d.brain, ...(input.brain || {}) },
+ storage: { ...d.storage, ...(input.storage || {}) },
+ };
+}
+
+export async function readEmbedPolicy(agentId) {
+ const [row] = await sql`
+ SELECT embed_policy FROM agent_identities
+ WHERE id = ${agentId} AND deleted_at IS NULL
+ `;
+ if (!row) return null; // agent not found
+ return normalizeLegacyPolicy(row.embed_policy);
+}
+
+export function validateEmbedPolicy(input) {
+ return policySchema.parse(normalizeLegacyPolicy(input));
+}
+```
+
+### 2. Extend `api/agents/[id]/embed-policy.js`
+
+Replace the existing `policySchema` import and the GET / PUT handlers so they delegate to `api/_lib/embed-policy.js`. Keep the file's overall shape (still uses `wrap`, `cors`, `json`, `error`, `method`).
+
+- **GET:** call `readEmbedPolicy(id)`. If null, return 404. Otherwise return `{ policy }` (always the normalized extended shape).
+- **PUT:** read the JSON body, run through `validateEmbedPolicy(body)` (which auto-normalizes legacy payloads), then `UPDATE ... SET embed_policy = ${JSON.stringify(normalized)}::jsonb`. Return `{ policy: normalized }`.
+- **DELETE:** unchanged — still nulls the column.
+
+Keep the auth + ownership check exactly as it is today.
+
+### 3. Extend `public/dashboard/embed-policy.html`
+
+Add three new `<fieldset>` blocks below the existing origin allowlist UI: **Surfaces**, **Brain**, **Storage**. Wire them into the same form submission. Specifically:
+
+- **Surfaces** — four checkboxes (script / iframe / widget / mcp), each labelled with a short description.
+- **Brain** — a `<select>` for `mode` (we-pay / key-proxy / wallet-gated / none), an `<input type="url">` for `proxy_url` (shown only when `mode === "key-proxy"`), `<input type="number">` for `monthly_quota` and `rate_limit_per_min` (allow blank → null), `<input>` for `model` (default `claude-opus-4-6`).
+- **Storage** — a `<select>` for `primary` (r2 / ipfs), checkboxes for `pinned_ipfs` and `onchain_attested` (read-only display for now — future prompts handle the actual pin / attestation flow).
+
+The existing form's `submit` handler must:
+
+1. Build the full extended-policy object from all four fieldsets.
+2. PUT to `/api/agents/:id/embed-policy` with `credentials: 'include'`.
+3. On success, repopulate the form from the response (so the user sees what was actually stored).
+4. On 400 validation error, surface `error_description` to the user.
+
+Keep the page's existing styling. Match indentation. Do not introduce any new CSS framework or build tooling.
+
+### 4. Append the schema migration (idempotent)
+
+At the end of the additive-migrations block in [api/\_lib/schema.sql:266](../../api/_lib/schema.sql#L266), add **one** line if it isn't already there:
+
+```sql
+alter table agent_identities add column if not exists embed_policy jsonb;
+```
+
+If prompt 01 has already shipped this line, leave it; do not duplicate.
+
+## Files you own (create / edit)
+
+- Create: `api/_lib/embed-policy.js`
+- Edit: [api/agents/[id]/embed-policy.js](../../api/agents/[id]/embed-policy.js)
+- Edit: [public/dashboard/embed-policy.html](../../public/dashboard/embed-policy.html)
+- Edit: [api/\_lib/schema.sql](../../api/_lib/schema.sql) — append one ALTER if missing
+
+## Files off-limits (other prompts edit these)
+
+- Anything in [src/](../../src/) — surface enforcement (prompt 03)
+- Any new `api/llm/*` files — LLM proxy (prompt 04)
+- Anything in [src/runtime/](../../src/runtime/) — providers / brain wiring (prompt 04)
+- The `avatars` table schema, any new `storage_mode` column — prompt 05
+- [public/dashboard/storage\*.html](../../public/dashboard/) (if it appears) — prompt 05
+
+## Idempotency / parallel-safety notes
+
+- If prompts 03 or 04 ship before this one and inline a local copy of `defaultEmbedPolicy()` / `readEmbedPolicy()`, your `api/_lib/embed-policy.js` becomes the source of truth. Their PRs should refactor to import from your file in a follow-up; do **not** edit their files yourself.
+- The legacy `{ mode, hosts }` shape must keep round-tripping: a legacy row read via `readEmbedPolicy()` returns the extended shape; a subsequent PUT of the same value persists the extended shape. Test this explicitly.
+- The endpoint must be safe to call against a database where the `embed_policy` column doesn't exist yet (i.e. neither this prompt nor prompt 01 have applied). In that case the SELECT will throw — catch the specific `column does not exist` error in `readEmbedPolicy` and return `null` so the API returns the default policy on GET. (`PUT` can still throw — that's an operator error, log loudly.)
+
+## Acceptance test
+
+1. `node --check api/_lib/embed-policy.js api/agents/[id]/embed-policy.js` passes.
+2. `npx prettier --write api/_lib/embed-policy.js api/agents/[id]/embed-policy.js public/dashboard/embed-policy.html api/_lib/schema.sql` clean.
+3. `npx vite build` passes.
+4. With a local dev server (`npm run dev`) and a signed-in session:
+ - `GET /api/agents/<your-agent-id>/embed-policy` → 200 with extended shape, `version: 1`, defaults filled in.
+ - `PUT /api/agents/<your-agent-id>/embed-policy` with the legacy body `{"mode":"allowlist","hosts":["foo.com"]}` → 200 with extended shape; `policy.origins` reflects the legacy input; other sections at defaults.
+ - `PUT` again with the full extended body → 200, all keys persisted.
+ - `PUT` with a bad body (e.g. `brain.mode === 'key-proxy'` but no `proxy_url`) → 400 `validation_error` with a clear field path.
+ - `GET /api/agents/<random-other-agent>/embed-policy` (not yours) → 200 read still works; `PUT` to it → 403.
+5. Open `/dashboard/embed-policy.html?id=<your-agent>` in a browser. All four sections render, populate from the GET, persist via PUT.
+
+## Reporting
+
+- **Files changed** with line counts.
+- **Commands run + output:** `node --check`, `prettier`, `vite build` last lines.
+- **Manual API test results:** the four PUT/GET cases above with response shape excerpts.
+- **Manual UI test:** screenshot or 1-line confirmation that all four sections appear and persist.
+- **Skipped:** anything you couldn't run, with reason.
+- **Unrelated bugs noticed:** list, do not fix.
+- **Off-limits files confirmation:** confirm none touched.
diff --git a/prompts/embed-hardening/03-surface-enforcement.md b/prompts/embed-hardening/03-surface-enforcement.md
new file mode 100644
index 000000000..5eacd51bf
--- /dev/null
+++ b/prompts/embed-hardening/03-surface-enforcement.md
@@ -0,0 +1,259 @@
+# Task 03 — Make every embed surface read the per-agent policy
+
+## Why this exists
+
+Today, only one of the four agent-rendering surfaces actually checks the per-agent `embed_policy`:
+
+| Surface | Where | Checks policy today? |
+| ----------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------- |
+| `<agent-3d>` script tag | [src/element.js](../../src/element.js) (registered as `<agent-3d>`) — runs in the host page's DOM | **No** |
+| Sandboxed iframe | [agent-embed.html](../../agent-embed.html) → `/agent/:id/embed` | Yes — origin allowlist via referrer / `ancestorOrigins` |
+| Saved widget | [api/widgets/page.js](../../api/widgets/page.js) → `/w/:id` | **No** (uses a separate `is_public` flag) |
+| MCP tool | [api/mcp.js](../../api/mcp.js) | **No** — bearer-token gated only |
+
+This prompt closes the gap. After it lands, all four surfaces consult the same `embed_policy` JSONB and **fail-closed** when the policy denies the surface or the calling origin.
+
+See [00-README.md](00-README.md) for the band-level design.
+
+## What you're building
+
+Four surface checks plus one CSP header, each independent:
+
+1. **`<agent-3d>` script tag** — at element-connect time, read the policy via the public API helper, refuse to mount (and emit `agent:error`) if `surfaces.script === false` OR if the host origin isn't allowed by `origins`.
+2. **Iframe page** — extend [agent-embed.html](../../agent-embed.html) to also gate on `surfaces.iframe`.
+3. **Widget page** — at [api/widgets/page.js](../../api/widgets/page.js), look up the widget's avatar→agent (best-effort; widgets aren't always tied to an agent identity, see notes), and if there is one, gate on `surfaces.widget` and `origins`.
+4. **MCP** — at [api/mcp.js](../../api/mcp.js), inside any tool that returns or invokes a specific agent (`render_avatar`, future agent-specific tools), gate on `surfaces.mcp`.
+5. **CSP `frame-ancestors`** — set on every response from [agent-embed.html](../../agent-embed.html) so browsers enforce the origin allowlist _in addition to_ the JS check.
+
+## The shape you're checking against
+
+This is the contract from [02-extended-policy.md](02-extended-policy.md):
+
+```jsonc
+{
+ "version": 1,
+ "origins": { "mode": "allowlist|denylist", "hosts": ["example.com", "*.foo.com"] },
+ "surfaces": { "script": bool, "iframe": bool, "widget": bool, "mcp": bool },
+ "brain": { ... }, // ignored here
+ "storage": { ... } // ignored here
+}
+```
+
+If `embed_policy` is null in the DB, treat it as **all surfaces allowed, all origins allowed** (legacy behaviour — first-party is always allowed regardless).
+
+## Read first (in this order)
+
+1. [00-README.md](00-README.md).
+2. [api/\_lib/embed-policy.js](../../api/_lib/embed-policy.js) — **if it exists** (created by prompt 02). If it doesn't exist, you'll inline a minimal local version (see "Independence fallbacks" below).
+3. [src/element.js](../../src/element.js) — focus on `connectedCallback()` and wherever the agent identity is resolved (search for `resolveAgentById` / `loadManifest`).
+4. [agent-embed.html](../../agent-embed.html) — focus on lines 49–88 where the existing referrer / `ancestorOrigins` policy check lives.
+5. [api/widgets/page.js](../../api/widgets/page.js) — see how `loadWidget` resolves the widget; check whether the widget row references an `agent_id` or just an `avatar_id`.
+6. [api/mcp.js](../../api/mcp.js) — find the `render_avatar` tool and any other tool that takes an agent ID.
+7. [api/\_lib/http.js](../../api/_lib/http.js) — for setting headers + writing responses.
+
+## Origin matching
+
+Implement once, in a small helper next to wherever you do the check (or in `api/_lib/embed-policy.js` if you create new exports — but only if you're certain prompt 02 has shipped; otherwise inline). Spec:
+
+- Hosts are case-insensitive ASCII.
+- Exact match: `example.com` matches `example.com` only.
+- Wildcard prefix: `*.foo.com` matches `bar.foo.com` and `baz.bar.foo.com`, but **not** `foo.com` itself.
+- The agent's own origin (`env.APP_ORIGIN`, plus `3dagent.vercel.app` and `localhost`-with-any-port for dev) is always allowed regardless of `origins.hosts`.
+- An empty `origins.hosts` with `mode === 'allowlist'` means **first-party only** — third-party origins are denied.
+
+```js
+export function originAllowed(originUrl, policy, firstParty = []) {
+ if (!originUrl) return false;
+ let host;
+ try {
+ host = new URL(originUrl).hostname.toLowerCase();
+ } catch {
+ return false;
+ }
+ if (firstParty.includes(host)) return true;
+ const matches = policy.origins.hosts.some((h) => {
+ const lower = h.toLowerCase();
+ if (lower.startsWith('*.')) return host.endsWith(lower.slice(1)) && host !== lower.slice(2);
+ return host === lower;
+ });
+ return policy.origins.mode === 'allowlist' ? matches : !matches;
+}
+```
+
+## What to change
+
+### 1. `<agent-3d>` element — refuse to mount when denied
+
+Edit [src/element.js](../../src/element.js). After the agent identity is resolved (you'll find a path that calls `resolveAgentById` or similar), and **before** the viewer / runtime mount, fetch the policy:
+
+```js
+// Public read — no auth required.
+const res = await fetch(`${apiOrigin}/api/agents/${agentId}/embed-policy`, { credentials: 'omit' });
+if (res.ok) {
+ const { policy } = await res.json();
+ if (policy) {
+ const hostOrigin = window.location.origin; // origin of the page the script is dropped into
+ if (!policy.surfaces?.script) {
+ this._fail('embed_denied_surface', 'This agent disallows the script-tag embed.');
+ return;
+ }
+ const firstParty = ['3dagent.vercel.app', 'localhost'];
+ if (
+ !originAllowed(hostOrigin, policy, firstParty) &&
+ !hostOrigin.startsWith('http://localhost')
+ ) {
+ this._fail('embed_denied_origin', `This agent isn't permitted on ${hostOrigin}.`);
+ return;
+ }
+ }
+}
+```
+
+`apiOrigin` should be the origin from which the script itself was loaded — derive from `import.meta.url` (you'll see this pattern elsewhere in the bundle) so cross-origin embeds query the right backend, not the host page's origin.
+
+`this._fail(code, message)` is a small helper you should add to the element: it dispatches `new CustomEvent('agent:error', { detail: { phase: 'policy', error: { code, message } }, bubbles: true, composed: true })` and renders a graceful in-element error state instead of throwing. Match the pattern of any existing error rendering in the file.
+
+If the policy fetch itself fails (network / 404 / 500), **fail open** — log a warning, continue mounting. The proxy / quota guards in prompt 04 are the real spend protection; this surface check is a soft policy.
+
+### 2. Iframe page — also check `surfaces.iframe`
+
+In [agent-embed.html](../../agent-embed.html), after the existing origin check (around line 88), add:
+
+```js
+// surfaces.iframe gate — fail-closed
+if (policy && policy.surfaces && policy.surfaces.iframe === false) {
+ showError("This agent's iframe embed is disabled.");
+ return;
+}
+```
+
+The existing origin check already handles `origins`. Don't duplicate it. Make sure your gate runs **after** the origin check so the user sees the more specific error first.
+
+### 3. Widget page — gate on `surfaces.widget` + origins
+
+Edit [api/widgets/page.js](../../api/widgets/page.js). After `loadWidget(widgetId)` succeeds:
+
+- If the widget row has an `agent_id`, fetch the policy via `readEmbedPolicy(agent_id)` (or inline SELECT — see fallback). If the agent isn't found, fall through to existing behaviour.
+- If `policy.surfaces.widget === false`, return a 403-style HTML page (use the same `notFound(res)` style the file already has, but with status 403 and message "This widget's embed is disabled by the agent owner.").
+- If the request's `Referer` header is set and `originAllowed(referer, policy, [APP_ORIGIN_HOST])` is false, do the same.
+
+If the widget row has **no** `agent_id` (widget tied to a bare avatar), skip the agent-policy check — the widget's own `is_public` flag is the existing gate.
+
+### 4. MCP — gate `render_avatar` on `surfaces.mcp`
+
+Edit [api/mcp.js](../../api/mcp.js). Inside the `render_avatar` tool handler (and any other tool that takes an agent ID), after argument validation:
+
+```js
+import { readEmbedPolicy } from './_lib/embed-policy.js';
+// ...
+const policy = await readEmbedPolicy(agentId);
+if (policy && policy.surfaces?.mcp === false) {
+ return mcpError(-32000, 'embed_denied_surface', 'This agent disallows the MCP surface.');
+}
+```
+
+Use the file's existing error helper / response shape — don't invent a new one.
+
+### 5. CSP `frame-ancestors` on the iframe response
+
+In [agent-embed.html](../../agent-embed.html) the page is static HTML. To set CSP, you have two options — pick **one**:
+
+**Option A (preferred):** Add a `<meta http-equiv="Content-Security-Policy" content="frame-ancestors 'self' https://3dagent.vercel.app ...">` tag inside `<head>`. The hosts list must reflect the policy. Build this `<meta>` element dynamically in the existing inline script after the policy fetch, so the allowlist is per-agent.
+
+**Option B (fallback):** Add a header in [vercel.json](../../vercel.json) for `/agent-embed.html` and `/agent/*/embed`. This is global, not per-agent, so use only if you can't set the meta dynamically.
+
+Go with Option A. Build the meta tag's content from `policy.origins.hosts` (translating wildcards to CSP form: `*.foo.com` → `https://*.foo.com`), always include `'self'` and `https://3dagent.vercel.app`. Insert before the first `<script>` tag in `<head>`.
+
+## Independence fallbacks
+
+If [api/\_lib/embed-policy.js](../../api/_lib/embed-policy.js) does **not** exist when you start (prompt 02 hasn't shipped), inline a minimal local copy in each file that needs it:
+
+```js
+async function readEmbedPolicyInline(agentId, sql) {
+ try {
+ const [row] =
+ await sql`SELECT embed_policy FROM agent_identities WHERE id = ${agentId} AND deleted_at IS NULL`;
+ if (!row) return null;
+ const p = row.embed_policy;
+ if (!p) return defaultEmbedPolicyInline();
+ if (!('version' in p) && 'mode' in p && 'hosts' in p) {
+ return {
+ ...defaultEmbedPolicyInline(),
+ origins: { mode: p.mode, hosts: p.hosts ?? [] },
+ };
+ }
+ return { ...defaultEmbedPolicyInline(), ...p };
+ } catch (err) {
+ // embed_policy column may not exist yet
+ if (/column .* does not exist/i.test(String(err?.message))) return null;
+ throw err;
+ }
+}
+function defaultEmbedPolicyInline() {
+ return {
+ version: 1,
+ origins: { mode: 'allowlist', hosts: [] },
+ surfaces: { script: true, iframe: true, widget: true, mcp: false },
+ brain: {
+ mode: 'we-pay',
+ proxy_url: null,
+ monthly_quota: 1000,
+ rate_limit_per_min: 10,
+ model: 'claude-opus-4-6',
+ },
+ storage: { primary: 'r2', pinned_ipfs: false, onchain_attested: false },
+ };
+}
+```
+
+For the `<agent-3d>` element, the inline fallback uses `fetch('/api/agents/:id/embed-policy')` instead of SQL — same logic, and the GET endpoint already exists today.
+
+If the helper file appears later, the file's owner (prompt 02) is responsible for switching imports — leave the inline version in place; do not edit other prompts' files.
+
+## Files you own (create / edit)
+
+- Edit: [src/element.js](../../src/element.js) — add policy fetch + gate + `_fail` helper.
+- Edit: [agent-embed.html](../../agent-embed.html) — add `surfaces.iframe` gate + dynamic CSP meta tag.
+- Edit: [api/widgets/page.js](../../api/widgets/page.js) — add agent-policy gate when widget→agent is resolvable.
+- Edit: [api/mcp.js](../../api/mcp.js) — add `surfaces.mcp` gate inside agent-touching tools.
+
+## Files off-limits (other prompts edit these)
+
+- [api/\_lib/embed-policy.js](../../api/_lib/embed-policy.js) — owned by prompt 02. You may **read** from it; do not write to it.
+- [api/agents/[id]/embed-policy.js](../../api/agents/[id]/embed-policy.js) — owned by prompt 02.
+- [public/dashboard/embed-policy.html](../../public/dashboard/embed-policy.html) — owned by prompt 02.
+- [api/\_lib/schema.sql](../../api/_lib/schema.sql) — owned by prompts 01, 02, 05. Do not edit.
+- [src/runtime/providers.js](../../src/runtime/providers.js) — owned by prompt 04.
+- Anything in `api/llm/` — owned by prompt 04.
+- The `avatars` schema and any new `storage_mode` column — owned by prompt 05.
+
+## Idempotency / parallel-safety notes
+
+- All four surface checks are **read-only** against `embed_policy`. They do not write.
+- Each gate fails closed on the **policy** (deny surface, deny origin) but fails open on **infrastructure** (network error, missing column, missing helper). This avoids self-DOS during partial deploys.
+- The CSP meta tag is per-agent — re-building it on each load is fine; no caching to invalidate.
+- Inlining the policy reader is OK in this prompt; do **not** export the inlined version, to avoid colliding with prompt 02's `api/_lib/embed-policy.js`.
+
+## Acceptance test
+
+1. `node --check src/element.js api/widgets/page.js api/mcp.js` passes.
+2. `npx prettier --write` over all four edited files; commit clean.
+3. `npx vite build` passes.
+4. Manual test (with a local dev server + a signed-in agent owner):
+ - **Origin allowlist on script:** Set `policy.origins = { mode: 'allowlist', hosts: ['example.com'] }` and `surfaces.script = true`. Drop the script tag on `localhost` (allowed: dev) → mounts. Drop on a different origin via a tiny test page → element renders error, dispatches `agent:error` with `code: 'embed_denied_origin'`.
+ - **Surface deny on script:** Set `surfaces.script = false`. Reload the host page → element renders error, `code: 'embed_denied_surface'`.
+ - **Iframe surface deny:** Set `surfaces.iframe = false`. `/agent/:id/embed` shows the iframe-disabled error.
+ - **Widget surface deny:** Set `surfaces.widget = false` and visit a widget that's tied to that agent → 403 page.
+ - **CSP frame-ancestors:** With a non-empty allowlist, view-source on `/agent/:id/embed` and confirm a `<meta http-equiv="Content-Security-Policy" content="frame-ancestors 'self' https://3dagent.vercel.app https://example.com">` is present.
+ - **MCP:** Call the `render_avatar` MCP tool with an agent whose `surfaces.mcp = false` → returns the embed_denied_surface error.
+
+If you can't run a particular surface (e.g. no MCP client handy), say so — do not skip it silently.
+
+## Reporting
+
+- Files changed with line counts.
+- Whether `api/_lib/embed-policy.js` existed at start; if not, where you inlined the fallback.
+- `node --check`, prettier, vite build outputs.
+- Each manual test case result (pass / fail / not-run-because-X).
+- Off-limits confirmation.
+- Unrelated bugs noticed.
diff --git a/prompts/embed-hardening/04-llm-proxy-quotas.md b/prompts/embed-hardening/04-llm-proxy-quotas.md
new file mode 100644
index 000000000..eaa0ae161
--- /dev/null
+++ b/prompts/embed-hardening/04-llm-proxy-quotas.md
@@ -0,0 +1,302 @@
+# Task 04 — We-pay LLM proxy with per-agent quotas and rate limits
+
+## Why this exists — the flood-day risk
+
+Right now, [src/runtime/providers.js:30](../../src/runtime/providers.js#L30) defaults its LLM calls to `https://api.anthropic.com/v1/messages` with no key when none is configured. That means:
+
+- If someone drops `<script src="/agent-3d/1.5.1/agent-3d.js"></script><agent-3d src="agent://base/42">` on any third-party site today, the brain call goes straight to Anthropic with no credentials → fails silently, the agent appears broken.
+- Any owner who injects a real API key via `api-key="sk-..."` exposes that key to every viewer of the page. The spec already warns against this.
+- The only safe path today — setting `key-proxy="https://owner.example/llm"` — requires every owner to run their own backend. That's not going to happen.
+
+This prompt builds the **we-pay** fallback: a single backend proxy at `/api/llm/anthropic` that authenticates the caller as a specific agent, enforces per-agent monthly quota + per-IP rate limit, proxies to Anthropic using a platform-owned key, and tracks usage. It's the piece that makes the one-line embed actually work on a third-party site **without** bankrupting us.
+
+See [00-README.md](00-README.md) for how this fits with the other prompts in the band.
+
+## What you're building
+
+1. **New endpoint:** `api/llm/anthropic.js` — `POST` only, accepts an agent id + an Anthropic messages request body, applies quota + rate limit, proxies to Anthropic, records usage, returns the Anthropic response.
+2. **New rate-limit preset:** `limits.embedLlmAgent` + `limits.embedLlmIp` in [api/\_lib/rate-limit.js](../../api/_lib/rate-limit.js).
+3. **Vercel rewrite:** `/api/llm/anthropic` → `/api/llm/anthropic.js` in [vercel.json](../../vercel.json).
+4. **Client wiring:** [src/runtime/providers.js](../../src/runtime/providers.js) defaults `proxyURL` to `<apiOrigin>/api/llm/anthropic?agent=<agentId>` when neither `apiKey` nor `proxyURL` is configured, and unconditionally when `policy.brain.mode === 'we-pay'`.
+5. **Owner-facing usage view:** `public/dashboard/usage.html` — read-only page showing per-agent monthly call count against quota, from `usage_events`.
+6. **Idempotent ALTER** for any new columns needed (none strictly required if you use `usage_events.meta` for quota accounting; see below).
+
+## The flow
+
+```
+<agent-3d> on acme.com
+ │
+ │ POST /api/llm/anthropic?agent=<id>
+ │ body: { system, messages, tools, model }
+ ▼
+api/llm/anthropic.js
+ ├─ read embed_policy → require policy.brain.mode === 'we-pay'
+ ├─ enforce surfaces.script + origins (Referer / Origin) — fail-closed
+ ├─ per-agent monthly quota check (Upstash counter keyed by agentId + YYYY-MM)
+ ├─ per-IP rate limit (limits.embedLlmIp)
+ ├─ per-agent rate limit (limits.embedLlmAgent, from policy.brain.rate_limit_per_min)
+ ├─ forward to api.anthropic.com with ANTHROPIC_API_KEY from env
+ ├─ recordEvent({ kind: 'llm', tool: 'anthropic.messages', agentId, bytes, latencyMs })
+ └─ return Anthropic response JSON
+```
+
+## Read first (in this order)
+
+1. [00-README.md](00-README.md).
+2. [src/runtime/providers.js](../../src/runtime/providers.js) — see how `AnthropicProvider.complete()` constructs the request. This is the caller.
+3. [api/\_lib/rate-limit.js](../../api/_lib/rate-limit.js) — how `limits.*` are declared; add new preset here following the existing pattern.
+4. [api/\_lib/usage.js](../../api/_lib/usage.js) — `recordEvent()` for per-call logging.
+5. [api/\_lib/embed-policy.js](../../api/_lib/embed-policy.js) — **if it exists** (prompt 02). Otherwise inline the reader using the same fallback as prompt 03 (see "Independence fallbacks" below).
+6. [api/\_lib/http.js](../../api/_lib/http.js), [api/\_lib/db.js](../../api/_lib/db.js), [api/\_lib/env.js](../../api/_lib/env.js).
+7. [api/CLAUDE.md](../../api/CLAUDE.md) — endpoint conventions (copy the template).
+8. [vercel.json](../../vercel.json) — for the rewrite. Add **inside** the routes array; order matters.
+9. An existing endpoint for reference, e.g. [api/agents/[id]/embed-policy.js](../../api/agents/[id]/embed-policy.js), for the idiomatic shape.
+
+## What to change
+
+### 1. Create `api/llm/anthropic.js`
+
+Core shape — copy the endpoint template from [api/CLAUDE.md](../../api/CLAUDE.md) and specialize:
+
+```js
+import { z } from 'zod';
+import { sql } from '../_lib/db.js';
+import { env } from '../_lib/env.js';
+import { cors, json, method, wrap, error, readJson } from '../_lib/http.js';
+import { parse } from '../_lib/validate.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { recordEvent } from '../_lib/usage.js';
+import { readEmbedPolicy } from '../_lib/embed-policy.js'; // or inline fallback — see below
+
+const bodySchema = z.object({
+ system: z.string().max(64_000).optional(),
+ messages: z
+ .array(
+ z.object({
+ role: z.enum(['user', 'assistant']),
+ content: z.union([z.string(), z.array(z.any())]), // Anthropic blocks; pass through
+ }),
+ )
+ .min(1)
+ .max(200),
+ tools: z.array(z.any()).max(64).optional(),
+ model: z.string().max(100).optional(),
+ max_tokens: z.number().int().positive().max(16_000).optional(),
+ temperature: z.number().min(0).max(2).optional(),
+ thinking: z.any().optional(),
+});
+
+const MODEL_ALLOWLIST = new Set([
+ 'claude-opus-4-6',
+ 'claude-opus-4-7',
+ 'claude-sonnet-4-6',
+ 'claude-haiku-4-5-20251001',
+]);
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'POST,OPTIONS' })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const url = new URL(req.url, 'http://x');
+ const agentId = url.searchParams.get('agent');
+ if (!agentId) return error(res, 400, 'validation_error', 'agent query param required');
+
+ // 1. Policy check
+ const policy = await readEmbedPolicy(agentId);
+ if (!policy) return error(res, 404, 'not_found', 'agent not found');
+ if (policy.brain?.mode !== 'we-pay') {
+ return error(
+ res,
+ 402,
+ 'payment_required',
+ `brain.mode is "${policy.brain?.mode}"; caller must supply its own key or proxy`,
+ );
+ }
+ if (policy.surfaces?.script === false) {
+ // LLM proxy is only meant to power the script surface; iframe/widget have their own runtimes
+ return error(res, 403, 'embed_denied_surface', 'script surface disabled for this agent');
+ }
+
+ // 2. Origin / referer check (fail-closed for third-party origins not in allowlist)
+ const origin = req.headers.origin || req.headers.referer || '';
+ if (!originAllowed(origin, policy)) {
+ return error(
+ res,
+ 403,
+ 'embed_denied_origin',
+ "origin not permitted by this agent's embed policy",
+ );
+ }
+
+ // 3. Per-IP rate limit
+ const ipRl = await limits.embedLlmIp(clientIp(req));
+ if (!ipRl.success) return error(res, 429, 'rate_limited', 'too many requests from this IP');
+
+ // 4. Per-agent rate limit
+ const perMin = policy.brain?.rate_limit_per_min;
+ if (perMin && perMin > 0) {
+ const agentRl = await limits.embedLlmAgent(agentId, perMin);
+ if (!agentRl.success) return error(res, 429, 'rate_limited', 'agent rate limit exceeded');
+ }
+
+ // 5. Monthly quota check (Upstash counter)
+ const quota = policy.brain?.monthly_quota;
+ if (quota !== null && typeof quota === 'number') {
+ const used = await incrementMonthlyQuota(agentId, quota);
+ if (used > quota) {
+ return error(res, 429, 'quota_exceeded', `monthly quota of ${quota} reached`);
+ }
+ }
+
+ // 6. Validate + normalize body
+ const body = parse(bodySchema, await readJson(req));
+ const model = body.model || policy.brain?.model || 'claude-opus-4-6';
+ if (!MODEL_ALLOWLIST.has(model)) {
+ return error(res, 400, 'validation_error', `model "${model}" not allowed`);
+ }
+
+ // 7. Forward to Anthropic
+ const t0 = Date.now();
+ const upstream = await fetch('https://api.anthropic.com/v1/messages', {
+ method: 'POST',
+ headers: {
+ 'content-type': 'application/json',
+ 'anthropic-version': '2023-06-01',
+ 'x-api-key': env.ANTHROPIC_API_KEY,
+ },
+ body: JSON.stringify({ ...body, model }),
+ });
+ const upstreamText = await upstream.text();
+ const latencyMs = Date.now() - t0;
+
+ // 8. Record usage (fire-and-forget)
+ recordEvent({
+ kind: 'llm',
+ tool: 'anthropic.messages',
+ agentId,
+ bytes: upstreamText.length,
+ latencyMs,
+ status: upstream.ok ? 'ok' : 'error',
+ meta: { model, ip_hash: null /* fill if your privacy policy needs this */ },
+ });
+
+ // 9. Proxy the response faithfully
+ res.statusCode = upstream.status;
+ res.setHeader('content-type', upstream.headers.get('content-type') || 'application/json');
+ return res.end(upstreamText);
+});
+```
+
+Add the `originAllowed` and `incrementMonthlyQuota` helpers inside the file (or next to `readEmbedPolicy` if you're inlining). `incrementMonthlyQuota` uses Upstash `redis.incr` with a key like `llm:quota:${agentId}:${yyyy}-${mm}` and `EXPIRE` of 40 days on first set; return the new count.
+
+**Env:** `ANTHROPIC_API_KEY` must be added to the env schema in [api/\_lib/env.js](../../api/_lib/env.js). If it's already there, use it; if not, add it. Document in [.env.example](../../.env.example) — one line.
+
+### 2. Add rate-limit presets
+
+Edit [api/\_lib/rate-limit.js](../../api/_lib/rate-limit.js). Add:
+
+```js
+limits.embedLlmIp = /* 60 / 1 min per IP */;
+limits.embedLlmAgent = (agentId, perMin) => /* perMin / 1 min per agent, dynamic bucket */;
+```
+
+Match the surrounding pattern exactly (the file likely uses `Ratelimit.slidingWindow` from `@upstash/ratelimit`). If `perMin` is variable per agent, you'll need a factory that memoizes limiters by `perMin` value — keep this small and readable.
+
+### 3. Vercel rewrite
+
+Edit [vercel.json](../../vercel.json). Inside the routes array, **before** the generic `/api/(.*) → /api/$1` line, add:
+
+```json
+{ "src": "/api/llm/anthropic", "dest": "/api/llm/anthropic.js" },
+```
+
+### 4. Client wiring in `src/runtime/providers.js`
+
+Edit [src/runtime/providers.js](../../src/runtime/providers.js). Extend the `AnthropicProvider` constructor so:
+
+- If `proxyURL` is explicitly set, use it (today's behaviour).
+- Else if `apiKey` is set (dev mode), call Anthropic directly (today's behaviour).
+- Else, fall back to `${apiOrigin}/api/llm/anthropic?agent=${agentId}` — where `apiOrigin` is the origin from which the `<agent-3d>` bundle was served (derive from `import.meta.url`), and `agentId` is a new constructor field.
+
+The element ([src/element.js](../../src/element.js)) must pass `agentId` and `apiOrigin` in when it constructs the provider. Find the instantiation site and thread them through. Do **not** change the element's connect/disconnect lifecycle beyond that — prompt 03 owns the element's policy gate.
+
+### 5. Usage dashboard — read-only view
+
+Create `public/dashboard/usage.html`. It's a small static HTML page with an inline script that:
+
+- Reads `?id=<agentId>` from the URL.
+- Calls `GET /api/agents/:id/embed-policy` (session-auth) to get `brain.monthly_quota`.
+- Calls a new `GET /api/agents/:id/usage` endpoint that returns the current month's LLM call count and a 30-day daily breakdown — **create this endpoint in `api/agents/[id]/usage.js`** with owner-only auth (`getSessionUser`) and a simple `SELECT COUNT(*) ... WHERE kind='llm' AND agent_id = ... AND created_at >= date_trunc('month', now())`. (`agent_id` may not be a column on `usage_events`; if it isn't, read the event's `meta->>'agent_id'` or add a column — see note below.)
+- Renders: quota used / quota total, a simple bar, and a tiny last-30-days sparkline (text-only is fine; no chart library).
+
+**If `usage_events` has no `agent_id` column**, either (a) add an idempotent ALTER `alter table usage_events add column if not exists agent_id uuid references agent_identities(id)` at the bottom of [api/\_lib/schema.sql](../../api/_lib/schema.sql) and extend `recordEvent` to accept it, **or** (b) store `agentId` in `meta` as `{ agent_id: agentId }` and query via `meta->>'agent_id'`. Pick (a) if the column doesn't exist; it's cleaner and lets us index.
+
+Wire the route in [vercel.json](../../vercel.json):
+
+```json
+{ "src": "/api/agents/([^/]+)/usage", "dest": "/api/agents/[id]/usage?id=$1" },
+{ "src": "/dashboard/usage", "dest": "/public/dashboard/usage.html" },
+```
+
+## Independence fallbacks
+
+If [api/\_lib/embed-policy.js](../../api/_lib/embed-policy.js) does not exist when you start, inline a minimal `readEmbedPolicy` (same as in prompt 03's "Independence fallbacks" section). Import-switch to the helper in a follow-up if / when prompt 02 ships.
+
+If [api/\_lib/schema.sql](../../api/_lib/schema.sql) doesn't yet have `embed_policy`, the inlined reader must catch `column does not exist` and return `null` → the endpoint then returns 404, which is correct (we can't enforce policy → deny).
+
+## Files you own (create / edit)
+
+- Create: `api/llm/anthropic.js`
+- Create: `api/agents/[id]/usage.js`
+- Create: `public/dashboard/usage.html`
+- Edit: [api/\_lib/rate-limit.js](../../api/_lib/rate-limit.js) — add presets
+- Edit: [src/runtime/providers.js](../../src/runtime/providers.js) — add `proxyURL` fallback
+- Edit: [src/element.js](../../src/element.js) — thread `agentId` + `apiOrigin` to provider construction **only** (do not touch the element's policy gate — that's prompt 03's territory; if both prompts edit this file, merge both edits)
+- Edit: [vercel.json](../../vercel.json) — two route adds
+- Edit: [api/\_lib/env.js](../../api/_lib/env.js) — add `ANTHROPIC_API_KEY` if missing
+- Edit: [.env.example](../../.env.example) — document `ANTHROPIC_API_KEY`
+- Edit (optional): [api/\_lib/schema.sql](../../api/_lib/schema.sql) — append `usage_events.agent_id` ALTER if you pick option (a)
+- Edit (if option a): [api/\_lib/usage.js](../../api/_lib/usage.js) — accept `agentId` field and insert into the new column
+
+## Files off-limits (other prompts edit these)
+
+- [api/\_lib/embed-policy.js](../../api/_lib/embed-policy.js) — prompt 02 (read-only for you)
+- [api/agents/[id]/embed-policy.js](../../api/agents/[id]/embed-policy.js) — prompt 02
+- [public/dashboard/embed-policy.html](../../public/dashboard/embed-policy.html) — prompt 02
+- [agent-embed.html](../../agent-embed.html) — prompt 03
+- [api/widgets/page.js](../../api/widgets/page.js) — prompt 03
+- [api/mcp.js](../../api/mcp.js) — prompt 03
+- `avatars` table schema + anything under `public/dashboard/storage*.html` — prompt 05
+
+## Idempotency / parallel-safety notes
+
+- The monthly quota counter lives in Upstash — there's no DB migration risk. If the bucket doesn't exist, `INCR` creates it.
+- The optional `usage_events.agent_id` ALTER is idempotent (`IF NOT EXISTS`). Keep it additive.
+- If prompt 03 ships first and already touches `src/element.js`, merge both edits: prompt 03 adds the policy gate in `connectedCallback`, you thread `agentId`/`apiOrigin` into the provider construction elsewhere in the file. These should touch different lines.
+- The `ANTHROPIC_API_KEY` must not land in any client bundle — double-check that nothing in `src/` imports from `api/_lib/env.js` directly.
+
+## Acceptance test
+
+1. `node --check api/llm/anthropic.js api/agents/[id]/usage.js api/_lib/rate-limit.js src/runtime/providers.js src/element.js` passes.
+2. `npx prettier --write` over edited files; commit clean.
+3. `npx vite build` and `npm run build:lib` both pass.
+4. `node scripts/apply-schema.mjs` (if you did option a) runs twice without error.
+5. Manual — with `ANTHROPIC_API_KEY` set in `.env.local`:
+ - `curl -X POST "http://localhost:3000/api/llm/anthropic?agent=<we-pay-agent-id>" -H 'content-type: application/json' -d '{"messages":[{"role":"user","content":"hi"}]}'` → 200 with an Anthropic response shape, `usage_events` row written.
+ - Same call with an agent whose `brain.mode !== 'we-pay'` → 402 `payment_required`.
+ - Same call 21+ times in a minute (with `rate_limit_per_min: 20`) → 429 `rate_limited`.
+ - Set `monthly_quota: 2` on a test agent, make 3 calls → third returns 429 `quota_exceeded`.
+ - Call with `Origin: https://evil.com` header and an allowlist that doesn't include it → 403 `embed_denied_origin`.
+6. Drop the `<agent-3d>` script on a local test page (a standalone HTML file with `<script src="http://localhost:3000/agent-3d/<version>/agent-3d.js">` and `<agent-3d src="agent://...">`) — confirm the network tab shows requests going to `/api/llm/anthropic?agent=...`, **not** to `api.anthropic.com`.
+7. Visit `/dashboard/usage?id=<your-agent>` in the browser (signed in) — confirm the current month's count matches what you'd expect from the manual curls above.
+
+## Reporting
+
+- Files created / edited with line counts.
+- Whether `api/_lib/embed-policy.js` existed; if not, where you inlined the fallback.
+- Whether you took option (a) or (b) for agent-id tracking in `usage_events`.
+- `node --check`, prettier, vite build, build:lib outputs.
+- The seven manual cases above with pass/fail and copied response bodies for the 4xx paths.
+- Confirmation no client bundle imports `ANTHROPIC_API_KEY`.
+- Off-limits files not touched.
+- Unrelated bugs noticed.
diff --git a/prompts/embed-hardening/05-storage-flags.md b/prompts/embed-hardening/05-storage-flags.md
new file mode 100644
index 000000000..fc841930a
--- /dev/null
+++ b/prompts/embed-hardening/05-storage-flags.md
@@ -0,0 +1,339 @@
+# Task 05 — Storage flags: track where an avatar's bytes actually live
+
+## Why this exists
+
+Today, [api/\_lib/schema.sql](../../api/_lib/schema.sql) `avatars.storage_key` tells us the file is in R2. That's it. Nothing tracks:
+
+- Whether the same bytes are also pinned to IPFS (for permanence / portability).
+- Whether the byte hash has been recorded on-chain (for attestation / tamper-evidence).
+- Whether the owner _wants_ the avatar replicated outside our custody.
+
+That means an agent described as "owned by 0xABCD on Base" is in reality a Postgres row with a link to R2 — if we vanish, the avatar vanishes. Fine for MVP, not fine for the on-chain / portable-embed stories.
+
+This prompt adds the schema + UI + minimal plumbing to flip an avatar from R2-only to R2-plus-IPFS, and to record its content hash. Actual on-chain transactions are out of scope — this prompt just records the hash and surfaces the attestation state in the UI.
+
+See [00-README.md](00-README.md) for the band-level design.
+
+## What you're building
+
+1. **Schema:** add a `storage_mode` JSONB column to the `avatars` table (idempotent ALTER, appended to the existing migration block).
+2. **Helper:** `api/_lib/storage-mode.js` — `defaultStorageMode()`, `readStorageMode(avatarId)`, `validateStorageMode(input)`.
+3. **Content hash capture:** extend the avatar-registration flow (the endpoint that runs after R2 upload) so `checksum_sha256` is always populated from the R2 object (`headObject` returns it today if the upload included it — see [api/\_lib/r2.js](../../api/_lib/r2.js)). If it isn't captured today, fetch the first N bytes and hash, or run a HEAD with `ChecksumMode: ENABLED` — **do not** re-download the whole GLB.
+4. **API:** `GET/PUT /api/avatars/:id/storage-mode` — owner-only; mirrors the shape of the embed-policy endpoint.
+5. **UI:** `public/dashboard/storage.html` — per-avatar storage settings, shows R2 state, lets the owner click "Pin to IPFS" (which calls a stubbed endpoint — see below), shows the on-chain attestation state read-only.
+6. **Pin endpoint (stub):** `POST /api/avatars/:id/pin-ipfs` — owner-only. For this prompt, **stub** it: compute the hash, record a `storage_mode.ipfs_cid` placeholder (use a deterministic pseudo-CID like `stub:<sha256>` for now) and flip `pinned_ipfs: true`. Real Pinata / Web3.Storage wiring is a follow-up; call it out in the reporting block.
+
+## The shape
+
+```jsonc
+// avatars.storage_mode JSONB
+{
+ "version": 1,
+ "primary": "r2", // always "r2" for now; "ipfs" means "IPFS is authoritative"
+ "r2": {
+ "present": true,
+ "key": "u/<userId>/<slug>/<ts>.glb", // echoes avatars.storage_key
+ },
+ "ipfs": {
+ "pinned": false,
+ "cid": null, // string once pinned
+ "pinned_at": null, // ISO timestamp
+ },
+ "attestation": {
+ "hash": null, // sha256 of the GLB bytes — always filled on avatar create going forward
+ "chain_id": null,
+ "tx_hash": null, // filled by a future on-chain attestation flow
+ "attested_at": null,
+ },
+}
+```
+
+### Defaults (`defaultStorageMode(avatarRow)`)
+
+```js
+{
+ version: 1,
+ primary: 'r2',
+ r2: { present: true, key: avatarRow.storage_key ?? null },
+ ipfs: { pinned: false, cid: null, pinned_at: null },
+ attestation: { hash: avatarRow.checksum_sha256 ?? null, chain_id: null, tx_hash: null, attested_at: null },
+}
+```
+
+## Read first (in this order)
+
+1. [00-README.md](00-README.md).
+2. [api/\_lib/schema.sql](../../api/_lib/schema.sql) — find the `avatars` table block and its additive-migrations section. (If none exists below the CREATE TABLE, add one — match the pattern used for `agent_identities` at lines 260+.)
+3. [api/avatars/index.js](../../api/avatars/index.js) — the avatar-registration endpoint (runs after R2 upload).
+4. [api/\_lib/r2.js](../../api/_lib/r2.js) — focus on `headObject`; figure out how to read the object's MD5/sha256.
+5. [api/\_lib/avatars.js](../../api/_lib/avatars.js) — helpers for avatar row reads.
+6. [api/\_lib/http.js](../../api/_lib/http.js), [api/\_lib/db.js](../../api/_lib/db.js), [api/\_lib/auth.js](../../api/_lib/auth.js).
+7. [api/CLAUDE.md](../../api/CLAUDE.md) — endpoint template.
+8. [public/dashboard/embed-policy.html](../../public/dashboard/embed-policy.html) — copy its structure for your new page (same sign-in flow, same fetch pattern, same styling).
+9. [vercel.json](../../vercel.json) — for route wiring.
+
+## What to change
+
+### 1. Schema migration (idempotent, append)
+
+Append to the additive-migrations block for `avatars` in [api/\_lib/schema.sql](../../api/_lib/schema.sql) (or create one immediately after the `create index` lines for `avatars`, matching the `agent_identities` pattern at lines 260–266):
+
+```sql
+-- Additive migrations for avatars columns added after initial deployment.
+alter table avatars add column if not exists storage_mode jsonb;
+```
+
+If a block already exists, just append the one line. Do **not** reorder.
+
+### 2. Create `api/_lib/storage-mode.js`
+
+```js
+// Per-avatar storage mode: one JSONB column on avatars tracking R2 / IPFS /
+// on-chain attestation state. See prompts/embed-hardening/05-storage-flags.md.
+
+import { z } from 'zod';
+import { sql } from './db.js';
+
+export const STORAGE_MODE_VERSION = 1;
+
+export const storageModeSchema = z.object({
+ version: z.literal(1).optional(),
+ primary: z.enum(['r2', 'ipfs']),
+ r2: z.object({
+ present: z.boolean(),
+ key: z.string().nullable(),
+ }),
+ ipfs: z.object({
+ pinned: z.boolean(),
+ cid: z.string().nullable(),
+ pinned_at: z.string().datetime().nullable(),
+ }),
+ attestation: z.object({
+ hash: z
+ .string()
+ .regex(/^[a-f0-9]{64}$/i)
+ .nullable(),
+ chain_id: z.number().int().nullable(),
+ tx_hash: z
+ .string()
+ .regex(/^0x[a-fA-F0-9]{64}$/)
+ .nullable(),
+ attested_at: z.string().datetime().nullable(),
+ }),
+});
+
+export function defaultStorageMode(avatarRow = {}) {
+ return {
+ version: STORAGE_MODE_VERSION,
+ primary: 'r2',
+ r2: { present: true, key: avatarRow.storage_key ?? null },
+ ipfs: { pinned: false, cid: null, pinned_at: null },
+ attestation: {
+ hash: avatarRow.checksum_sha256 ?? null,
+ chain_id: null,
+ tx_hash: null,
+ attested_at: null,
+ },
+ };
+}
+
+export async function readStorageMode(avatarId) {
+ try {
+ const [row] = await sql`
+ SELECT id, owner_id, storage_key, checksum_sha256, storage_mode
+ FROM avatars
+ WHERE id = ${avatarId} AND deleted_at IS NULL
+ `;
+ if (!row) return null;
+ const base = defaultStorageMode(row);
+ if (!row.storage_mode) return base;
+ return {
+ ...base,
+ ...row.storage_mode,
+ r2: { ...base.r2, ...(row.storage_mode.r2 || {}) },
+ ipfs: { ...base.ipfs, ...(row.storage_mode.ipfs || {}) },
+ attestation: { ...base.attestation, ...(row.storage_mode.attestation || {}) },
+ };
+ } catch (err) {
+ if (/column .* does not exist/i.test(String(err?.message))) return null;
+ throw err;
+ }
+}
+
+export function validateStorageMode(input) {
+ return storageModeSchema.parse(input);
+}
+```
+
+### 3. Capture content hash on avatar create
+
+In [api/avatars/index.js](../../api/avatars/index.js) (or wherever the post-upload registration handler lives), after the existing `headObject` check that verifies the file exists:
+
+- If `headObject` response includes an `ETag` that's a single MD5 (no hyphens → single-part upload), that's **not** sha256 — don't use it as a substitute. Instead, call `headObject` with `ChecksumMode: 'ENABLED'` to get the sha256 if the client sent one. If the response includes `ChecksumSHA256`, record it (decoded from base64 to hex).
+- If no sha256 is available from R2 (common — the browser upload doesn't send it by default), **skip hash capture for this avatar** — leave `checksum_sha256` null. Do **not** download and re-hash the GLB in this request; that's a job for a background worker.
+- Populate `storage_mode` on insert using `defaultStorageMode({ storage_key, checksum_sha256 })` so every new avatar row has a canonical storage_mode from the start.
+
+Small PR — don't refactor the rest of the endpoint.
+
+### 4. Create `api/avatars/[id]/storage-mode.js`
+
+Mirrors the embed-policy endpoint shape. GET is public-read-of-public-avatars (or owner-only if visibility === 'private'); PUT is owner-only:
+
+```js
+import { z } from 'zod';
+import { sql } from '../../_lib/db.js';
+import { getSessionUser } from '../../_lib/auth.js';
+import { cors, json, method, wrap, error, readJson } from '../../_lib/http.js';
+import { parse } from '../../_lib/validate.js';
+import { readStorageMode, storageModeSchema, defaultStorageMode } from '../../_lib/storage-mode.js';
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,PUT,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET', 'PUT'])) return;
+
+ const id = req.query?.id || new URL(req.url, 'http://x').pathname.split('/').filter(Boolean)[2];
+ if (!id) return error(res, 400, 'validation_error', 'avatar id required');
+
+ const [row] =
+ await sql`SELECT id, owner_id, visibility FROM avatars WHERE id = ${id} AND deleted_at IS NULL`;
+ if (!row) return error(res, 404, 'not_found', 'avatar not found');
+
+ if (req.method === 'GET') {
+ if (row.visibility === 'private') {
+ const session = await getSessionUser(req);
+ if (!session || session.id !== row.owner_id)
+ return error(res, 403, 'forbidden', 'private avatar');
+ }
+ const mode = await readStorageMode(id);
+ return json(res, 200, { storage_mode: mode });
+ }
+
+ // PUT — owner only
+ const session = await getSessionUser(req);
+ if (!session) return error(res, 401, 'unauthorized', 'sign in required');
+ if (session.id !== row.owner_id) return error(res, 403, 'forbidden', 'not your avatar');
+
+ const body = parse(storageModeSchema, await readJson(req));
+ await sql`UPDATE avatars SET storage_mode = ${JSON.stringify(body)}::jsonb WHERE id = ${id}`;
+ return json(res, 200, { storage_mode: body });
+});
+```
+
+Gotcha: allow the owner to edit only **safe** fields (they shouldn't be able to forge `attestation.tx_hash` from the UI). Add server-side gatekeeping: overlay the user-submitted object on top of the current stored mode, but drop any keys under `attestation.*` — always re-read those from the DB unchanged. Document this in a short comment.
+
+### 5. Create the stub pin endpoint
+
+`api/avatars/[id]/pin-ipfs.js`:
+
+```js
+// STUB — real pinning (Pinata / Web3.Storage) is a follow-up. For now this
+// computes a placeholder CID from the stored sha256 and flips pinned_ipfs.
+
+import { sql } from '../../_lib/db.js';
+import { getSessionUser } from '../../_lib/auth.js';
+import { cors, json, method, wrap, error } from '../../_lib/http.js';
+import { readStorageMode } from '../../_lib/storage-mode.js';
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const id = req.query?.id || new URL(req.url, 'http://x').pathname.split('/').filter(Boolean)[2];
+ if (!id) return error(res, 400, 'validation_error', 'avatar id required');
+
+ const session = await getSessionUser(req);
+ if (!session) return error(res, 401, 'unauthorized', 'sign in required');
+
+ const [row] =
+ await sql`SELECT id, owner_id, checksum_sha256 FROM avatars WHERE id = ${id} AND deleted_at IS NULL`;
+ if (!row) return error(res, 404, 'not_found', 'avatar not found');
+ if (row.owner_id !== session.id) return error(res, 403, 'forbidden', 'not your avatar');
+
+ const mode = await readStorageMode(id);
+ if (!mode) return error(res, 500, 'internal', 'storage_mode unavailable');
+
+ const stubCid = row.checksum_sha256
+ ? `stub:sha256-${row.checksum_sha256}`
+ : `stub:no-hash-${id}`;
+
+ const next = {
+ ...mode,
+ ipfs: { pinned: true, cid: stubCid, pinned_at: new Date().toISOString() },
+ };
+
+ await sql`UPDATE avatars SET storage_mode = ${JSON.stringify(next)}::jsonb WHERE id = ${id}`;
+ return json(res, 200, { storage_mode: next, stub: true });
+});
+```
+
+### 6. Create the owner UI
+
+`public/dashboard/storage.html` — structure after [public/dashboard/embed-policy.html](../../public/dashboard/embed-policy.html). Sections:
+
+- **R2** — show `r2.key` (the storage path) read-only; show "present" badge.
+- **IPFS** — show `ipfs.pinned` + `ipfs.cid`. If not pinned, a button "Pin to IPFS (stub)" that `POST`s to `/api/avatars/:id/pin-ipfs`.
+- **Attestation** — show hash + tx_hash + chain_id read-only. If hash is null, show "Not yet computed" with a note that hashing runs server-side post-upload.
+
+### 7. Vercel routes
+
+Edit [vercel.json](../../vercel.json). Inside routes, before the generic `/api/(.*) → /api/$1`:
+
+```json
+{ "src": "/api/avatars/([^/]+)/storage-mode", "dest": "/api/avatars/[id]/storage-mode?id=$1" },
+{ "src": "/api/avatars/([^/]+)/pin-ipfs", "dest": "/api/avatars/[id]/pin-ipfs?id=$1" },
+{ "src": "/dashboard/storage", "dest": "/public/dashboard/storage.html" },
+```
+
+## Files you own (create / edit)
+
+- Create: `api/_lib/storage-mode.js`
+- Create: `api/avatars/[id]/storage-mode.js`
+- Create: `api/avatars/[id]/pin-ipfs.js`
+- Create: `public/dashboard/storage.html`
+- Edit: [api/\_lib/schema.sql](../../api/_lib/schema.sql) — append one ALTER under `avatars`
+- Edit: [api/avatars/index.js](../../api/avatars/index.js) — capture `checksum_sha256` when R2 provides it; populate `storage_mode` on insert
+- Edit: [vercel.json](../../vercel.json) — three route adds
+
+## Files off-limits (other prompts edit these)
+
+- [api/\_lib/embed-policy.js](../../api/_lib/embed-policy.js) — prompt 02
+- [api/agents/[id]/embed-policy.js](../../api/agents/[id]/embed-policy.js) — prompt 02
+- [public/dashboard/embed-policy.html](../../public/dashboard/embed-policy.html) — prompt 02
+- [src/element.js](../../src/element.js) — prompt 03 (for policy), prompt 04 (for provider threading)
+- [agent-embed.html](../../agent-embed.html) — prompt 03
+- [api/widgets/page.js](../../api/widgets/page.js) — prompt 03
+- [api/mcp.js](../../api/mcp.js) — prompt 03
+- [src/runtime/providers.js](../../src/runtime/providers.js) — prompt 04
+- Anything under `api/llm/` — prompt 04
+- `public/dashboard/usage.html`, `api/agents/[id]/usage.js` — prompt 04
+
+## Idempotency / parallel-safety notes
+
+- The `ALTER TABLE avatars ADD COLUMN IF NOT EXISTS storage_mode jsonb` is safe to run multiple times.
+- `readStorageMode` catches "column does not exist" so your endpoints stay useful during partial deploys.
+- If another prompt adds columns to `avatars` later, this one does not conflict — each lands its own ALTER.
+- The pin endpoint is deliberately a stub. Do **not** add Pinata / Web3.Storage credentials in this prompt; that's a follow-up with real cost considerations.
+
+## Acceptance test
+
+1. `node --check api/_lib/storage-mode.js api/avatars/[id]/storage-mode.js api/avatars/[id]/pin-ipfs.js api/avatars/index.js` passes.
+2. `npx prettier --write` over everything; commit clean.
+3. `npx vite build` passes.
+4. `node scripts/apply-schema.mjs` runs, then re-runs cleanly (idempotent).
+5. Manual — signed in as an avatar owner:
+ - `GET /api/avatars/<your-avatar-id>/storage-mode` → 200 with `{ storage_mode: { primary: 'r2', r2: { present: true, key: '...' }, ipfs: { pinned: false, ... }, attestation: { hash: null-or-hex, ... } } }`.
+ - `POST /api/avatars/<your-avatar-id>/pin-ipfs` → 200, `storage_mode.ipfs.pinned === true`, `cid` starts with `stub:`.
+ - `PUT /api/avatars/<your-avatar-id>/storage-mode` with a body that tries to set `attestation.tx_hash: "0x..."` → the response's `attestation.tx_hash` is unchanged (still null), i.e. the write silently dropped the attestation edit.
+ - `GET /api/avatars/<someone-else's-private-avatar>/storage-mode` → 403.
+6. Upload a new avatar via the existing flow. Confirm the new row has a populated `storage_mode` (defaults), and if the browser sent an `x-amz-checksum-sha256` header, the hash is captured (else null is fine).
+7. Visit `/dashboard/storage?id=<your-avatar>` in the browser. Confirm the three sections render and the Pin button round-trips.
+
+## Reporting
+
+- Files created / edited with line counts.
+- Which fields in `storage_mode` are populated end-to-end (R2 key: yes; hash: yes or no; IPFS: stubbed; attestation: empty).
+- `node --check`, prettier, vite build, schema-apply outputs (both runs).
+- Each manual case with pass / fail / not-run.
+- Explicit call-out: **Pin endpoint is a stub; real Pinata integration is a follow-up.**
+- Off-limits files confirmation.
+- Unrelated bugs noticed.
diff --git a/public/dashboard/embed-policy.html b/public/dashboard/embed-policy.html
index 7667d2e3b..e9985f065 100644
--- a/public/dashboard/embed-policy.html
+++ b/public/dashboard/embed-policy.html
@@ -1,182 +1,612 @@
<!doctype html>
<html lang="en">
-<head>
-<meta charset="utf-8">
-<meta name="viewport" content="width=device-width,initial-scale=1">
-<title>Embed policy · 3D Agent</title>
-<link rel="icon" href="/favicon.ico">
-<style>
- :root { color-scheme: dark; --accent:#6a5cff; --accent2:#ff5ca8; --border:#22222e; --bg:#0b0b10; --panel:#14141c; }
- * { box-sizing: border-box; }
- body { font:15px/1.55 -apple-system,system-ui,Segoe UI,Roboto,sans-serif; color:#eee; margin:0; background:var(--bg); min-height:100vh; }
- a { color:#9a8cff; text-decoration:none; }
- header { display:flex; align-items:center; justify-content:space-between; padding:16px 24px; border-bottom:1px solid var(--border); position:sticky; top:0; background:var(--bg); z-index:5; }
- .brand { font-weight:600; letter-spacing:-.01em; }
- main { padding:28px; max-width:720px; margin:0 auto; }
- h1 { font-size:22px; margin:0 0 6px; letter-spacing:-.01em; }
- .sub { color:#888; margin:0 0 22px; font-size:14px; }
- .card { background:var(--panel); border:1px solid var(--border); border-radius:14px; padding:20px; }
- label { display:block; margin:14px 0 6px; font-size:13px; color:#bbb; }
- input, select, textarea { background:#0f0f17; border:1px solid var(--border); color:#eee; padding:9px 11px; border-radius:8px; font-size:14px; font-family:inherit; width:100%; }
- textarea { min-height:120px; font-family: ui-monospace, SF Mono, Menlo, monospace; font-size:13px; }
- input:focus, textarea:focus, select:focus { outline:none; border-color:var(--accent); }
- .row { display:flex; gap:10px; align-items:center; }
- .btn { padding:9px 14px; border-radius:9px; border:0; font-size:13px; font-weight:600; cursor:pointer; background:var(--accent); color:#fff; }
- .btn.sec { background:#222230; color:#ddd; }
- .btn.danger { background:#3a1f24; color:#ff9c9c; }
- .muted { color:#888; font-size:13px; }
- .err { padding:12px; background:rgba(255,92,92,.1); border:1px solid rgba(255,92,92,.3); border-radius:8px; color:#ffb3b3; margin-bottom:14px; }
- .ok { padding:12px; background:rgba(92,255,140,.07); border:1px solid rgba(92,255,140,.2); border-radius:8px; color:#b6f2c6; margin-bottom:14px; }
- code { font-family: ui-monospace, SF Mono, Menlo, monospace; background:#0f0f17; border:1px solid var(--border); border-radius:4px; padding:1px 6px; font-size:12px; }
- .actions { display:flex; gap:10px; margin-top:22px; }
- hr { border:0; border-top:1px solid var(--border); margin:22px 0; }
-</style>
-</head>
-<body>
-<header>
- <div class="brand"><a href="/dashboard">← Dashboard</a></div>
- <div class="muted"><span id="agent-name">Agent</span></div>
-</header>
-<main>
- <h1>Embed policy</h1>
- <p class="sub">Control which sites can iframe <code id="embed-url"></code>. An unset policy allows embedding everywhere (today's default).</p>
-
- <div id="status"></div>
-
- <div class="card">
- <label for="mode">Policy mode</label>
- <select id="mode">
- <option value="off">Off — allow all embeds</option>
- <option value="allowlist">Allowlist — only these hosts</option>
- <option value="denylist">Denylist — everywhere except these hosts</option>
- </select>
-
- <div id="hosts-wrap">
- <label for="hosts">Hosts (one per line)</label>
- <textarea id="hosts" placeholder="example.com&#10;*.substack.com"></textarea>
- <div class="muted" style="margin-top:6px">One host per line. Use <code>*.example.com</code> to match all subdomains.</div>
- </div>
-
- <div class="actions">
- <button class="btn" id="save">Save</button>
- <button class="btn sec" id="reload">Reload</button>
- <button class="btn danger" id="clear" style="margin-left:auto">Clear policy</button>
- </div>
- </div>
-
- <hr>
-
- <div class="muted">
- Signed-in owners can preview the embed bypassing this policy by appending <code>?preview=1</code> to the embed URL.
- </div>
-</main>
-<script type="module">
-const params = new URL(location.href).searchParams;
-const agentId = params.get('agent');
-const statusEl = document.getElementById('status');
-const modeSel = document.getElementById('mode');
-const hostsEl = document.getElementById('hosts');
-const wrap = document.getElementById('hosts-wrap');
-const nameEl = document.getElementById('agent-name');
-const urlEl = document.getElementById('embed-url');
-
-if (!agentId) {
- statusEl.innerHTML = '<div class="err">Missing <code>?agent=ID</code> in URL.</div>';
- throw new Error('no agent id');
-}
-urlEl.textContent = `/agent/${agentId}/embed`;
-
-async function api(method, path, body) {
- const res = await fetch(path, {
- method,
- credentials: 'include',
- headers: body ? { 'content-type': 'application/json' } : {},
- body: body ? JSON.stringify(body) : undefined,
- });
- const ct = res.headers.get('content-type') || '';
- const data = ct.includes('application/json') ? await res.json() : null;
- if (!res.ok) throw Object.assign(new Error((data && data.error_description) || res.statusText), { status: res.status });
- return data;
-}
-
-function setStatus(html) { statusEl.innerHTML = html; }
-function updateVisibility() { wrap.style.display = modeSel.value === 'off' ? 'none' : ''; }
-
-async function loadMe() {
- try {
- await api('GET', '/api/auth/me');
- } catch {
- location.href = '/login?next=' + encodeURIComponent(location.pathname + location.search);
- throw new Error('redirecting');
- }
-}
-
-async function loadAgent() {
- try {
- const { agent } = await api('GET', `/api/agents/${agentId}`);
- nameEl.textContent = agent.name || 'Agent';
- } catch (e) {
- setStatus(`<div class="err">Could not load agent: ${escapeHtml(e.message)}</div>`);
- }
-}
-
-async function loadPolicy() {
- try {
- const { policy } = await api('GET', `/api/agents/${agentId}/embed-policy`);
- if (!policy) {
- modeSel.value = 'off';
- hostsEl.value = '';
- } else {
- modeSel.value = policy.mode === 'denylist' ? 'denylist' : 'allowlist';
- hostsEl.value = (policy.hosts || []).join('\n');
- }
- updateVisibility();
- } catch (e) {
- setStatus(`<div class="err">Could not load policy: ${escapeHtml(e.message)}</div>`);
- }
-}
-
-async function save() {
- setStatus('');
- if (modeSel.value === 'off') {
- try {
- await api('DELETE', `/api/agents/${agentId}/embed-policy`);
- setStatus('<div class="ok">Policy cleared. All hosts can embed this agent.</div>');
- } catch (e) { setStatus(`<div class="err">${escapeHtml(e.message)}</div>`); }
- return;
- }
- const hosts = hostsEl.value.split(/\r?\n/).map(s => s.trim()).filter(Boolean);
- try {
- await api('PUT', `/api/agents/${agentId}/embed-policy`, { mode: modeSel.value, hosts });
- setStatus('<div class="ok">Policy saved.</div>');
- } catch (e) {
- setStatus(`<div class="err">${escapeHtml(e.message)}</div>`);
- }
-}
-
-async function clearPolicy() {
- if (!confirm('Clear the embed policy? Any site will be able to embed this agent.')) return;
- try {
- await api('DELETE', `/api/agents/${agentId}/embed-policy`);
- modeSel.value = 'off';
- hostsEl.value = '';
- updateVisibility();
- setStatus('<div class="ok">Policy cleared.</div>');
- } catch (e) { setStatus(`<div class="err">${escapeHtml(e.message)}</div>`); }
-}
-
-function escapeHtml(s) { return String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;' }[c])); }
-
-modeSel.addEventListener('change', updateVisibility);
-document.getElementById('save').addEventListener('click', save);
-document.getElementById('reload').addEventListener('click', loadPolicy);
-document.getElementById('clear').addEventListener('click', clearPolicy);
-
-(async () => {
- await loadMe();
- await loadAgent();
- await loadPolicy();
-})();
-</script>
-</body>
+ <head>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width,initial-scale=1" />
+ <title>Embed policy · 3D Agent</title>
+ <link rel="icon" href="/favicon.ico" />
+ <style>
+ :root {
+ color-scheme: dark;
+ --accent: #6a5cff;
+ --accent2: #ff5ca8;
+ --border: #22222e;
+ --bg: #0b0b10;
+ --panel: #14141c;
+ }
+ * {
+ box-sizing: border-box;
+ }
+ body {
+ font:
+ 15px/1.55 -apple-system,
+ system-ui,
+ Segoe UI,
+ Roboto,
+ sans-serif;
+ color: #eee;
+ margin: 0;
+ background: var(--bg);
+ min-height: 100vh;
+ }
+ a {
+ color: #9a8cff;
+ text-decoration: none;
+ }
+ header {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ padding: 16px 24px;
+ border-bottom: 1px solid var(--border);
+ position: sticky;
+ top: 0;
+ background: var(--bg);
+ z-index: 5;
+ }
+ .brand {
+ font-weight: 600;
+ letter-spacing: -0.01em;
+ }
+ main {
+ padding: 28px;
+ max-width: 720px;
+ margin: 0 auto;
+ }
+ h1 {
+ font-size: 22px;
+ margin: 0 0 6px;
+ letter-spacing: -0.01em;
+ }
+ .sub {
+ color: #888;
+ margin: 0 0 22px;
+ font-size: 14px;
+ }
+ .card {
+ background: var(--panel);
+ border: 1px solid var(--border);
+ border-radius: 14px;
+ padding: 20px;
+ margin-bottom: 20px;
+ }
+ fieldset {
+ border: 0;
+ padding: 0;
+ margin: 0;
+ }
+ legend {
+ font-size: 13px;
+ font-weight: 600;
+ color: #ccc;
+ margin-bottom: 12px;
+ letter-spacing: 0.02em;
+ text-transform: uppercase;
+ }
+ label {
+ display: block;
+ margin: 14px 0 6px;
+ font-size: 13px;
+ color: #bbb;
+ }
+ label.check {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ margin: 8px 0;
+ cursor: pointer;
+ color: #ccc;
+ }
+ label.check input {
+ width: auto;
+ margin: 0;
+ }
+ input,
+ select,
+ textarea {
+ background: #0f0f17;
+ border: 1px solid var(--border);
+ color: #eee;
+ padding: 9px 11px;
+ border-radius: 8px;
+ font-size: 14px;
+ font-family: inherit;
+ width: 100%;
+ }
+ textarea {
+ min-height: 120px;
+ font-family:
+ ui-monospace,
+ SF Mono,
+ Menlo,
+ monospace;
+ font-size: 13px;
+ }
+ input:focus,
+ textarea:focus,
+ select:focus {
+ outline: none;
+ border-color: var(--accent);
+ }
+ input[type='checkbox'] {
+ width: 16px;
+ height: 16px;
+ accent-color: var(--accent);
+ }
+ input[type='number'] {
+ -moz-appearance: textfield;
+ }
+ .row {
+ display: flex;
+ gap: 10px;
+ align-items: center;
+ }
+ .col2 {
+ display: grid;
+ grid-template-columns: 1fr 1fr;
+ gap: 12px;
+ }
+ .btn {
+ padding: 9px 14px;
+ border-radius: 9px;
+ border: 0;
+ font-size: 13px;
+ font-weight: 600;
+ cursor: pointer;
+ background: var(--accent);
+ color: #fff;
+ }
+ .btn.sec {
+ background: #222230;
+ color: #ddd;
+ }
+ .btn.danger {
+ background: #3a1f24;
+ color: #ff9c9c;
+ }
+ .muted {
+ color: #888;
+ font-size: 13px;
+ }
+ .err {
+ padding: 12px;
+ background: rgba(255, 92, 92, 0.1);
+ border: 1px solid rgba(255, 92, 92, 0.3);
+ border-radius: 8px;
+ color: #ffb3b3;
+ margin-bottom: 14px;
+ }
+ .ok {
+ padding: 12px;
+ background: rgba(92, 255, 140, 0.07);
+ border: 1px solid rgba(92, 255, 140, 0.2);
+ border-radius: 8px;
+ color: #b6f2c6;
+ margin-bottom: 14px;
+ }
+ code {
+ font-family:
+ ui-monospace,
+ SF Mono,
+ Menlo,
+ monospace;
+ background: #0f0f17;
+ border: 1px solid var(--border);
+ border-radius: 4px;
+ padding: 1px 6px;
+ font-size: 12px;
+ }
+ .actions {
+ display: flex;
+ gap: 10px;
+ margin-top: 22px;
+ }
+ hr {
+ border: 0;
+ border-top: 1px solid var(--border);
+ margin: 22px 0;
+ }
+ .hidden {
+ display: none !important;
+ }
+ </style>
+ </head>
+ <body>
+ <header>
+ <div class="brand"><a href="/dashboard">← Dashboard</a></div>
+ <div class="muted"><span id="agent-name">Agent</span></div>
+ </header>
+ <main>
+ <h1>Embed policy</h1>
+ <p class="sub">
+ Control how <code id="embed-url"></code> can be embedded across the web.
+ </p>
+
+ <div id="status"></div>
+
+ <!-- Origins -->
+ <div class="card">
+ <fieldset>
+ <legend>Origins</legend>
+ <label for="mode">Policy mode</label>
+ <select id="mode">
+ <option value="off">Off — allow all embeds</option>
+ <option value="allowlist">Allowlist — only these hosts</option>
+ <option value="denylist">Denylist — everywhere except these hosts</option>
+ </select>
+
+ <div id="hosts-wrap">
+ <label for="hosts">Hosts (one per line)</label>
+ <textarea
+ id="hosts"
+ placeholder="example.com&#10;*.substack.com"
+ ></textarea>
+ <div class="muted" style="margin-top: 6px">
+ One host per line. Use <code>*.example.com</code> to match all
+ subdomains.
+ </div>
+ </div>
+ </fieldset>
+ </div>
+
+ <!-- Surfaces -->
+ <div class="card">
+ <fieldset>
+ <legend>Surfaces</legend>
+ <div class="muted" style="margin-bottom: 12px">
+ Choose which embed surfaces are enabled for this agent.
+ </div>
+ <label class="check"
+ ><input type="checkbox" id="surf-script" />
+ <span
+ ><strong>Script tag</strong> — <code>&lt;agent-3d&gt;</code> on
+ third-party pages</span
+ ></label
+ >
+ <label class="check"
+ ><input type="checkbox" id="surf-iframe" />
+ <span
+ ><strong>iframe</strong> —
+ <code>&lt;iframe src="/agent/:id/embed"&gt;</code></span
+ ></label
+ >
+ <label class="check"
+ ><input type="checkbox" id="surf-widget" />
+ <span
+ ><strong>Widget</strong> — <code>/w/:id</code> widget pages</span
+ ></label
+ >
+ <label class="check"
+ ><input type="checkbox" id="surf-mcp" />
+ <span
+ ><strong>MCP</strong> — exposed as an MCP tool over
+ <code>/api/mcp</code></span
+ ></label
+ >
+ </fieldset>
+ </div>
+
+ <!-- Brain -->
+ <div class="card">
+ <fieldset>
+ <legend>Brain / LLM</legend>
+ <label for="brain-mode">Payment mode</label>
+ <select id="brain-mode">
+ <option value="we-pay">
+ We-pay — 3D Agent covers API costs (quota-limited)
+ </option>
+ <option value="key-proxy">
+ Key-proxy — calls routed through your proxy URL
+ </option>
+ <option value="wallet-gated">
+ Wallet-gated — user pays via connected wallet
+ </option>
+ <option value="none">None — LLM disabled for this agent</option>
+ </select>
+
+ <div id="proxy-url-wrap">
+ <label for="brain-proxy-url">Proxy URL</label>
+ <input
+ type="url"
+ id="brain-proxy-url"
+ placeholder="https://owner.example/llm"
+ />
+ </div>
+
+ <div class="col2" style="margin-top: 14px">
+ <div>
+ <label for="brain-quota">Monthly quota (completions)</label>
+ <input
+ type="number"
+ id="brain-quota"
+ min="0"
+ placeholder="1000 (blank = unlimited)"
+ />
+ </div>
+ <div>
+ <label for="brain-rate">Rate limit (req / min)</label>
+ <input
+ type="number"
+ id="brain-rate"
+ min="0"
+ placeholder="10 (blank = unlimited)"
+ />
+ </div>
+ </div>
+
+ <label for="brain-model">Model</label>
+ <input type="text" id="brain-model" placeholder="claude-opus-4-6" />
+ </fieldset>
+ </div>
+
+ <!-- Storage -->
+ <div class="card">
+ <fieldset>
+ <legend>Storage</legend>
+ <label for="storage-primary">Primary storage</label>
+ <select id="storage-primary">
+ <option value="r2">R2 (Cloudflare) — default</option>
+ <option value="ipfs">IPFS — decentralised</option>
+ </select>
+
+ <label class="check" style="margin-top: 14px">
+ <input type="checkbox" id="storage-ipfs" disabled />
+ <span
+ ><strong>IPFS pin</strong> — avatar pinned to IPFS
+ <em class="muted">(pin flow coming soon)</em></span
+ >
+ </label>
+ <label class="check">
+ <input type="checkbox" id="storage-attested" disabled />
+ <span
+ ><strong>On-chain attestation</strong> — content hash recorded on-chain
+ <em class="muted">(coming soon)</em></span
+ >
+ </label>
+ </fieldset>
+ </div>
+
+ <div class="actions">
+ <button class="btn" id="save">Save</button>
+ <button class="btn sec" id="reload">Reload</button>
+ <button class="btn danger" id="clear" style="margin-left: auto">
+ Clear policy
+ </button>
+ </div>
+
+ <hr />
+
+ <div class="muted">
+ Signed-in owners can preview the embed bypassing this policy by appending
+ <code>?preview=1</code> to the embed URL.
+ </div>
+ </main>
+ <script type="module">
+ const params = new URL(location.href).searchParams;
+ const agentId = params.get('agent');
+ const statusEl = document.getElementById('status');
+ const modeSel = document.getElementById('mode');
+ const hostsEl = document.getElementById('hosts');
+ const hostsWrap = document.getElementById('hosts-wrap');
+ const nameEl = document.getElementById('agent-name');
+ const urlEl = document.getElementById('embed-url');
+ const brainModeSel = document.getElementById('brain-mode');
+ const proxyWrap = document.getElementById('proxy-url-wrap');
+
+ if (!agentId) {
+ statusEl.innerHTML =
+ '<div class="err">Missing <code>?agent=ID</code> in URL.</div>';
+ throw new Error('no agent id');
+ }
+ urlEl.textContent = `/agent/${agentId}/embed`;
+
+ async function api(method, path, body) {
+ const res = await fetch(path, {
+ method,
+ credentials: 'include',
+ headers: body ? { 'content-type': 'application/json' } : {},
+ body: body ? JSON.stringify(body) : undefined,
+ });
+ const ct = res.headers.get('content-type') || '';
+ const data = ct.includes('application/json') ? await res.json() : null;
+ if (!res.ok)
+ throw Object.assign(
+ new Error((data && data.error_description) || res.statusText),
+ { status: res.status, fields: data?.fields },
+ );
+ return data;
+ }
+
+ function setStatus(html) {
+ statusEl.innerHTML = html;
+ }
+
+ function updateOriginVisibility() {
+ hostsWrap.style.display = modeSel.value === 'off' ? 'none' : '';
+ }
+
+ function updateBrainVisibility() {
+ proxyWrap.classList.toggle('hidden', brainModeSel.value !== 'key-proxy');
+ }
+
+ async function loadMe() {
+ try {
+ await api('GET', '/api/auth/me');
+ } catch {
+ location.href =
+ '/login?next=' + encodeURIComponent(location.pathname + location.search);
+ throw new Error('redirecting');
+ }
+ }
+
+ async function loadAgent() {
+ try {
+ const { agent } = await api('GET', `/api/agents/${agentId}`);
+ nameEl.textContent = agent.name || 'Agent';
+ } catch (e) {
+ setStatus(
+ `<div class="err">Could not load agent: ${escapeHtml(e.message)}</div>`,
+ );
+ }
+ }
+
+ function populateForm(policy) {
+ if (!policy) {
+ modeSel.value = 'off';
+ hostsEl.value = '';
+ document.getElementById('surf-script').checked = true;
+ document.getElementById('surf-iframe').checked = true;
+ document.getElementById('surf-widget').checked = true;
+ document.getElementById('surf-mcp').checked = false;
+ brainModeSel.value = 'we-pay';
+ document.getElementById('brain-proxy-url').value = '';
+ document.getElementById('brain-quota').value = '1000';
+ document.getElementById('brain-rate').value = '10';
+ document.getElementById('brain-model').value = 'claude-opus-4-6';
+ document.getElementById('storage-primary').value = 'r2';
+ document.getElementById('storage-ipfs').checked = false;
+ document.getElementById('storage-attested').checked = false;
+ updateOriginVisibility();
+ updateBrainVisibility();
+ return;
+ }
+
+ const orig = policy.origins || {};
+ modeSel.value = orig.mode === 'denylist' ? 'denylist' : 'allowlist';
+ hostsEl.value = (orig.hosts || []).join('\n');
+
+ const surf = policy.surfaces || {};
+ document.getElementById('surf-script').checked = surf.script !== false;
+ document.getElementById('surf-iframe').checked = surf.iframe !== false;
+ document.getElementById('surf-widget').checked = surf.widget !== false;
+ document.getElementById('surf-mcp').checked = !!surf.mcp;
+
+ const brain = policy.brain || {};
+ brainModeSel.value = brain.mode || 'we-pay';
+ document.getElementById('brain-proxy-url').value = brain.proxy_url || '';
+ document.getElementById('brain-quota').value =
+ brain.monthly_quota != null ? String(brain.monthly_quota) : '';
+ document.getElementById('brain-rate').value =
+ brain.rate_limit_per_min != null ? String(brain.rate_limit_per_min) : '';
+ document.getElementById('brain-model').value = brain.model || 'claude-opus-4-6';
+
+ const storage = policy.storage || {};
+ document.getElementById('storage-primary').value = storage.primary || 'r2';
+ document.getElementById('storage-ipfs').checked = !!storage.pinned_ipfs;
+ document.getElementById('storage-attested').checked = !!storage.onchain_attested;
+
+ updateOriginVisibility();
+ updateBrainVisibility();
+ }
+
+ async function loadPolicy() {
+ try {
+ const { policy } = await api('GET', `/api/agents/${agentId}/embed-policy`);
+ populateForm(policy);
+ } catch (e) {
+ setStatus(
+ `<div class="err">Could not load policy: ${escapeHtml(e.message)}</div>`,
+ );
+ }
+ }
+
+ function buildPolicy() {
+ const numOrNull = (id) => {
+ const v = document.getElementById(id).value.trim();
+ return v === '' ? null : parseInt(v, 10);
+ };
+
+ return {
+ version: 1,
+ origins: {
+ mode: modeSel.value === 'off' ? 'allowlist' : modeSel.value,
+ hosts:
+ modeSel.value === 'off'
+ ? []
+ : hostsEl.value
+ .split(/\r?\n/)
+ .map((s) => s.trim())
+ .filter(Boolean),
+ },
+ surfaces: {
+ script: document.getElementById('surf-script').checked,
+ iframe: document.getElementById('surf-iframe').checked,
+ widget: document.getElementById('surf-widget').checked,
+ mcp: document.getElementById('surf-mcp').checked,
+ },
+ brain: {
+ mode: brainModeSel.value,
+ proxy_url: document.getElementById('brain-proxy-url').value.trim() || null,
+ monthly_quota: numOrNull('brain-quota'),
+ rate_limit_per_min: numOrNull('brain-rate'),
+ model:
+ document.getElementById('brain-model').value.trim() ||
+ 'claude-opus-4-6',
+ },
+ storage: {
+ primary: document.getElementById('storage-primary').value,
+ pinned_ipfs: document.getElementById('storage-ipfs').checked,
+ onchain_attested: document.getElementById('storage-attested').checked,
+ },
+ };
+ }
+
+ async function save() {
+ setStatus('');
+ try {
+ const { policy } = await api(
+ 'PUT',
+ `/api/agents/${agentId}/embed-policy`,
+ buildPolicy(),
+ );
+ populateForm(policy);
+ setStatus('<div class="ok">Policy saved.</div>');
+ } catch (e) {
+ let msg = escapeHtml(e.message);
+ if (e.fields && e.fields.length) {
+ msg +=
+ '<br><small>' +
+ e.fields
+ .map((f) => escapeHtml(f.path?.join('.') + ': ' + f.message))
+ .join('<br>') +
+ '</small>';
+ }
+ setStatus(`<div class="err">${msg}</div>`);
+ }
+ }
+
+ async function clearPolicy() {
+ if (!confirm('Clear the embed policy? Defaults will apply.')) return;
+ try {
+ await api('DELETE', `/api/agents/${agentId}/embed-policy`);
+ populateForm(null);
+ setStatus('<div class="ok">Policy cleared.</div>');
+ } catch (e) {
+ setStatus(`<div class="err">${escapeHtml(e.message)}</div>`);
+ }
+ }
+
+ function escapeHtml(s) {
+ return String(s ?? '').replace(
+ /[&<>"']/g,
+ (c) =>
+ ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[
+ c
+ ],
+ );
+ }
+
+ modeSel.addEventListener('change', updateOriginVisibility);
+ brainModeSel.addEventListener('change', updateBrainVisibility);
+ document.getElementById('save').addEventListener('click', save);
+ document.getElementById('reload').addEventListener('click', loadPolicy);
+ document.getElementById('clear').addEventListener('click', clearPolicy);
+
+ (async () => {
+ await loadMe();
+ await loadAgent();
+ await loadPolicy();
+ })();
+ </script>
+ </body>
</html>
diff --git a/specs/schema/embed-policy.sql b/specs/schema/embed-policy.sql
index 0a0c68870..483e2e6a7 100644
--- a/specs/schema/embed-policy.sql
+++ b/specs/schema/embed-policy.sql
@@ -1,18 +1,15 @@
-- Task 03 — Per-agent embed referrer allowlist
--
--- Adds an `embed_policy` column to `agent_identities` that controls where the
--- `/agent/:id/embed` page is allowed to be iframed. NULL means "no policy",
--- which preserves the current behaviour of allowing any embedding site.
+-- MERGED into api/_lib/schema.sql on 2026-04-17. This file is kept for
+-- historical reference and as a one-shot ALTER for any database that was
+-- provisioned before the canonical schema picked up this column.
--
--- When non-null, the column stores JSON of the shape:
--- { "mode": "allowlist" | "denylist", "hosts": ["example.com", "*.substack.com"] }
--- Hosts support exact matches and a single leading-wildcard segment.
---
--- No dedicated migrations directory exists in this repo yet. Apply manually
--- against the target database (e.g. Neon) before deploying the embed-policy
--- endpoint and UI:
+-- Adds an `embed_policy` JSONB column to `agent_identities`. NULL means
+-- "no policy" — preserves the legacy "embed anywhere" behaviour.
--
+-- Apply once against any pre-existing database that wasn't reset:
-- psql "$DATABASE_URL" -f specs/schema/embed-policy.sql
+-- Or just re-run `node scripts/apply-schema.mjs` (idempotent).
ALTER TABLE agent_identities
ADD COLUMN IF NOT EXISTS embed_policy JSONB;
diff --git a/src/agent-hub-actions.js b/src/agent-hub-actions.js
index 23376d608..9a0e72c12 100644
--- a/src/agent-hub-actions.js
+++ b/src/agent-hub-actions.js
@@ -17,7 +17,6 @@ export function renderHubActions(panel, identity, rawAgent) {
const isRegistered = Boolean(rawAgent.is_registered);
const chainId = rawAgent.chain_id || null;
const walletAddress = rawAgent.wallet_address || null;
- const erc8004Registry = rawAgent.erc8004_registry || null;
const erc8004AgentId = rawAgent.erc8004_agent_id || null;
const row = document.createElement('div');
@@ -32,7 +31,7 @@ export function renderHubActions(panel, identity, rawAgent) {
<span>Embed</span>
</button>
<button class="agent-hub-btn${isRegistered ? ' hub-btn--deployed' : ''}" id="hub-deploy"
- title="${isRegistered ? 'View registry record' : 'Deploy on-chain — optional'}">
+ title="${isRegistered ? 'Manage on-chain record (edit, transfer, redeploy)' : 'Deploy on-chain — optional'}">
${_iconChain()}
<span>${isRegistered ? _deployedLabel(chainId, walletAddress, erc8004AgentId) : 'Deploy on-chain'}</span>
${isRegistered ? '' : '<span class="agent-hub-opt">· Optional</span>'}
@@ -52,16 +51,31 @@ export function renderHubActions(panel, identity, rawAgent) {
const embedModal = new AgentEmbedModal(agentId);
row.querySelector('#hub-embed').addEventListener('click', () => embedModal.open());
- // Deploy on-chain → RegisterUI (lazy-imported) OR open explorer link if already deployed
+ // Deploy on-chain → RegisterUI (lazy-imported). For a registered agent we
+ // open directly on the "My Agents" tab so the owner gets Edit / Redeploy /
+ // Transfer without re-selecting their chain + agent.
const deployBtn = row.querySelector('#hub-deploy');
if (isRegistered) {
deployBtn.addEventListener('click', async () => {
- const { addressExplorerUrl } = await import('./erc8004/chain-meta.js');
- const { REGISTRY_DEPLOYMENTS } = await import('./erc8004/abi.js');
- const registry =
- erc8004Registry || REGISTRY_DEPLOYMENTS?.[chainId]?.identityRegistry || null;
- const url = registry && chainId ? addressExplorerUrl(chainId, registry) : null;
- if (url) window.open(url, '_blank', 'noopener');
+ deployBtn.disabled = true;
+ try {
+ const { RegisterUI } = await import('./erc8004/register-ui.js');
+ const wrap = document.createElement('div');
+ wrap.className = 'agent-register-overlay';
+ document.body.appendChild(wrap);
+ new RegisterUI(
+ wrap,
+ () => {
+ wrap.remove();
+ location.reload();
+ },
+ { initialTab: 'my' },
+ );
+ } catch (err) {
+ console.error('[hub] register-ui load failed', err);
+ } finally {
+ deployBtn.disabled = false;
+ }
});
} else {
deployBtn.addEventListener('click', async () => {
diff --git a/src/element.js b/src/element.js
index 5a70a3cb5..ea2a8cf41 100644
--- a/src/element.js
+++ b/src/element.js
@@ -13,6 +13,34 @@ import { parseAgentRef, resolveOnchainAgent, toManifest } from './erc8004/resolv
const MODES = ['inline', 'floating', 'section', 'fullscreen'];
+// Derive the origin of the script itself so cross-origin embeds hit the right API.
+const _scriptOrigin = (() => {
+ try {
+ return new URL(import.meta.url).origin;
+ } catch {
+ return '';
+ }
+})();
+
+function originAllowed(originUrl, policy, firstParty = []) {
+ if (!originUrl) return false;
+ let host;
+ try {
+ host = new URL(originUrl).hostname.toLowerCase();
+ } catch {
+ return false;
+ }
+ if (firstParty.some((fp) => host === fp || host.endsWith('.' + fp))) return true;
+ const hosts = policy?.origins?.hosts ?? [];
+ const mode = policy?.origins?.mode ?? 'allowlist';
+ const matches = hosts.some((h) => {
+ const lower = h.toLowerCase();
+ if (lower.startsWith('*.')) return host.endsWith(lower.slice(1)) && host !== lower.slice(2);
+ return host === lower;
+ });
+ return mode === 'allowlist' ? matches : !matches;
+}
+
const BASE_STYLE = `
:host {
display: block;
@@ -561,6 +589,49 @@ class Agent3DElement extends HTMLElement {
manifest.instructions = manifest.brain.instructions;
}
+ // Embed-policy surface + origin gate (fail-open on infra errors)
+ const _backendId = (() => {
+ const a = this.getAttribute('agent-id') || manifest.id?.agentId || '';
+ return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(a)
+ ? a
+ : null;
+ })();
+ if (_backendId) {
+ try {
+ const _policyBase = _scriptOrigin || window.location.origin;
+ const _pr = await fetch(
+ `${_policyBase}/api/agents/${_backendId}/embed-policy`,
+ { credentials: 'omit' },
+ );
+ if (_pr.ok) {
+ const { policy } = await _pr.json();
+ if (policy) {
+ if (policy.surfaces?.script === false) {
+ this._fail(
+ 'embed_denied_surface',
+ 'This agent disallows the script-tag embed.',
+ );
+ return;
+ }
+ const _fp = ['3dagent.vercel.app', 'localhost'];
+ const _host = window.location.origin;
+ if (
+ !_host.startsWith('http://localhost') &&
+ !originAllowed(_host, policy, _fp)
+ ) {
+ this._fail(
+ 'embed_denied_origin',
+ `This agent isn't permitted on ${_host}.`,
+ );
+ return;
+ }
+ }
+ }
+ } catch (_e) {
+ console.warn('[agent-3d] embed-policy fetch failed; continuing', _e);
+ }
+ }
+
// Build Viewer
this.dispatchEvent(
new CustomEvent('agent:load-progress', { detail: { phase: 'body', pct: 0.45 } }),
@@ -759,6 +830,21 @@ class Agent3DElement extends HTMLElement {
this.shadowRoot.appendChild(el);
}
+ _fail(code, message) {
+ this._loadingEl.hidden = true;
+ const el = document.createElement('div');
+ el.className = 'error';
+ el.textContent = message;
+ this.shadowRoot.appendChild(el);
+ this.dispatchEvent(
+ new CustomEvent('agent:error', {
+ detail: { phase: 'policy', error: { code, message } },
+ bubbles: true,
+ composed: true,
+ }),
+ );
+ }
+
async _toggleMic() {
if (!this._runtime) return;
if (this._listening) {
diff --git a/src/erc8004/register-ui.js b/src/erc8004/register-ui.js
index 7bbaba118..29b559527 100644
--- a/src/erc8004/register-ui.js
+++ b/src/erc8004/register-ui.js
@@ -156,6 +156,7 @@ const TEMPLATES = [
description:
'Automated DeFi yield optimization, liquidity management, and token swaps across protocols.',
services: [S.a2a, S.mcp, S.x402],
+ x402Support: true,
},
{
id: 'support',
@@ -172,6 +173,7 @@ const TEMPLATES = [
description:
'Automated code analysis, security auditing, gas optimization, and best-practice enforcement.',
services: [S.a2a, S.mcp, S.x402],
+ x402Support: true,
},
{
id: 'data',
@@ -188,6 +190,7 @@ const TEMPLATES = [
description:
'AI content generation for social posts, documentation, technical writing, and marketing copy.',
services: [S.a2a, S.x402],
+ x402Support: true,
},
{
id: 'research',
@@ -252,7 +255,7 @@ export class RegisterUI {
this.selectedChainId = DEFAULT_CHAIN_ID;
// Tab state
- this.activeTab = 'create';
+ this.activeTab = opts.initialTab || 'create';
const initial = opts.initial || {};
@@ -1349,6 +1352,7 @@ export class RegisterUI {
imageUrl: imageUrl || undefined,
apiToken: apiToken || undefined,
services: extraServices,
+ x402Support: !!this.form.x402Support,
onStatus: say,
});
}
@@ -1753,6 +1757,10 @@ export class RegisterUI {
</label>`
: ''
}
+ <label class="erc8004-checkbox">
+ <input type="checkbox" name="x402Support" ${currentMeta?.x402Support || currentMeta?.x402 ? 'checked' : ''} />
+ Accept x402 payments (HTTP-native micropayments)
+ </label>
<label class="erc8004-label">Pinata JWT (optional)
<input class="erc8004-input" name="apiToken" placeholder="leave blank for R2 backend" />
</label>
@@ -1793,6 +1801,7 @@ export class RegisterUI {
const fileInput = modal.querySelector('[name="glb"]');
const glbFile = fileInput.files?.[0] || null;
const removeAvatar = !!modal.querySelector('[name="removeAvatar"]')?.checked;
+ const x402Support = !!modal.querySelector('[name="x402Support"]')?.checked;
await this._doUpdateAgent({
agentId,
@@ -1801,6 +1810,7 @@ export class RegisterUI {
imageUrl: imageUrlInput,
glbFile,
removeAvatar,
+ x402Support,
apiToken,
currentMeta: meta,
say,
@@ -1828,6 +1838,7 @@ export class RegisterUI {
imageUrl,
glbFile,
removeAvatar = false,
+ x402Support,
apiToken,
currentMeta,
say,
@@ -1890,7 +1901,10 @@ export class RegisterUI {
chainId,
registryAddr,
services: preservedServices,
- x402Support: !!(currentMeta?.x402Support || currentMeta?.x402),
+ x402Support:
+ typeof x402Support === 'boolean'
+ ? x402Support
+ : !!(currentMeta?.x402Support || currentMeta?.x402),
});
say('Uploading new registration metadata…');
@@ -2254,6 +2268,7 @@ export class RegisterUI {
if (Array.isArray(t.services)) {
this.form.services = t.services.map((s) => ({ ...s }));
}
+ this.form.x402Support = !!t.x402Support;
this.wizardStep = 1;
this._setTab('create');
});