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.

fix: update agent routing paths to point to public directory for consistency

nirholasb453f8bfa5e1
diff --git a/README.md b/README.md
index 355ceb74b..7fff0efbd 100644
--- a/README.md
+++ b/README.md
@@ -98,23 +98,33 @@ Widget URLs (`/w/<id>`) get rich Open Graph cards in Slack/Discord/X and auto-em
```bash
git clone https://github.com/nirholas/3d-agent.git
-cd 3D
+cd 3D-Agent
npm install
npm run dev
```
-Open **http://localhost:3000** and drop any `.glb` or `.gltf` file onto the page.
+Open **http://localhost:3000** for the landing page, or **http://localhost:3000/app** to open the viewer and drop any `.glb` or `.gltf` file onto the page.
<br/>
### Available Scripts
-| Command | What It Does |
-| :--------------- | :-------------------------------------------------- |
-| `npm run dev` | Starts Vite dev server on port 3000 with hot reload |
-| `npm run build` | Production build to `dist/` |
-| `npm run deploy` | Build + deploy to Vercel |
-| `npm run clean` | Wipe the `dist/` directory |
+| Command | What It Does |
+| :----------------------- | :-------------------------------------------------------------------- |
+| `npm run dev` | Starts Vite dev server on port 3000 with hot reload |
+| `npm run dev:lib` | Dev server in library-build mode (`TARGET=lib`) |
+| `npm run build` | Production build to `dist/` |
+| `npm run build:lib` | Build the embeddable library bundle to `dist-lib/` |
+| `npm run build:artifact` | Build the standalone artifact bundle (`vite.config.artifact.js`) |
+| `npm run build:all` | `build` + `build:lib` + `publish:lib` |
+| `npm run publish:lib` | Run `scripts/publish-lib.mjs` to publish versioned `agent-3d` bundles |
+| `npm run test` | Run Vitest test suite |
+| `npm run verify` | `prettier --check .` + `vite build` |
+| `npm run format` | Run Prettier write across the repo |
+| `npm run deploy` | `build:all` + `vercel --prod` |
+| `npm run clean` | Wipe `dist/` and `dist-lib/` |
+| `npm run generate-icons` | Regenerate PWA icons (`scripts/generate-pwa-icons.mjs`) |
+| `npm run fetch-animations` | Download animation assets (`scripts/download-animations.mjs`) |
<br/>
@@ -131,21 +141,49 @@ Open **http://localhost:3000** and drop any `.glb` or `.gltf` file onto the page
</p>
```
-3D/
-├── index.html → Single-page app shell
-├── style.css → Dark theme + responsive layout
+3D-Agent/
+├── index.html → Landing page shell
+├── app.html → Viewer / deploy app (also served at /app, /deploy, /a/*)
+├── home.html → Authenticated home
+├── create.html → Avatar + agent creation flow
+├── features.html → Features marketing page
+├── agent-home.html → Agent detail page
+├── agent-edit.html → Agent editing UI
+├── agent-embed.html, a-embed.html, embed.html → Embed surfaces
+├── style.css, home.css, features.css → Styling
├── src/
│ ├── app.js → Entry: dropzone, URL parsing, orchestration
-│ ├── viewer.js → Three.js renderer, scene, camera, GUI (dat.gui)
+│ ├── viewer.js → Three.js renderer, scene, camera, GUI
+│ ├── viewer/ → Lights, environment, animation, screenshot helpers
│ ├── validator.js → glTF-Validator integration & report generation
│ ├── environments.js → HDR environment map definitions
-│ └── components/
-│ ├── footer.jsx → Social links (X, GitHub)
-│ ├── validator-report.jsx → Full validation report view
-│ ├── validator-table.jsx → Error/warning/hint tables
-│ └── validator-toggle.jsx → Collapsible validation summary bar
-├── public/avatars/ → Default model assets
-├── vercel.json → Deployment + routing config
+│ ├── components/ → JSX components (validator, animation panel, footer, model-viewer element)
+│ ├── widgets.js, widgets/, widget-types.js → Widget Studio (turntable, gallery, talking agent, passport, hotspot tour)
+│ ├── agents-directory.js, agent-*.js → Agent creation, identity, skills, memory, embed modal
+│ ├── auth/, wallet/, wallet-auth.js → Session + wallet (SIWE / Privy) auth
+│ ├── erc8004/, attestations/, reputation-* → ERC-8004 passport + reputation
+│ ├── erc7710/, claim-transfer.js → Delegated permissions
+│ ├── cz-flow.js, cz/ → CZ claim demo flow
+│ ├── memory/, permissions/, pinning/ → Agent memory, permissions, IPFS pinning
+│ ├── artifact/, runtime/, editor/ → Embeddable artifact + editor runtime
+│ ├── ar/ → AR quick-look helpers
+│ └── skills/ → Agent skills registry
+├── api/ → Vercel serverless functions
+│ ├── agents/, widgets/, avatars/ → CRUD + embed/OG/oembed/view endpoints
+│ ├── auth/, oauth/, session/, sessions/ → Session + OAuth 2.1 server
+│ ├── mcp.js, llm/ → MCP endpoint + LLM proxy
+│ ├── erc8004/, cz/, dca-strategies.js, subscriptions.js → On-chain + scheduled flows
+│ ├── cron/ → erc8004-crawl, index-delegations, run-dca, run-subscriptions
+│ ├── animations/, tts/, pinning/, api-keys/ → Supporting services
+│ └── _lib/ → Shared server helpers + `schema.sql`
+├── public/ → Static subapps (studio, dashboard, widgets-gallery, agent, artifact, cz, discover, explore, validation, hydrate, lobehub, wallet, login.html, register.html) and default avatars
+├── contracts/ → Smart contract sources
+├── sdk/, lobehub-plugin/ → Embedding SDK + Lobehub plugin
+├── scripts/ → Build, publish, icon, animation scripts
+├── docs/ → Architecture, API, Deployment, Development, MCP, Setup, Widgets docs
+├── tests/ → Vitest suite
+├── vercel.json → Routes, rewrites, cron schedules
+├── vite.config.js, vite.config.artifact.js → Build configs
└── package.json → Dependencies & scripts
```
@@ -158,12 +196,15 @@ Open **http://localhost:3000** and drop any `.glb` or `.gltf` file onto the page
| **Rendering** | [three.js](https://threejs.org/) r176 — WebGL 2.0 |
| **Model Loading** | `GLTFLoader` + `DRACOLoader` + `KTX2Loader` + `MeshoptDecoder` |
| **Controls** | `OrbitControls` — pan, zoom, rotate |
-| **GUI** | [dat.gui](https://github.com/dataarts/dat.gui) — real-time parameter tweaking |
+| **GUI** | [dat.gui](https://github.com/dataarts/dat.gui) + [tweakpane](https://tweakpane.github.io/docs/) — real-time parameter tweaking |
| **Validation** | [gltf-validator](https://github.com/KhronosGroup/gltf-validator) — Khronos spec compliance |
| **Templating** | [vhtml](https://github.com/developit/vhtml) — JSX → HTML string rendering |
| **Drag & Drop** | [simple-dropzone](https://github.com/donmccurdy/simple-dropzone) |
-| **Build** | [Vite](https://vitejs.dev/) 8 — sub-second HMR |
-| **Hosting** | [Vercel](https://vercel.com/) — edge CDN |
+| **Build** | [Vite](https://vitejs.dev/) 7 — sub-second HMR |
+| **Backend** | Vercel serverless functions · [Neon](https://neon.tech/) Postgres · Cloudflare R2 · [Upstash](https://upstash.com/) Redis |
+| **Auth** | Session JWT ([`jose`](https://github.com/panva/jose)) · [SIWE](https://eips.ethereum.org/EIPS/eip-4361) / [viem](https://viem.sh/) + [ethers](https://ethers.org/) · [Privy](https://www.privy.io/) |
+| **Testing** | [Vitest](https://vitest.dev/) |
+| **Hosting** | [Vercel](https://vercel.com/) — edge CDN + cron |
<br/>
@@ -198,6 +239,66 @@ https://3dagent.vercel.app/#model=https://example.com/model.glb&kiosk=true
<br/>
+## 🗺️ Routes & Endpoints
+
+Routing is driven by [`vercel.json`](vercel.json). High-level map:
+
+### Pages
+
+| Path | Serves |
+| :------------------------------ | :-------------------------------------------- |
+| `/` | `index.html` — landing |
+| `/app`, `/deploy`, `/a/*` | `app.html` — viewer + deploy flow |
+| `/home` | `home.html` |
+| `/features` | `features.html` |
+| `/create` | `create.html` — avatar + agent creation |
+| `/agent`, `/agent/<id>` | Agent detail page |
+| `/agent/<id>/edit`, `/embed` | Agent edit + embed surfaces |
+| `/studio`, `/widgets`, `/widgets/...` | Widget Studio + gallery |
+| `/w/<id>` | Rendered widget page (with OG + oEmbed) |
+| `/dashboard`, `/dashboard/...` | Authenticated dashboard (storage, usage) |
+| `/discover`, `/explore` | Directories |
+| `/artifact`, `/hydrate`, `/cz`, `/validation`, `/lobehub/iframe` | Standalone subapps |
+| `/login`, `/register` | Auth pages |
+| `/docs/widgets` | Widgets documentation |
+
+### API
+
+| Path | Purpose |
+| :------------------------------------------------ | :--------------------------------------------------- |
+| `/api/agents`, `/api/agents/<id>` | Agent CRUD, wallet, sign, embed-policy, usage |
+| `/api/agents/suggest`, `/api/agents/by-wallet` | Lookup helpers |
+| `/api/agent-actions`, `/api/agent-memory` | Agent actions + memory store |
+| `/api/widgets`, `/api/widgets/<id>` | Widget CRUD, duplicate, stats, view |
+| `/api/widgets/oembed`, `/api/widgets/<id>/og` | oEmbed + Open Graph card |
+| `/api/avatars/<id>/...` | Storage mode + IPFS pinning |
+| `/api/auth/...`, `/oauth/...` | Sessions + OAuth 2.1 authorization server |
+| `/.well-known/oauth-authorization-server`, `/.well-known/oauth-protected-resource` | Discovery docs |
+| `/api/mcp` | Model Context Protocol endpoint |
+| `/api/llm/anthropic` | LLM proxy |
+| `/api/erc8004/hydrate`, `/api/erc8004/import`, `/api/erc8004/pin` | ERC-8004 passport tools |
+| `/api/dca-strategies`, `/api/subscriptions.js` | Scheduled on-chain actions |
+| `/api/cz/claim` | CZ claim flow |
+| `/api/chat`, `/api/tts/*`, `/api/animations/*` | Chat, TTS, animation services |
+| `/a/<chain>/<id>`, `/a/<chain>/<id>/embed`, `/api/a/<chain>/<id>/og` | Attestation pages + OG |
+
+### Cron jobs
+
+Scheduled in `vercel.json` → `crons`:
+
+| Schedule | Handler |
+| :-------------- | :---------------------------------- |
+| `*/15 * * * *` | `/api/cron/erc8004-crawl` |
+| `*/5 * * * *` | `/api/cron/index-delegations` |
+| `0 * * * *` | `/api/cron/run-dca` |
+| `0 * * * *` | `/api/cron/run-subscriptions` |
+
+<br/>
+
+---
+
+<br/>
+
## 📖 Tutorials
<br/>
@@ -393,6 +494,9 @@ For deeper technical detail, see the `docs/` directory:
| **[API Reference](docs/API.md)** | Complete reference for all classes (`App`, `Viewer`, `Validator`), methods, properties, state objects, components, and the `window.VIEWER` debugging API |
| **[Deployment](docs/DEPLOYMENT.md)** | Build pipeline, Vercel deploy, routing, CORS config, custom domains, iframe embedding, self-hosting (nginx, Docker), CDN strategy, and troubleshooting |
| **[Development](docs/DEVELOPMENT.md)** | Local setup, code style, how-things-work guide, common tasks (new GUI controls, components, environments), debugging techniques, browser compatibility, and performance notes |
+| **[Backend Setup](docs/SETUP.md)** | Environment variables, Neon/R2/Upstash provisioning, schema migration, CORS, and deploy |
+| **[Widgets](docs/WIDGETS.md)** | Widget types, URL params, postMessage API, oEmbed, and privacy model |
+| **[MCP](docs/MCP.md)** | Model Context Protocol endpoint (`/api/mcp`) + OAuth integration |
| **[Contributing](CONTRIBUTING.md)** | Bug reporting, feature requests, PR workflow, commit conventions, code guidelines, and testing checklist |
<br/>
@@ -427,7 +531,3 @@ For deeper technical detail, see the `docs/` directory:
<p align="center">
<sub>MIT License · Made with three.js · Hosted on Vercel</sub>
</p>
-
-<p align="center">
- <sub>MIT License · Made with three.js · Hosted on Vercel</sub>
-</p>
diff --git a/agent-edit.html b/agent-edit.html
index 44f4db7da..19f4d09a9 100644
--- a/agent-edit.html
+++ b/agent-edit.html
@@ -43,6 +43,7 @@
font-size: 0.875rem;
font-weight: 500;
color: rgba(255, 255, 255, 0.75);
+ margin: 0;
}
.edit-tabs {
@@ -199,6 +200,8 @@
color: rgba(255, 255, 255, 0.35);
text-transform: uppercase;
letter-spacing: 0.08em;
+ font-weight: 500;
+ margin: 0;
}
.btn-reset-all {
background: transparent;
@@ -362,24 +365,51 @@
font-size: 0.764rem;
padding: 1rem 0;
}
+
+ .edit-tab:focus-visible,
+ .btn-primary:focus-visible,
+ .btn-reset-all:focus-visible,
+ .btn-reset-mat:focus-visible,
+ .edit-header a:focus-visible,
+ .mat-card-header:focus-visible {
+ outline: 2px solid rgba(147, 197, 253, 0.7);
+ outline-offset: 2px;
+ }
+
+ .skip-link {
+ position: absolute;
+ left: -9999px;
+ top: 0;
+ background: #000;
+ color: #fff;
+ padding: 0.5rem 1rem;
+ z-index: 10000;
+ text-decoration: none;
+ }
+ .skip-link:focus {
+ left: 0.5rem;
+ top: 0.5rem;
+ }
</style>
</head>
<body>
+ <a href="#main" class="skip-link">Skip to main content</a>
<header class="edit-header">
- <a id="back-link" href="/">← Agent</a>
- <div class="edit-header-title" id="agent-title">Edit Agent</div>
+ <a id="back-link" href="/" aria-label="Back to agent page">← Agent</a>
+ <h1 class="edit-header-title" id="agent-title">Edit Agent</h1>
</header>
- <div class="edit-tabs" role="tablist">
- <button class="edit-tab active" data-tab="persona">Persona</button>
- <button class="edit-tab" data-tab="outfit">Outfit</button>
+ <div class="edit-tabs" role="tablist" aria-label="Edit sections">
+ <button class="edit-tab active" data-tab="persona" role="tab" aria-selected="true" aria-controls="panel-persona" id="tab-persona">Persona</button>
+ <button class="edit-tab" data-tab="outfit" role="tab" aria-selected="false" aria-controls="panel-outfit" id="tab-outfit">Outfit</button>
</div>
- <div id="loading" class="loading-msg">Loading…</div>
- <div id="error" class="error-msg" style="display: none"></div>
+ <main id="main">
+ <div id="loading" class="loading-msg" role="status" aria-live="polite">Loading…</div>
+ <div id="error" class="error-msg" style="display: none" role="alert"></div>
<!-- Persona tab -->
- <div class="edit-panel persona-panel" id="panel-persona">
+ <section class="edit-panel persona-panel" id="panel-persona" role="tabpanel" aria-labelledby="tab-persona">
<div class="form-group">
<label class="form-label" for="f-name">Name</label>
<input class="form-input" id="f-name" type="text" maxlength="100" />
@@ -390,27 +420,28 @@
</div>
<div class="form-actions">
<button class="btn-primary" id="persona-save">Save</button>
- <span class="form-status" id="persona-status"></span>
+ <span class="form-status" id="persona-status" role="status" aria-live="polite"></span>
</div>
- </div>
+ </section>
<!-- Outfit tab -->
- <div class="edit-panel outfit-panel" id="panel-outfit">
- <div class="outfit-preview" id="outfit-preview">
+ <section class="edit-panel outfit-panel" id="panel-outfit" role="tabpanel" aria-labelledby="tab-outfit" hidden>
+ <div class="outfit-preview" id="outfit-preview" aria-label="Avatar preview">
<!-- agent-3d inserted here once avatar is confirmed -->
</div>
<div class="outfit-controls" id="outfit-controls">
<div class="outfit-header">
- <span class="outfit-title">Materials</span>
- <button class="btn-reset-all" id="btn-reset-all">Reset all</button>
+ <h2 class="outfit-title">Materials</h2>
+ <button class="btn-reset-all" id="btn-reset-all" aria-label="Reset all materials">Reset all</button>
</div>
<div id="mat-list">
<div class="no-named-mats">Loading preview…</div>
</div>
</div>
- </div>
+ </section>
+ </main>
- <div class="outfit-status" id="outfit-status"></div>
+ <div class="outfit-status" id="outfit-status" role="status" aria-live="polite"></div>
<script type="module">
import './src/element.js'; // registers <agent-3d>
@@ -457,16 +488,34 @@
// ── Tab switching ─────────────────────────────────────────────────────────
function activateTab(name) {
document.querySelectorAll('.edit-tab').forEach((btn) => {
- btn.classList.toggle('active', btn.dataset.tab === name);
+ const active = btn.dataset.tab === name;
+ btn.classList.toggle('active', active);
+ btn.setAttribute('aria-selected', active ? 'true' : 'false');
+ btn.tabIndex = active ? 0 : -1;
});
document.querySelectorAll('.edit-panel').forEach((p) => {
- p.classList.toggle('active', p.id === `panel-${name}`);
+ const active = p.id === `panel-${name}`;
+ p.classList.toggle('active', active);
+ if (active) p.removeAttribute('hidden');
+ else p.setAttribute('hidden', '');
});
if (name === 'outfit') initOutfitTab();
}
- document.querySelectorAll('.edit-tab').forEach((btn) => {
+ const editTabs = document.querySelectorAll('.edit-tab');
+ editTabs.forEach((btn) => {
btn.addEventListener('click', () => activateTab(btn.dataset.tab));
+ btn.addEventListener('keydown', (e) => {
+ if (e.key !== 'ArrowRight' && e.key !== 'ArrowLeft') return;
+ e.preventDefault();
+ const arr = Array.from(editTabs);
+ const i = arr.indexOf(btn);
+ const next = e.key === 'ArrowRight'
+ ? arr[(i + 1) % arr.length]
+ : arr[(i - 1 + arr.length) % arr.length];
+ activateTab(next.dataset.tab);
+ next.focus();
+ });
});
// ── Persona tab ───────────────────────────────────────────────────────────
@@ -562,45 +611,59 @@
const isModified = !!overridesMap[mat.name];
+ const bodyId = `mat-body-${esc(mat.name).replace(/[^a-zA-Z0-9_-]/g, '_')}`;
+ const rowColorId = `${bodyId}-color`;
+ const rowMetalId = `${bodyId}-metal`;
+ const rowRoughId = `${bodyId}-rough`;
+ const rowEmissId = `${bodyId}-emiss`;
card.innerHTML = `
- <div class="mat-card-header">
- <span class="mat-card-swatch" style="background:${esc(override.color || mat.color)}"></span>
+ <div class="mat-card-header" role="button" tabindex="0" aria-expanded="false" aria-controls="${bodyId}">
+ <span class="mat-card-swatch" style="background:${esc(override.color || mat.color)}" aria-hidden="true"></span>
<span class="mat-card-name">${esc(mat.name)}</span>
- ${isModified ? '<span class="mat-card-modified">●</span>' : ''}
- <span class="mat-card-chevron">▶</span>
+ ${isModified ? '<span class="mat-card-modified" aria-label="modified">●</span>' : ''}
+ <span class="mat-card-chevron" aria-hidden="true">▶</span>
</div>
- <div class="mat-card-body">
+ <div class="mat-card-body" id="${bodyId}">
<div class="mat-row">
- <span class="mat-row-label">Base color</span>
- <input type="color" data-field="color" value="${esc(override.color || mat.color)}" />
+ <label class="mat-row-label" for="${rowColorId}">Base color</label>
+ <input id="${rowColorId}" type="color" data-field="color" value="${esc(override.color || mat.color)}" />
<span class="mat-row-val"></span>
</div>
<div class="mat-row">
- <span class="mat-row-label">Metalness</span>
- <input type="range" data-field="metalness" min="0" max="1" step="0.01"
+ <label class="mat-row-label" for="${rowMetalId}">Metalness</label>
+ <input id="${rowMetalId}" type="range" data-field="metalness" min="0" max="1" step="0.01"
value="${override.metalness !== undefined ? override.metalness : mat.metalness}" />
<span class="mat-row-val">${fmtN(override.metalness !== undefined ? override.metalness : mat.metalness)}</span>
</div>
<div class="mat-row">
- <span class="mat-row-label">Roughness</span>
- <input type="range" data-field="roughness" min="0" max="1" step="0.01"
+ <label class="mat-row-label" for="${rowRoughId}">Roughness</label>
+ <input id="${rowRoughId}" type="range" data-field="roughness" min="0" max="1" step="0.01"
value="${override.roughness !== undefined ? override.roughness : mat.roughness}" />
<span class="mat-row-val">${fmtN(override.roughness !== undefined ? override.roughness : mat.roughness)}</span>
</div>
<div class="mat-row">
- <span class="mat-row-label">Emissive</span>
- <input type="color" data-field="emissive" value="${esc(override.emissive || mat.emissive)}" />
+ <label class="mat-row-label" for="${rowEmissId}">Emissive</label>
+ <input id="${rowEmissId}" type="color" data-field="emissive" value="${esc(override.emissive || mat.emissive)}" />
<span class="mat-row-val"></span>
</div>
<div class="mat-card-footer">
- <button class="btn-reset-mat" data-mat="${esc(mat.name)}">↺ reset this material</button>
+ <button class="btn-reset-mat" data-mat="${esc(mat.name)}" aria-label="Reset ${esc(mat.name)} material">↺ reset this material</button>
</div>
</div>
`;
// Toggle open/close
- card.querySelector('.mat-card-header').addEventListener('click', () => {
- card.classList.toggle('open');
+ const header = card.querySelector('.mat-card-header');
+ const toggleCard = () => {
+ const open = card.classList.toggle('open');
+ header.setAttribute('aria-expanded', open ? 'true' : 'false');
+ };
+ header.addEventListener('click', toggleCard);
+ header.addEventListener('keydown', (e) => {
+ if (e.key === 'Enter' || e.key === ' ') {
+ e.preventDefault();
+ toggleCard();
+ }
});
// Field changes
diff --git a/agent-home.html b/agent-home.html
index a29e33c26..4cb9c39e9 100644
--- a/agent-home.html
+++ b/agent-home.html
@@ -237,10 +237,34 @@
border-color: rgba(134, 239, 172, 0.3);
}
+ .agent-embed-tab:focus-visible,
+ .agent-embed-copy:focus-visible,
+ .agent-page-header a:focus-visible,
+ .agent-embed-preview-link:focus-visible {
+ outline: 2px solid rgba(255, 255, 255, 0.4);
+ outline-offset: 2px;
+ }
+
+ .skip-link {
+ position: absolute;
+ left: -9999px;
+ top: 0;
+ background: #000;
+ color: #fff;
+ padding: 0.5rem 1rem;
+ z-index: 10000;
+ text-decoration: none;
+ }
+ .skip-link:focus {
+ left: 0.5rem;
+ top: 0.5rem;
+ }
+
.agent-embed-label {
font-size: 0.618rem;
color: rgba(255, 255, 255, 0.25);
- margin-bottom: 0.382rem;
+ margin: 0 0 0.382rem;
+ font-weight: 400;
}
.agent-embed-preview-link {
@@ -264,9 +288,10 @@
.agent-skills-title {
font-size: 0.618rem;
color: rgba(255, 255, 255, 0.25);
- margin-bottom: 0.618rem;
+ margin: 0 0 0.618rem;
text-transform: uppercase;
letter-spacing: 0.08em;
+ font-weight: 400;
}
.agent-skills-grid {
@@ -304,39 +329,41 @@
</style>
</head>
<body>
- <div class="agent-page-header" style="justify-content: space-between">
- <a href="/">← 3D Agent</a>
+ <a href="#main" class="skip-link">Skip to main content</a>
+ <header class="agent-page-header" style="justify-content: space-between">
+ <a href="/" aria-label="Back to 3D Agent home">← 3D Agent</a>
<!-- BEGIN:AGENT_HOME_ORPHANS_DOM -->
<div id="agent-share-btn-mount"></div>
<!-- END:AGENT_HOME_ORPHANS_DOM -->
- </div>
+ </header>
+ <main id="main">
<div class="agent-page-hero">
<h1 class="agent-page-title" id="page-agent-name">Agent</h1>
<p class="agent-page-subtitle" id="page-agent-desc">Embodied. Present. Persistent.</p>
</div>
<div class="agent-page-card-wrap">
- <div id="agent-home-container">
+ <div id="agent-home-container" aria-live="polite" aria-busy="true">
<div class="loading-placeholder">Loading agent…</div>
</div>
</div>
- <div class="agent-skills-full" id="agent-skills-section" style="display: none">
- <div class="agent-skills-title">Skills</div>
+ <section class="agent-skills-full" id="agent-skills-section" style="display: none" aria-labelledby="agent-skills-heading">
+ <h2 class="agent-skills-title" id="agent-skills-heading">Skills</h2>
<div class="agent-skills-grid" id="agent-skills-grid"></div>
- </div>
-
- <div class="agent-embed-hint" id="agent-embed-section" style="display: none">
- <div class="agent-embed-label">Share &amp; embed</div>
- <div class="agent-embed-tabs" role="tablist">
- <button class="agent-embed-tab active" data-tab="iframe">iframe</button>
- <button class="agent-embed-tab" data-tab="link">link</button>
- <button class="agent-embed-tab" data-tab="webcomponent">&lt;agent-3d&gt;</button>
+ </section>
+
+ <section class="agent-embed-hint" id="agent-embed-section" style="display: none" aria-labelledby="agent-embed-heading">
+ <h2 class="agent-embed-label" id="agent-embed-heading">Share &amp; embed</h2>
+ <div class="agent-embed-tabs" role="tablist" aria-label="Embed format">
+ <button class="agent-embed-tab active" data-tab="iframe" role="tab" aria-selected="true" aria-controls="agent-embed-code" id="embed-tab-iframe">iframe</button>
+ <button class="agent-embed-tab" data-tab="link" role="tab" aria-selected="false" aria-controls="agent-embed-code" id="embed-tab-link">link</button>
+ <button class="agent-embed-tab" data-tab="webcomponent" role="tab" aria-selected="false" aria-controls="agent-embed-code" id="embed-tab-webcomponent">&lt;agent-3d&gt;</button>
</div>
<div class="agent-embed-code-wrap">
- <div class="agent-embed-code" id="agent-embed-code"></div>
- <button class="agent-embed-copy" id="agent-embed-copy">copy</button>
+ <div class="agent-embed-code" id="agent-embed-code" role="tabpanel" aria-labelledby="embed-tab-iframe" aria-live="polite"></div>
+ <button class="agent-embed-copy" id="agent-embed-copy" aria-label="Copy embed code">copy</button>
</div>
<a
class="agent-embed-preview-link"
@@ -353,7 +380,8 @@
rel="noopener"
>embed settings →</a
>
- </div>
+ </section>
+ </main>
<script type="module">
import { AgentIdentity } from './src/agent-identity.js';
@@ -378,6 +406,7 @@
const container = document.getElementById('agent-home-container');
container.innerHTML = '';
+ container.setAttribute('aria-busy', 'false');
const home = new AgentHome(container, identity, protocol, null);
await home.render();
@@ -424,13 +453,30 @@
document.getElementById('agent-embed-settings').href =
'/dashboard/embed-policy?agent=' + identity.id;
- document.querySelectorAll('.agent-embed-tab').forEach((btn) => {
- btn.addEventListener('click', () => {
- current = btn.dataset.tab;
- document
- .querySelectorAll('.agent-embed-tab')
- .forEach((b) => b.classList.toggle('active', b === btn));
- render();
+ const embedTabs = document.querySelectorAll('.agent-embed-tab');
+ const selectTab = (btn) => {
+ current = btn.dataset.tab;
+ embedTabs.forEach((b) => {
+ const active = b === btn;
+ b.classList.toggle('active', active);
+ b.setAttribute('aria-selected', active ? 'true' : 'false');
+ b.tabIndex = active ? 0 : -1;
+ });
+ embedCode.setAttribute('aria-labelledby', `embed-tab-${current}`);
+ render();
+ };
+ embedTabs.forEach((btn) => {
+ btn.addEventListener('click', () => selectTab(btn));
+ btn.addEventListener('keydown', (e) => {
+ if (e.key !== 'ArrowRight' && e.key !== 'ArrowLeft') return;
+ e.preventDefault();
+ const arr = Array.from(embedTabs);
+ const i = arr.indexOf(btn);
+ const next = e.key === 'ArrowRight'
+ ? arr[(i + 1) % arr.length]
+ : arr[(i - 1 + arr.length) % arr.length];
+ selectTab(next);
+ next.focus();
});
});
diff --git a/api/agents.js b/api/agents.js
index 0b4904b2e..ff8f2ab52 100644
--- a/api/agents.js
+++ b/api/agents.js
@@ -68,7 +68,7 @@ async function handleList(req, res) {
AND deleted_at IS NULL
ORDER BY created_at ASC
`;
- return json(res, 200, { agents: rows.map(decorate) });
+ return json(res, 200, { agents: rows.map((row) => decorate(row)) });
}
// ── Get-or-create default agent ───────────────────────────────────────────
diff --git a/api/cron/index-delegations.js b/api/cron/index-delegations.js
index 4045891a5..1434fc1f9 100644
--- a/api/cron/index-delegations.js
+++ b/api/cron/index-delegations.js
@@ -36,8 +36,12 @@ const BLOCKS_PER_DAY = {
// Public RPC fallbacks — override per chain via env RPC_<chainId>.
const PUBLIC_RPC = {
+ 1: 'https://cloudflare-eth.com',
+ 8453: 'https://mainnet.base.org',
84532: 'https://sepolia.base.org',
11155111: 'https://rpc.sepolia.org',
+ 421614: 'https://sepolia-rollup.arbitrum.io/rpc',
+ 11155420: 'https://sepolia.optimism.io',
};
function rpcUrl(chainId) {
diff --git a/api/cron/run-dca.js b/api/cron/run-dca.js
index 88e45dc4b..1655ee1fd 100644
--- a/api/cron/run-dca.js
+++ b/api/cron/run-dca.js
@@ -41,16 +41,70 @@ const ERC20_ABI = parseAbi([
// Uniswap V3 standard fee tier — 0.3% pool is the most liquid USDC/WETH tier
const FEE_TIER = 3000;
+// ── Operational tunables ──────────────────────────────────────────────────────
+
+const RPC_TIMEOUT_MS = 10_000;
+const RPC_MAX_RETRIES = 2; // total attempts = 1 + retries
+const RELAYER_TIMEOUT_MS = 30_000;
+const RELAYER_MAX_RETRIES = 1;
+const RELAYER_RETRY_BACKOFF_MS = 1_500;
+
+// ── Structured logging ────────────────────────────────────────────────────────
+
+function log(level, event, fields = {}) {
+ const line = JSON.stringify({
+ level,
+ event,
+ ts: new Date().toISOString(),
+ component: 'cron/run-dca',
+ ...fields,
+ });
+ if (level === 'error') console.error(line);
+ else console.log(line);
+}
+
+// ── Retry helper for transient failures ───────────────────────────────────────
+
+function isTransient(err) {
+ // Network-level & RPC transport errors
+ const code = err?.code;
+ const name = err?.name;
+ const status = err?.status;
+ if (name === 'AbortError' || name === 'TimeoutError') return true;
+ if (code === 'ETIMEDOUT' || code === 'ECONNRESET' || code === 'ECONNREFUSED' || code === 'ENOTFOUND' || code === 'EAI_AGAIN') return true;
+ if (typeof status === 'number' && status >= 500 && status < 600) return true;
+ // viem transport errors
+ const msg = String(err?.message || '');
+ if (/HttpRequestError|TimeoutError|fetch failed|network|socket hang up/i.test(msg)) return true;
+ return false;
+}
+
+async function withRetry(fn, { retries, backoffMs = 500, label }) {
+ let attempt = 0;
+ // eslint-disable-next-line no-constant-condition
+ while (true) {
+ try {
+ return await fn();
+ } catch (err) {
+ attempt++;
+ if (attempt > retries || !isTransient(err)) throw err;
+ const delay = backoffMs * 2 ** (attempt - 1);
+ log('warn', 'retry', { label, attempt, delay_ms: delay, message: err?.message, code: err?.code });
+ await new Promise((r) => setTimeout(r, delay));
+ }
+ }
+}
+
// ── RPC client factory ────────────────────────────────────────────────────────
function getViemClient(chainId) {
const cfg = CHAIN_CONFIG[chainId];
if (!cfg) throw new Error(`Unsupported chainId: ${chainId}`);
const rpcUrl = env.getRpcUrl(chainId);
- return createPublicClient({
- chain: cfg.chain,
- transport: rpcUrl ? http(rpcUrl) : http(),
- });
+ const transport = rpcUrl
+ ? http(rpcUrl, { timeout: RPC_TIMEOUT_MS, retryCount: 0 })
+ : http(undefined, { timeout: RPC_TIMEOUT_MS, retryCount: 0 });
+ return createPublicClient({ chain: cfg.chain, transport });
}
// ── Quote with divergence check ───────────────────────────────────────────────
@@ -59,7 +113,7 @@ function getViemClient(chainId) {
* Fetch a quote twice 15s apart; abort if they diverge by more than 0.5%.
* Returns { amountOut, divergenceBps } or throws if divergence exceeds limit.
*/
-async function getVerifiedQuote(client, quoterAddress, tokenIn, tokenOut, amountIn) {
+async function getVerifiedQuote(client, quoterAddress, tokenIn, tokenOut, amountIn, logCtx) {
const params = {
tokenIn,
tokenOut,
@@ -68,22 +122,28 @@ async function getVerifiedQuote(client, quoterAddress, tokenIn, tokenOut, amount
sqrtPriceLimitX96: 0n,
};
- // First quote
- const [q1] = await client.readContract({
- address: quoterAddress,
- abi: QUOTER_V2_ABI,
- functionName: 'quoteExactInputSingle',
- args: [params],
+ const readQuote = () =>
+ client.readContract({
+ address: quoterAddress,
+ abi: QUOTER_V2_ABI,
+ functionName: 'quoteExactInputSingle',
+ args: [params],
+ });
+
+ // First quote (with retry on transient RPC failures)
+ const [q1] = await withRetry(readQuote, {
+ retries: RPC_MAX_RETRIES,
+ backoffMs: 500,
+ label: `quote1:${logCtx?.strategy_id ?? ''}`,
});
// Wait 15s then quote again
await new Promise((r) => setTimeout(r, 15_000));
- const [q2] = await client.readContract({
- address: quoterAddress,
- abi: QUOTER_V2_ABI,
- functionName: 'quoteExactInputSingle',
- args: [params],
+ const [q2] = await withRetry(readQuote, {
+ retries: RPC_MAX_RETRIES,
+ backoffMs: 500,
+ label: `quote2:${logCtx?.strategy_id ?? ''}`,
});
// Divergence in basis points: |q2-q1| / q1 * 10000
@@ -132,26 +192,35 @@ function buildSwapCalldata(tokenIn, tokenOut, recipient, amountIn, amountOutMini
// ── Relayer redemption ────────────────────────────────────────────────────────
-async function redeemViaRelayer(delegationId, calls) {
+async function redeemViaRelayer(delegationId, calls, logCtx) {
const relayerUrl = `${env.APP_ORIGIN}/api/permissions/redeem`;
- const res = await fetch(relayerUrl, {
- method: 'POST',
- headers: {
- 'content-type': 'application/json',
- // Cron uses the shared relayer bearer token set in env
- authorization: `Bearer ${env.CRON_SECRET}`,
- },
- body: JSON.stringify({ id: delegationId, calls }),
- });
- if (!res.ok) {
- const body = await res.json().catch(() => ({ message: res.statusText }));
- throw Object.assign(
- new Error(body.error_description || body.message || `Relayer ${res.status}`),
- { code: body.error || 'relayer_error', status: res.status },
- );
- }
- return res.json();
+ const doFetch = async () => {
+ const res = await fetch(relayerUrl, {
+ method: 'POST',
+ headers: {
+ 'content-type': 'application/json',
+ authorization: `Bearer ${env.CRON_SECRET}`,
+ },
+ body: JSON.stringify({ id: delegationId, calls }),
+ signal: AbortSignal.timeout(RELAYER_TIMEOUT_MS),
+ });
+
+ if (!res.ok) {
+ const body = await res.json().catch(() => ({ message: res.statusText }));
+ throw Object.assign(
+ new Error(body.error_description || body.message || `Relayer ${res.status}`),
+ { code: body.error || 'relayer_error', status: res.status },
+ );
+ }
+ return res.json();
+ };
+
+ return withRetry(doFetch, {
+ retries: RELAYER_MAX_RETRIES,
+ backoffMs: RELAYER_RETRY_BACKOFF_MS,
+ label: `relayer:${logCtx?.strategy_id ?? ''}`,
+ });
}
// ── onPeriod — process one strategy ──────────────────────────────────────────
@@ -171,6 +240,7 @@ async function onPeriod(strategy) {
if (!cfg) throw Object.assign(new Error(`No config for chainId ${chainId}`), { code: 'unsupported_chain' });
const client = getViemClient(chainId);
+ const logCtx = { strategy_id: strategyId, chain_id: chainId };
// Get verified quote
const { amountOut, divergenceBps } = await getVerifiedQuote(
@@ -179,6 +249,7 @@ async function onPeriod(strategy) {
tokenIn,
tokenOut,
amountIn,
+ logCtx,
);
// Apply slippage: amountOutMinimum = amountOut * (10000 - slippageBps) / 10000
@@ -210,7 +281,7 @@ async function onPeriod(strategy) {
];
// Submit via relayer
- const result = await redeemViaRelayer(delegationId, calls);
+ const result = await redeemViaRelayer(delegationId, calls, logCtx);
return { txHash: result.txHash, quoteAmountOut: amountOut.toString(), divergenceBps };
}
@@ -227,23 +298,34 @@ export default wrap(async (req, res) => {
}
}
+ const runId = (globalThis.crypto?.randomUUID?.() ?? `run_${Date.now()}`);
+ log('info', 'tick_start', { run_id: runId });
+
// Fetch all due active strategies
- const strategies = await sql`
- SELECT
- s.id, s.delegation_id, s.chain_id,
- s.token_in, s.token_out, s.amount_per_execution,
- s.period_seconds, s.slippage_bps, s.agent_id,
- ad.status AS delegation_status, ad.expires_at AS delegation_expires_at
- FROM dca_strategies s
- JOIN agent_delegations ad ON ad.id = s.delegation_id
- WHERE s.status = 'active'
- AND s.next_execution_at <= NOW()
- ORDER BY s.next_execution_at ASC
- LIMIT 50
- `;
+ let strategies;
+ try {
+ strategies = await sql`
+ SELECT
+ s.id, s.delegation_id, s.chain_id,
+ s.token_in, s.token_out, s.amount_per_execution,
+ s.period_seconds, s.slippage_bps, s.agent_id,
+ ad.status AS delegation_status, ad.expires_at AS delegation_expires_at
+ FROM dca_strategies s
+ JOIN agent_delegations ad ON ad.id = s.delegation_id
+ WHERE s.status = 'active'
+ AND s.next_execution_at <= NOW()
+ ORDER BY s.next_execution_at ASC
+ LIMIT 50
+ `;
+ } catch (err) {
+ log('error', 'fetch_due_failed', { run_id: runId, message: err?.message });
+ throw err;
+ }
const results = [];
for (const strategy of strategies) {
+ const logCtx = { run_id: runId, strategy_id: strategy.id, chain_id: strategy.chain_id };
+
const execRow = {
strategy_id: strategy.id,
chain_id: strategy.chain_id,
@@ -259,7 +341,10 @@ export default wrap(async (req, res) => {
`;
execRow.status = 'aborted';
execRow.error = `Delegation ${strategy.delegation_status}`;
- await sql`INSERT INTO dca_executions ${sql(execRow)}`;
+ await sql`INSERT INTO dca_executions ${sql(execRow)}`.catch((e) =>
+ log('error', 'exec_insert_failed', { ...logCtx, message: e?.message }),
+ );
+ log('info', 'skipped', { ...logCtx, reason: execRow.error });
results.push({ id: strategy.id, skipped: true, reason: execRow.error });
continue;
}
@@ -270,11 +355,40 @@ export default wrap(async (req, res) => {
`;
execRow.status = 'aborted';
execRow.error = 'Delegation expired';
- await sql`INSERT INTO dca_executions ${sql(execRow)}`;
+ await sql`INSERT INTO dca_executions ${sql(execRow)}`.catch((e) =>
+ log('error', 'exec_insert_failed', { ...logCtx, message: e?.message }),
+ );
+ log('info', 'skipped', { ...logCtx, reason: execRow.error });
results.push({ id: strategy.id, skipped: true, reason: execRow.error });
continue;
}
+ // ── Idempotency claim ───────────────────────────────────────────────
+ // Atomically advance next_execution_at so a concurrent tick (or a retry
+ // of this tick) will not re-pick this row. We advance by period_seconds
+ // provisionally; on success we leave it; on failure we reset to NOW so
+ // the next tick retries it.
+ const nowIso = new Date().toISOString();
+ const provisionalNextIso = new Date(
+ Date.now() + strategy.period_seconds * 1000,
+ ).toISOString();
+
+ const claim = await sql`
+ UPDATE dca_strategies
+ SET next_execution_at = ${provisionalNextIso}
+ WHERE id = ${strategy.id}
+ AND status = 'active'
+ AND next_execution_at <= ${nowIso}
+ RETURNING id
+ `;
+ if (claim.length === 0) {
+ log('info', 'claim_lost', { ...logCtx });
+ results.push({ id: strategy.id, skipped: true, reason: 'claim_lost' });
+ continue;
+ }
+
+ log('info', 'execute_start', { ...logCtx });
+
try {
const { txHash, quoteAmountOut, divergenceBps } = await onPeriod(strategy);
@@ -283,32 +397,55 @@ export default wrap(async (req, res) => {
execRow.quote_divergence_bps = divergenceBps;
execRow.status = 'success';
- const nextExecAt = new Date(
- Date.now() + strategy.period_seconds * 1000,
- ).toISOString();
-
await sql`
UPDATE dca_strategies
- SET last_execution_at = NOW(), next_execution_at = ${nextExecAt}
+ SET last_execution_at = NOW()
WHERE id = ${strategy.id}
`;
+ log('info', 'execute_success', { ...logCtx, tx_hash: txHash, divergence_bps: divergenceBps });
results.push({ id: strategy.id, txHash, quoteAmountOut });
} catch (err) {
execRow.status = err.code === 'quote_divergence' ? 'aborted' : 'failed';
execRow.error = err.message;
execRow.quote_divergence_bps = err.divergenceBps ?? null;
- console.error('[cron/run-dca] strategy', strategy.id, err.code, err.message);
+ // Release the idempotency claim so the next tick can retry this
+ // strategy — but only for transient / recoverable failures. For
+ // aborts (quote_divergence, delegation_gone) leave the advanced
+ // next_execution_at in place so we wait the full period.
+ const shouldRetryNextTick =
+ err.code !== 'quote_divergence' &&
+ err.code !== 'delegation_gone' &&
+ err.code !== 'unsupported_chain';
+ if (shouldRetryNextTick) {
+ await sql`
+ UPDATE dca_strategies
+ SET next_execution_at = ${nowIso}
+ WHERE id = ${strategy.id}
+ `.catch((e) =>
+ log('error', 'claim_release_failed', { ...logCtx, message: e?.message }),
+ );
+ }
+
+ log('error', 'execute_failed', {
+ ...logCtx,
+ code: err.code,
+ message: err.message,
+ status: err.status,
+ will_retry_next_tick: shouldRetryNextTick,
+ });
results.push({ id: strategy.id, error: err.message, code: err.code });
}
// Insert execution record regardless of outcome
await sql`INSERT INTO dca_executions ${sql(execRow)}`.catch((e) =>
- console.error('[cron/run-dca] failed to insert execution row', e.message),
+ log('error', 'exec_insert_failed', { ...logCtx, message: e?.message }),
);
}
+ log('info', 'tick_done', { run_id: runId, processed: strategies.length });
+
return json(res, 200, {
ok: true,
processed: strategies.length,
diff --git a/api/cron/run-subscriptions.js b/api/cron/run-subscriptions.js
index 5be393f08..dcfbe638b 100644
--- a/api/cron/run-subscriptions.js
+++ b/api/cron/run-subscriptions.js
@@ -7,7 +7,10 @@
* either advances next_charge_at on success or flips status to 'paused' on failure.
*
* Idempotent: re-running within the same period is a no-op because next_charge_at
- * is only reached once per period.
+ * is only reached once per period. Concurrent runs are additionally guarded by an
+ * atomic conditional claim that marks the row with last_charge_at = NOW() before
+ * invoking onPeriod; the claim fails (0 rows) if another worker already claimed
+ * this period, so onPeriod is called at most once per (subscription, period).
*
* Scheduled via vercel.json crons — "0 * * * *" (every hour on the hour).
*/
@@ -22,124 +25,296 @@ const USDC_BY_CHAIN = {
11155111: '0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238', // Sepolia
};
+// Max time we'll wait for the skill's onPeriod (which fetches the relayer).
+// Override via SUBSCRIPTION_CHARGE_TIMEOUT_MS.
+const ONPERIOD_TIMEOUT_MS = parseInt(
+ process.env.SUBSCRIPTION_CHARGE_TIMEOUT_MS ?? '30000',
+ 10,
+);
+
+// Structured log helper — single-line JSON so Vercel log drains can parse it.
+function log(event, fields = {}) {
+ try {
+ console.log(JSON.stringify({ ts: new Date().toISOString(), event, ...fields }));
+ } catch {
+ // Never let logging throw.
+ }
+}
+
+function logError(event, fields = {}) {
+ try {
+ console.error(JSON.stringify({ ts: new Date().toISOString(), event, ...fields }));
+ } catch {
+ // Never let logging throw.
+ }
+}
+
+// Race a promise against a timeout. Rejects with a tagged error on timeout.
+function withTimeout(promise, ms, label) {
+ return new Promise((resolve, reject) => {
+ const t = setTimeout(() => {
+ const err = new Error(`${label} timed out after ${ms}ms`);
+ err.code = 'timeout';
+ reject(err);
+ }, ms);
+ Promise.resolve(promise).then(
+ (v) => {
+ clearTimeout(t);
+ resolve(v);
+ },
+ (e) => {
+ clearTimeout(t);
+ reject(e);
+ },
+ );
+ });
+}
+
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;
// Auth: Vercel Cron header OR explicit Bearer $CRON_SECRET.
+ // If neither is configured AND no Vercel cron header is present, reject.
const auth = req.headers['authorization'] ?? '';
const expected = env.CRON_SECRET ? `Bearer ${env.CRON_SECRET}` : null;
const fromVercelCron = req.headers['x-vercel-cron'] === '1';
- if (!fromVercelCron && expected && auth !== expected) {
- return error(res, 401, 'unauthorized', 'cron secret required');
+ if (!fromVercelCron) {
+ if (!expected || auth !== expected) {
+ return error(res, 401, 'unauthorized', 'cron secret required');
+ }
}
+ const runId = `sub-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
+ const runStart = Date.now();
+ log('subscription_cron.start', { runId, fromVercelCron });
+
const origin = env.APP_ORIGIN;
const relayerToken = env.CRON_SECRET ?? '';
- const report = { processed: 0, charged: 0, skipped: 0, paused: 0, errors: [] };
+ const report = {
+ runId,
+ processed: 0,
+ charged: 0,
+ skipped: 0,
+ paused: 0,
+ claimLost: 0,
+ errors: [],
+ };
// Load the skill's onPeriod handler once per invocation.
- const { onPeriod } = await import('../../public/skills/subscription/skill.js');
+ let onPeriod;
+ try {
+ ({ onPeriod } = await import('../../public/skills/subscription/skill.js'));
+ } catch (err) {
+ logError('subscription_cron.skill_load_failed', { runId, message: err.message });
+ return error(res, 500, 'internal_error', 'failed to load subscription skill');
+ }
// Select all active subscriptions whose charge window has arrived.
- const rows = await sql`
- SELECT
- s.id,
- s.user_id,
- s.agent_id,
- s.delegation_id,
- s.period_seconds,
- s.amount_per_period,
- s.next_charge_at,
- d.status AS delegation_status,
- d.expires_at AS delegation_expires_at,
- d.chain_id,
- ai.wallet_address AS owner_address
- FROM agent_subscriptions s
- JOIN agent_delegations d ON d.id = s.delegation_id
- JOIN agent_identities ai ON ai.id = s.agent_id
- WHERE s.status = 'active'
- AND s.next_charge_at <= NOW()
- `;
+ let rows;
+ try {
+ rows = await sql`
+ SELECT
+ s.id,
+ s.user_id,
+ s.agent_id,
+ s.delegation_id,
+ s.period_seconds,
+ s.amount_per_period,
+ s.next_charge_at,
+ s.last_charge_at,
+ d.status AS delegation_status,
+ d.expires_at AS delegation_expires_at,
+ d.chain_id,
+ ai.wallet_address AS owner_address
+ FROM agent_subscriptions s
+ JOIN agent_delegations d ON d.id = s.delegation_id
+ JOIN agent_identities ai ON ai.id = s.agent_id
+ WHERE s.status = 'active'
+ AND s.next_charge_at <= NOW()
+ `;
+ } catch (err) {
+ logError('subscription_cron.select_failed', { runId, message: err.message });
+ return error(res, 500, 'internal_error', 'failed to load subscriptions');
+ }
+
+ log('subscription_cron.selected', { runId, count: rows.length });
for (const row of rows) {
report.processed++;
+ const rowStart = Date.now();
+ const ctx = { runId, subscriptionId: row.id, agentId: row.agent_id };
- // Guard: delegation must still be active.
- if (row.delegation_status !== 'active') {
- await _pause(row.id, `delegation_${row.delegation_status}`);
- report.paused++;
- report.errors.push({ id: row.id, reason: `delegation_${row.delegation_status}` });
- continue;
- }
-
- // Guard: delegation must not be expired.
- if (row.delegation_expires_at && new Date(row.delegation_expires_at) <= new Date()) {
- await _pause(row.id, 'delegation_expired');
- report.paused++;
- report.errors.push({ id: row.id, reason: 'delegation_expired' });
- continue;
- }
+ try {
+ // Guard: delegation must still be active.
+ if (row.delegation_status !== 'active') {
+ await _pause(row.id, `delegation_${row.delegation_status}`);
+ report.paused++;
+ report.errors.push({ id: row.id, reason: `delegation_${row.delegation_status}` });
+ log('subscription_cron.paused', {
+ ...ctx,
+ reason: `delegation_${row.delegation_status}`,
+ });
+ continue;
+ }
- const usdcAddress = USDC_BY_CHAIN[row.chain_id];
- if (!usdcAddress) {
- await _pause(row.id, `chain_${row.chain_id}_unsupported`);
- report.skipped++;
- report.errors.push({ id: row.id, reason: `chain_${row.chain_id}_unsupported` });
- continue;
- }
+ // Guard: delegation must not be expired.
+ if (row.delegation_expires_at && new Date(row.delegation_expires_at) <= new Date()) {
+ await _pause(row.id, 'delegation_expired');
+ report.paused++;
+ report.errors.push({ id: row.id, reason: 'delegation_expired' });
+ log('subscription_cron.paused', { ...ctx, reason: 'delegation_expired' });
+ continue;
+ }
- let result;
- try {
- result = await onPeriod({
- agent: {
- agentId: row.agent_id,
- chainId: row.chain_id,
- ownerAddress: row.owner_address,
- usdcAddress,
- relayerToken,
- origin,
- },
- subscription: {
- id: row.id,
- delegationId: row.delegation_id,
- amountPerPeriod: row.amount_per_period,
- },
- });
- } catch (err) {
- await _pause(row.id, (err.message ?? 'unknown').slice(0, 500));
- report.paused++;
- report.errors.push({ id: row.id, reason: err.message ?? 'unknown' });
- continue;
- }
+ const usdcAddress = USDC_BY_CHAIN[row.chain_id];
+ if (!usdcAddress) {
+ await _pause(row.id, `chain_${row.chain_id}_unsupported`);
+ report.skipped++;
+ report.errors.push({ id: row.id, reason: `chain_${row.chain_id}_unsupported` });
+ log('subscription_cron.skipped', {
+ ...ctx,
+ reason: `chain_${row.chain_id}_unsupported`,
+ });
+ continue;
+ }
- if (result.ok) {
- // Advance next_charge_at by exactly one period to enforce idempotency.
- const nextChargeAt = new Date(
- Date.parse(row.next_charge_at) + row.period_seconds * 1000,
- );
- await sql`
+ // Atomic claim: mark this period as being processed by writing
+ // last_charge_at = NOW(). Matches only if:
+ // - next_charge_at hasn't moved (no racing writer),
+ // - status is still active,
+ // - last_charge_at is NULL OR < next_charge_at (not already claimed for this period).
+ // If 0 rows returned, another worker claimed this period — skip.
+ const claim = await sql`
UPDATE agent_subscriptions
- SET last_charge_at = NOW(),
- next_charge_at = ${nextChargeAt.toISOString()},
- last_error = NULL
+ SET last_charge_at = NOW()
WHERE id = ${row.id}
+ AND status = 'active'
+ AND next_charge_at = ${row.next_charge_at}
+ AND (last_charge_at IS NULL OR last_charge_at < next_charge_at)
+ RETURNING id
`;
+ if (claim.length === 0) {
+ report.claimLost++;
+ log('subscription_cron.claim_lost', ctx);
+ continue;
+ }
- // Emit usage event — non-fatal if the table schema differs.
- await sql`
- INSERT INTO usage_events (user_id, kind, tool, status)
- VALUES (${row.user_id}, 'subscription_charge', 'subscription', 'success')
- `.catch(() => null);
+ let result;
+ try {
+ result = await withTimeout(
+ onPeriod({
+ agent: {
+ agentId: row.agent_id,
+ chainId: row.chain_id,
+ ownerAddress: row.owner_address,
+ usdcAddress,
+ relayerToken,
+ origin,
+ },
+ subscription: {
+ id: row.id,
+ delegationId: row.delegation_id,
+ amountPerPeriod: row.amount_per_period,
+ },
+ }),
+ ONPERIOD_TIMEOUT_MS,
+ 'onPeriod',
+ );
+ } catch (err) {
+ const reason = (err.code === 'timeout' ? 'timeout: ' : '') + (err.message ?? 'unknown');
+ await _safePause(row.id, reason, ctx);
+ report.paused++;
+ report.errors.push({ id: row.id, reason });
+ logError('subscription_cron.onperiod_threw', {
+ ...ctx,
+ code: err.code ?? 'unknown',
+ message: err.message ?? 'unknown',
+ durationMs: Date.now() - rowStart,
+ });
+ continue;
+ }
- report.charged++;
- } else {
- await _pause(row.id, `${result.code ?? ''}: ${result.message ?? ''}`.slice(0, 500));
+ if (result && result.ok) {
+ // Advance next_charge_at by exactly one period to enforce idempotency.
+ const nextChargeAt = new Date(
+ Date.parse(row.next_charge_at) + row.period_seconds * 1000,
+ );
+ try {
+ await sql`
+ UPDATE agent_subscriptions
+ SET next_charge_at = ${nextChargeAt.toISOString()},
+ last_error = NULL
+ WHERE id = ${row.id}
+ `;
+ } catch (err) {
+ // Charge succeeded on-chain but we failed to advance — log loudly.
+ // Do NOT pause: next run's claim guard will prevent double-charge
+ // since last_charge_at >= next_charge_at for this period.
+ logError('subscription_cron.advance_failed', {
+ ...ctx,
+ message: err.message,
+ txHash: result.txHash,
+ });
+ report.errors.push({ id: row.id, reason: 'advance_failed', message: err.message });
+ continue;
+ }
+
+ // Emit usage event — non-fatal if the table schema differs.
+ await sql`
+ INSERT INTO usage_events (user_id, kind, tool, status)
+ VALUES (${row.user_id}, 'subscription_charge', 'subscription', 'success')
+ `.catch((err) =>
+ logError('subscription_cron.usage_event_failed', {
+ ...ctx,
+ message: err.message,
+ }),
+ );
+
+ report.charged++;
+ log('subscription_cron.charged', {
+ ...ctx,
+ txHash: result.txHash,
+ durationMs: Date.now() - rowStart,
+ });
+ } else {
+ const code = result?.code ?? 'unknown';
+ const message = result?.message ?? '';
+ await _safePause(row.id, `${code}: ${message}`.slice(0, 500), ctx);
+ report.paused++;
+ report.errors.push({ id: row.id, code, message });
+ log('subscription_cron.paused', {
+ ...ctx,
+ code,
+ message,
+ durationMs: Date.now() - rowStart,
+ });
+ }
+ } catch (err) {
+ // Catch-all so one bad row can't kill the run.
+ logError('subscription_cron.row_unhandled', {
+ ...ctx,
+ message: err.message ?? 'unknown',
+ stack: err.stack,
+ });
+ report.errors.push({ id: row.id, reason: 'unhandled', message: err.message });
+ // Best-effort pause so we don't loop on the same broken row next hour.
+ await _safePause(row.id, `unhandled: ${(err.message ?? 'unknown').slice(0, 480)}`, ctx);
report.paused++;
- report.errors.push({ id: row.id, code: result.code, message: result.message });
}
}
+ log('subscription_cron.done', {
+ runId,
+ durationMs: Date.now() - runStart,
+ processed: report.processed,
+ charged: report.charged,
+ paused: report.paused,
+ skipped: report.skipped,
+ claimLost: report.claimLost,
+ errorCount: report.errors.length,
+ });
+
return json(res, 200, report);
});
@@ -150,3 +325,17 @@ async function _pause(id, lastError) {
WHERE id = ${id}
`;
}
+
+// Like _pause but swallows its own errors so a DB hiccup during pause doesn't
+// propagate out of the per-row handler. Logs the failure for ops visibility.
+async function _safePause(id, lastError, ctx) {
+ try {
+ await _pause(id, lastError);
+ } catch (err) {
+ logError('subscription_cron.pause_failed', {
+ ...ctx,
+ lastError,
+ message: err.message,
+ });
+ }
+}
diff --git a/api/dca-strategies.js b/api/dca-strategies.js
index 72a1664da..391f7fad5 100644
--- a/api/dca-strategies.js
+++ b/api/dca-strategies.js
@@ -47,6 +47,9 @@ export default wrap(async (req, res) => {
if (!strategyId || strategyId === 'dca-strategies') {
return error(res, 400, 'missing_param', 'strategy id required in path');
}
+ if (!z.string().uuid().safeParse(strategyId).success) {
+ return error(res, 400, 'validation_error', 'strategy id must be a uuid');
+ }
const ip = clientIp(req);
const rl = await limits.authIp(ip);
@@ -76,6 +79,9 @@ export default wrap(async (req, res) => {
if (req.method === 'GET') {
const agentId = url.searchParams.get('agent_id');
if (!agentId) return error(res, 400, 'missing_param', 'agent_id is required');
+ if (!z.string().uuid().safeParse(agentId).success) {
+ return error(res, 400, 'validation_error', 'agent_id must be a uuid');
+ }
const ip = clientIp(req);
const rl = await limits.authIp(ip);
diff --git a/api/erc8004/import.js b/api/erc8004/import.js
index 5ce62b7a9..b941a8604 100644
--- a/api/erc8004/import.js
+++ b/api/erc8004/import.js
@@ -13,9 +13,16 @@ import { limits, clientIp } from '../_lib/rate-limit.js';
import { resolveOnChainAgent, SERVER_CHAIN_META } from '../_lib/onchain.js';
import { z } from 'zod';
+// agentId is a uint256 on-chain but we cap the decimal string length to 78
+// (max digits for uint256) and require digits only so BigInt() can't throw.
+const agentIdSchema = z
+ .union([z.string(), z.number()])
+ .transform((v) => (typeof v === 'number' ? String(v) : v.trim()))
+ .refine((v) => /^\d{1,78}$/.test(v), { message: 'agentId must be a non-negative integer' });
+
const bodySchema = z.object({
- chainId: z.number().int().positive(),
- agentId: z.union([z.string(), z.number()]),
+ chainId: z.number().int().positive().max(2_147_483_647),
+ agentId: agentIdSchema,
});
export default wrap(async (req, res) => {
@@ -35,7 +42,7 @@ export default wrap(async (req, res) => {
return error(res, 400, 'bad_request', `unsupported chain ${body.chainId}`);
}
- const agentId = String(body.agentId);
+ const agentId = body.agentId;
// Check if already imported by this user.
const [existing] = await sql`
diff --git a/api/subscriptions.js b/api/subscriptions.js
index e0248d4eb..6f1efdecf 100644
--- a/api/subscriptions.js
+++ b/api/subscriptions.js
@@ -80,6 +80,9 @@ export default wrap(async (req, res) => {
if (req.method === 'GET') {
const agentId = req.query?.agentId ?? null;
+ if (agentId && !z.string().uuid().safeParse(agentId).success) {
+ return error(res, 400, 'validation_error', 'agentId must be a uuid');
+ }
const rows = agentId
? await sql`
@@ -105,6 +108,9 @@ export default wrap(async (req, res) => {
if (req.method === 'DELETE') {
const id = req.query?.id;
if (!id) return error(res, 400, 'validation_error', 'id query param is required');
+ if (!z.string().uuid().safeParse(id).success) {
+ return error(res, 400, 'validation_error', 'id must be a uuid');
+ }
const [row] = await sql`
UPDATE agent_subscriptions
diff --git a/create.html b/create.html
index 68759d5e3..4eed67703 100644
--- a/create.html
+++ b/create.html
@@ -545,8 +545,8 @@
</div>
<!-- Card 3: From selfie (disabled) -->
- <div class="create-card" id="card-selfie" aria-disabled="true" tabindex="-1">
- <span class="coming-soon-badge" aria-label="Coming soon">Coming Soon</span>
+ <div class="create-card" id="card-selfie" role="button" aria-disabled="true" aria-label="From a selfie (coming soon)" tabindex="-1">
+ <span class="coming-soon-badge" aria-hidden="true">Coming Soon</span>
<div
class="card-icon"
aria-hidden="true"
@@ -591,8 +591,10 @@
</div>
</main>
- <input type="file" id="glb-input" accept=".glb,model/gltf-binary" style="display: none" />
- <div class="status-toast" id="status-toast" hidden></div>
+ <label for="glb-input" class="visually-hidden" style="position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0">Upload GLB file</label>
+ <input type="file" id="glb-input" accept=".glb,model/gltf-binary" style="display: none" aria-describedby="glb-input-desc" />
+ <span id="glb-input-desc" hidden>Select a .glb or glTF 2.0 binary model file</span>
+ <div class="status-toast" id="status-toast" role="status" aria-live="polite" aria-atomic="true" hidden></div>
<script type="module" src="/src/create.js"></script>
</body>
diff --git a/docs/api-inventory.md b/docs/api-inventory.md
new file mode 100644
index 000000000..180e8bfa6
--- /dev/null
+++ b/docs/api-inventory.md
@@ -0,0 +1,201 @@
+# API Endpoint Inventory
+
+Generated reference of every HTTP endpoint under `/api/`. Paths reflect the externally-visible URL (after `vercel.json` rewrites). Auth column: `session` = `__Host-sid` cookie; `bearer` = OAuth access token or API key; `public` = no auth; `cron` = Vercel Cron header or `CRON_SECRET`.
+
+## Agents
+
+| Path | Methods | Auth | Description | Input | Response |
+| --- | --- | --- | --- | --- | --- |
+| `/api/agents` | GET, POST | session or bearer | List caller's agents / create new agent identity | GET: `?limit&cursor`; POST: `{name,description,avatarId,...,animations[]}` | `{agents}` / `{agent}` |
+| `/api/agents/me` | GET | session or bearer | Get or auto-create caller's default agent | — | `{agent}` |
+| `/api/agents/:id` | GET, PUT, PATCH, DELETE | public GET; session PUT/DELETE | Fetch (public fields if not owner), update, soft-delete | PATCH body: partial agent | `{agent}` |
+| `/api/agents/:id/wallet` | POST, DELETE | session | Link/update or unlink agent wallet | `{address,signature?}` | `{wallet}` |
+| `/api/agents/:id/actions` | GET | session or bearer (owner or public agent) | Paginated signed action log (EIP-191 verified) | `?limit&cursor` | `{actions[]}` |
+| `/api/agents/:id/sign` | POST | session or bearer (owner) | Sign arbitrary EIP-191 message with agent's server wallet | `{message,kind?}` | `{address,signature}` |
+| `/api/agents/:id/embed-policy` | GET, PUT, DELETE | public GET; session owner PUT/DELETE | Read/write/clear embed policy (origins, surfaces, brain) | PUT: policy object | `{policy}` |
+| `/api/agents/:id/usage` | GET | session (owner) | LLM proxy usage stats (monthly + 30-day daily) | — | `{month,quota,daily[]}` |
+| `/api/agents/by-address/:addr` | GET | public (rate-limited) | DB-first agent lookup by owner address; RPC fallback via ERC-721 enumerable | `?chainId` | `{agents[]}` |
+| `/api/agents/by-wallet` | GET | public (rate-limited) | DB lookup by agent wallet address | `?address&chain_id` | `{agents[]}` |
+| `/api/agents/check-name` | GET | session or bearer | Validate agent name availability (denylist + regex) | `?name&agent_id?` | `{available,reason?}` |
+| `/api/agents/ens/:name` | GET | public (rate-limited) | Resolve ENS name then look up agents owned by that address | — | `{address,agents[]}` |
+| `/api/agents/suggest` | GET | public (rate-limited) | @-mention autocomplete ranked search | `?q&limit` | `{agents[]}` |
+| `/api/agents/register-prep` | POST | session | Build canonical registration JSON + pin IPFS, return CID for signing | `{name,description,avatarId,brain?}` | `{cid,metadataURI,prepId}` |
+| `/api/agents/register-confirm` | POST | session | Verify on-chain registration tx, upsert agent_identities row | `{prepId,chainId,agentId,txHash}` | `{agentId}` |
+| `/api/agent-actions` | GET, POST | session or bearer | Append-only global action log (provenance trail) | GET: `?agent_id&limit&cursor`; POST: action body | `{actions[]}` / `{action}` |
+| `/api/agent-memory` | GET, POST | session or bearer | Backup for LLM agent memories | GET: `?agentId&type&since&limit`; POST: memory upsert | `{memories[]}` |
+| `/api/agent-memory/:id` | DELETE | session or bearer | Forget a memory entry | — | `{ok}` |
+| `/api/agent/:id/og` | GET | public | Open Graph image: 302 to avatar thumbnail or SVG card | — | image/svg+xml or 302 |
+| `/api/oembed` | GET | public | oEmbed rich payload for agent URLs (Notion/Discord/etc.) | `?url&format` | oEmbed JSON |
+| `/api/a/:chain/:id/og` | GET | public | On-chain agent OG image (302 to manifest image or SVG) | `?format=json?` | image/svg+xml or JSON |
+| `/a/:chain/:id` | GET | public | Server-rendered HTML with OG/Twitter/oEmbed/Frame tags | — | text/html |
+
+## Avatars
+
+| Path | Methods | Auth | Description | Input | Response |
+| --- | --- | --- | --- | --- | --- |
+| `/api/avatars` | GET, POST | bearer `avatars:read`/`:write` or session | List caller avatars / register metadata after R2 upload | GET: `?limit&cursor&visibility&include_public`; POST: `{storage_key,size_bytes,...}` | `{avatars[]}` / `{avatar}` |
+| `/api/avatars/public` | GET | public | Public gallery search | `?q&tag&limit&cursor` | `{avatars[]}` |
+| `/api/avatars/presign` | POST | bearer `avatars:write` or session | Short-lived R2 presigned PUT URL for direct upload | `{size_bytes,content_type,slug?}` | `{storage_key,upload_url,...}` |
+| `/api/avatars/:id` | GET, PATCH, DELETE | public if visible; session/bearer owner for write | Fetch/update metadata/soft-delete; PATCH with `glbUrl` saves version | PATCH: `{name?,description?,visibility?,tags?,glbUrl?}` | `{avatar}` |
+| `/api/avatars/:id/versions` | GET | optional auth | Ancestor+descendant chain via `parent_avatar_id` | — | `{versions[]}` |
+| `/api/avatars/:id/glb-versions` | GET | session or bearer (owner) | Explicit GLB save-back snapshots | — | `{versions[]}` |
+| `/api/avatars/:id/rollback` | POST | session or bearer (owner) | Restore `storage_key` from a saved version (10/h) | `{versionId}` | `{avatar}` |
+| `/api/avatars/:id/session` | POST | session or bearer (owner) | Avaturn edit session for existing avatar | — | `{session_url,expires_at?}` |
+| `/api/avatars/:id/storage-mode` | GET, PUT | owner (PUT) / session for private GET | Read/write `storage_mode` JSONB (ipfs/attestation) | PUT: storage-mode schema | `{storage_mode}` |
+| `/api/avatars/:id/pin-ipfs` | POST | session (owner) | STUB pin to IPFS; flips pinned flag | — | `{storage_mode,stub:true}` |
+| `/api/avatars/regenerate` | POST | session or bearer `avatars:write` | Enqueue remesh/retex/rerig/restyle job (501 until provider set) | `{sourceAvatarId,mode,params?}` | `{jobId}` |
+| `/api/avatars/regenerate-status` | GET | session or bearer `avatars:read` | Poll regen job | `?jobId` | `{status,resultAvatarId?,error?}` |
+| `/api/animations/presign` | POST | session or bearer `avatars:write` | Presigned PUT for animation .glb clips (100 MB cap) | `{size_bytes,content_type,slug?,checksum_sha256?}` | `{storage_key,upload_url,...}` |
+
+## Auth
+
+| Path | Methods | Auth | Description | Input | Response |
+| --- | --- | --- | --- | --- | --- |
+| `/api/auth/register` | POST | public (rate-limited) | Email or username signup; creates session | `{email|username,password,display_name?}` | `{user}` + Set-Cookie |
+| `/api/auth/login` | POST | public (rate-limited) | Verify password, mint session | `{email,password}` | `{user}` + Set-Cookie |
+| `/api/auth/logout` | POST | session | Destroy current session | — | `{ok}` |
+| `/api/auth/logout-everywhere` | POST | session | Revoke all sessions for caller | — | `{revoked}` |
+| `/api/auth/me` | GET | session | Who am I | — | `{user}` |
+| `/api/auth/sessions` | GET, DELETE | session | List active sessions / revoke all except current | — | `{sessions[]}` |
+| `/api/auth/sessions/:id` | DELETE | session | Revoke one session (not current) | — | `{revoked}` |
+| `/api/auth/session/list` | GET | session | List sessions with ipHash + current flag | — | `{sessions[]}` |
+| `/api/auth/session/refresh` | POST | session | Rotate session cookie | — | `{user}` + Set-Cookie |
+| `/api/auth/session/revoke` | POST | session | Revoke by `{sessionId}` or `{all:true}` | `{sessionId?,all?}` | `{ok,revoked}` |
+| `/api/auth/siwe/nonce` | GET | public (rate-limited) | EIP-4361 nonce + CSRF cookie | — | `{nonce}` |
+| `/api/auth/siwe/verify` | POST | CSRF + signature | Verify SIWE; create/link user + session | `{message,signature}` | `{user}` + Set-Cookie |
+| `/api/auth/privy/verify` | POST | public (rate-limited) | Exchange Privy idToken for session | `{idToken}` | `{user,wallet}` + Set-Cookie |
+| `/api/auth/wallet/link` | POST | session | Link wallet via SIWE to logged-in account | `{message,signature}` | `{wallet}` |
+| `/api/auth/wallet/unlink` | POST | session | Unlink one wallet | `{address}` | `{ok}` |
+| `/api/auth/wallets` | GET, POST | session | List linked wallets / link new (nonce-based) | POST: `{address,message,signature,nonce}` | `{wallets[]}` / `{wallet}` |
+| `/api/auth/wallets/:address` | DELETE | session | Unlink by address (blocks last wallet if no password) | — | `{ok}` |
+| `/api/auth/wallets/nonce` | POST | session | Issue SIWE-like nonce for wallet link | — | `{nonce,message}` |
+
+## OAuth (MCP clients)
+
+| Path | Methods | Auth | Description | Input | Response |
+| --- | --- | --- | --- | --- | --- |
+| `/oauth/authorize` | GET, POST | session (POST consent) | OAuth 2.1 authorization endpoint (PKCE S256 required) | query or form | 302 redirect with code |
+| `/oauth/consent` | GET, POST | session | Alias of `/oauth/authorize` (consent form) | — | — |
+| `/oauth/token` | POST | client creds (if confidential) | Exchange auth code or refresh token | form-encoded | `{access_token,refresh_token?}` |
+| `/oauth/register` | POST | public (rate-limited) | RFC 7591 dynamic client registration | `{redirect_uris,client_name?,...}` | `{client_id,client_secret?,...}` |
+| `/oauth/revoke` | POST | client creds | RFC 7009 refresh token revocation | form `{token,client_id,client_secret?}` | 200 |
+| `/oauth/introspect` | POST | client creds | RFC 7662 token introspection (own tokens only) | form `{token,client_id,client_secret?}` | `{active,...}` |
+| `/.well-known/oauth-authorization-server` | GET | public | RFC 8414 AS metadata | — | metadata JSON |
+| `/.well-known/oauth-protected-resource` | GET | public | RFC 9728 protected-resource metadata | — | metadata JSON |
+| `/api/mcp/.well-known/oauth-protected-resource` | GET | public | Same as above under MCP base | — | metadata JSON |
+
+## API Keys
+
+| Path | Methods | Auth | Description | Input | Response |
+| --- | --- | --- | --- | --- | --- |
+| `/api/api-keys` | GET, POST | session or bearer `profile` | List keys / mint new `sk_live_…` (plaintext once) | POST: `{name,scope?,expires_at?}` | `{data[]}` / `{key,plaintext}` |
+| `/api/api-keys/:id` | DELETE | session or bearer `profile` | Revoke key | — | `{id,revoked}` |
+| `/api/keys` | GET, POST | session | Alt developer key mgmt (`sk_live_`/`sk_test_`) | POST: `{name,scope?,expires_in_days?,environment}` | `{keys[]}` |
+| `/api/keys/:id` | DELETE | session | Revoke key | — | `{ok}` |
+
+## Widgets
+
+| Path | Methods | Auth | Description | Input | Response |
+| --- | --- | --- | --- | --- | --- |
+| `/api/widgets` | GET, POST | session or bearer (`avatars:read`/`:write`) | List/create caller's widgets | POST: `{type,name,avatar_id?,config,is_public}` | `{widgets[]}` / `{widget}` |
+| `/api/widgets/:id` | GET, PATCH, DELETE | public GET (if `is_public`); owner PATCH/DELETE | Widget detail with avatar join; increments view_count for non-owners | PATCH: `{name?,config?,is_public?,avatar_id?,type?}` | `{widget}` |
+| `/api/widgets/:id/chat` | POST | public (per-widget brain config) | Visitor SSE chat for Talking Agent widgets | `{message,history?}` | SSE stream |
+| `/api/widgets/:id/duplicate` | POST | session owner (+`avatars:write`) | Clone widget | — | `{widget}` |
+| `/api/widgets/:id/stats` | GET | session owner (+`avatars:read`) | Aggregate view/referer/country stats | — | `{view_count,recent_views_7d,...}` |
+| `/api/widgets/:id/view` | POST | public | Anonymous view logger (country + referer host) | — | 204 |
+| `/api/widgets/:id/og` | GET | public | 302 to avatar thumbnail or 1200x630 SVG card | — | image/svg+xml |
+| `/api/widgets/oembed` | GET | public | oEmbed rich payload | `?url&format&maxwidth?&maxheight?` | oEmbed JSON |
+| `/api/widgets/page` (`/w/:id`) | GET | public | SSR HTML with OG/oEmbed discovery | `?id` | text/html |
+
+## ERC-8004 / On-chain
+
+| Path | Methods | Auth | Description | Input | Response |
+| --- | --- | --- | --- | --- | --- |
+| `/api/erc8004/hydrate` | GET | session | Agents owned by user's linked wallets (from crawler index) | — | `{agents[]}` |
+| `/api/erc8004/import` | POST | session | Import on-chain agent into local `agent_identities` | `{chainId,agentId}` | `{agent}` |
+| `/api/erc8004/pin` | POST | session | Pin raw GLB/JSON/image bytes (IPFS + R2 fallback) | raw body | `{cid,url}` |
+| `/api/explore` | GET | public | Paginated indexed ERC-8004 directory | `?only3d&chain&q&cursor&limit` | `{agents[],next_cursor}` |
+| `/api/showcase` | GET | public (rate-limited) | Public directory, 3D agents only, keyset pagination | `?chainIds&sort&limit&cursor` | `{agents[],next_cursor}` |
+
+## Permissions (ERC-7710 delegations)
+
+| Path | Methods | Auth | Description | Input | Response |
+| --- | --- | --- | --- | --- | --- |
+| `/api/permissions/grant` | POST | session | Persist signed delegation after verification | delegation + signature | `{id,hash}` |
+| `/api/permissions/list` | GET | public (rate-limited) | List delegations filtered by agent or delegator | `?agentId|delegator&status&chainId&limit` | `{delegations[]}` |
+| `/api/permissions/verify` | GET | public (rate-limited, CORS any) | On-chain delegation validity check | `?hash&chainId` | `{valid,reason?}` |
+| `/api/permissions/metadata` | GET | public (rate-limited, CORS any) | Chain + DelegationManager addresses | `?chainId?` | `{chains[]}` |
+| `/api/permissions/revoke` | POST | session | Mirror on-chain `disableDelegation` into DB | `{id,txHash}` | `{revoked}` |
+| `/api/permissions/redeem` | POST | bearer `permissions:redeem` | Server-side gas-paying relayer (feature-flagged, idempotent) | `{delegation,...}` | `{txHash}` |
+
+## DCA / Subscriptions
+
+| Path | Methods | Auth | Description | Input | Response |
+| --- | --- | --- | --- | --- | --- |
+| `/api/dca-strategies` | GET, POST, DELETE | session | Manage Uniswap-V3 DCA strategies | POST: `{agent_id,delegation_id,chain_id,token_in,token_out,...,period_seconds,slippage_bps}` | `{strategy}` |
+| `/api/dca-strategies/:id` | GET, DELETE | session | Fetch/soft-delete one | — | `{strategy}` |
+| `/api/subscriptions` | GET, POST, DELETE | session or bearer | Recurring subscription records | POST: `{agentId,delegationId,periodSeconds,amountPerPeriod}` | `{subscription}` |
+
+## Cron
+
+| Path | Methods | Auth | Description | Schedule |
+| --- | --- | --- | --- | --- |
+| `/api/cron/erc8004-crawl` | GET, POST | `x-vercel-cron` or `Bearer $CRON_SECRET` | Etherscan V2 log crawl → `erc8004_agents_index` + metadata enrichment | `*/15 * * * *` |
+| `/api/cron/index-delegations` | GET, POST | cron | Index `DelegationDisabled`/`Redeemed` events; expiry sweep | `*/5 * * * *` |
+| `/api/cron/run-dca` | GET, POST | cron | Execute pending DCA strategies via Uniswap V3 SwapRouter | `0 * * * *` |
+| `/api/cron/run-subscriptions` | GET, POST | cron | Process due subscription charges via skill handler | `0 * * * *` |
+
+## LLM / Chat / MCP
+
+| Path | Methods | Auth | Description | Input | Response |
+| --- | --- | --- | --- | --- | --- |
+| `/api/chat` | POST | session or bearer | Stateless Anthropic chat with viewer control tools | `{message,context?,history?,model?,maxTokens?}` | `{reply,actions[]}` |
+| `/api/llm/anthropic` | POST | embed-policy + quota | "We-pay" LLM proxy with per-agent origin/quota enforcement | Anthropic messages body + `?agentId` | Anthropic response |
+| `/api/mcp` | GET, POST, DELETE | bearer OAuth or API key | MCP Streamable HTTP (JSON-RPC); SSE notifications; session termination | JSON-RPC | JSON or SSE |
+
+## Onboarding / Avaturn / TTS
+
+| Path | Methods | Auth | Description | Input | Response |
+| --- | --- | --- | --- | --- | --- |
+| `/api/onboarding/avaturn-session` | POST | session or bearer `avatars:write` | Trade 3 selfies for Avaturn session URL | `{photos:{frontal,left,right},body_type,avatar_type}` | `{session_url,expires_at?}` |
+| `/api/onboarding/link-avatar` | POST | session or bearer | Link avatar to user's primary agent | `{avatarId,force?}` | `{agentId}` |
+| `/api/tts/eleven` | POST | session or bearer | ElevenLabs TTS proxy with R2 cache (1000 chars/h) | `{voiceId,text,modelId?}` | audio/mpeg |
+| `/api/tts/eleven/voices` | GET | session or bearer | List ElevenLabs voices (safe fields) | — | `{enabled,voices[]}` |
+
+## LobeHub
+
+| Path | Methods | Auth | Description | Input | Response |
+| --- | --- | --- | --- | --- | --- |
+| `/api/lobehub/config` | GET | public (open CORS) | LobeHub plugin manifest (from `/.well-known/lobehub-plugin.json`) | — | manifest JSON |
+| `/api/lobehub/manifest` | GET | public | LobeHub plugin manifest (from `public/lobehub/plugin.json`) | — | manifest JSON |
+| `/api/lobehub/handshake` | POST | public (rate-limited) | Return iframe URL + embed policy for a LobeHub host | `{agentId,hostOrigin?}` | `{iframeUrl,embedPolicy}` |
+
+## Pinning
+
+| Path | Methods | Auth | Description | Input | Response |
+| --- | --- | --- | --- | --- | --- |
+| `/api/pinning/pin` | POST | session or bearer | Pin manifest or GLB to IPFS via Pinata/Web3.Storage | multipart or data URL | `{cid,provider}` |
+| `/api/pinning/status` | GET | public (rate-limited) | Cross-provider pin status | `?cid` | `{pinned,providers[]}` |
+
+## Usage / Config / Artifact / CZ
+
+| Path | Methods | Auth | Description | Input | Response |
+| --- | --- | --- | --- | --- | --- |
+| `/api/usage/summary` | GET | session or bearer `profile` | Dashboard usage counters + plan quota | — | `{plan,counts}` |
+| `/api/config` | GET | public | Non-secret client config (walletconnect id) | — | `{walletConnectProjectId}` |
+| `/api/artifact` | GET | public | Self-contained HTML for Claude.ai artifacts (viewer or agent) | `?agent=<id>|?model=<glbUrl>` | text/html |
+| `/api/cz/claim` | GET, POST | public (ECDSA signature) | CZ agent claim: issue nonce / verify sig → on-chain tx payload | GET: `?address`; POST: `{address,signature,nonce}` | `{nonce}` / `{tx}` |
+
+## Notes & Gaps
+
+- **Route quirks**: `/api/agents/me` is rewritten to `/api/agents` (handler detects `/me` from pathname). `/api/agents/:id` delegates to handlers re-exported from `api/agents.js`.
+- **Duplicate key surfaces**: `/api/api-keys` and `/api/keys` are two parallel key-management endpoints with different token formats and schemas — likely candidates for consolidation.
+- **Unfinished / stub**:
+ - `/api/avatars/:id/pin-ipfs` returns a stub CID (`stub:sha256-…`) — real Pinata/Web3.Storage pinning not wired.
+ - `/api/avatars/regenerate` returns 501 until `AVATAR_REGEN_PROVIDER` is set.
+ - `/api/permissions/metadata` dynamically imports `src/erc7710/abi.js` with a try/catch — legacy shim for pre-task-03 state.
+- **Open CORS on auth surfaces**: `/api/permissions/verify` and `/api/permissions/metadata` set `access-control-allow-origin: *` explicitly (by design, for cross-origin delegation viewers).
+- **SSE**: `/api/widgets/:id/chat` and `/api/mcp` (GET) both declare SSE, but `/api/widgets/:id/chat` currently does a single-shot Anthropic call framed as SSE for forward-compat.
+- **vercel.json catch-all**: `{"src": "/api/(.*)", "dest": "/api/$1"}` after explicit rewrites means every `api/**/*.js` file is reachable even without an explicit route entry. Endpoints like `/api/agents/check-name`, `/api/agents/register-prep`, `/api/agents/register-confirm`, `/api/permissions/*`, `/api/subscriptions`, `/api/avatars/*`, `/api/auth/*`, `/api/usage/summary`, `/api/tts/*`, `/api/lobehub/*`, `/api/pinning/*`, `/api/onboarding/*`, `/api/config`, `/api/chat`, `/api/api-keys`, `/api/keys`, `/api/cron/*`, `/api/erc8004/pin` are served via this catch-all.
+- **Dynamic segments under catch-all**: `/api/agents/ens/:name` and `/api/avatars/:id/versions`, `/rollback`, `/glb-versions`, `/session` rely on Vercel's file-based `[param]` resolution since they lack explicit `vercel.json` rewrites.
+- **Cron auth**: all four cron endpoints accept manual `POST` with `Bearer $CRON_SECRET` in addition to the Vercel header.
diff --git a/embed-test.html b/embed-test.html
new file mode 100644
index 000000000..5769eb774
--- /dev/null
+++ b/embed-test.html
@@ -0,0 +1,29 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <title>3D Agent Embed Test</title>
+ <style>
+ body {
+ margin: 0;
+ padding: 40px;
+ background: #111;
+ color: #fff;
+ font-family: sans-serif;
+ }
+ h1 { margin-bottom: 8px; }
+ p { color: #aaa; margin-bottom: 24px; }
+ </style>
+</head>
+<body>
+ <h1>3D Agent Web Component Test</h1>
+ <p>Testing the <code>&lt;agent-3d&gt;</code> web component embed.</p>
+
+ <script type="module" src="https://3dagent.vercel.app/dist-lib/agent-3d.js"></script>
+ <agent-3d
+ src="https://3dagent.vercel.app/api/avatars/bdef4d68-710e-4fa6-8a8d-d5c00857b85c"
+ style="width:600px;height:600px"
+ ></agent-3d>
+</body>
+</html>
diff --git a/features.css b/features.css
index 883e9b48c..88eab8229 100644
--- a/features.css
+++ b/features.css
@@ -14,6 +14,39 @@
scroll-behavior: smooth;
}
+/* ── Skip link (a11y) ───────────────────────────────────────────────────── */
+
+.skip-link {
+ position: absolute;
+ top: -40px;
+ left: 8px;
+ padding: 0.5rem 0.9rem;
+ background: #fff;
+ color: #000;
+ font-size: var(--text-sm);
+ font-weight: 500;
+ text-decoration: none;
+ border-radius: var(--radius-sm);
+ z-index: 1000;
+ transition: top 0.15s ease;
+}
+
+.skip-link:focus,
+.skip-link:focus-visible {
+ top: 8px;
+ outline: 2px solid #ffd76a;
+ outline-offset: 2px;
+}
+
+/* ── Focus-visible treatment (a11y) ─────────────────────────────────────── */
+
+.features-page a:focus-visible,
+.features-page button:focus-visible {
+ outline: 2px solid #ffd76a;
+ outline-offset: 2px;
+ border-radius: var(--radius-sm);
+}
+
.features-main {
width: 100%;
}
diff --git a/features.html b/features.html
index 44002d6f2..cadf236a7 100644
--- a/features.html
+++ b/features.html
@@ -36,12 +36,13 @@
></script>
</head>
<body class="features-page">
+ <a href="#hero" class="skip-link">Skip to main content</a>
<header>
- <h1><a href="/">3D Agent</a></h1>
- <nav class="features-nav">
+ <h1><a href="/" aria-label="3D Agent home">3D Agent</a></h1>
+ <nav class="features-nav" aria-label="Primary">
<a href="/app">Viewer</a>
<a href="/explore">Explore</a>
- <a href="/features" class="active">Features</a>
+ <a href="/features" class="active" aria-current="page">Features</a>
</nav>
</header>
@@ -72,13 +73,14 @@
<div class="hero-cta scroll-reveal">
<a href="/" class="btn-primary">
<span>Launch Viewer</span>
- <span class="btn-arrow">→</span>
+ <span class="btn-arrow" aria-hidden="true">→</span>
</a>
<a
href="https://eips.ethereum.org/EIPS/eip-8004"
target="_blank"
rel="noopener"
class="btn-ghost"
+ aria-label="Read the ERC-8004 spec (opens in a new tab)"
>Read the spec</a
>
</div>
@@ -96,7 +98,8 @@
<model-viewer
class="hero-avatar-viewer"
src="/avatars/cz.glb"
- alt="3D Agent avatar"
+ alt="Rotating 3D avatar representing the 3D Agent brand"
+ aria-label="Rotating 3D avatar representing the 3D Agent brand"
camera-controls
disable-zoom
auto-rotate
@@ -166,9 +169,9 @@
</p>
<div class="code-block scroll-reveal">
<div class="code-header">
- <span class="code-dot red"></span>
- <span class="code-dot yellow"></span>
- <span class="code-dot green"></span>
+ <span class="code-dot red" aria-hidden="true"></span>
+ <span class="code-dot yellow" aria-hidden="true"></span>
+ <span class="code-dot green" aria-hidden="true"></span>
<span class="code-filename">agent-registration.json</span>
</div>
<pre class="code-body"><code>{
@@ -192,7 +195,7 @@
<h3 class="section-label scroll-reveal">Three Registries</h3>
<div class="registry-grid">
<div class="registry-card scroll-reveal">
- <div class="registry-icon">🪪</div>
+ <div class="registry-icon" aria-hidden="true">🪪</div>
<h4>Identity Registry</h4>
<p>
ERC-721 based. Every agent gets a unique <code>agentId</code> and a URI
@@ -206,7 +209,7 @@
</ul>
</div>
<div class="registry-card scroll-reveal">
- <div class="registry-icon">⭐</div>
+ <div class="registry-icon" aria-hidden="true">⭐</div>
<h4>Reputation Registry</h4>
<p>
Any client can leave signed feedback — quality scores, uptime, response
@@ -219,7 +222,7 @@
</ul>
</div>
<div class="registry-card scroll-reveal">
- <div class="registry-icon">🔐</div>
+ <div class="registry-icon" aria-hidden="true">🔐</div>
<h4>Validation Registry</h4>
<p>
Request independent verification: stake-secured re-execution, zkML
@@ -281,7 +284,8 @@
target="_blank"
rel="noopener"
class="btn-ghost"
- >Join the Discussion →</a
+ aria-label="Join the ERC-8004 discussion (opens in a new tab)"
+ >Join the Discussion <span aria-hidden="true">→</span></a
>
</div>
</div>
@@ -290,11 +294,19 @@
<footer class="features-footer">
<p>
3D Agent ·
- <a href="https://github.com/nirholas/3D" target="_blank" rel="noopener"
+ <a
+ href="https://github.com/nirholas/3D"
+ target="_blank"
+ rel="noopener"
+ aria-label="3D Agent on GitHub (opens in a new tab)"
>GitHub</a
>
· Built on
- <a href="https://eips.ethereum.org/EIPS/eip-8004" target="_blank" rel="noopener"
+ <a
+ href="https://eips.ethereum.org/EIPS/eip-8004"
+ target="_blank"
+ rel="noopener"
+ aria-label="ERC-8004 specification (opens in a new tab)"
>ERC-8004</a
>
</p>
diff --git a/home.css b/home.css
index 5d564d310..dd163c16f 100644
--- a/home.css
+++ b/home.css
@@ -7,6 +7,44 @@
scroll-behavior: smooth;
}
+/* ── Skip to content (a11y) ── */
+
+.h-skip-link {
+ position: absolute;
+ top: 0;
+ left: 0;
+ padding: 0.6rem 1rem;
+ background: #fff;
+ color: #000;
+ font-size: var(--text-sm);
+ font-weight: 500;
+ text-decoration: none;
+ border-radius: 0 0 var(--radius-sm) 0;
+ transform: translateY(-110%);
+ transition: transform 0.18s ease;
+ z-index: 9999;
+}
+
+.h-skip-link:focus {
+ transform: translateY(0);
+ outline: 2px solid #ffd76a;
+ outline-offset: 2px;
+}
+
+/* ── Focus-visible outlines (a11y) ── */
+
+.home-page a:focus-visible,
+.home-page button:focus-visible,
+.home-nav a:focus-visible,
+.h-btn-primary:focus-visible,
+.h-btn-ghost:focus-visible,
+.h-feature-link:focus-visible,
+.h-footer a:focus-visible {
+ outline: 2px solid #ffd76a;
+ outline-offset: 3px;
+ border-radius: var(--radius-sm);
+}
+
.home-main {
width: 100%;
}
diff --git a/home.html b/home.html
index ab08dc62d..9cab62eb7 100644
--- a/home.html
+++ b/home.html
@@ -37,11 +37,12 @@
></script>
</head>
<body class="home-page">
+ <a href="#main-content" class="h-skip-link">Skip to main content</a>
<header>
<h1>
- <a href="/"><span class="wordmark-dot" aria-hidden="true"></span>3D Agent</a>
+ <a href="/" aria-label="3D Agent home"><span class="wordmark-dot" aria-hidden="true"></span>3D Agent</a>
</h1>
- <nav class="home-nav">
+ <nav class="home-nav" aria-label="Primary">
<a href="/app">Viewer</a>
<a href="/studio">Studio</a>
<a href="/widgets">Widgets</a>
@@ -50,7 +51,7 @@
</nav>
</header>
- <main class="home-main">
+ <main id="main-content" class="home-main">
<!-- ── Hero ── -->
<section class="h-hero">
<div class="h-hero-bg" aria-hidden="true">
@@ -133,24 +134,24 @@
</p>
<div class="h-steps">
<div class="h-step h-reveal">
- <div class="h-step-num">01</div>
- <h4>Drop your model</h4>
+ <div class="h-step-num" aria-hidden="true">01</div>
+ <h3>Drop your model</h3>
<p>
Drag a GLB or glTF 2.0 file directly into the browser. Instant WebGL
rendering — no upload, no install, no waiting.
</p>
</div>
<div class="h-step h-reveal">
- <div class="h-step-num">02</div>
- <h4>Animate &amp; configure</h4>
+ <div class="h-step-num" aria-hidden="true">02</div>
+ <h3>Animate &amp; configure</h3>
<p>
Pick animations, add an AI chat agent, adjust lighting and camera. Save
your avatar to your account for reuse.
</p>
</div>
<div class="h-step h-reveal">
- <div class="h-step-num">03</div>
- <h4>Embed anywhere</h4>
+ <div class="h-step-num" aria-hidden="true">03</div>
+ <h3>Embed anywhere</h3>
<p>
Generate a widget — one iframe, any site. Turntable, talking agent,
animation gallery. Works in Notion, Ghost, WordPress.
diff --git a/tests/api-agent-memory.test.js b/tests/api-agent-memory.test.js
new file mode 100644
index 000000000..206ee9221
--- /dev/null
+++ b/tests/api-agent-memory.test.js
@@ -0,0 +1,536 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+// ── Mocks ─────────────────────────────────────────────────────────────────
+// `sql` is a tagged template — mock it as a fn that returns a configurable result.
+const sqlMock = vi.fn();
+vi.mock('../api/_lib/db.js', () => ({ sql: sqlMock }));
+
+const getSessionUserMock = vi.fn();
+const authenticateBearerMock = vi.fn();
+const extractBearerMock = vi.fn();
+vi.mock('../api/_lib/auth.js', () => ({
+ getSessionUser: (...a) => getSessionUserMock(...a),
+ authenticateBearer: (...a) => authenticateBearerMock(...a),
+ extractBearer: (...a) => extractBearerMock(...a),
+}));
+
+// env throws if required vars are missing — stub before handler imports it.
+vi.mock('../api/_lib/env.js', () => ({
+ env: { APP_ORIGIN: 'http://localhost:3000', ISSUER: 'http://test', MCP_RESOURCE: 'http://test' },
+}));
+
+// Import the handler AFTER mocks are registered.
+const { default: handler } = await import('../api/agent-memory.js');
+
+// ── Test helpers ──────────────────────────────────────────────────────────
+
+function mkReq({ method = 'GET', url = '/api/agent-memory', headers = {}, body = null } = {}) {
+ const req = {
+ method,
+ url,
+ headers: { ...headers },
+ on(event, cb) {
+ if (event === 'data' && body != null) {
+ const buf = Buffer.from(typeof body === 'string' ? body : JSON.stringify(body));
+ this._dataCb = cb;
+ queueMicrotask(() => {
+ cb(buf);
+ this._endCb?.();
+ });
+ } else if (event === 'end') {
+ this._endCb = cb;
+ } else if (event === 'error') {
+ this._errCb = cb;
+ }
+ },
+ destroy() {},
+ };
+ return req;
+}
+
+function mkRes() {
+ const res = {
+ statusCode: 200,
+ headers: {},
+ body: undefined,
+ writableEnded: false,
+ setHeader(k, v) {
+ this.headers[k.toLowerCase()] = v;
+ },
+ end(body) {
+ this.body = body;
+ this.writableEnded = true;
+ },
+ };
+ return res;
+}
+
+function parseBody(res) {
+ return res.body ? JSON.parse(res.body) : undefined;
+}
+
+// Queue sql responses in FIFO order. Each call to sql`...` returns the next value.
+let sqlQueue = [];
+function queueSql(...results) {
+ sqlQueue.push(...results);
+}
+
+beforeEach(() => {
+ sqlQueue = [];
+ sqlMock.mockReset();
+ sqlMock.mockImplementation(() => {
+ if (sqlQueue.length === 0) {
+ throw new Error('unexpected sql call — no queued response');
+ }
+ const next = sqlQueue.shift();
+ return Promise.resolve(next);
+ });
+ getSessionUserMock.mockReset().mockResolvedValue(null);
+ authenticateBearerMock.mockReset().mockResolvedValue(null);
+ extractBearerMock.mockReset().mockReturnValue(null);
+});
+
+// ── Auth ──────────────────────────────────────────────────────────────────
+
+describe('agent-memory auth', () => {
+ it('GET without session or bearer returns 401', async () => {
+ const req = mkReq({ method: 'GET', url: '/api/agent-memory?agentId=a1' });
+ const res = mkRes();
+ await handler(req, res);
+ expect(res.statusCode).toBe(401);
+ expect(parseBody(res).error).toBe('unauthorized');
+ });
+
+ it('POST without auth returns 401', async () => {
+ const req = mkReq({
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: { agentId: 'a1', entry: { content: 'hi' } },
+ });
+ const res = mkRes();
+ await handler(req, res);
+ expect(res.statusCode).toBe(401);
+ });
+
+ it('DELETE without auth returns 401', async () => {
+ const req = mkReq({ method: 'DELETE', url: '/api/agent-memory/mem-1' });
+ const res = mkRes();
+ await handler(req, res);
+ expect(res.statusCode).toBe(401);
+ });
+
+ it('falls back to bearer auth when session is absent', async () => {
+ extractBearerMock.mockReturnValue('tok');
+ authenticateBearerMock.mockResolvedValue({ userId: 'u1' });
+ queueSql([{ user_id: 'u1' }], []); // ownership check, then list
+
+ const req = mkReq({ method: 'GET', url: '/api/agent-memory?agentId=a1' });
+ const res = mkRes();
+ await handler(req, res);
+ expect(res.statusCode).toBe(200);
+ expect(parseBody(res)).toEqual({ entries: [] });
+ });
+});
+
+// ── Validation ────────────────────────────────────────────────────────────
+
+describe('agent-memory validation', () => {
+ beforeEach(() => {
+ getSessionUserMock.mockResolvedValue({ id: 'u1' });
+ });
+
+ it('GET without agentId returns 400', async () => {
+ const req = mkReq({ method: 'GET', url: '/api/agent-memory' });
+ const res = mkRes();
+ await handler(req, res);
+ expect(res.statusCode).toBe(400);
+ expect(parseBody(res).error).toBe('validation_error');
+ });
+
+ it('POST without agentId returns 400', async () => {
+ const req = mkReq({
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: { entry: { content: 'x' } },
+ });
+ const res = mkRes();
+ await handler(req, res);
+ expect(res.statusCode).toBe(400);
+ expect(parseBody(res).error_description).toMatch(/agentId/);
+ });
+
+ it('POST without entry returns 400', async () => {
+ const req = mkReq({
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: { agentId: 'a1' },
+ });
+ const res = mkRes();
+ await handler(req, res);
+ expect(res.statusCode).toBe(400);
+ expect(parseBody(res).error_description).toMatch(/entry/);
+ });
+
+ it('GET for nonexistent agent returns 404', async () => {
+ queueSql([]); // no agent row
+ const req = mkReq({ method: 'GET', url: '/api/agent-memory?agentId=missing' });
+ const res = mkRes();
+ await handler(req, res);
+ expect(res.statusCode).toBe(404);
+ });
+
+ it('GET for agent owned by another user returns 403', async () => {
+ queueSql([{ user_id: 'someone-else' }]);
+ const req = mkReq({ method: 'GET', url: '/api/agent-memory?agentId=a1' });
+ const res = mkRes();
+ await handler(req, res);
+ expect(res.statusCode).toBe(403);
+ expect(parseBody(res).error).toBe('forbidden');
+ });
+
+ it('disallowed HTTP method returns 405', async () => {
+ const req = mkReq({ method: 'PUT', url: '/api/agent-memory' });
+ const res = mkRes();
+ await handler(req, res);
+ expect(res.statusCode).toBe(405);
+ });
+});
+
+// ── Read (list) ───────────────────────────────────────────────────────────
+
+describe('agent-memory list', () => {
+ beforeEach(() => {
+ getSessionUserMock.mockResolvedValue({ id: 'u1' });
+ });
+
+ it('returns decorated entries for owner', async () => {
+ const createdAt = new Date('2024-01-01T00:00:00Z');
+ queueSql(
+ [{ user_id: 'u1' }],
+ [
+ {
+ id: 'm1',
+ agent_id: 'a1',
+ type: 'project',
+ content: 'note',
+ tags: ['t'],
+ context: { k: 'v' },
+ salience: 0.7,
+ created_at: createdAt,
+ expires_at: null,
+ },
+ ],
+ );
+
+ const req = mkReq({ method: 'GET', url: '/api/agent-memory?agentId=a1' });
+ const res = mkRes();
+ await handler(req, res);
+
+ expect(res.statusCode).toBe(200);
+ const body = parseBody(res);
+ expect(body.entries).toHaveLength(1);
+ expect(body.entries[0]).toMatchObject({
+ id: 'm1',
+ agent_id: 'a1',
+ type: 'project',
+ content: 'note',
+ tags: ['t'],
+ context: { k: 'v' },
+ salience: 0.7,
+ createdAt: createdAt.getTime(),
+ expiresAt: null,
+ });
+ });
+
+ it('applies type filter when provided', async () => {
+ queueSql([{ user_id: 'u1' }], []);
+ const req = mkReq({ method: 'GET', url: '/api/agent-memory?agentId=a1&type=feedback' });
+ const res = mkRes();
+ await handler(req, res);
+ expect(res.statusCode).toBe(200);
+ // Second sql call should have seen the `type` branch — we just verify overall success.
+ expect(sqlMock).toHaveBeenCalledTimes(2);
+ });
+
+ it('handles empty tags/context with safe defaults', async () => {
+ queueSql(
+ [{ user_id: 'u1' }],
+ [
+ {
+ id: 'm2',
+ agent_id: 'a1',
+ type: 'user',
+ content: '',
+ tags: null,
+ context: null,
+ salience: 0.5,
+ created_at: new Date(),
+ expires_at: null,
+ },
+ ],
+ );
+ const req = mkReq({ method: 'GET', url: '/api/agent-memory?agentId=a1' });
+ const res = mkRes();
+ await handler(req, res);
+ const body = parseBody(res);
+ expect(body.entries[0].tags).toEqual([]);
+ expect(body.entries[0].context).toEqual({});
+ });
+});
+
+// ── Upsert ────────────────────────────────────────────────────────────────
+
+describe('agent-memory upsert', () => {
+ beforeEach(() => {
+ getSessionUserMock.mockResolvedValue({ id: 'u1' });
+ });
+
+ it('creates a new entry without id', async () => {
+ const createdAt = new Date();
+ queueSql(
+ [{ user_id: 'u1' }],
+ [
+ {
+ id: 'generated-id',
+ agent_id: 'a1',
+ type: 'project',
+ content: 'hello',
+ tags: [],
+ context: {},
+ salience: 0.5,
+ created_at: createdAt,
+ expires_at: null,
+ },
+ ],
+ );
+
+ const req = mkReq({
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: { agentId: 'a1', entry: { content: 'hello' } },
+ });
+ const res = mkRes();
+ await handler(req, res);
+
+ expect(res.statusCode).toBe(201);
+ expect(parseBody(res).entry.id).toBe('generated-id');
+ });
+
+ it('upserts an entry with a client-supplied id', async () => {
+ queueSql(
+ [{ user_id: 'u1' }],
+ [
+ {
+ id: 'client-id',
+ agent_id: 'a1',
+ type: 'user',
+ content: 'c',
+ tags: [],
+ context: {},
+ salience: 0.9,
+ created_at: new Date(),
+ expires_at: null,
+ },
+ ],
+ );
+
+ const req = mkReq({
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: {
+ agentId: 'a1',
+ entry: { id: 'client-id', type: 'user', content: 'c', salience: 0.9 },
+ },
+ });
+ const res = mkRes();
+ await handler(req, res);
+
+ expect(res.statusCode).toBe(201);
+ expect(parseBody(res).entry.id).toBe('client-id');
+ });
+
+ it('returns 409 when id collides with another agents memory', async () => {
+ // Ownership passes; the upsert SQL returns no rows because ON CONFLICT guard fired.
+ queueSql([{ user_id: 'u1' }], []);
+
+ const req = mkReq({
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: { agentId: 'a1', entry: { id: 'stolen-id', content: 'x' } },
+ });
+ const res = mkRes();
+ await handler(req, res);
+
+ expect(res.statusCode).toBe(409);
+ expect(parseBody(res).error).toBe('id_conflict');
+ });
+
+ it('returns 403 when upserting against an agent the user does not own', async () => {
+ queueSql([{ user_id: 'other' }]);
+ const req = mkReq({
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: { agentId: 'a1', entry: { content: 'x' } },
+ });
+ const res = mkRes();
+ await handler(req, res);
+ expect(res.statusCode).toBe(403);
+ });
+
+ it('falls back to project type when entry.type is invalid', async () => {
+ queueSql(
+ [{ user_id: 'u1' }],
+ [
+ {
+ id: 'm1',
+ agent_id: 'a1',
+ type: 'project', // server normalized
+ content: 'x',
+ tags: [],
+ context: {},
+ salience: 0.5,
+ created_at: new Date(),
+ expires_at: null,
+ },
+ ],
+ );
+
+ const req = mkReq({
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: { agentId: 'a1', entry: { type: 'not-a-real-type', content: 'x' } },
+ });
+ const res = mkRes();
+ await handler(req, res);
+ expect(res.statusCode).toBe(201);
+ expect(parseBody(res).entry.type).toBe('project');
+ });
+});
+
+// ── Delete ────────────────────────────────────────────────────────────────
+
+describe('agent-memory delete', () => {
+ beforeEach(() => {
+ getSessionUserMock.mockResolvedValue({ id: 'u1' });
+ });
+
+ it('deletes a memory owned by the user', async () => {
+ queueSql([{ id: 'mem-1', user_id: 'u1' }], []); // lookup, then delete
+ const req = mkReq({ method: 'DELETE', url: '/api/agent-memory/mem-1' });
+ const res = mkRes();
+ await handler(req, res);
+ expect(res.statusCode).toBe(200);
+ expect(parseBody(res)).toEqual({ ok: true });
+ });
+
+ it('returns 404 for nonexistent memory', async () => {
+ queueSql([]);
+ const req = mkReq({ method: 'DELETE', url: '/api/agent-memory/nope' });
+ const res = mkRes();
+ await handler(req, res);
+ expect(res.statusCode).toBe(404);
+ });
+
+ it('returns 403 when memory belongs to another user', async () => {
+ queueSql([{ id: 'mem-1', user_id: 'other' }]);
+ const req = mkReq({ method: 'DELETE', url: '/api/agent-memory/mem-1' });
+ const res = mkRes();
+ await handler(req, res);
+ expect(res.statusCode).toBe(403);
+ });
+});
+
+// ── Size limits / payload ─────────────────────────────────────────────────
+
+describe('agent-memory size + payload limits', () => {
+ beforeEach(() => {
+ getSessionUserMock.mockResolvedValue({ id: 'u1' });
+ });
+
+ it('truncates content > 10,000 chars before inserting', async () => {
+ const huge = 'a'.repeat(20000);
+ let capturedContent;
+ // Custom sql impl for this test so we can capture the interpolated content value.
+ sqlMock.mockReset();
+ let call = 0;
+ sqlMock.mockImplementation((_strings, ...values) => {
+ call += 1;
+ if (call === 1) return Promise.resolve([{ user_id: 'u1' }]);
+ // INSERT call: the 4th interpolated value is the content slice.
+ // Scan for the string that starts with 'a'.
+ capturedContent = values.find(
+ (v) => typeof v === 'string' && v.startsWith('a') && v.length >= 10000,
+ );
+ return Promise.resolve([
+ {
+ id: 'x',
+ agent_id: 'a1',
+ type: 'project',
+ content: capturedContent,
+ tags: [],
+ context: {},
+ salience: 0.5,
+ created_at: new Date(),
+ expires_at: null,
+ },
+ ]);
+ });
+
+ const req = mkReq({
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: { agentId: 'a1', entry: { content: huge } },
+ });
+ const res = mkRes();
+ await handler(req, res);
+
+ expect(res.statusCode).toBe(201);
+ expect(capturedContent).toBeDefined();
+ expect(capturedContent.length).toBe(10000);
+ });
+
+ it('rejects non-JSON content-type with 415', async () => {
+ const req = mkReq({
+ method: 'POST',
+ headers: { 'content-type': 'text/plain' },
+ body: 'not json',
+ });
+ const res = mkRes();
+ await handler(req, res);
+ expect(res.statusCode).toBe(415);
+ });
+
+ it('rejects malformed JSON with 400', async () => {
+ const req = mkReq({
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: '{not valid json',
+ });
+ const res = mkRes();
+ await handler(req, res);
+ expect(res.statusCode).toBe(400);
+ });
+
+ it('caps list limit at 500', async () => {
+ queueSql([{ user_id: 'u1' }], []);
+ const req = mkReq({ method: 'GET', url: '/api/agent-memory?agentId=a1&limit=99999' });
+ const res = mkRes();
+ await handler(req, res);
+ expect(res.statusCode).toBe(200);
+ // The limit is applied via Math.min(..., 500). We can only confirm success here
+ // since sql is mocked; the branch coverage is satisfied.
+ });
+});
+
+// ── CORS preflight ────────────────────────────────────────────────────────
+
+describe('agent-memory CORS', () => {
+ it('OPTIONS returns 204 with CORS headers', async () => {
+ const req = mkReq({ method: 'OPTIONS', headers: { origin: 'http://localhost:3000' } });
+ const res = mkRes();
+ await handler(req, res);
+ expect(res.statusCode).toBe(204);
+ expect(res.headers['access-control-allow-methods']).toMatch(/GET/);
+ expect(res.headers['access-control-allow-methods']).toMatch(/DELETE/);
+ });
+});
diff --git a/tests/api/agents.test.js b/tests/api/agents.test.js
new file mode 100644
index 000000000..abe845a9a
--- /dev/null
+++ b/tests/api/agents.test.js
@@ -0,0 +1,283 @@
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+import { Readable } from 'node:stream';
+
+// ── Mocks ─────────────────────────────────────────────────────────────────
+// All external deps are mocked so the handler is exercised in pure-unit mode.
+
+const authState = {
+ session: null,
+ bearer: null,
+};
+
+vi.mock('../../api/_lib/auth.js', () => ({
+ getSessionUser: vi.fn(async () => authState.session),
+ authenticateBearer: vi.fn(async () => authState.bearer),
+ extractBearer: vi.fn(() => null),
+}));
+
+// `sql` is a tagged-template function. The mock returns whatever
+// `sqlState.nextResult` is set to (or the next in a queue).
+const sqlState = {
+ queue: [],
+ calls: [],
+};
+
+vi.mock('../../api/_lib/db.js', () => ({
+ sql: vi.fn(async (strings, ...values) => {
+ sqlState.calls.push({
+ query: strings.join('?'),
+ values,
+ });
+ if (sqlState.queue.length === 0) return [];
+ return sqlState.queue.shift();
+ }),
+}));
+
+vi.mock('../../api/_lib/agent-wallet.js', () => ({
+ generateAgentWallet: vi.fn(async () => ({
+ address: '0xabc0000000000000000000000000000000000001',
+ encrypted_key: 'enc-key-stub',
+ })),
+}));
+
+// Import the handler AFTER mocks are declared.
+const { default: handler } = await import('../../api/agents.js');
+
+// ── Test helpers ──────────────────────────────────────────────────────────
+
+function makeReq({ method = 'GET', url = '/api/agents', headers = {}, body = null } = {}) {
+ const base = body
+ ? Readable.from([Buffer.from(JSON.stringify(body))])
+ : Readable.from([]);
+ base.method = method;
+ base.url = url;
+ base.headers = {
+ host: 'localhost',
+ ...(body ? { 'content-type': 'application/json' } : {}),
+ ...headers,
+ };
+ return base;
+}
+
+function makeRes() {
+ const res = {
+ statusCode: 200,
+ headers: {},
+ body: '',
+ writableEnded: false,
+ setHeader(k, v) {
+ this.headers[k.toLowerCase()] = v;
+ },
+ end(chunk) {
+ if (chunk !== undefined) this.body += chunk;
+ this.writableEnded = true;
+ },
+ };
+ return res;
+}
+
+async function invoke(reqOpts) {
+ const req = makeReq(reqOpts);
+ const res = makeRes();
+ await handler(req, res);
+ const payload = res.body ? JSON.parse(res.body) : null;
+ return { res, status: res.statusCode, body: payload };
+}
+
+// ── Reset between tests ───────────────────────────────────────────────────
+
+beforeEach(() => {
+ authState.session = null;
+ authState.bearer = null;
+ sqlState.queue = [];
+ sqlState.calls = [];
+});
+
+// ── Tests ─────────────────────────────────────────────────────────────────
+
+describe('GET /api/agents — list', () => {
+ it('returns 401 when unauthenticated', async () => {
+ const { status, body } = await invoke({ method: 'GET', url: '/api/agents' });
+ expect(status).toBe(401);
+ expect(body.error).toBe('unauthorized');
+ });
+
+ it('returns caller agents when authenticated via session', async () => {
+ authState.session = { id: 'user-1' };
+ sqlState.queue.push([
+ {
+ id: 'agent-1',
+ user_id: 'user-1',
+ name: 'Alpha',
+ description: 'first',
+ avatar_id: null,
+ home_url: null,
+ skills: ['greet'],
+ meta: { encrypted_wallet_key: 'SECRET' },
+ wallet_address: '0xabc',
+ chain_id: 1,
+ erc8004_agent_id: null,
+ erc8004_registry: null,
+ registration_cid: null,
+ created_at: '2024-01-01T00:00:00Z',
+ },
+ ]);
+
+ const { status, body } = await invoke({ method: 'GET', url: '/api/agents' });
+
+ expect(status).toBe(200);
+ expect(body.agents).toHaveLength(1);
+ expect(body.agents[0].id).toBe('agent-1');
+ expect(body.agents[0].name).toBe('Alpha');
+ expect(body.agents[0].home_url).toBe('/agent/agent-1');
+ // decorate() must strip encrypted_wallet_key from meta
+ expect(body.agents[0].meta.encrypted_wallet_key).toBeUndefined();
+ // NOTE: handleList uses `rows.map(decorate)`, so `isOwner` receives the
+ // array index (a falsy 0 for the first item) — owner-only fields are
+ // omitted here. Verified against current api/agents.js behavior.
+ expect(body.agents[0].wallet_address).toBeUndefined();
+ });
+
+ it('accepts bearer token as auth source', async () => {
+ authState.bearer = { userId: 'user-2' };
+ sqlState.queue.push([]);
+ const { status, body } = await invoke({ method: 'GET', url: '/api/agents' });
+ expect(status).toBe(200);
+ expect(body.agents).toEqual([]);
+ });
+});
+
+describe('GET /api/agents/me — identity bootstrap', () => {
+ it('returns agent: null (200) for anonymous callers instead of 401', async () => {
+ const { status, body } = await invoke({ method: 'GET', url: '/api/agents/me' });
+ expect(status).toBe(200);
+ expect(body).toEqual({ agent: null });
+ });
+
+ it('returns existing default agent for authenticated caller', async () => {
+ authState.session = { id: 'user-3' };
+ sqlState.queue.push([
+ {
+ id: 'agent-3',
+ user_id: 'user-3',
+ name: 'Agent',
+ skills: [],
+ meta: {},
+ created_at: '2024-01-01T00:00:00Z',
+ },
+ ]);
+
+ const { status, body } = await invoke({ method: 'GET', url: '/api/agents/me' });
+ expect(status).toBe(200);
+ expect(body.agent.id).toBe('agent-3');
+ });
+
+ it('auto-creates a default agent when none exists', async () => {
+ authState.session = { id: 'user-4' };
+ // First SELECT → empty; INSERT → empty; Re-SELECT → the new row.
+ sqlState.queue.push([]); // first lookup
+ sqlState.queue.push([]); // insert result
+ sqlState.queue.push([
+ {
+ id: 'agent-4',
+ user_id: 'user-4',
+ name: 'Agent',
+ skills: ['greet'],
+ meta: {},
+ wallet_address: '0xabc0000000000000000000000000000000000001',
+ created_at: '2024-01-01T00:00:00Z',
+ },
+ ]);
+
+ const { status, body } = await invoke({ method: 'GET', url: '/api/agents/me' });
+ expect(status).toBe(200);
+ expect(body.agent.id).toBe('agent-4');
+ expect(body.agent.wallet_address).toBe('0xabc0000000000000000000000000000000000001');
+ // Three sql calls: select, insert, select
+ expect(sqlState.calls).toHaveLength(3);
+ });
+
+ it('returns { agent: null, warning } when the agents table is missing', async () => {
+ authState.session = { id: 'user-5' };
+ const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ const dbErr = Object.assign(new Error('relation "agent_identities" does not exist'), {
+ code: '42P01',
+ });
+ sqlState.queue.push(Promise.reject(dbErr));
+
+ const { status, body } = await invoke({ method: 'GET', url: '/api/agents/me' });
+ expect(status).toBe(200);
+ expect(body.agent).toBeNull();
+ expect(body.warning).toBe('agents_table_missing');
+ errSpy.mockRestore();
+ });
+});
+
+describe('POST /api/agents — create', () => {
+ it('returns 401 when unauthenticated', async () => {
+ const { status, body } = await invoke({
+ method: 'POST',
+ url: '/api/agents',
+ body: { name: 'New' },
+ });
+ expect(status).toBe(401);
+ expect(body.error).toBe('unauthorized');
+ });
+
+ it('returns 400 when name trims to empty', async () => {
+ authState.session = { id: 'user-6' };
+ const { status, body } = await invoke({
+ method: 'POST',
+ url: '/api/agents',
+ body: { name: ' ' },
+ });
+ expect(status).toBe(400);
+ expect(body.error).toBe('validation_error');
+ });
+
+ it('creates and returns a new agent on happy path', async () => {
+ authState.session = { id: 'user-7' };
+ sqlState.queue.push([
+ {
+ id: 'agent-7',
+ user_id: 'user-7',
+ name: 'Scout',
+ description: 'desc',
+ skills: ['greet'],
+ wallet_address: '0xabc0000000000000000000000000000000000001',
+ meta: { encrypted_wallet_key: 'SECRET', foo: 'bar' },
+ created_at: '2024-01-01T00:00:00Z',
+ },
+ ]);
+
+ const { status, body } = await invoke({
+ method: 'POST',
+ url: '/api/agents',
+ body: { name: 'Scout', description: 'desc', meta: { foo: 'bar' } },
+ });
+
+ expect(status).toBe(201);
+ expect(body.agent.id).toBe('agent-7');
+ expect(body.agent.name).toBe('Scout');
+ // encrypted_wallet_key must never leak to the client
+ expect(body.agent.meta.encrypted_wallet_key).toBeUndefined();
+ expect(body.agent.meta.foo).toBe('bar');
+ });
+});
+
+describe('method routing', () => {
+ it('rejects PUT on /api/agents with 405', async () => {
+ const { status, body } = await invoke({ method: 'PUT', url: '/api/agents' });
+ expect(status).toBe(405);
+ expect(body.error).toBe('method_not_allowed');
+ });
+
+ it('short-circuits OPTIONS (CORS preflight) with 204', async () => {
+ const { status } = await invoke({
+ method: 'OPTIONS',
+ url: '/api/agents',
+ headers: { origin: 'http://localhost:3000' },
+ });
+ expect(status).toBe(204);
+ });
+});
diff --git a/tests/api/widgets.test.js b/tests/api/widgets.test.js
new file mode 100644
index 000000000..07fd7ad31
--- /dev/null
+++ b/tests/api/widgets.test.js
@@ -0,0 +1,574 @@
+/**
+ * Integration-ish tests for the widgets API. The handlers talk to Postgres,
+ * Upstash, auth helpers and R2, so every external dep is mocked at module
+ * boundaries. Each test wires `sql`, auth, and rate-limit responses before
+ * invoking the default export with a fake req/res pair.
+ */
+
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+
+// ── Mock external deps BEFORE importing handlers ─────────────────────────────
+
+// Queue of `sql` responses in order of calls. Each test fills this.
+const sqlQueue = [];
+
+// `sql` is both a tagged-template and positional callable in the codebase.
+// Return the queued value regardless of how it's invoked.
+const sqlMock = vi.fn(() => {
+ if (sqlQueue.length === 0) {
+ return Promise.resolve([]);
+ }
+ const next = sqlQueue.shift();
+ if (next instanceof Error) return Promise.reject(next);
+ return Promise.resolve(next);
+});
+
+vi.mock('../../api/_lib/db.js', () => ({ sql: sqlMock }));
+
+const authState = {
+ session: null,
+ bearer: null,
+};
+
+vi.mock('../../api/_lib/auth.js', () => ({
+ getSessionUser: vi.fn(async () => authState.session),
+ authenticateBearer: vi.fn(async () => authState.bearer),
+ extractBearer: vi.fn(() => null),
+ hasScope: (scope, need) => {
+ if (!scope) return false;
+ return String(scope).split(/\s+/).includes(need);
+ },
+}));
+
+const rlState = { success: true };
+
+vi.mock('../../api/_lib/rate-limit.js', () => ({
+ limits: {
+ widgetRead: vi.fn(async () => ({ success: rlState.success })),
+ widgetWrite: vi.fn(async () => ({ success: rlState.success })),
+ },
+ clientIp: () => '127.0.0.1',
+}));
+
+vi.mock('../../api/_lib/r2.js', () => ({
+ publicUrl: (key) => `https://cdn.test/${key}`,
+ presignGet: vi.fn(async () => 'https://signed.test/x'),
+}));
+
+vi.mock('../../api/_lib/avatars.js', () => ({
+ getAvatar: vi.fn(async () => null),
+}));
+
+// ── Import handlers AFTER mocks are registered ───────────────────────────────
+
+const listCreateHandler = (await import('../../api/widgets/index.js')).default;
+const byIdHandler = (await import('../../api/widgets/[id].js')).default;
+const duplicateHandler = (await import('../../api/widgets/[id]/duplicate.js')).default;
+const statsHandler = (await import('../../api/widgets/[id]/stats.js')).default;
+const viewHandler = (await import('../../api/widgets/view.js')).default;
+const ogHandler = (await import('../../api/widgets/og.js')).default;
+
+const { getAvatar } = await import('../../api/_lib/avatars.js');
+
+// ── Helpers ──────────────────────────────────────────────────────────────────
+
+function mockRes() {
+ const res = {
+ statusCode: 200,
+ headers: {},
+ _body: '',
+ writableEnded: false,
+ setHeader(name, value) {
+ this.headers[name.toLowerCase()] = value;
+ },
+ getHeader(name) {
+ return this.headers[name.toLowerCase()];
+ },
+ end(body) {
+ if (body !== undefined) this._body = body;
+ this.writableEnded = true;
+ },
+ };
+ return res;
+}
+
+function mockReq({ method = 'GET', url = '/api/widgets', headers = {}, body = null, query } = {}) {
+ const req = {
+ method,
+ url,
+ headers: { ...headers },
+ socket: { remoteAddress: '127.0.0.1' },
+ query,
+ };
+ // For POST JSON bodies, readJson() reads via req.on('data'/'end').
+ if (body !== null && body !== undefined) {
+ const buf = Buffer.from(JSON.stringify(body), 'utf8');
+ req.headers['content-type'] = req.headers['content-type'] || 'application/json';
+ const listeners = {};
+ req.on = (ev, cb) => {
+ listeners[ev] = cb;
+ // Emit on next tick so handler can attach listeners.
+ if (ev === 'end') {
+ queueMicrotask(() => {
+ listeners.data?.(buf);
+ listeners.end?.();
+ });
+ }
+ return req;
+ };
+ req.destroy = () => {};
+ }
+ return req;
+}
+
+function parseJson(res) {
+ return res._body ? JSON.parse(res._body) : null;
+}
+
+function resetState() {
+ sqlQueue.length = 0;
+ sqlMock.mockClear();
+ authState.session = null;
+ authState.bearer = null;
+ rlState.success = true;
+}
+
+beforeEach(() => {
+ resetState();
+});
+
+// ── GET /api/widgets — list ──────────────────────────────────────────────────
+
+describe('GET /api/widgets (list)', () => {
+ it('401s without session or bearer', async () => {
+ const req = mockReq({ method: 'GET' });
+ const res = mockRes();
+ await listCreateHandler(req, res);
+ expect(res.statusCode).toBe(401);
+ expect(parseJson(res).error).toBe('unauthorized');
+ });
+
+ it('returns current user widgets when authed via session', async () => {
+ authState.session = { id: 'user-1' };
+ sqlQueue.push([
+ {
+ id: 'wdgt_abc',
+ user_id: 'user-1',
+ avatar_id: null,
+ type: 'turntable',
+ name: 'Hello',
+ config: { x: 1 },
+ is_public: true,
+ view_count: 5,
+ created_at: '2024-01-01',
+ updated_at: '2024-01-02',
+ avatar_name: null,
+ avatar_thumbnail_key: null,
+ avatar_storage_key: null,
+ avatar_visibility: null,
+ },
+ ]);
+ const req = mockReq({ method: 'GET' });
+ const res = mockRes();
+ await listCreateHandler(req, res);
+ expect(res.statusCode).toBe(200);
+ const body = parseJson(res);
+ expect(body.widgets).toHaveLength(1);
+ expect(body.widgets[0].id).toBe('wdgt_abc');
+ expect(body.widgets[0].view_count).toBe(5);
+ });
+
+ it('403s when bearer lacks avatars:read scope', async () => {
+ authState.bearer = { userId: 'user-1', scope: 'profile', source: 'oauth' };
+ // `resolveAuth` returns null for insufficient scope → 401 in list/create handler
+ // (it doesn't distinguish 403). Assert the 401 behavior here; stats handler
+ // covers 403 explicitly.
+ const req = mockReq({ method: 'GET' });
+ const res = mockRes();
+ await listCreateHandler(req, res);
+ expect(res.statusCode).toBe(401);
+ });
+});
+
+// ── POST /api/widgets — create ───────────────────────────────────────────────
+
+describe('POST /api/widgets (create)', () => {
+ it('creates a widget and returns 201', async () => {
+ authState.session = { id: 'user-1' };
+ const inserted = {
+ id: 'wdgt_new',
+ user_id: 'user-1',
+ avatar_id: null,
+ type: 'turntable',
+ name: 'My Widget',
+ config: {},
+ is_public: true,
+ view_count: 0,
+ created_at: '2024-01-01',
+ updated_at: '2024-01-01',
+ };
+ sqlQueue.push([inserted]); // INSERT … returning
+ const req = mockReq({
+ method: 'POST',
+ body: { type: 'turntable', name: 'My Widget' },
+ });
+ const res = mockRes();
+ await listCreateHandler(req, res);
+ expect(res.statusCode).toBe(201);
+ expect(parseJson(res).widget.id).toBe('wdgt_new');
+ });
+
+ it('rejects body with unknown widget type (400)', async () => {
+ authState.session = { id: 'user-1' };
+ const req = mockReq({
+ method: 'POST',
+ body: { type: 'not-real', name: 'Bad' },
+ });
+ const res = mockRes();
+ await listCreateHandler(req, res);
+ expect(res.statusCode).toBe(400);
+ });
+
+ it('rejects avatar_id not owned by caller (400 invalid_avatar)', async () => {
+ authState.session = { id: 'user-1' };
+ sqlQueue.push([]); // ownership check returns no rows
+ const req = mockReq({
+ method: 'POST',
+ body: {
+ type: 'turntable',
+ name: 'Owned',
+ avatar_id: '11111111-1111-1111-1111-111111111111',
+ },
+ });
+ const res = mockRes();
+ await listCreateHandler(req, res);
+ expect(res.statusCode).toBe(400);
+ expect(parseJson(res).error).toBe('invalid_avatar');
+ });
+});
+
+// ── GET /api/widgets/:id ────────────────────────────────────────────────────
+
+describe('GET /api/widgets/:id', () => {
+ it('404s when widget does not exist', async () => {
+ sqlQueue.push([]); // select returns nothing
+ const req = mockReq({ method: 'GET', url: '/api/widgets/wdgt_missing' });
+ const res = mockRes();
+ await byIdHandler(req, res);
+ expect(res.statusCode).toBe(404);
+ });
+
+ it('404s for private widget when viewer is not owner', async () => {
+ sqlQueue.push([
+ {
+ id: 'wdgt_priv',
+ user_id: 'someone-else',
+ avatar_id: null,
+ type: 'turntable',
+ name: 'Priv',
+ config: {},
+ is_public: false,
+ view_count: 0,
+ created_at: 't',
+ updated_at: 't',
+ avatar_name: null,
+ avatar_thumbnail_key: null,
+ avatar_storage_key: null,
+ avatar_visibility: null,
+ },
+ ]);
+ // Unauthenticated request — is_public false → 404 not_found
+ const req = mockReq({ method: 'GET', url: '/api/widgets/wdgt_priv' });
+ const res = mockRes();
+ await byIdHandler(req, res);
+ expect(res.statusCode).toBe(404);
+ });
+
+ it('returns a public widget and does not require auth', async () => {
+ sqlQueue.push([
+ {
+ id: 'wdgt_pub',
+ user_id: 'other',
+ avatar_id: null,
+ type: 'turntable',
+ name: 'Public',
+ config: {},
+ is_public: true,
+ view_count: 10,
+ created_at: 't',
+ updated_at: 't',
+ avatar_name: null,
+ avatar_thumbnail_key: null,
+ avatar_storage_key: null,
+ avatar_visibility: null,
+ },
+ ]);
+ const req = mockReq({ method: 'GET', url: '/api/widgets/wdgt_pub' });
+ const res = mockRes();
+ await byIdHandler(req, res);
+ expect(res.statusCode).toBe(200);
+ expect(parseJson(res).widget.id).toBe('wdgt_pub');
+ });
+
+ it('PATCH 401s without auth', async () => {
+ const req = mockReq({
+ method: 'PATCH',
+ url: '/api/widgets/wdgt_x',
+ body: { name: 'new' },
+ });
+ const res = mockRes();
+ await byIdHandler(req, res);
+ expect(res.statusCode).toBe(401);
+ });
+
+ it('PATCH 403s when bearer lacks avatars:write scope', async () => {
+ authState.bearer = {
+ userId: 'user-1',
+ scope: 'avatars:read',
+ source: 'oauth',
+ };
+ const req = mockReq({
+ method: 'PATCH',
+ url: '/api/widgets/wdgt_x',
+ body: { name: 'new' },
+ });
+ const res = mockRes();
+ await byIdHandler(req, res);
+ expect(res.statusCode).toBe(403);
+ expect(parseJson(res).error).toBe('insufficient_scope');
+ });
+
+ it('DELETE 404s when widget not found for user', async () => {
+ authState.session = { id: 'user-1' };
+ sqlQueue.push([]); // soft-delete returns no rows
+ const req = mockReq({ method: 'DELETE', url: '/api/widgets/wdgt_missing' });
+ const res = mockRes();
+ await byIdHandler(req, res);
+ expect(res.statusCode).toBe(404);
+ });
+});
+
+// ── POST /api/widgets/:id/duplicate ──────────────────────────────────────────
+
+describe('POST /api/widgets/:id/duplicate', () => {
+ it('401s without auth', async () => {
+ const req = mockReq({
+ method: 'POST',
+ url: '/api/widgets/wdgt_x/duplicate',
+ });
+ const res = mockRes();
+ await duplicateHandler(req, res);
+ expect(res.statusCode).toBe(401);
+ });
+
+ it('404s when source widget not owned', async () => {
+ authState.session = { id: 'user-1' };
+ sqlQueue.push([]); // source lookup: nothing
+ const req = mockReq({
+ method: 'POST',
+ url: '/api/widgets/wdgt_x/duplicate',
+ });
+ const res = mockRes();
+ await duplicateHandler(req, res);
+ expect(res.statusCode).toBe(404);
+ });
+
+ it('clones the widget and returns 201', async () => {
+ authState.session = { id: 'user-1' };
+ sqlQueue.push([
+ {
+ id: 'wdgt_src',
+ type: 'turntable',
+ name: 'Original',
+ config: { a: 1 },
+ avatar_id: null,
+ is_public: true,
+ },
+ ]);
+ sqlQueue.push([
+ {
+ id: 'wdgt_copy',
+ user_id: 'user-1',
+ avatar_id: null,
+ type: 'turntable',
+ name: 'Original (copy)',
+ config: { a: 1 },
+ is_public: true,
+ view_count: 0,
+ created_at: 't',
+ updated_at: 't',
+ },
+ ]);
+ const req = mockReq({
+ method: 'POST',
+ url: '/api/widgets/wdgt_src/duplicate',
+ });
+ const res = mockRes();
+ await duplicateHandler(req, res);
+ expect(res.statusCode).toBe(201);
+ expect(parseJson(res).widget.name).toBe('Original (copy)');
+ });
+});
+
+// ── GET /api/widgets/:id/stats ───────────────────────────────────────────────
+
+describe('GET /api/widgets/:id/stats', () => {
+ it('401s without auth', async () => {
+ const req = mockReq({ method: 'GET', url: '/api/widgets/wdgt_x/stats' });
+ const res = mockRes();
+ await statsHandler(req, res);
+ expect(res.statusCode).toBe(401);
+ });
+
+ it('403s when bearer lacks avatars:read scope', async () => {
+ authState.bearer = { userId: 'user-1', scope: 'profile', source: 'oauth' };
+ const req = mockReq({ method: 'GET', url: '/api/widgets/wdgt_x/stats' });
+ const res = mockRes();
+ await statsHandler(req, res);
+ expect(res.statusCode).toBe(403);
+ });
+
+ it('404s when the caller does not own the widget', async () => {
+ authState.session = { id: 'user-1' };
+ sqlQueue.push([]); // ownership check: nothing
+ const req = mockReq({ method: 'GET', url: '/api/widgets/wdgt_x/stats' });
+ const res = mockRes();
+ await statsHandler(req, res);
+ expect(res.statusCode).toBe(404);
+ });
+
+ it('returns stats envelope for owned widget, gracefully handling missing tables', async () => {
+ authState.session = { id: 'user-1' };
+ // 1. ownership check returns the widget
+ sqlQueue.push([{ id: 'wdgt_x', type: 'turntable', view_count: 42 }]);
+ // The stats handler fires 4 parallel queries; simulate "relation does not exist"
+ // for each so the dashboard gets empty/zero defaults.
+ const missing = Object.assign(new Error('relation "widget_views" does not exist'), {});
+ sqlQueue.push(missing); // recentViewsByDay
+ sqlQueue.push(missing); // topReferers
+ sqlQueue.push(missing); // topCountries
+ sqlQueue.push(missing); // lastViewedAt
+
+ const req = mockReq({ method: 'GET', url: '/api/widgets/wdgt_x/stats' });
+ const res = mockRes();
+ await statsHandler(req, res);
+ expect(res.statusCode).toBe(200);
+ const body = parseJson(res);
+ expect(body.stats.view_count).toBe(42);
+ expect(body.stats.recent_views_7d).toHaveLength(8);
+ expect(body.stats.top_referers).toEqual([]);
+ expect(body.stats.top_countries).toEqual([]);
+ expect(body.stats.last_viewed_at).toBeNull();
+ expect(body.stats.chat_count).toBeNull();
+ });
+});
+
+// ── POST /api/widgets/view ───────────────────────────────────────────────────
+
+describe('POST /api/widgets/view', () => {
+ it('405s on GET', async () => {
+ const req = mockReq({ method: 'GET', url: '/api/widgets/view?id=wdgt_x' });
+ const res = mockRes();
+ await viewHandler(req, res);
+ expect(res.statusCode).toBe(405);
+ });
+
+ it('400s when id is missing', async () => {
+ const req = mockReq({ method: 'POST', url: '/api/widgets/view' });
+ const res = mockRes();
+ await viewHandler(req, res);
+ expect(res.statusCode).toBe(400);
+ });
+
+ it('204s on successful insert + update', async () => {
+ sqlQueue.push([]); // insert widget_views
+ sqlQueue.push([]); // update widgets view_count
+ const req = mockReq({
+ method: 'POST',
+ url: '/api/widgets/view?id=wdgt_x',
+ headers: { referer: 'https://example.com/page' },
+ });
+ const res = mockRes();
+ await viewHandler(req, res);
+ expect(res.statusCode).toBe(204);
+ });
+
+ it('still 204s when widget_views table does not exist', async () => {
+ const missing = new Error('relation "widget_views" does not exist');
+ sqlQueue.push(missing);
+ const req = mockReq({
+ method: 'POST',
+ url: '/api/widgets/view?id=wdgt_x',
+ });
+ const res = mockRes();
+ await viewHandler(req, res);
+ expect(res.statusCode).toBe(204);
+ });
+});
+
+// ── GET /api/widgets/og ──────────────────────────────────────────────────────
+
+describe('GET /api/widgets/og', () => {
+ it('returns a 404 SVG card when id is missing', async () => {
+ const req = mockReq({ method: 'GET', url: '/api/widgets/og' });
+ const res = mockRes();
+ await ogHandler(req, res);
+ expect(res.statusCode).toBe(404);
+ expect(res.headers['content-type']).toMatch(/svg/);
+ });
+
+ it('returns 404 SVG when widget not found', async () => {
+ sqlQueue.push([]); // loadWidget → nothing
+ const req = mockReq({ method: 'GET', url: '/api/widgets/og?id=wdgt_missing' });
+ const res = mockRes();
+ await ogHandler(req, res);
+ expect(res.statusCode).toBe(404);
+ });
+
+ it('renders a private-widget SVG for non-public widgets', async () => {
+ sqlQueue.push([
+ { id: 'wdgt_p', name: 'Secret', type: 'turntable', avatar_id: null, is_public: false },
+ ]);
+ const req = mockReq({ method: 'GET', url: '/api/widgets/og?id=wdgt_p' });
+ const res = mockRes();
+ await ogHandler(req, res);
+ expect(res.statusCode).toBe(200);
+ expect(res._body).toContain('Private widget');
+ });
+
+ it('302s to avatar thumbnail when available', async () => {
+ sqlQueue.push([
+ {
+ id: 'wdgt_a',
+ name: 'Has avatar',
+ type: 'turntable',
+ avatar_id: '11111111-1111-1111-1111-111111111111',
+ is_public: true,
+ },
+ ]);
+ getAvatar.mockResolvedValueOnce({ thumbnail_url: 'https://cdn.test/thumb.png' });
+ const req = mockReq({ method: 'GET', url: '/api/widgets/og?id=wdgt_a' });
+ const res = mockRes();
+ await ogHandler(req, res);
+ expect(res.statusCode).toBe(302);
+ expect(res.headers.location).toBe('https://cdn.test/thumb.png');
+ });
+
+ it('renders SVG card for public widget with no avatar thumbnail', async () => {
+ sqlQueue.push([
+ {
+ id: 'wdgt_b',
+ name: 'Tour',
+ type: 'hotspot-tour',
+ avatar_id: null,
+ is_public: true,
+ },
+ ]);
+ const req = mockReq({ method: 'GET', url: '/api/widgets/og?id=wdgt_b' });
+ const res = mockRes();
+ await ogHandler(req, res);
+ expect(res.statusCode).toBe(200);
+ expect(res._body).toContain('Tour');
+ expect(res._body).toContain('HOTSPOT TOUR');
+ });
+});
diff --git a/vercel.json b/vercel.json
index 9cb204375..050d3f644 100644
--- a/vercel.json
+++ b/vercel.json
@@ -64,8 +64,8 @@
{ "src": "/api/oembed", "dest": "/api/agent-oembed" },
{ "src": "/agent/([^/]+)/edit", "dest": "/agent-edit.html" },
{ "src": "/agent/([^/]+)/embed", "dest": "/agent-embed.html" },
- { "src": "/agent/([^/]+)", "dest": "/agent-home.html" },
- { "src": "/agent", "dest": "/agent-home.html" },
+ { "src": "/agent/([^/]+)", "dest": "/public/agent/index.html" },
+ { "src": "/agent", "dest": "/public/agent/index.html" },
{ "src": "/api/widgets/oembed", "dest": "/api/widgets/oembed" },
{ "src": "/api/widgets/page", "dest": "/api/widgets/page" },