Skip to content

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

feat(tts+status): free NVIDIA NIM Riva TTS lane, NIM reranker, first-party uptime monitor + public status page

nirholasb4c6f8e3f20b
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 123924d24..26300656c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,6 +6,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
## 2026-06-11
+- **Status** (`/status`) — Live operational status and 90-day uptime history for the platform, API, and x402 surfaces — probed every 5 minutes.
- **Accurate uptime on the x402 Provider Hub** — The payment directory was counting every unpaid x402 discovery request (the protocol's standard 402 challenge) as a failed call, dragging three.ws endpoint success rates down even when every endpoint was healthy. Telemetry now reports only real payment attempts, so the published uptime reflects actual service health. `[fix, infra]`
- **Agents dashboard renders reliably again** — Fixed a crash that could blank out the agent list on your dashboard while it built each agent's card. The page now renders every agent — on-chain, Pump.fun, and off-chain — without errors, including the Deploy onchain and registry links. (`/dashboard/agents`) `[fix]`
- **Avatar pages back online after image-engine outage** — Fetching an individual avatar was failing with a server error, which also broke the walking avatar on the home page. The image-processing engine the avatar dress-up baker relies on failed to load in production and took the whole endpoint down with it. Avatar lookups now load independently of the baker, and the missing image libraries ship with the deployment, so avatar pages and the home hero are back. `[fix, infra]`
@@ -17,6 +18,8 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **Hardened the explore feed and marketplace pricing against bad requests** — The explore discovery feed and marketplace asset-pricing lookup now reject malformed query parameters with a clear 400 instead of failing with a server error. A non-numeric page size on explore, or a malformed asset id on a price lookup, no longer surfaces a 500 — the endpoints validate input up front and respond cleanly. (`/explore`) `[fix]`
- **Live $THREE market data, longer trade streams, and tutor session fixes** — $THREE market stats (price, holders, liquidity) are flowing again from our primary data source — a missing request header had been silently failing it to backups for days. Live trade streams no longer cut out after 30 seconds; they now run their full duration. The Pay-As-You-Learn Tutor no longer errors when resuming a session — running tabs persist correctly across questions — and Fact Checker results are cached properly so repeat checks of the same claim return instantly. `[fix, improvement]`
- **MetaMask Agent Wallet skills for every agent** — Two new skills in the marketplace under the new Wallet category: MetaMask Agent Wallet and MetaMask Agent Workflows. Install them on any agent to let it check balances, transfer tokens, swap, bridge across chains, trade perps and prediction markets, and manage Aave positions through MetaMask's mm CLI — each user signs in with their own MetaMask Agent Wallet, so keys stay with you, never with three.ws. Platform chat agents pick the skills up automatically. (`/skills`) `[feature]`
+- **Pluggable memory backends + a portable snapshot format for the agent SDK** — Agent developers can now plug a custom memory backend — a vector database, an episodic event log, or their own API — behind a named mode with Memory.registerBackend, no forking required. All built-in modes (local, remote, ipfs, encrypted-ipfs, none) are unchanged. We also formalized a memory/0.1 snapshot contract: memory.snapshot() returns a JSON-safe object and Memory.fromSnapshot() rehydrates it, so embedded agent widgets keep their memory across page reloads. Documented in the Memory spec, agent manifest, and README. `[sdk, docs]`
+- **Public status page with live uptime monitoring** — three.ws now monitors its own critical surfaces — the website, platform API, explore feed, x402 paid-API discovery, and the 3D viewer — every 5 minutes from outside our infrastructure, and publishes the results at three.ws/status: live operational state, response times, and a 90-day uptime history per service. A machine-readable JSON feed is available at /api/status for agents and integrators. Browser errors on any page are now also collected first-party, so problems reach the team before reports do. (`/status`) `[feature, infra]`
- **Scheduled jobs restored after dependency outage** — Every background job — pump.fun monitoring, coin payouts, club payouts, scheduled X posts, DCA runs, subscription billing, and the rest — had been failing since a recent dependency upgrade left a required Solana staking library out of the deployment. The missing library now ships with every deploy, and the image-processing engine behind avatar baking was rolled back to its proven version so it loads reliably in production. All scheduled jobs run again. `[fix, infra]`
- **Sharper search and richer link previews across the blog** — Every blog post now ships full social-card images and structured data, so links to three.ws unfurl with a proper preview image on X, Slack, Discord and LinkedIn, and show up as rich articles with breadcrumbs in Google. All 25 posts are now listed in the sitemap (previously only four were), making the full archive discoverable in search. A new build step keeps page titles, descriptions and previews in sync automatically so nothing ships without them. (`/blog`) `[improvement]`
- **Text-to-3D and image-to-3D generation restored** — Fixed two provider regressions that blocked Forge generation: model submissions now pin the latest published model version automatically, and the text-to-image step falls back to a healthy provider instead of failing when the preferred one is misconfigured. (`/forge`) `[fix]`
diff --git a/README.md b/README.md
index e39f8c1fd..c719ce9c6 100644
--- a/README.md
+++ b/README.md
@@ -1045,12 +1045,52 @@ A `MEMORY.md` index file is auto-maintained. At the start of each conversation t
**Storage modes:**
- `local` — stored in the browser's local storage (default for development)
+- `remote` — persisted per-agent via `/api/agent-memory` (owner-only)
- `ipfs` — pinned to IPFS via Pinata or Web3.Storage
- `encrypted-ipfs` — encrypted before pinning (user holds the key)
- `none` — stateless, no memory between sessions
Memory types (`user`, `feedback`, `project`, `reference`) follow the same taxonomy used by this codebase's own Claude guidelines.
+#### Plugging a custom memory backend
+
+You don't fork `Memory` to add a vector store or episodic log — register a backend and select it by name. Built-in modes are unchanged; your mode is just another option.
+
+```js
+import { Memory } from 'https://three.ws/agent-3d/latest/agent-3d.js';
+
+Memory.registerBackend('vector', {
+ async load({ namespace }) {
+ const rows = await myVectorStore.fetchAll(namespace);
+ return { files: Object.fromEntries(rows.map((r) => [r.filename, r.markdown])) };
+ },
+ async persist(memory) { // after every write()/note()
+ await myVectorStore.replace(memory.namespace, [...memory.files]);
+ await myEpisodicLog.replace(memory.namespace, memory.timeline);
+ },
+ async recall(query, memory, { limit = 5 } = {}) { // real semantic search
+ const m = await myVectorStore.search(memory.namespace, query, limit);
+ return m.map((x) => ({ file: x.filename, meta: x.meta, body: x.body, score: x.score }));
+ },
+});
+```
+
+```html
+<agent-3d src="agent://…" memory="vector"></agent-3d>
+```
+
+Only `load` is required; `persist` makes it durable, `recall` makes search semantic (it falls back to substring matching if it throws). To swap *only* the ranker while keeping built-in storage, point `manifest.json → memory.retriever` at a skill instead. Full reference: [specs/MEMORY_SPEC.md → Custom backends](specs/MEMORY_SPEC.md).
+
+#### Memory snapshot contract
+
+`memory.snapshot()` returns a synchronous, JSON-safe `memory/0.1` object so embedded widgets can serialize/deserialize state across page reloads; `Memory.fromSnapshot(snap, { mode, namespace })` rehydrates it (rebuilding the index if absent).
+
+```js
+sessionStorage.setItem('agent-mem', JSON.stringify(agent.memory.snapshot()));
+// …after reload:
+const restored = Memory.fromSnapshot(JSON.parse(sessionStorage.getItem('agent-mem')));
+```
+
---
## Web Component & Embedding
diff --git a/api/_lib/embeddings.js b/api/_lib/embeddings.js
index eb8281f88..3394d6cb7 100644
--- a/api/_lib/embeddings.js
+++ b/api/_lib/embeddings.js
@@ -1,65 +1,261 @@
-// OpenAI text-embedding-3-small @ 256 dimensions (Matryoshka truncation).
-// 12× cheaper storage than the full 3072-dim model with ~98% of recall, which
-// is the right tradeoff for grounding a small set of widget knowledge docs
-// where chunk counts stay in the low thousands.
+// Multi-provider text embeddings with vector-space tagging.
//
-// We keep this here (rather than reaching for an SDK) so the talking-agent
-// chat path remains a single zero-dep fetch call — matching the existing
-// pattern in api/widgets/[id]/[action].js.
+// Provider policy (free-first, per the platform LLM policy): NVIDIA NIM's
+// nv-embedqa-e5-v5 (1024-dim, free with one nvapi key) is the default for new
+// ingests; OpenAI text-embedding-3-small @ 256 dims (Matryoshka truncation)
+// is the paid backstop and the space every pre-tagging row lives in.
+//
+// THE TRAP this module exists to prevent: embeddings from different models are
+// different vector spaces. A query embedded with model A compared against
+// passages embedded with model B returns garbage similarity scores that look
+// plausible. So every embed call here names its embedder explicitly via a
+// `tag` (model id + dimension, e.g. "nvidia/nv-embedqa-e5-v5@1024"), callers
+// persist that tag next to every stored vector, and query-time code must
+// resolve the stored tag back through this module — never pick a provider ad
+// hoc. Untagged legacy rows are OpenAI text-embedding-3-small@256 by
+// definition (`LEGACY_EMBED_TAG`): that was the only embedder before tagging
+// shipped.
+//
+// We keep this zero-dep (plain fetch, no SDK) so the talking-agent chat path
+// stays a single cheap import — matching api/widgets/[id]/[action].js.
+
+const NIM_EMBED_URL = 'https://integrate.api.nvidia.com/v1/embeddings';
+const OPENAI_EMBED_URL = 'https://api.openai.com/v1/embeddings';
+
+// NIM nv-embedqa-e5-v5 hard-caps inputs at 512 tokens (probed: longer inputs
+// 400 with "exceeds maximum allowed token size"). The chunker already targets
+// ≤512 estimated tokens (4 chars/token), but dense text (code, CJK) can run
+// more tokens per char — so the NIM lane retries an over-length 400 once with
+// inputs truncated to a conservative 3 chars/token budget.
+const NIM_MAX_TOKENS = 512;
+const NIM_SAFE_CHARS = NIM_MAX_TOKENS * 3;
-const EMBED_URL = 'https://api.openai.com/v1/embeddings';
-const EMBED_MODEL = 'text-embedding-3-small';
-const EMBED_DIMS = 256;
+export const NIM_EMBED_TAG = 'nvidia/nv-embedqa-e5-v5@1024';
+export const OPENAI_EMBED_TAG = 'text-embedding-3-small@256';
+// Rows written before embedder tagging existed were embedded with OpenAI
+// text-embedding-3-small @ 256 — encode that assumption in exactly one place.
+export const LEGACY_EMBED_TAG = OPENAI_EMBED_TAG;
+
+const EMBEDDERS = Object.freeze({
+ [NIM_EMBED_TAG]: Object.freeze({
+ tag: NIM_EMBED_TAG,
+ provider: 'nim',
+ model: 'nvidia/nv-embedqa-e5-v5',
+ dim: 1024,
+ free: true,
+ configured: () => !!process.env.NVIDIA_API_KEY,
+ }),
+ [OPENAI_EMBED_TAG]: Object.freeze({
+ tag: OPENAI_EMBED_TAG,
+ provider: 'openai',
+ model: 'text-embedding-3-small',
+ dim: 256,
+ free: false,
+ configured: () => !!process.env.OPENAI_API_KEY,
+ }),
+});
+
+// Free lane first, paid backstop last.
+const INGEST_PREFERENCE = Object.freeze([NIM_EMBED_TAG, OPENAI_EMBED_TAG]);
+
+/** True when at least one embedding provider can actually serve. */
export function embeddingsConfigured() {
- return !!process.env.OPENAI_API_KEY;
+ return INGEST_PREFERENCE.some((tag) => EMBEDDERS[tag].configured());
+}
+
+/**
+ * The embedder tag new document sets should be ingested with — free NIM when
+ * the key is present, OpenAI otherwise, null when nothing is configured.
+ */
+export function defaultIngestEmbedderTag() {
+ for (const tag of INGEST_PREFERENCE) {
+ if (EMBEDDERS[tag].configured()) return tag;
+ }
+ return null;
+}
+
+/**
+ * Normalize a stored embedder tag (null/'' = legacy OpenAI) to a known tag,
+ * or null when the tag names an embedder this build doesn't know — an unknown
+ * space can never be queried, only re-embedded.
+ */
+export function resolveEmbedderTag(storedTag) {
+ const tag = storedTag || LEGACY_EMBED_TAG;
+ return EMBEDDERS[tag] ? tag : null;
+}
+
+/** Embedder metadata ({tag, provider, model, dim, free}) or null if unknown. */
+export function embedderInfo(storedTag) {
+ const tag = resolveEmbedderTag(storedTag);
+ return tag ? EMBEDDERS[tag] : null;
+}
+
+/** True when the provider behind `storedTag`'s space can serve right now. */
+export function embedderConfigured(storedTag) {
+ const tag = resolveEmbedderTag(storedTag);
+ return !!tag && EMBEDDERS[tag].configured();
}
/**
- * Embed an array of strings. Returns Float64Array[].
- * Throws if OPENAI_API_KEY isn't configured or the API errors.
+ * Embed `texts` in the vector space named by `tag`.
+ * `inputType` is 'passage' for corpus chunks at ingest and 'query' for search
+ * strings — NIM's retrieval models are asymmetric and REQUIRE the distinction;
+ * the OpenAI lane ignores it. Returns Float64Array[] aligned with `texts`.
+ * Throws { code: 'unknown_embedder' | 'no_embedder' | 'embedder_error' }.
*/
-export async function embed(texts) {
- const apiKey = process.env.OPENAI_API_KEY;
- if (!apiKey)
- throw Object.assign(new Error('OPENAI_API_KEY not configured'), { code: 'no_embedder' });
+export async function embedWith(tag, texts, inputType) {
+ const embedder = EMBEDDERS[resolveEmbedderTag(tag) || ''];
+ if (!embedder) {
+ throw Object.assign(new Error(`unknown embedder tag: ${tag}`), {
+ code: 'unknown_embedder',
+ });
+ }
+ if (!embedder.configured()) {
+ throw Object.assign(new Error(`${embedder.provider} embedder not configured (${embedder.tag})`), {
+ code: 'no_embedder',
+ });
+ }
+ if (inputType !== 'passage' && inputType !== 'query') {
+ throw Object.assign(new Error(`inputType must be 'passage' or 'query', got: ${inputType}`), {
+ code: 'embedder_error',
+ });
+ }
if (!texts.length) return [];
- const upstream = await fetch(EMBED_URL, {
+ return embedder.provider === 'nim'
+ ? embedNim(embedder, texts, inputType)
+ : embedOpenAi(embedder, texts);
+}
+
+/** Convenience: embed corpus chunks at ingest time. */
+export function embedPassages(tag, texts) {
+ return embedWith(tag, texts, 'passage');
+}
+
+/** Convenience: embed one search string; resolves to a single Float64Array. */
+export async function embedQuery(tag, text) {
+ const [vec] = await embedWith(tag, [text], 'query');
+ return vec;
+}
+
+async function embedNim(embedder, texts, inputType, { truncated = false } = {}) {
+ const upstream = await fetch(NIM_EMBED_URL, {
method: 'POST',
headers: {
- Authorization: `Bearer ${apiKey}`,
+ Authorization: `Bearer ${process.env.NVIDIA_API_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
- model: EMBED_MODEL,
+ model: embedder.model,
input: texts,
- dimensions: EMBED_DIMS,
+ input_type: inputType,
}),
+ signal: AbortSignal.timeout(30_000),
});
if (!upstream.ok) {
const body = await upstream.text().catch(() => '');
- throw Object.assign(new Error(`embedding api ${upstream.status}: ${body.slice(0, 200)}`), {
+ // Over-length input: retry once with every input clamped to a budget that
+ // cannot exceed the 512-token cap. Better to truncate one outlier chunk
+ // than to fail a whole ingest batch.
+ if (upstream.status === 400 && /maximum allowed token size/i.test(body) && !truncated) {
+ return embedNim(embedder, texts.map((t) => t.slice(0, NIM_SAFE_CHARS)), inputType, {
+ truncated: true,
+ });
+ }
+ throw upstreamError('nim', upstream.status, body);
+ }
+ return parseEmbeddings(await upstream.json(), texts.length, 'nim');
+}
+
+async function embedOpenAi(embedder, texts) {
+ const upstream = await fetch(OPENAI_EMBED_URL, {
+ method: 'POST',
+ headers: {
+ Authorization: `Bearer ${process.env.OPENAI_API_KEY}`,
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify({
+ model: embedder.model,
+ input: texts,
+ dimensions: embedder.dim,
+ }),
+ signal: AbortSignal.timeout(30_000),
+ });
+ if (!upstream.ok) {
+ const body = await upstream.text().catch(() => '');
+ throw upstreamError('openai', upstream.status, body);
+ }
+ return parseEmbeddings(await upstream.json(), texts.length, 'openai');
+}
+
+function parseEmbeddings(data, expected, provider) {
+ const rows = (data?.data || []).sort((a, b) => a.index - b.index);
+ if (rows.length !== expected || rows.some((r) => !Array.isArray(r.embedding))) {
+ throw Object.assign(new Error(`${provider} embedding response shape mismatch`), {
code: 'embedder_error',
- status: upstream.status,
});
}
- const data = await upstream.json();
- return (data.data || [])
- .sort((a, b) => a.index - b.index)
- .map((row) => Float64Array.from(row.embedding));
+ return rows.map((row) => Float64Array.from(row.embedding));
+}
+
+function upstreamError(provider, status, body) {
+ return Object.assign(new Error(`${provider} embedding api ${status}: ${body.slice(0, 200)}`), {
+ code: 'embedder_error',
+ status,
+ });
+}
+
+/**
+ * Score stored vector rows against a search string without ever crossing
+ * vector spaces. Rows are grouped by their `embedder` tag (untagged legacy
+ * rows are OpenAI — LEGACY_EMBED_TAG), the query is embedded once per space
+ * whose provider is configured, and cosine runs strictly within each space.
+ * Rows in a space no configured provider can serve are counted in
+ * `needsReembed` — reported, never silently compared.
+ *
+ * @param {Array<{embedder?: string|null, embedding: number[]|{values:number[]}}>} rows
+ * @param {string} query
+ * @returns {Promise<{scored: Array<object & {embedder: string, score: number}>,
+ * needsReembed: Array<{embedder: string, chunks: number}>}>}
+ */
+export async function scoreRowsBySpace(rows, query) {
+ const bySpace = new Map();
+ for (const r of rows) {
+ const tag = r.embedder || LEGACY_EMBED_TAG;
+ if (!bySpace.has(tag)) bySpace.set(tag, []);
+ bySpace.get(tag).push(r);
+ }
+
+ const scored = [];
+ const needsReembed = [];
+ for (const [tag, group] of bySpace) {
+ if (!embedderConfigured(tag)) {
+ needsReembed.push({ embedder: tag, chunks: group.length });
+ continue;
+ }
+ const queryEmbedding = await embedQuery(tag, query);
+ for (const r of group) {
+ const e = Array.isArray(r.embedding) ? r.embedding : r.embedding?.values || [];
+ scored.push({ ...r, embedder: tag, score: cosine(queryEmbedding, e) });
+ }
+ }
+ return { scored, needsReembed };
}
/**
* Cosine similarity between two equal-length numeric arrays. Inputs come from
- * embed() (Float64Array) or from the DB (plain Array via JSONB) — both work.
+ * embedWith() (Float64Array) or from the DB (plain Array via JSONB) — both
+ * work. Mismatched lengths score 0: vectors of different dimensionality are
+ * by definition different spaces, and comparing a shared prefix would be
+ * exactly the silent cross-space garbage this module is built to prevent.
*/
export function cosine(a, b) {
- const n = Math.min(a.length, b.length);
+ if (!a || !b || a.length !== b.length) return 0;
let dot = 0;
let na = 0;
let nb = 0;
- for (let i = 0; i < n; i++) {
+ for (let i = 0; i < a.length; i++) {
const x = a[i];
const y = b[i];
dot += x * y;
diff --git a/api/_lib/http.js b/api/_lib/http.js
index 34a701a10..de4b0dc84 100644
--- a/api/_lib/http.js
+++ b/api/_lib/http.js
@@ -3,6 +3,7 @@
import { webcrypto } from 'node:crypto';
import { env } from './env.js';
import { captureException } from './sentry.js';
+import { sendOpsAlert } from './alerts.js';
import { instrument as zauthInstrument, drain as zauthDrain } from './zauth.js';
export function json(res, status, body, headers = {}) {
@@ -49,8 +50,13 @@ export function serverError(res, status, code, err, extra = {}) {
console.error(`[server-error ${ref}] ${code} (${status}): ${detail}`);
try {
captureException(err instanceof Error ? err : new Error(detail), { ref, code, status });
+ // Fire-and-forget like captureException; deduped per error class+message
+ // (ref excluded from the signature so each occurrence doesn't re-alert).
+ sendOpsAlert(`${status} ${code}`, `${detail}\nref ${ref}`, {
+ signature: `server:${code}:${status}:${detail}`,
+ });
} catch {
- /* sentry best-effort; never mask the original failure */
+ /* sentry/alerts best-effort; never mask the original failure */
}
return json(res, status, {
error: code,
@@ -212,6 +218,9 @@ export function wrap(handler) {
if (status >= 500) {
console.error('[api] unhandled', err);
captureException(err, { url: req.url, method: req.method });
+ sendOpsAlert(`unhandled 5xx in ${req.method} ${req.url}`, err?.message || String(err), {
+ signature: `unhandled:${req.url}:${err?.message}`,
+ });
}
if (!res.headersSent && !res.writableEnded) {
if (err.code === 'validation_error' && Array.isArray(err.issues)) {
diff --git a/api/_lib/rerank.js b/api/_lib/rerank.js
new file mode 100644
index 000000000..078278975
--- /dev/null
+++ b/api/_lib/rerank.js
@@ -0,0 +1,64 @@
+// Post-retrieval reranking via NVIDIA NIM's free rerank-qa-mistral-4b.
+//
+// Cosine-over-embeddings recall is cheap but coarse; a cross-encoder reranker
+// reads the query and each candidate passage together and produces a much
+// sharper relevance ordering for the handful of chunks that actually get
+// injected into the prompt. Wired as an OPTIONAL stage behind
+// KNOWLEDGE_RERANK_ENABLED=1 (plus the NVIDIA key) so retrieval behavior only
+// changes when explicitly opted in, and strictly fail-open: any rerank error
+// keeps the cosine ordering — reranking may never break retrieval.
+//
+// Endpoint (probed live, tasks/nvidia-nim/probes/embeddings.md): NOT
+// OpenAI-shaped — query/passages in, `rankings: [{index, logit}]` out,
+// sorted best-first, `index` pointing back into the input passage array.
+
+const RERANK_URL = 'https://ai.api.nvidia.com/v1/retrieval/nvidia/reranking';
+const RERANK_MODEL = 'nvidia/rerank-qa-mistral-4b';
+
+/** True when the rerank stage is opted in AND the free NIM key can serve it. */
+export function rerankConfigured() {
+ return process.env.KNOWLEDGE_RERANK_ENABLED === '1' && !!process.env.NVIDIA_API_KEY;
+}
+
+/**
+ * Rerank candidate passages against a query. Returns the candidate indexes
+ * best-first (e.g. [2, 0, 1]), or null on ANY failure so callers keep their
+ * existing cosine order (fail-open by contract).
+ *
+ * @param {string} query
+ * @param {string[]} passages
+ */
+export async function rerankPassages(query, passages, { timeoutMs = 8_000 } = {}) {
+ if (!rerankConfigured() || !query || passages.length < 2) return null;
+ try {
+ const upstream = await fetch(RERANK_URL, {
+ method: 'POST',
+ headers: {
+ Authorization: `Bearer ${process.env.NVIDIA_API_KEY}`,
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify({
+ model: RERANK_MODEL,
+ query: { text: query },
+ passages: passages.map((text) => ({ text })),
+ }),
+ signal: AbortSignal.timeout(timeoutMs),
+ });
+ if (!upstream.ok) {
+ console.warn('[rerank] upstream', upstream.status);
+ return null;
+ }
+ const data = await upstream.json();
+ const rankings = Array.isArray(data?.rankings) ? data.rankings : null;
+ if (!rankings) return null;
+ const order = rankings
+ .map((r) => r.index)
+ .filter((i) => Number.isInteger(i) && i >= 0 && i < passages.length);
+ // A partial/garbled ranking is worse than no ranking — require a full
+ // permutation of the candidates before trusting it.
+ return new Set(order).size === passages.length ? order : null;
+ } catch (err) {
+ console.warn('[rerank] failed', err?.message);
+ return null;
+ }
+}
diff --git a/api/_lib/riva-protos/descriptor.js b/api/_lib/riva-protos/descriptor.js
new file mode 100644
index 000000000..2f583875a
--- /dev/null
+++ b/api/_lib/riva-protos/descriptor.js
@@ -0,0 +1,197 @@
+// GENERATED FILE — do not edit by hand.
+// Regenerate with: node scripts/generate-riva-tts-descriptor.mjs
+// protobufjs JSON descriptor for the NVIDIA Riva TTS service, parsed
+// (keepCase) from the vendored protos in api/_lib/riva-protos/*.proto,
+// themselves from https://github.com/nvidia-riva/common (riva/proto/).
+// SPDX-FileCopyrightText: Copyright (c) 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+// SPDX-License-Identifier: MIT
+export default {
+ "nested": {
+ "nvidia": {
+ "nested": {
+ "riva": {
+ "options": {
+ "cc_enable_arenas": true,
+ "go_package": "nvidia.com/riva_speech"
+ },
+ "nested": {
+ "RequestId": {
+ "fields": {
+ "value": {
+ "type": "string",
+ "id": 1
+ }
+ }
+ },
+ "AudioEncoding": {
+ "values": {
+ "ENCODING_UNSPECIFIED": 0,
+ "LINEAR_PCM": 1,
+ "FLAC": 2,
+ "MULAW": 3,
+ "OGGOPUS": 4,
+ "ALAW": 20
+ }
+ },
+ "tts": {
+ "options": {
+ "cc_enable_arenas": true,
+ "go_package": "nvidia.com/riva_speech"
+ },
+ "nested": {
+ "RivaSpeechSynthesis": {
+ "methods": {
+ "Synthesize": {
+ "requestType": "SynthesizeSpeechRequest",
+ "responseType": "SynthesizeSpeechResponse"
+ },
+ "SynthesizeOnline": {
+ "requestType": "SynthesizeSpeechRequest",
+ "requestStream": true,
+ "responseType": "SynthesizeSpeechResponse",
+ "responseStream": true
+ },
+ "GetRivaSynthesisConfig": {
+ "requestType": "RivaSynthesisConfigRequest",
+ "responseType": "RivaSynthesisConfigResponse"
+ }
+ }
+ },
+ "RivaSynthesisConfigRequest": {
+ "fields": {
+ "model_name": {
+ "type": "string",
+ "id": 1
+ }
+ }
+ },
+ "RivaSynthesisConfigResponse": {
+ "fields": {
+ "model_config": {
+ "rule": "repeated",
+ "type": "Config",
+ "id": 1
+ }
+ },
+ "nested": {
+ "Config": {
+ "fields": {
+ "model_name": {
+ "type": "string",
+ "id": 1
+ },
+ "parameters": {
+ "keyType": "string",
+ "type": "string",
+ "id": 2
+ }
+ }
+ }
+ }
+ },
+ "ZeroShotData": {
+ "fields": {
+ "audio_prompt": {
+ "type": "bytes",
+ "id": 1
+ },
+ "sample_rate_hz": {
+ "type": "int32",
+ "id": 2
+ },
+ "encoding": {
+ "type": "AudioEncoding",
+ "id": 3
+ },
+ "quality": {
+ "type": "int32",
+ "id": 4
+ },
+ "transcript": {
+ "type": "string",
+ "id": 5
+ }
+ }
+ },
+ "SynthesizeSpeechRequest": {
+ "fields": {
+ "text": {
+ "type": "string",
+ "id": 1
+ },
+ "language_code": {
+ "type": "string",
+ "id": 2
+ },
+ "encoding": {
+ "type": "AudioEncoding",
+ "id": 3
+ },
+ "sample_rate_hz": {
+ "type": "int32",
+ "id": 4
+ },
+ "voice_name": {
+ "type": "string",
+ "id": 5
+ },
+ "zero_shot_data": {
+ "type": "ZeroShotData",
+ "id": 6
+ },
+ "custom_dictionary": {
+ "type": "string",
+ "id": 7
+ },
+ "custom_configuration": {
+ "keyType": "string",
+ "type": "string",
+ "id": 8
+ },
+ "id": {
+ "type": "RequestId",
+ "id": 100
+ }
+ }
+ },
+ "SynthesizeSpeechResponseMetadata": {
+ "fields": {
+ "text": {
+ "type": "string",
+ "id": 1
+ },
+ "processed_text": {
+ "type": "string",
+ "id": 2
+ },
+ "predicted_durations": {
+ "rule": "repeated",
+ "type": "float",
+ "id": 8
+ }
+ }
+ },
+ "SynthesizeSpeechResponse": {
+ "fields": {
+ "audio": {
+ "type": "bytes",
+ "id": 1
+ },
+ "meta": {
+ "type": "SynthesizeSpeechResponseMetadata",
+ "id": 2
+ },
+ "id": {
+ "type": "RequestId",
+ "id": 100
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+};
diff --git a/api/_lib/riva-protos/riva_audio.proto b/api/_lib/riva-protos/riva_audio.proto
new file mode 100644
index 000000000..f1a4b17a5
--- /dev/null
+++ b/api/_lib/riva-protos/riva_audio.proto
@@ -0,0 +1,37 @@
+// SPDX-FileCopyrightText: Copyright (c) 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+// SPDX-License-Identifier: MIT
+
+syntax = "proto3";
+
+package nvidia.riva;
+
+option cc_enable_arenas = true;
+option go_package = "nvidia.com/riva_speech";
+
+/*
+ * AudioEncoding specifies the encoding of the audio bytes in the encapsulating
+ * message.
+ */
+enum AudioEncoding {
+ // Not specified.
+ ENCODING_UNSPECIFIED = 0;
+
+ // Uncompressed 16-bit signed little-endian samples (Linear PCM).
+ LINEAR_PCM = 1;
+
+ // `FLAC` (Free Lossless Audio
+ // Codec) is the recommended encoding because it is
+ // lossless--therefore recognition is not compromised--and
+ // requires only about half the bandwidth of `LINEAR16`. `FLAC` stream
+ // encoding supports 16-bit and 24-bit samples, however, not all fields in
+ // `STREAMINFO` are supported.
+ FLAC = 2;
+
+ // 8-bit samples that compand 14-bit audio samples using G.711 PCMU/mu-law.
+ MULAW = 3;
+
+ OGGOPUS = 4;
+
+ // 8-bit samples that compand 13-bit audio samples using G.711 PCMU/a-law.
+ ALAW = 20;
+}
diff --git a/api/_lib/riva-protos/riva_common.proto b/api/_lib/riva-protos/riva_common.proto
new file mode 100644
index 000000000..43ce2c805
--- /dev/null
+++ b/api/_lib/riva-protos/riva_common.proto
@@ -0,0 +1,16 @@
+// SPDX-FileCopyrightText: Copyright (c) 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+// SPDX-License-Identifier: MIT
+
+syntax = "proto3";
+
+package nvidia.riva;
+
+option cc_enable_arenas = true;
+option go_package = "nvidia.com/riva_speech";
+
+/*
+ * Specifies the request ID of the request.
+ */
+message RequestId {
+ string value = 1;
+}
diff --git a/api/_lib/riva-protos/riva_tts.proto b/api/_lib/riva-protos/riva_tts.proto
new file mode 100644
index 000000000..6bc329d0c
--- /dev/null
+++ b/api/_lib/riva-protos/riva_tts.proto
@@ -0,0 +1,119 @@
+// SPDX-FileCopyrightText: Copyright (c) 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+// SPDX-License-Identifier: MIT
+
+syntax = "proto3";
+
+package nvidia.riva.tts;
+
+option cc_enable_arenas = true;
+option go_package = "nvidia.com/riva_speech";
+
+import "riva/proto/riva_audio.proto";
+import "riva/proto/riva_common.proto";
+
+service RivaSpeechSynthesis {
+ // Used to request text-to-speech from the service. Submit a request
+ // containing the desired text and configuration, and receive audio bytes in
+ // the requested format.
+ rpc Synthesize(SynthesizeSpeechRequest) returns (SynthesizeSpeechResponse) {}
+
+ // Used to request text-to-speech returned via stream as it becomes available.
+ // Submit a stream of SynthesizeSpeechRequest messages with desired text and
+ // configuration, and receive a stream of bytes in the requested format.
+ rpc SynthesizeOnline(stream SynthesizeSpeechRequest)
+ returns (stream SynthesizeSpeechResponse) {}
+
+ // Enables clients to request the configuration of the current Synthesize
+ // service, or a specific model within the service.
+ rpc GetRivaSynthesisConfig(RivaSynthesisConfigRequest)
+ returns (RivaSynthesisConfigResponse) {}
+}
+
+message RivaSynthesisConfigRequest {
+ // If model is specified only return config for model, otherwise return all
+ // configs.
+ string model_name = 1;
+}
+
+message RivaSynthesisConfigResponse {
+ message Config {
+ string model_name = 1;
+ map<string, string> parameters = 2;
+ }
+
+ repeated Config model_config = 1;
+}
+
+// Required for Zero Shot model
+message ZeroShotData {
+ // Audio prompt for Zero Shot model. Duration should be between 3 to 10
+ // seconds.
+ bytes audio_prompt = 1;
+ // Sample rate for input audio prompt. Current defaults to 22050, can be user
+ // provided.
+ int32 sample_rate_hz = 2;
+ // Encoding of audio prompt. Supported encodings are LINEAR_PCM and OGGOPUS.
+ AudioEncoding encoding = 3;
+ // The number of times user wants to pass audio through decoder. This ranges
+ // between 1-40. Defaults to 20.
+ int32 quality = 4;
+ // Transcript corresponding to audio_prompt.
+ string transcript = 5;
+}
+
+message SynthesizeSpeechRequest {
+ // Text to be converted to audio
+ string text = 1;
+ string language_code = 2;
+ // audio encoding params
+ AudioEncoding encoding = 3;
+
+ // The sample rate in hertz (Hz) of the audio output requested through
+ // `SynthesizeSpeechRequest` messages. Models produce an output at a fixed
+ // rate. The sample rate enables you to resample the generated audio output
+ // if required. You use the sample rate to up-sample or down-sample the audio
+ // for various scenarios. For example, the sample rate can be set to 8kHz
+ // (kilohertz) if the output audio is desired for a low bandwidth
+ // application. The sample rate values below 8kHz will not produce any
+ // meaningful output. Also, up-sampling too much will increase the size of
+ // the output without improving the output audio quality.
+
+ int32 sample_rate_hz = 4;
+ // voice params
+ string voice_name = 5;
+
+ // Zero Shot model params
+ ZeroShotData zero_shot_data = 6;
+
+ // A string containing comma-separated key-value pairs of
+ // grapheme and corresponding phoneme separated by double spaces.
+ string custom_dictionary = 7;
+
+ // Free-form key/value parameters for the synthesizer. Lets the server
+ // accept additional or model-specific options without proto changes.
+ // Currently recognized keys include "exaggeration_factor".
+ map<string, string> custom_configuration = 8;
+
+ // The ID to be associated with the request. If provided, this will be
+ // returned in the corresponding response.
+ RequestId id = 100;
+}
+
+message SynthesizeSpeechResponseMetadata {
+ // Currently experimental API addition that returns the input text
+ // after preprocessing has been completed as well as the predicted
+ // duration for each token.
+ // Note: this message is subject to future breaking changes, and potential
+ // removal.
+ string text = 1;
+ string processed_text = 2;
+ repeated float predicted_durations = 8;
+}
+
+message SynthesizeSpeechResponse {
+ bytes audio = 1;
+ SynthesizeSpeechResponseMetadata meta = 2;
+
+ // The ID associated with the request
+ RequestId id = 100;
+}
diff --git a/api/_lib/tts-nvidia.js b/api/_lib/tts-nvidia.js
new file mode 100644
index 000000000..90b0eb408
--- /dev/null
+++ b/api/_lib/tts-nvidia.js
@@ -0,0 +1,230 @@
+// Free NVIDIA NIM TTS lane — Magpie multilingual (Riva) over NVCF gRPC.
+//
+// Magpie has NO REST surface: it is hosted as an NVCF gRPC function on
+// grpc.nvcf.nvidia.com:443, selected by a `function-id` metadata entry, with
+// the nvapi key as a bearer `authorization` metadata entry (live-verified —
+// see tasks/nvidia-nim/probes/tts.md). The wire contract is the standard Riva
+// SpeechSynthesis service; the proto definitions are vendored under
+// ./riva-protos/ and loaded from a generated JSON descriptor so no .proto
+// file needs to exist on the serverless filesystem (api/ routes are
+// esbuild-bundled in place — scripts/bundle-api.mjs).
+//
+// Platform policy (api/_lib/llm.js doctrine): this free lane leads the TTS
+// chain; OpenAI is the paid last-resort backstop wired by the callers
+// (api/tts/speak.js, packages/avatar-agent-mcp). Mirrored for the published
+// MCP package at packages/avatar-agent-mcp/src/lib/tts-nvidia.js — keep both
+// in sync.
+
+import { env } from './env.js';
+import rivaDescriptor from './riva-protos/descriptor.js';
+
+export const NVIDIA_TTS_MODEL = 'magpie-tts-multilingual';
+export const NVIDIA_TTS_HOST = 'grpc.nvcf.nvidia.com:443';
+// NVCF function id for `ai-magpie-tts-multilingual` (from the probed function
+// list — GET api.nvcf.nvidia.com/v2/nvcf/functions).
+export const MAGPIE_FUNCTION_ID = '877104f7-e885-42b9-8de8-f6e4c6303969';
+
+// Magpie's native model rate is 22050 Hz; the server resamples. 44100 was
+// live-verified and keeps playback quality high for avatar speech.
+const SAMPLE_RATE_HZ = 44100;
+const DEFAULT_TIMEOUT_MS = 30_000;
+
+// The 9 languages the live model config reports, plus bare-tag aliases so
+// callers can pass "en" / "ja" etc.
+export const MAGPIE_LANGUAGES = new Map([
+ ['en-US', 'en-US'], ['es-US', 'es-US'], ['fr-FR', 'fr-FR'], ['de-DE', 'de-DE'],
+ ['zh-CN', 'zh-CN'], ['vi-VN', 'vi-VN'], ['it-IT', 'it-IT'], ['hi-IN', 'hi-IN'],
+ ['ja-JP', 'ja-JP'],
+ ['en', 'en-US'], ['es', 'es-US'], ['fr', 'fr-FR'], ['de', 'de-DE'],
+ ['zh', 'zh-CN'], ['vi', 'vi-VN'], ['it', 'it-IT'], ['hi', 'hi-IN'], ['ja', 'ja-JP'],
+]);
+
+// OpenAI-style voice name → nearest Magpie persona (en-US set, live-verified
+// by scripts/verify-nvidia-tts.mjs). Full voice ids are built as
+// `Magpie-Multilingual.<LANG>.<Persona>`; the persona is held constant across
+// languages so a caller switching language keeps a consistent character.
+export const VOICE_TO_MAGPIE = {
+ alloy: 'Mia',
+ ash: 'Jason',
+ ballad: 'Leo',
+ coral: 'Sofia',
+ echo: 'Ray',
+ fable: 'Leo',
+ nova: 'Aria',
+ onyx: 'Ray',
+ sage: 'Mia',
+ shimmer: 'Sofia',
+ verse: 'Jason',
+};
+const DEFAULT_PERSONA = 'Sofia';
+
+export function nvidiaTtsConfigured() {
+ return Boolean(env.NVIDIA_API_KEY);
+}
+
+export function resolveMagpieLanguage(language) {
+ if (!language) return 'en-US';
+ const exact = MAGPIE_LANGUAGES.get(language) || MAGPIE_LANGUAGES.get(String(language).toLowerCase());
+ if (exact) return exact;
+ // Try the primary subtag ("en-GB" → "en" → "en-US").
+ const primary = String(language).toLowerCase().split('-')[0];
+ return MAGPIE_LANGUAGES.get(primary) || 'en-US';
+}
+
+// Returns the full Riva voice_name for an OpenAI-style voice (or passes a raw
+// Magpie voice id straight through, emotion suffixes included).
+export function resolveMagpieVoice(voice, language) {
+ if (typeof voice === 'string' && voice.startsWith('Magpie-')) return voice;
+ const lang = resolveMagpieLanguage(language);
+ const persona = VOICE_TO_MAGPIE[voice] || DEFAULT_PERSONA;
+ // Subvoice ids are upper-cased on the server ("EN-US.Aria", "ZH-CN.Mia") —
+ // lowercase language tags come back as INVALID_ARGUMENT "subvoice not found".
+ return `Magpie-Multilingual.${lang.toUpperCase()}.${persona}`;
+}
+
+// Magpie outputs raw PCM or Ogg/Opus — it cannot encode mp3/aac/flac. Those
+// requests are served as WAV instead (every browser decoder sniffs the
+// container; content-type + x-tts-format stay truthful about what was sent).
+export function resolveMagpieFormat(format) {
+ if (format === 'opus') return { encoding: 'OGGOPUS', wrapWav: false, format: 'opus', contentType: 'audio/ogg' };
+ if (format === 'pcm') return { encoding: 'LINEAR_PCM', wrapWav: false, format: 'pcm', contentType: 'audio/pcm' };
+ return { encoding: 'LINEAR_PCM', wrapWav: true, format: 'wav', contentType: 'audio/wav' };
+}
+
+// Standard 44-byte RIFF/WAVE header around raw little-endian s16 PCM.
+export function pcmToWav(pcm, { sampleRateHz = SAMPLE_RATE_HZ, channels = 1, bitsPerSample = 16 } = {}) {
+ const blockAlign = channels * (bitsPerSample >> 3);
+ const byteRate = sampleRateHz * blockAlign;
+ const header = Buffer.alloc(44);
+ header.write('RIFF', 0, 'ascii');
+ header.writeUInt32LE(36 + pcm.length, 4);
+ header.write('WAVE', 8, 'ascii');
+ header.write('fmt ', 12, 'ascii');
+ header.writeUInt32LE(16, 16); // PCM fmt chunk size
+ header.writeUInt16LE(1, 20); // audio format: PCM
+ header.writeUInt16LE(channels, 22);
+ header.writeUInt32LE(sampleRateHz, 24);
+ header.writeUInt32LE(byteRate, 28);
+ header.writeUInt16LE(blockAlign, 32);
+ header.writeUInt16LE(bitsPerSample, 34);
+ header.write('data', 36, 'ascii');
+ header.writeUInt32LE(pcm.length, 40);
+ return Buffer.concat([header, pcm]);
+}
+
+// gRPC status code → platform error code (numeric codes so the mapping does
+// not depend on the grpc-js import being resolved).
+function normalizeGrpcError(err) {
+ const code = typeof err?.code === 'number' ? err.code : null;
+ const map = {
+ 3: 'invalid_argument', // bad voice/lang/text
+ 4: 'timeout', // DEADLINE_EXCEEDED
+ 7: 'invalid_key', // PERMISSION_DENIED
+ 8: 'rate_limited', // RESOURCE_EXHAUSTED (credit-metered free tier)
+ 14: 'provider_unreachable', // UNAVAILABLE
+ 16: 'invalid_key', // UNAUTHENTICATED
+ };
+ const normalized = new Error(
+ `NVIDIA Magpie TTS failed${code !== null ? ` (gRPC ${code})` : ''}: ${err?.details || err?.message || 'unknown error'}`,
+ );
+ normalized.code = (code !== null && map[code]) || 'provider_error';
+ normalized.grpcCode = code;
+ return normalized;
+}
+
+// The TLS channel is keyless (auth rides in per-call metadata), so one cached
+// client serves the whole warm lambda. @grpc/grpc-js is imported lazily to
+// keep cold starts of non-TTS importers free of the dependency.
+let clientPromise = null;
+async function getClient() {
+ if (!clientPromise) {
+ clientPromise = (async () => {
+ const [{ default: grpc }, { default: protoLoader }] = await Promise.all([
+ import('@grpc/grpc-js'),
+ import('@grpc/proto-loader'),
+ ]);
+ const definition = protoLoader.fromJSON(rivaDescriptor, {
+ keepCase: true,
+ longs: Number,
+ enums: String,
+ defaults: true,
+ oneofs: true,
+ });
+ const pkg = grpc.loadPackageDefinition(definition);
+ const Synthesis = pkg.nvidia.riva.tts.RivaSpeechSynthesis;
+ return {
+ grpc,
+ client: new Synthesis(NVIDIA_TTS_HOST, grpc.credentials.createSsl(), {
+ 'grpc.max_receive_message_length': 64 * 1024 * 1024,
+ }),
+ };
+ })().catch((e) => {
+ clientPromise = null; // a failed init must not poison the warm lambda
+ throw e;
+ });
+ }
+ return clientPromise;
+}
+
+// Synthesize speech on the free NIM lane. Resolves with the COMPLETE audio
+// buffer (non-streaming Synthesize RPC) so callers can fail over to the paid
+// backstop before a single byte reaches the client.
+//
+// { text, voice?, language?, format?, timeoutMs?, apiKey? }
+// → { audio: Buffer, contentType, format, voiceName, model, sampleRateHz }
+//
+// Throws Error with .code ∈ invalid_key | rate_limited | invalid_argument |
+// timeout | provider_unreachable | provider_error | not_configured.
+export async function synthesizeNvidiaTts({
+ text,
+ voice = 'nova',
+ language = 'en-US',
+ format = 'mp3',
+ timeoutMs = DEFAULT_TIMEOUT_MS,
+ apiKey,
+} = {}) {
+ const key = apiKey || env.NVIDIA_API_KEY;
+ if (!key) {
+ const err = new Error('NVIDIA_API_KEY not set');
+ err.code = 'not_configured';
+ throw err;
+ }
+ const voiceName = resolveMagpieVoice(voice, language);
+ const languageCode = resolveMagpieLanguage(language);
+ const out = resolveMagpieFormat(format);
+
+ const { grpc, client } = await getClient();
+ const metadata = new grpc.Metadata();
+ metadata.set('function-id', MAGPIE_FUNCTION_ID);
+ metadata.set('authorization', `Bearer ${key}`);
+
+ const response = await new Promise((resolveCall, rejectCall) => {
+ client.synthesize(
+ {
+ text,
+ language_code: languageCode,
+ encoding: out.encoding,
+ sample_rate_hz: SAMPLE_RATE_HZ,
+ voice_name: voiceName,
+ },
+ metadata,
+ { deadline: new Date(Date.now() + timeoutMs) },
+ (err, res) => (err ? rejectCall(normalizeGrpcError(err)) : resolveCall(res)),
+ );
+ });
+
+ const raw = Buffer.isBuffer(response?.audio) ? response.audio : Buffer.from(response?.audio || []);
+ if (!raw.length) {
+ const err = new Error('NVIDIA Magpie TTS returned empty audio');
+ err.code = 'provider_error';
+ throw err;
+ }
+ return {
+ audio: out.wrapWav ? pcmToWav(raw, { sampleRateHz: SAMPLE_RATE_HZ }) : raw,
+ contentType: out.contentType,
+ format: out.format,
+ voiceName,
+ model: NVIDIA_TTS_MODEL,
+ sampleRateHz: SAMPLE_RATE_HZ,
+ };
+}
diff --git a/api/client-errors.js b/api/client-errors.js
index ff7f867fa..bd7836b55 100644
--- a/api/client-errors.js
+++ b/api/client-errors.js
@@ -11,6 +11,7 @@
import { cors, json, method, readJson, wrap, error, rateLimited } from './_lib/http.js';
import { limits, clientIp } from './_lib/rate-limit.js';
import { captureException } from './_lib/sentry.js';
+import { sendOpsAlert } from './_lib/alerts.js';
const MAX_EVENTS_PER_BATCH = 25;
const EVENT_TYPES = new Set(['error', 'unhandledrejection', 'resource', 'manual']);
@@ -79,7 +80,8 @@ export default wrap(async (req, res) => {
console.error('[client-error]', JSON.stringify({ ...event, ...context }));
// Resource 404s stay log-only — they group terribly as exceptions.
- // Real JS errors carry their original browser stack into Sentry.
+ // Real JS errors carry their original browser stack into Sentry and
+ // page the ops channel (sendOpsAlert dedups per message per hour).
if (event.type !== 'resource') {
const synthetic = new Error(event.message);
synthetic.name = event.name || `client.${event.type}`;
@@ -92,6 +94,11 @@ export default wrap(async (req, res) => {
col: event.col,
ua: context.ua,
});
+ sendOpsAlert(
+ `client ${event.type} on ${context.page || 'unknown page'}`,
+ `${event.name ? `${event.name}: ` : ''}${event.message}${event.source ? `\n${event.source}:${event.line ?? '?'}` : ''}`,
+ { signature: `client:${event.type}:${event.message}:${event.source}` },
+ );
}
}
diff --git a/api/cron/uptime-check.js b/api/cron/uptime-check.js
new file mode 100644
index 000000000..3978552ed
--- /dev/null
+++ b/api/cron/uptime-check.js
@@ -0,0 +1,140 @@
+// GET /api/cron/uptime-check — first-party synthetic uptime monitor.
+//
+// Every 5 minutes (vercel.json crons) this probes the platform's critical
+// public surfaces from the outside (real HTTPS against APP_ORIGIN, exactly
+// what a user or paying agent hits), records the results in the shared cache,
+// and pages the ops Telegram channel on failure and recovery. /api/status
+// serves the aggregates; /status renders them as the public status page.
+//
+// Storage layout (Upstash Redis via _lib/cache.js):
+// uptime:snapshots — rolling 24h of raw probe rounds (288 @ 5-min cadence)
+// uptime:daily — 90 days of per-target daily aggregates {n, up, msSum}
+//
+// A concrete file here outranks the [name].js dynamic dispatcher for this
+// path, which keeps this handler's import graph tiny — a monitor must not
+// share a 10s cold start with ethers/viem/pump-sdk.
+
+import { error, json, method, wrap } from '../_lib/http.js';
+import { env } from '../_lib/env.js';
+import { cacheGet, cacheSet } from '../_lib/cache.js';
+import { sendOpsAlert } from '../_lib/alerts.js';
+import { constantTimeEquals } from '../_lib/crypto.js';
+
+// The surfaces that constitute "the platform is up". Each is a cheap public
+// GET — no auth, no side effects, no spend.
+export const UPTIME_TARGETS = [
+ { id: 'site', label: 'Website', path: '/' },
+ { id: 'api', label: 'Platform API', path: '/api/healthz' },
+ { id: 'explore', label: 'Explore feed', path: '/api/explore' },
+ {
+ id: 'x402',
+ label: 'x402 paid-API discovery',
+ path: '/.well-known/x402-discovery?name=x402-discovery',
+ },
+ { id: 'viewer', label: '3D viewer', path: '/viewer' },
+];
+
+const PROBE_TIMEOUT_MS = 10_000;
+const SNAPSHOT_WINDOW = 288; // 24h at 5-minute cadence
+const DAILY_WINDOW = 90;
+const SNAPSHOTS_KEY = 'uptime:snapshots';
+const DAILY_KEY = 'uptime:daily';
+const SNAPSHOTS_TTL_S = 2 * 24 * 60 * 60;
+const DAILY_TTL_S = 100 * 24 * 60 * 60;
+
+async function probe(target, origin) {
+ const controller = new AbortController();
+ const timer = setTimeout(() => controller.abort(), PROBE_TIMEOUT_MS);
+ const started = Date.now();
+ try {
+ const res = await fetch(origin + target.path, {
+ redirect: 'follow',
+ headers: { 'user-agent': 'threews-uptime/1.0' },
+ signal: controller.signal,
+ });
+ return { ok: res.ok, status: res.status, ms: Date.now() - started };
+ } catch (e) {
+ return {
+ ok: false,
+ status: 0,
+ ms: Date.now() - started,
+ error: e?.name === 'AbortError' ? 'timeout' : e?.message || 'fetch failed',
+ };
+ } finally {
+ clearTimeout(timer);
+ }
+}
+
+function requireCron(req, res) {
+ const secret = process.env.CRON_SECRET || env.CRON_SECRET;
+ if (!secret) {
+ error(res, 503, 'not_configured', 'CRON_SECRET unset');
+ return false;
+ }
+ const auth = req.headers['authorization'] || '';
+ const presented = auth.startsWith('Bearer ') ? auth.slice(7) : '';
+ if (!constantTimeEquals(presented, secret)) {
+ error(res, 401, 'unauthorized', 'invalid cron secret');
+ return false;
+ }
+ return true;
+}
+
+export default wrap(async (req, res) => {
+ if (!method(req, res, ['GET'])) return;
+ if (!requireCron(req, res)) return;
+
+ const origin = env.APP_ORIGIN || 'https://three.ws';
+ const results = Object.fromEntries(
+ await Promise.all(
+ UPTIME_TARGETS.map(async (t) => [t.id, await probe(t, origin)]),
+ ),
+ );
+ const now = Date.now();
+
+ // Rolling raw snapshots (24h window).
+ const snapshots = (await cacheGet(SNAPSHOTS_KEY)) || [];
+ const previous = snapshots[snapshots.length - 1] || null;
+ snapshots.push({ t: now, results });
+ while (snapshots.length > SNAPSHOT_WINDOW) snapshots.shift();
+ await cacheSet(SNAPSHOTS_KEY, snapshots, SNAPSHOTS_TTL_S);
+
+ // Per-day aggregates (90-day window) — drives the status page uptime bars.
+ const day = new Date(now).toISOString().slice(0, 10);
+ const daily = (await cacheGet(DAILY_KEY)) || [];
+ let today = daily[daily.length - 1];
+ if (!today || today.d !== day) {
+ today = { d: day, targets: {} };
+ daily.push(today);
+ while (daily.length > DAILY_WINDOW) daily.shift();
+ }
+ for (const [id, r] of Object.entries(results)) {
+ const agg = (today.targets[id] ||= { n: 0, up: 0, msSum: 0 });
+ agg.n += 1;
+ if (r.ok) agg.up += 1;
+ agg.msSum += r.ms;
+ }
+ await cacheSet(DAILY_KEY, daily, DAILY_TTL_S);
+
+ // Alert on failures; announce recovery once the target answers again.
+ // sendOpsAlert dedups per signature per hour, so a sustained outage pages
+ // once an hour instead of every 5 minutes.
+ for (const target of UPTIME_TARGETS) {
+ const r = results[target.id];
+ const prev = previous?.results?.[target.id];
+ if (!r.ok) {
+ sendOpsAlert(
+ `DOWN: ${target.label}`,
+ `${origin}${target.path}\n${r.error || `HTTP ${r.status}`} after ${r.ms}ms`,
+ { signature: `uptime:down:${target.id}` },
+ );
+ } else if (prev && !prev.ok) {
+ sendOpsAlert(`RECOVERED: ${target.label}`, `${origin}${target.path} — ${r.ms}ms`, {
+ signature: `uptime:recovered:${target.id}:${now}`,
+ });
+ }
+ }
+
+ const downCount = Object.values(results).filter((r) => !r.ok).length;
+ return json(res, 200, { ok: downCount === 0, down: downCount, results });
+});
diff --git a/api/status.js b/api/status.js
new file mode 100644
index 000000000..07b1a6533
--- /dev/null
+++ b/api/status.js
@@ -0,0 +1,86 @@
+// GET /api/status — public platform status, computed from the probe history
+// written by api/cron/uptime-check.js. Powers the /status page and is itself
+// a machine-readable status feed for agents and integrators.
+//
+// Returns per-target: current state (latest probe), 24h uptime + median-ish
+// latency from raw snapshots, and 90 days of daily uptime cells for the bars.
+// No probe data yet (fresh deploy, cache flush) → ok:true with empty history
+// and `monitoring: 'warming-up'`, so the page renders an honest empty state
+// rather than fake green.
+
+import { cors, json, method, wrap, rateLimited } from './_lib/http.js';
+import { limits, clientIp } from './_lib/rate-limit.js';
+import { cacheGet } from './_lib/cache.js';
+import { UPTIME_TARGETS } from './cron/uptime-check.js';
+
+const round = (n) => Math.round(n * 100) / 100;
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { origins: '*', methods: 'GET,OPTIONS' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const rl = await limits.publicIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ const [snapshots, daily] = await Promise.all([
+ cacheGet('uptime:snapshots'),
+ cacheGet('uptime:daily'),
+ ]);
+ const snaps = Array.isArray(snapshots) ? snapshots : [];
+ const days = Array.isArray(daily) ? daily : [];
+ const latest = snaps[snaps.length - 1] || null;
+
+ const services = UPTIME_TARGETS.map((target) => {
+ const current = latest?.results?.[target.id] || null;
+
+ let up24 = 0;
+ let n24 = 0;
+ let msSum = 0;
+ for (const snap of snaps) {
+ const r = snap.results?.[target.id];
+ if (!r) continue;
+ n24 += 1;
+ if (r.ok) up24 += 1;
+ msSum += r.ms;
+ }
+
+ let up90 = 0;
+ let n90 = 0;
+ const history = days.map((d) => {
+ const agg = d.targets?.[target.id];
+ if (!agg || !agg.n) return { date: d.d, uptime: null };
+ n90 += agg.n;
+ up90 += agg.up;
+ return { date: d.d, uptime: round((agg.up / agg.n) * 100) };
+ });
+
+ return {
+ id: target.id,
+ label: target.label,
+ path: target.path,
+ operational: current ? current.ok : null,
+ latencyMs: current?.ms ?? null,
+ uptime24h: n24 ? round((up24 / n24) * 100) : null,
+ avgLatency24hMs: n24 ? Math.round(msSum / n24) : null,
+ uptime90d: n90 ? round((up90 / n90) * 100) : null,
+ history,
+ };
+ });
+
+ const probed = services.filter((s) => s.operational !== null);
+ const allOk = probed.length > 0 && probed.every((s) => s.operational);
+
+ return json(
+ res,
+ 200,
+ {
+ ok: probed.length === 0 ? true : allOk,
+ monitoring: probed.length === 0 ? 'warming-up' : 'active',
+ checkedAt: latest?.t ?? null,
+ services,
+ },
+ // json() defaults to no-store; status is probed every 5 minutes, so a
+ // short shared cache absorbs page-load bursts without staleness.
+ { 'cache-control': 'public, max-age=60' },
+ );
+});
diff --git a/api/tts/speak.js b/api/tts/speak.js
index d6f5faaee..17869ae2d 100644
--- a/api/tts/speak.js
+++ b/api/tts/speak.js
@@ -1,16 +1,28 @@
-// POST /api/tts/speak — OpenAI TTS proxy used by /demos/lipsync-tts.
+// POST /api/tts/speak — text-to-speech used by /demos/lipsync-tts and the
+// avatar speech surfaces.
//
-// Body: { text, voice?, model?, format? }
-// Response: streaming audio in the requested format (default audio/mpeg).
+// Body: { text, voice?, model?, format?, language?, speed? }
+// Response: complete audio in the served format (content-type is truthful).
+//
+// Provider policy (api/_lib/llm.js doctrine — free first, paid backstop):
+// 1. NVIDIA NIM Magpie TTS (free, gRPC — api/_lib/tts-nvidia.js) leads
+// whenever NVIDIA_API_KEY is set. Note: Magpie emits PCM/Opus, so
+// mp3/aac/flac requests are served as WAV — the content-type and
+// x-tts-* headers always describe the bytes actually sent.
+// 2. OpenAI /v1/audio/speech is the paid last-resort backstop (the prod key
+// is routinely over quota — nothing may depend on it).
+// Failover happens only while zero audio bytes have been written; 503 only
+// when no lane is configured at all.
//
// The browser pipes the response into a Web Audio source and feeds the
-// analyser into wawa-lipsync for real-time viseme generation — no server-side
-// audio analysis required.
+// analyser into wawa-lipsync for real-time viseme generation — decodeAudioData
+// sniffs the container, so wav/ogg/mp3 all work without caller changes.
import { env } from '../_lib/env.js';
import { cors, method, readJson, error, wrap, rateLimited } from '../_lib/http.js';
import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
+import { synthesizeNvidiaTts, nvidiaTtsConfigured } from '../_lib/tts-nvidia.js';
export const maxDuration = 60;
@@ -28,16 +40,24 @@ const FORMATS = {
pcm: 'audio/pcm',
};
+// Per-attempt budget for the free lane: generous enough for 4096 chars of
+// synthesis, small enough that the paid backstop still fits in maxDuration.
+const NVIDIA_TIMEOUT_MS = 30_000;
+
export default wrap(async function handler(req, res) {
if (cors(req, res, { methods: 'POST,OPTIONS' })) return;
if (!method(req, res, ['POST'])) return;
- const key = env.OPENAI_API_KEY;
- if (!key) return error(res, 503, 'not_configured', 'OPENAI_API_KEY not set');
+ const nvidiaLane = nvidiaTtsConfigured();
+ const openaiKey = env.OPENAI_API_KEY;
+ if (!nvidiaLane && !openaiKey) {
+ return error(res, 503, 'not_configured', 'No TTS provider configured (set NVIDIA_API_KEY or OPENAI_API_KEY)');
+ }
- // OpenAI TTS bills per character against the server key, so meter every call.
- // Authenticated callers get a per-user budget; anonymous callers a tight
- // per-IP one. Without this the endpoint is an open, unbounded paid-API drain.
+ // TTS is metered (free tier is credit-limited, OpenAI bills per character),
+ // so budget every call. Authenticated callers get a per-user budget;
+ // anonymous callers a tight per-IP one. Without this the endpoint is an
+ // open, unbounded synthesis drain.
const session = await getSessionUser(req);
const bearer = session ? null : await authenticateBearer(extractBearer(req));
const userId = session?.id ?? bearer?.userId ?? null;
@@ -65,28 +85,60 @@ export default wrap(async function handler(req, res) {
const voice = VOICES.has(body.voice) ? body.voice : 'nova';
const model = MODELS.has(body.model) ? body.model : 'gpt-4o-mini-tts';
const formatKey = body.format && FORMATS[body.format] ? body.format : 'mp3';
+ const language = typeof body.language === 'string' ? body.language : 'en-US';
const speed = Math.min(Math.max(Number(body.speed) || 1.0, 0.5), 2.0);
+ const laneErrors = [];
+
+ // ── Lane 1: NVIDIA NIM Magpie (free) ─────────────────────────────────────
+ // The whole clip is buffered before a single byte is written, so a failure
+ // here always falls through to the paid backstop cleanly.
+ if (nvidiaLane) {
+ try {
+ const out = await synthesizeNvidiaTts({
+ text, voice, language, format: formatKey, timeoutMs: NVIDIA_TIMEOUT_MS,
+ });
+ res.statusCode = 200;
+ res.setHeader('content-type', out.contentType);
+ res.setHeader('cache-control', 'no-store');
+ res.setHeader('x-tts-voice', out.voiceName);
+ res.setHeader('x-tts-model', out.model);
+ res.setHeader('x-tts-format', out.format);
+ res.end(out.audio);
+ return;
+ } catch (e) {
+ laneErrors.push(`nvidia: ${e?.code || 'error'} — ${e?.message || 'failed'}`);
+ }
+ }
+
+ // ── Lane 2: OpenAI (paid backstop) ───────────────────────────────────────
+ if (!openaiKey) {
+ return error(res, 502, 'upstream_error', `All TTS lanes failed: ${laneErrors.join('; ')}`);
+ }
+
let upstream;
try {
upstream = await fetch('https://api.openai.com/v1/audio/speech', {
method: 'POST',
headers: {
- 'authorization': `Bearer ${key}`,
+ 'authorization': `Bearer ${openaiKey}`,
'content-type': 'application/json',
},
body: JSON.stringify({
model, voice, input: text, response_format: formatKey, speed,
}),
+ signal: AbortSignal.timeout(NVIDIA_TIMEOUT_MS),
});
} catch (e) {
- return error(res, 502, 'upstream_unreachable', e?.message || 'fetch failed');
+ laneErrors.push(`openai: ${e?.message || 'fetch failed'}`);
+ return error(res, 502, 'upstream_unreachable', `All TTS lanes failed: ${laneErrors.join('; ')}`);
}
if (!upstream.ok || !upstream.body) {
let detail = '';
try { detail = (await upstream.text()).slice(0, 500); } catch {}
- return error(res, 502, 'upstream_error', `OpenAI TTS ${upstream.status}: ${detail}`);
+ laneErrors.push(`openai: ${upstream.status} ${detail}`);
+ return error(res, 502, 'upstream_error', `All TTS lanes failed: ${laneErrors.join('; ')}`);
}
res.statusCode = 200;
@@ -94,6 +146,7 @@ export default wrap(async function handler(req, res) {
res.setHeader('cache-control', 'no-store');
res.setHeader('x-tts-voice', voice);
res.setHeader('x-tts-model', model);
+ res.setHeader('x-tts-format', formatKey);
const reader = upstream.body.getReader();
try {
diff --git a/api/widgets/[id]/[action].js b/api/widgets/[id]/[action].js
index a135eec02..c6b089d1c 100644
--- a/api/widgets/[id]/[action].js
+++ b/api/widgets/[id]/[action].js
@@ -17,7 +17,8 @@ import { isDemoWidgetId, getDemoWidget } from '../_demo-fixtures.js';
import { decorate } from '../index.js';
import { PROVIDER_MODEL_DEFAULTS, DEFAULT_PROVIDER_ORDER, MODEL_CATALOG, PER_CALL_TIMEOUT_MS } from '../../_lib/chat-models.js';
import { redactPii } from '../../_lib/pii.js';
-import { embed, cosine, embeddingsConfigured } from '../../_lib/embeddings.js';
+import { embeddingsConfigured, scoreRowsBySpace } from '../../_lib/embeddings.js';
+import { rerankConfigured, rerankPassages } from '../../_lib/rerank.js';
import { watsonxConfig, watsonxToken } from '../../_lib/watsonx.js';
import { listTranscripts, getTranscript } from './_transcripts.js';
// _knowledge.js is loaded on demand (dynamic import in handleKnowledge) so the
@@ -792,6 +793,9 @@ async function persistTurn({ widgetId, req, body, userMessage, reply, actions, p
const RETRIEVAL_TOP_K = 3;
const RETRIEVAL_MIN_SCORE = 0.18;
const RETRIEVAL_MAX_CHARS = 4_500; // ~ 1100 tokens, keeps room for chat history
+// When the optional NIM reranker is enabled, hand it a wider cosine pool so it
+// has real reordering room before we cut down to TOP_K.
+const RETRIEVAL_RERANK_POOL = 12;
async function retrieveKnowledge(widgetId, message) {
if (!message || !embeddingsConfigured()) return null;
@@ -799,7 +803,7 @@ async function retrieveKnowledge(widgetId, message) {
let rows;
try {
rows = await sql`
- select c.id, c.doc_id, c.content, c.embedding,
+ select c.id, c.doc_id, c.content, c.embedding, c.embedder,
d.title, d.source_url, d.source_type
from widget_knowledge_chunks c
join widget_knowledge_docs d on d.id = c.doc_id
@@ -811,15 +815,26 @@ async function retrieveKnowledge(widgetId, message) {
}
if (!rows.length) return null;
- const [queryEmbedding] = await embed([message]);
- const scored = rows
- .map((r) => {
- const e = Array.isArray(r.embedding) ? r.embedding : r.embedding?.values || [];
- return { ...r, score: cosine(queryEmbedding, e) };
- })
+ // Same-space rule: each chunk is scored against a query embedded with the
+ // SAME model that produced the chunk's vector. Chunks whose embedder is no
+ // longer servable are skipped (and logged) rather than compared cross-space.
+ const { scored: spaceScored, needsReembed } = await scoreRowsBySpace(rows, message);
+ for (const n of needsReembed) {
+ console.warn(
+ `[widget-chat] ${n.chunks} knowledge chunks for ${widgetId} are in unservable embedding space ${n.embedder} — run scripts/reembed-widget-knowledge.mjs`,
+ );
+ }
+
+ const candidates = spaceScored
.filter((r) => r.score >= RETRIEVAL_MIN_SCORE)
- .sort((a, b) => b.score - a.score)
- .slice(0, RETRIEVAL_TOP_K);
+ .sort((a, b) => b.score - a.score);
+
+ let scored = candidates.slice(0, RETRIEVAL_TOP_K);
+ if (rerankConfigured() && candidates.length > 1) {
+ const pool = candidates.slice(0, RETRIEVAL_RERANK_POOL);
+ const order = await rerankPassages(message, pool.map((r) => String(r.content)));
+ if (order) scored = order.slice(0, RETRIEVAL_TOP_K).map((i) => pool[i]);
+ }
if (!scored.length) return null;
diff --git a/api/widgets/[id]/_knowledge.js b/api/widgets/[id]/_knowledge.js
index 12598ca35..ef14330cb 100644
--- a/api/widgets/[id]/_knowledge.js
+++ b/api/widgets/[id]/_knowledge.js
@@ -10,7 +10,15 @@
import { z } from 'zod';
import { sql } from '../../_lib/db.js';
-import { embed, embeddingsConfigured, cosine } from '../../_lib/embeddings.js';
+import {
+ embedPassages,
+ embeddingsConfigured,
+ embedderConfigured,
+ defaultIngestEmbedderTag,
+ resolveEmbedderTag,
+ scoreRowsBySpace,
+} from '../../_lib/embeddings.js';
+import { rerankConfigured, rerankPassages } from '../../_lib/rerank.js';
import { chunk, estimateTokens } from '../../_lib/chunker.js';
import { fetchAndExtract } from '../../_lib/text-extract.js';
import { shortId } from '../../_lib/ids.js';
@@ -90,7 +98,7 @@ export async function testRetrieval({ widgetId, query, topK = 5 }) {
throw httpError(
503,
'embedder_unavailable',
- 'Knowledge test needs an OpenAI key on the server (OPENAI_API_KEY).',
+ 'Knowledge test needs an embedding provider on the server — set NVIDIA_API_KEY (free) or OPENAI_API_KEY.',
);
}
const q = String(query || '').trim();
@@ -98,39 +106,62 @@ export async function testRetrieval({ widgetId, query, topK = 5 }) {
const rows = await sql`
select c.id, c.doc_id, c.chunk_index, c.content, c.embedding, c.token_count,
- d.title, d.source_url, d.source_type
+ c.embedder, d.title, d.source_url, d.source_type
from widget_knowledge_chunks c
join widget_knowledge_docs d on d.id = c.doc_id
where c.widget_id = ${widgetId}
`;
if (!rows.length) return { query: q, results: [], chunks_searched: 0 };
- const [queryEmbedding] = await embed([q]);
- const scored = rows
- .map((r) => {
- const e = Array.isArray(r.embedding) ? r.embedding : r.embedding?.values || [];
- return {
- id: Number(r.id),
- doc_id: r.doc_id,
- chunk_index: Number(r.chunk_index),
- score: cosine(queryEmbedding, e),
- token_count: Number(r.token_count || 0),
- excerpt: truncate(String(r.content), 280),
- title: r.title,
- source_url: r.source_url,
- source_type: r.source_type,
- };
- })
+ // Same-space rule: the query must be embedded with the SAME model each
+ // stored chunk was embedded with. Group chunks by their embedder tag,
+ // embed the query once per servable space, and refuse (never guess) for
+ // spaces whose provider isn't configured.
+ const { scored, needsReembed } = await scoreRowsBySpace(rows, q);
+
+ if (!scored.length && needsReembed.length) {
+ const spaces = needsReembed.map((n) => n.embedder).join(', ');
+ throw httpError(
+ 503,
+ 'needs_reembed',
+ `Stored knowledge was embedded with ${spaces}, which no configured provider can query. ` +
+ 'Re-embed it with scripts/reembed-widget-knowledge.mjs, or configure the matching provider key.',
+ );
+ }
+
+ let top = scored
.sort((a, b) => b.score - a.score)
.slice(0, Math.max(1, Math.min(20, topK)));
+ let reranked = false;
+ if (rerankConfigured() && top.length > 1) {
+ const order = await rerankPassages(q, top.map((r) => r.content));
+ if (order) {
+ top = order.map((i) => top[i]);
+ reranked = true;
+ }
+ }
return {
query: q,
- results: scored,
+ results: top.map((r) => ({
+ id: Number(r.id),
+ doc_id: r.doc_id,
+ chunk_index: Number(r.chunk_index),
+ score: r.score,
+ embedder: r.embedder,
+ token_count: Number(r.token_count || 0),
+ excerpt: truncate(String(r.content), 280),
+ title: r.title,
+ source_url: r.source_url,
+ source_type: r.source_type,
+ })),
chunks_searched: rows.length,
+ reranked,
+ ...(needsReembed.length ? { needs_reembed: needsReembed } : {}),
};
}
+
function truncate(s, n) {
if (s.length <= n) return s;
return s.slice(0, n).trim() + '…';
@@ -146,11 +177,15 @@ export async function deleteKnowledge({ widgetId, userId, docId }) {
}
export async function ingestKnowledge({ widgetId, userId, input }) {
- if (!embeddingsConfigured()) {
+ // Free-first: new document sets embed via NVIDIA NIM when its key is
+ // present, OpenAI otherwise. The chosen embedder tag is stamped on the doc
+ // and every chunk so query time can stay in the same vector space.
+ const ingestTag = defaultIngestEmbedderTag();
+ if (!ingestTag) {
throw httpError(
503,
'embedder_unavailable',
- 'Knowledge upload needs an OpenAI key on the server (OPENAI_API_KEY).',
+ 'Knowledge upload needs an embedding provider on the server — set NVIDIA_API_KEY (free) or OPENAI_API_KEY.',
);
}
@@ -211,12 +246,12 @@ export async function ingestKnowledge({ widgetId, userId, input }) {
await sql`
insert into widget_knowledge_docs
(id, widget_id, user_id, title, source_type, source_url, byte_size,
- chunk_count, token_count, status, source_text)
+ chunk_count, token_count, status, source_text, embedder)
values
(${docId}, ${widgetId}, ${userId}, ${title.slice(0, 160)}, ${body.source_type},
${sourceUrl}, ${byteSize}, ${chunks.length}, ${tokenSum},
${shouldQueue ? 'queued' : 'processing'},
- ${shouldQueue ? text : null})
+ ${shouldQueue ? text : null}, ${ingestTag})
`;
if (shouldQueue) {
@@ -253,7 +288,7 @@ export async function ingestKnowledge({ widgetId, userId, input }) {
// Inline path for small docs: embed + insert here, return when ready.
try {
- await embedAndInsertChunks({ docId, widgetId, chunks });
+ await embedAndInsertChunks({ docId, widgetId, chunks, embedderTag: ingestTag });
await sql`update widget_knowledge_docs set status = 'ready' where id = ${docId}`;
} catch (err) {
await sql`
@@ -278,18 +313,21 @@ export async function ingestKnowledge({ widgetId, userId, input }) {
}
// Shared embed+insert loop used by both the inline path and the QStash worker.
-async function embedAndInsertChunks({ docId, widgetId, chunks }) {
+// Chunks are corpus text, so they embed as 'passage' (NIM's asymmetric
+// retrieval models require the ingest/search distinction); every row stores
+// the embedder tag it was produced with.
+async function embedAndInsertChunks({ docId, widgetId, chunks, embedderTag }) {
for (let i = 0; i < chunks.length; i += EMBED_BATCH) {
const slice = chunks.slice(i, i + EMBED_BATCH);
- const embedded = await embed(slice.map((c) => c.content));
+ const embedded = await embedPassages(embedderTag, slice.map((c) => c.content));
const inserts = slice.map((c, j) => {
const vec = Array.from(embedded[j]);
return sql`
insert into widget_knowledge_chunks
- (doc_id, widget_id, chunk_index, content, embedding, token_count)
+ (doc_id, widget_id, chunk_index, content, embedding, token_count, embedder)
values
(${docId}, ${widgetId}, ${i + j}, ${c.content},
- ${JSON.stringify(vec)}::jsonb, ${c.token_count})
+ ${JSON.stringify(vec)}::jsonb, ${c.token_count}, ${embedderTag})
`;
});
await sql.transaction(inserts);
@@ -303,7 +341,7 @@ async function embedAndInsertChunks({ docId, widgetId, chunks }) {
// failure picks up where chunks left off.
export async function processQueuedDoc({ docId, widgetId }) {
const [doc] = await sql`
- select id, widget_id, source_text, status, chunk_count
+ select id, widget_id, source_text, status, chunk_count, embedder
from widget_knowledge_docs
where id = ${docId} and widget_id = ${widgetId}
limit 1
@@ -311,6 +349,27 @@ export async function processQueuedDoc({ docId, widgetId }) {
if (!doc) throw httpError(404, 'not_found', 'doc not found');
if (doc.status === 'ready') return { ok: true, status: 'ready' };
+ // Re-resolve the embedder at processing time: the worker may run on a
+ // deployment whose keys differ from the one that queued the doc. The doc
+ // has no chunks yet (any partials are wiped below), so switching to the
+ // current default embedder is safe — the tag we actually use is written
+ // back to the doc and to every chunk.
+ const queuedTag = resolveEmbedderTag(doc.embedder);
+ const embedderTag =
+ queuedTag && embedderConfigured(queuedTag) ? queuedTag : defaultIngestEmbedderTag();
+ if (!embedderTag) {
+ await sql`
+ update widget_knowledge_docs set status = 'failed',
+ error = 'no embedding provider configured'
+ where id = ${docId}
+ `.catch(() => {});
+ throw httpError(
+ 503,
+ 'embedder_unavailable',
+ 'No embedding provider configured — set NVIDIA_API_KEY (free) or OPENAI_API_KEY.',
+ );
+ }
+
if (!doc.source_text || doc.source_text.length < 12) {
await sql`
update widget_knowledge_docs set status = 'failed',
@@ -329,12 +388,12 @@ export async function processQueuedDoc({ docId, widgetId }) {
// don't end up with duplicates at the same chunk_index.
await sql`delete from widget_knowledge_chunks where doc_id = ${docId}`;
- await embedAndInsertChunks({ docId, widgetId: doc.widget_id, chunks });
+ await embedAndInsertChunks({ docId, widgetId: doc.widget_id, chunks, embedderTag });
await sql`
update widget_knowledge_docs
set status = 'ready', source_text = null, error = null,
- chunk_count = ${chunks.length}
+ chunk_count = ${chunks.length}, embedder = ${embedderTag}
where id = ${docId}
`;
return { ok: true, status: 'ready', chunk_count: chunks.length };
diff --git a/data/changelog.json b/data/changelog.json
index ac52bb2bf..d98deb021 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,25 @@
{
"$comment": "Curated changelog entries for three.ws — the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.",
"entries": [
+ {
+ "date": "2026-06-11",
+ "title": "Public status page with live uptime monitoring",
+ "summary": "three.ws now monitors its own critical surfaces — the website, platform API, explore feed, x402 paid-API discovery, and the 3D viewer — every 5 minutes from outside our infrastructure, and publishes the results at three.ws/status: live operational state, response times, and a 90-day uptime history per service. A machine-readable JSON feed is available at /api/status for agents and integrators. Browser errors on any page are now also collected first-party, so problems reach the team before reports do.",
+ "tags": [
+ "feature",
+ "infra"
+ ],
+ "link": "/status"
+ },
+ {
+ "date": "2026-06-11",
+ "title": "Pluggable memory backends + a portable snapshot format for the agent SDK",
+ "summary": "Agent developers can now plug a custom memory backend — a vector database, an episodic event log, or their own API — behind a named mode with Memory.registerBackend, no forking required. All built-in modes (local, remote, ipfs, encrypted-ipfs, none) are unchanged. We also formalized a memory/0.1 snapshot contract: memory.snapshot() returns a JSON-safe object and Memory.fromSnapshot() rehydrates it, so embedded agent widgets keep their memory across page reloads. Documented in the Memory spec, agent manifest, and README.",
+ "tags": [
+ "sdk",
+ "docs"
+ ]
+ },
{
"date": "2026-06-11",
"title": "Agents dashboard renders reliably again",
diff --git a/data/pages.json b/data/pages.json
index 604f8eb79..51447772d 100644
--- a/data/pages.json
+++ b/data/pages.json
@@ -731,6 +731,14 @@
"path": "/tutorials",
"title": "Tutorials",
"description": "Step-by-step build guides."
+ },
+ {
+ "path": "/status",
+ "title": "Status",
+ "description": "Live operational status and 90-day uptime history for the platform, API, and x402 surfaces — probed every 5 minutes.",
+ "priority": 0.5,
+ "changefreq": "always",
+ "added": "2026-06-11"
}
]
},
diff --git a/packages/avatar-agent-mcp/package.json b/packages/avatar-agent-mcp/package.json
index ae140a9af..7b993339e 100644
--- a/packages/avatar-agent-mcp/package.json
+++ b/packages/avatar-agent-mcp/package.json
@@ -1,6 +1,6 @@
{
"name": "@three-ws/avatar-agent",
- "version": "1.0.3",
+ "version": "1.1.0",
"mcpName": "io.github.nirholas/3D-AI-Agent-Avatar",
"description": "3D AI Agent Avatar — MCP server that spawns a textured GLB avatar, inspects/validates/optimizes any 3D model, gives the agent a Solana wallet + a voice, and ships full pump.fun powers (atomic Jito-bundled launches + creator-fee collection). Powered by three.ws.",
"type": "module",
@@ -59,6 +59,8 @@
},
"dependencies": {
"@gltf-transform/core": "^4.3.0",
+ "@grpc/grpc-js": "^1.14.4",
+ "@grpc/proto-loader": "^0.8.1",
"@gltf-transform/extensions": "^4.3.0",
"@gltf-transform/functions": "^4.3.0",
"@modelcontextprotocol/sdk": "^1.29.0",
diff --git a/packages/avatar-agent-mcp/src/config.js b/packages/avatar-agent-mcp/src/config.js
index 3d818297c..ce602a922 100644
--- a/packages/avatar-agent-mcp/src/config.js
+++ b/packages/avatar-agent-mcp/src/config.js
@@ -36,6 +36,9 @@ export const SOLANA_RPC_URL = validateRpcUrl(
export const ETH_RPC_URL = env('ETH_RPC_URL') || env('MAINNET_RPC_URL') || null;
export const HELIUS_API_KEY = env('HELIUS_API_KEY', '');
export const OPENAI_API_KEY = env('OPENAI_API_KEY', '');
+// NVIDIA NIM key (build.nvidia.com, nvapi-…) — powers the FREE Magpie TTS
+// lane that leads the speak tool's provider chain; OpenAI is the paid backstop.
+export const NVIDIA_API_KEY = env('NVIDIA_API_KEY', '');
export const REPLICATE_API_TOKEN = env('REPLICATE_API_TOKEN', '');
export const REPLICATE_TEXT_TO_AVATAR_MODEL = env('REPLICATE_TEXT_TO_AVATAR_MODEL', '');
diff --git a/packages/avatar-agent-mcp/src/lib/riva-protos/descriptor.js b/packages/avatar-agent-mcp/src/lib/riva-protos/descriptor.js
new file mode 100644
index 000000000..2f583875a
--- /dev/null
+++ b/packages/avatar-agent-mcp/src/lib/riva-protos/descriptor.js
@@ -0,0 +1,197 @@
+// GENERATED FILE — do not edit by hand.
+// Regenerate with: node scripts/generate-riva-tts-descriptor.mjs
+// protobufjs JSON descriptor for the NVIDIA Riva TTS service, parsed
+// (keepCase) from the vendored protos in api/_lib/riva-protos/*.proto,
+// themselves from https://github.com/nvidia-riva/common (riva/proto/).
+// SPDX-FileCopyrightText: Copyright (c) 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+// SPDX-License-Identifier: MIT
+export default {
+ "nested": {
+ "nvidia": {
+ "nested": {
+ "riva": {
+ "options": {
+ "cc_enable_arenas": true,
+ "go_package": "nvidia.com/riva_speech"
+ },
+ "nested": {
+ "RequestId": {
+ "fields": {
+ "value": {
+ "type": "string",
+ "id": 1
+ }
+ }
+ },
+ "AudioEncoding": {
+ "values": {
+ "ENCODING_UNSPECIFIED": 0,
+ "LINEAR_PCM": 1,
+ "FLAC": 2,
+ "MULAW": 3,
+ "OGGOPUS": 4,
+ "ALAW": 20
+ }
+ },
+ "tts": {
+ "options": {
+ "cc_enable_arenas": true,
+ "go_package": "nvidia.com/riva_speech"
+ },
+ "nested": {
+ "RivaSpeechSynthesis": {
+ "methods": {
+ "Synthesize": {
+ "requestType": "SynthesizeSpeechRequest",
+ "responseType": "SynthesizeSpeechResponse"
+ },
+ "SynthesizeOnline": {
+ "requestType": "SynthesizeSpeechRequest",
+ "requestStream": true,
+ "responseType": "SynthesizeSpeechResponse",
+ "responseStream": true
+ },
+ "GetRivaSynthesisConfig": {
+ "requestType": "RivaSynthesisConfigRequest",
+ "responseType": "RivaSynthesisConfigResponse"
+ }
+ }
+ },
+ "RivaSynthesisConfigRequest": {
+ "fields": {
+ "model_name": {
+ "type": "string",
+ "id": 1
+ }
+ }
+ },
+ "RivaSynthesisConfigResponse": {
+ "fields": {
+ "model_config": {
+ "rule": "repeated",
+ "type": "Config",
+ "id": 1
+ }
+ },
+ "nested": {
+ "Config": {
+ "fields": {
+ "model_name": {
+ "type": "string",
+ "id": 1
+ },
+ "parameters": {
+ "keyType": "string",
+ "type": "string",
+ "id": 2
+ }
+ }
+ }
+ }
+ },
+ "ZeroShotData": {
+ "fields": {
+ "audio_prompt": {
+ "type": "bytes",
+ "id": 1
+ },
+ "sample_rate_hz": {
+ "type": "int32",
+ "id": 2
+ },
+ "encoding": {
+ "type": "AudioEncoding",
+ "id": 3
+ },
+ "quality": {
+ "type": "int32",
+ "id": 4
+ },
+ "transcript": {
+ "type": "string",
+ "id": 5
+ }
+ }
+ },
+ "SynthesizeSpeechRequest": {
+ "fields": {
+ "text": {
+ "type": "string",
+ "id": 1
+ },
+ "language_code": {
+ "type": "string",
+ "id": 2
+ },
+ "encoding": {
+ "type": "AudioEncoding",
+ "id": 3
+ },
+ "sample_rate_hz": {
+ "type": "int32",
+ "id": 4
+ },
+ "voice_name": {
+ "type": "string",
+ "id": 5
+ },
+ "zero_shot_data": {
+ "type": "ZeroShotData",
+ "id": 6
+ },
+ "custom_dictionary": {
+ "type": "string",
+ "id": 7
+ },
+ "custom_configuration": {
+ "keyType": "string",
+ "type": "string",
+ "id": 8
+ },
+ "id": {
+ "type": "RequestId",
+ "id": 100
+ }
+ }
+ },
+ "SynthesizeSpeechResponseMetadata": {
+ "fields": {
+ "text": {
+ "type": "string",
+ "id": 1
+ },
+ "processed_text": {
+ "type": "string",
+ "id": 2
+ },
+ "predicted_durations": {
+ "rule": "repeated",
+ "type": "float",
+ "id": 8
+ }
+ }
+ },
+ "SynthesizeSpeechResponse": {
+ "fields": {
+ "audio": {
+ "type": "bytes",
+ "id": 1
+ },
+ "meta": {
+ "type": "SynthesizeSpeechResponseMetadata",
+ "id": 2
+ },
+ "id": {
+ "type": "RequestId",
+ "id": 100
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+};
diff --git a/packages/avatar-agent-mcp/src/lib/tts-nvidia.js b/packages/avatar-agent-mcp/src/lib/tts-nvidia.js
new file mode 100644
index 000000000..f053e66f1
--- /dev/null
+++ b/packages/avatar-agent-mcp/src/lib/tts-nvidia.js
@@ -0,0 +1,200 @@
+// Free NVIDIA NIM TTS lane — Magpie multilingual (Riva) over NVCF gRPC.
+//
+// MIRROR of /api/_lib/tts-nvidia.js in the three.ws repo, self-contained for
+// this published package (it cannot import across the repo boundary). Keep
+// both in sync. Magpie has NO REST surface: it is an NVCF gRPC function on
+// grpc.nvcf.nvidia.com:443, selected by a `function-id` metadata entry, with
+// the nvapi key as a bearer `authorization` metadata entry. The proto
+// definitions ship as a generated JSON descriptor (./riva-protos/descriptor.js,
+// regenerated by scripts/generate-riva-tts-descriptor.mjs in the repo root).
+
+import rivaDescriptor from './riva-protos/descriptor.js';
+
+export const NVIDIA_TTS_MODEL = 'magpie-tts-multilingual';
+export const NVIDIA_TTS_HOST = 'grpc.nvcf.nvidia.com:443';
+// NVCF function id for `ai-magpie-tts-multilingual`.
+export const MAGPIE_FUNCTION_ID = '877104f7-e885-42b9-8de8-f6e4c6303969';
+
+// Magpie's native model rate is 22050 Hz; the server resamples to 44100.
+const SAMPLE_RATE_HZ = 44100;
+const DEFAULT_TIMEOUT_MS = 30_000;
+
+export const MAGPIE_LANGUAGES = new Map([
+ ['en-US', 'en-US'], ['es-US', 'es-US'], ['fr-FR', 'fr-FR'], ['de-DE', 'de-DE'],
+ ['zh-CN', 'zh-CN'], ['vi-VN', 'vi-VN'], ['it-IT', 'it-IT'], ['hi-IN', 'hi-IN'],
+ ['ja-JP', 'ja-JP'],
+ ['en', 'en-US'], ['es', 'es-US'], ['fr', 'fr-FR'], ['de', 'de-DE'],
+ ['zh', 'zh-CN'], ['vi', 'vi-VN'], ['it', 'it-IT'], ['hi', 'hi-IN'], ['ja', 'ja-JP'],
+]);
+
+// OpenAI-style voice name → nearest Magpie persona (en-US set).
+export const VOICE_TO_MAGPIE = {
+ alloy: 'Mia',
+ ash: 'Jason',
+ ballad: 'Leo',
+ coral: 'Sofia',
+ echo: 'Ray',
+ fable: 'Leo',
+ nova: 'Aria',
+ onyx: 'Ray',
+ sage: 'Mia',
+ shimmer: 'Sofia',
+ verse: 'Jason',
+};
+const DEFAULT_PERSONA = 'Sofia';
+
+export function resolveMagpieLanguage(language) {
+ if (!language) return 'en-US';
+ const exact = MAGPIE_LANGUAGES.get(language) || MAGPIE_LANGUAGES.get(String(language).toLowerCase());
+ if (exact) return exact;
+ const primary = String(language).toLowerCase().split('-')[0];
+ return MAGPIE_LANGUAGES.get(primary) || 'en-US';
+}
+
+export function resolveMagpieVoice(voice, language) {
+ if (typeof voice === 'string' && voice.startsWith('Magpie-')) return voice;
+ const lang = resolveMagpieLanguage(language);
+ const persona = VOICE_TO_MAGPIE[voice] || DEFAULT_PERSONA;
+ // Subvoice ids are upper-cased on the server ("EN-US.Aria", "ZH-CN.Mia") —
+ // lowercase language tags come back as INVALID_ARGUMENT "subvoice not found".
+ return `Magpie-Multilingual.${lang.toUpperCase()}.${persona}`;
+}
+
+// Magpie outputs raw PCM or Ogg/Opus — mp3/aac/flac requests are served as
+// WAV instead; the returned mime/format always describe the actual bytes.
+export function resolveMagpieFormat(format) {
+ if (format === 'opus') return { encoding: 'OGGOPUS', wrapWav: false, format: 'opus', contentType: 'audio/ogg' };
+ if (format === 'pcm') return { encoding: 'LINEAR_PCM', wrapWav: false, format: 'pcm', contentType: 'audio/pcm' };
+ return { encoding: 'LINEAR_PCM', wrapWav: true, format: 'wav', contentType: 'audio/wav' };
+}
+
+// Standard 44-byte RIFF/WAVE header around raw little-endian s16 PCM.
+export function pcmToWav(pcm, { sampleRateHz = SAMPLE_RATE_HZ, channels = 1, bitsPerSample = 16 } = {}) {
+ const blockAlign = channels * (bitsPerSample >> 3);
+ const byteRate = sampleRateHz * blockAlign;
+ const header = Buffer.alloc(44);
+ header.write('RIFF', 0, 'ascii');
+ header.writeUInt32LE(36 + pcm.length, 4);
+ header.write('WAVE', 8, 'ascii');
+ header.write('fmt ', 12, 'ascii');
+ header.writeUInt32LE(16, 16); // PCM fmt chunk size
+ header.writeUInt16LE(1, 20); // audio format: PCM
+ header.writeUInt16LE(channels, 22);
+ header.writeUInt32LE(sampleRateHz, 24);
+ header.writeUInt32LE(byteRate, 28);
+ header.writeUInt16LE(blockAlign, 32);
+ header.writeUInt16LE(bitsPerSample, 34);
+ header.write('data', 36, 'ascii');
+ header.writeUInt32LE(pcm.length, 40);
+ return Buffer.concat([header, pcm]);
+}
+
+function normalizeGrpcError(err) {
+ const code = typeof err?.code === 'number' ? err.code : null;
+ const map = {
+ 3: 'invalid_argument',
+ 4: 'timeout',
+ 7: 'invalid_key',
+ 8: 'rate_limited',
+ 14: 'provider_unreachable',
+ 16: 'invalid_key',
+ };
+ const normalized = new Error(
+ `NVIDIA Magpie TTS failed${code !== null ? ` (gRPC ${code})` : ''}: ${err?.details || err?.message || 'unknown error'}`,
+ );
+ normalized.code = (code !== null && map[code]) || 'provider_error';
+ normalized.grpcCode = code;
+ return normalized;
+}
+
+// The TLS channel is keyless (auth rides in per-call metadata) — one cached
+// client serves the whole process. grpc-js is imported lazily so the MCP
+// server starts fast for users who never call speak.
+let clientPromise = null;
+async function getClient() {
+ if (!clientPromise) {
+ clientPromise = (async () => {
+ const [{ default: grpc }, { default: protoLoader }] = await Promise.all([
+ import('@grpc/grpc-js'),
+ import('@grpc/proto-loader'),
+ ]);
+ const definition = protoLoader.fromJSON(rivaDescriptor, {
+ keepCase: true,
+ longs: Number,
+ enums: String,
+ defaults: true,
+ oneofs: true,
+ });
+ const pkg = grpc.loadPackageDefinition(definition);
+ const Synthesis = pkg.nvidia.riva.tts.RivaSpeechSynthesis;
+ return {
+ grpc,
+ client: new Synthesis(NVIDIA_TTS_HOST, grpc.credentials.createSsl(), {
+ 'grpc.max_receive_message_length': 64 * 1024 * 1024,
+ }),
+ };
+ })().catch((e) => {
+ clientPromise = null; // a failed init must not poison the process
+ throw e;
+ });
+ }
+ return clientPromise;
+}
+
+// Synthesize speech on the free NIM lane (non-streaming Synthesize RPC; the
+// complete buffer comes back so callers can fail over before emitting bytes).
+//
+// { text, voice?, language?, format?, timeoutMs?, apiKey }
+// → { audio: Buffer, contentType, format, voiceName, model, sampleRateHz }
+export async function synthesizeNvidiaTts({
+ text,
+ voice = 'nova',
+ language = 'en-US',
+ format = 'mp3',
+ timeoutMs = DEFAULT_TIMEOUT_MS,
+ apiKey,
+} = {}) {
+ if (!apiKey) {
+ const err = new Error('NVIDIA_API_KEY not set');
+ err.code = 'not_configured';
+ throw err;
+ }
+ const voiceName = resolveMagpieVoice(voice, language);
+ const languageCode = resolveMagpieLanguage(language);
+ const out = resolveMagpieFormat(format);
+
+ const { grpc, client } = await getClient();
+ const metadata = new grpc.Metadata();
+ metadata.set('function-id', MAGPIE_FUNCTION_ID);
+ metadata.set('authorization', `Bearer ${apiKey}`);
+
+ const response = await new Promise((resolveCall, rejectCall) => {
+ client.synthesize(
+ {
+ text,
+ language_code: languageCode,
+ encoding: out.encoding,
+ sample_rate_hz: SAMPLE_RATE_HZ,
+ voice_name: voiceName,
+ },
+ metadata,
+ { deadline: new Date(Date.now() + timeoutMs) },
+ (err, res) => (err ? rejectCall(normalizeGrpcError(err)) : resolveCall(res)),
+ );
+ });
+
+ const raw = Buffer.isBuffer(response?.audio) ? response.audio : Buffer.from(response?.audio || []);
+ if (!raw.length) {
+ const err = new Error('NVIDIA Magpie TTS returned empty audio');
+ err.code = 'provider_error';
+ throw err;
+ }
+ return {
+ audio: out.wrapWav ? pcmToWav(raw, { sampleRateHz: SAMPLE_RATE_HZ }) : raw,
+ contentType: out.contentType,
+ format: out.format,
+ voiceName,
+ model: NVIDIA_TTS_MODEL,
+ sampleRateHz: SAMPLE_RATE_HZ,
+ };
+}
diff --git a/packages/avatar-agent-mcp/src/tools/speak.js b/packages/avatar-agent-mcp/src/tools/speak.js
index 5bd528163..e09ec7aa8 100644
--- a/packages/avatar-agent-mcp/src/tools/speak.js
+++ b/packages/avatar-agent-mcp/src/tools/speak.js
@@ -1,14 +1,21 @@
-// `speak` — synthesize audio for the avatar via OpenAI's text-to-speech
-// API. Returns the audio as a base64 data URL by default so clients can
-// embed it directly. The avatar's voice (set when spawn_avatar runs) is
-// used unless explicitly overridden.
+// `speak` — synthesize audio for the avatar. Returns the audio as a base64
+// data URL by default so clients can embed it directly. The avatar's voice
+// (set when spawn_avatar runs) is used unless explicitly overridden.
//
-// Requires OPENAI_API_KEY in the MCP server's environment.
+// Provider chain (free first, paid backstop — same policy as the three.ws
+// platform's /api/tts/speak):
+// 1. NVIDIA NIM Magpie TTS (free, gRPC) when NVIDIA_API_KEY is set. Magpie
+// emits PCM/Opus, so mp3/aac/flac requests are served as WAV — the
+// returned `mime`/`format`/`voice`/`model` fields describe the actual
+// audio.
+// 2. OpenAI /v1/audio/speech when OPENAI_API_KEY is set.
+// `not_configured` only when neither key is present.
import { z } from 'zod';
-import { OPENAI_API_KEY } from '../config.js';
+import { OPENAI_API_KEY, NVIDIA_API_KEY } from '../config.js';
import { getSession, updateSession } from '../lib/avatars.js';
+import { synthesizeNvidiaTts } from '../lib/tts-nvidia.js';
const VOICES = ['alloy', 'ash', 'ballad', 'coral', 'echo', 'fable', 'nova', 'onyx', 'sage', 'shimmer', 'verse'];
const MODELS = ['tts-1', 'tts-1-hd', 'gpt-4o-mini-tts'];
@@ -20,27 +27,29 @@ const FORMATS = {
wav: 'audio/wav',
pcm: 'audio/pcm',
};
+const NVIDIA_TIMEOUT_MS = 30_000;
export const def = {
name: 'speak',
- title: 'Avatar speaks (OpenAI TTS)',
+ title: 'Avatar speaks (TTS)',
description:
- 'Synthesize speech for an avatar session via OpenAI TTS and return a base64 audio data URL the client can play. Picks the session\'s configured voice unless overridden. Requires OPENAI_API_KEY on the MCP server.',
+ 'Synthesize speech for an avatar session and return a base64 audio data URL the client can play. Free NVIDIA NIM Magpie TTS leads when NVIDIA_API_KEY is set (mp3/aac/flac requests are served as WAV); OpenAI TTS is the paid backstop when OPENAI_API_KEY is set. Picks the session\'s configured voice unless overridden.',
inputSchema: {
sessionId: z.string().optional()
.describe('Avatar session id (optional — when omitted, voice falls back to the override or "nova").'),
text: z.string().min(1).max(4096).describe('Text the avatar should say.'),
voice: z.enum(VOICES).optional().describe('Override the session voice for this call.'),
- model: z.enum(MODELS).optional().describe('TTS model (default gpt-4o-mini-tts).'),
- format: z.enum(Object.keys(FORMATS)).optional().describe('Audio format (default mp3).'),
- speed: z.number().min(0.5).max(2.0).optional().describe('Playback speed multiplier.'),
+ model: z.enum(MODELS).optional().describe('OpenAI TTS model used on the paid backstop lane (default gpt-4o-mini-tts). The free NVIDIA lane always serves magpie-tts-multilingual.'),
+ format: z.enum(Object.keys(FORMATS)).optional().describe('Audio format (default mp3; the free NVIDIA lane serves mp3/aac/flac as wav).'),
+ language: z.string().optional().describe('BCP-47 language for the free NVIDIA lane (en-US default; also es-US, fr-FR, de-DE, zh-CN, vi-VN, it-IT, hi-IN, ja-JP).'),
+ speed: z.number().min(0.5).max(2.0).optional().describe('Playback speed multiplier (OpenAI lane only).'),
},
async handler(args) {
- if (!OPENAI_API_KEY) {
+ if (!NVIDIA_API_KEY && !OPENAI_API_KEY) {
return {
ok: false,
error: 'not_configured',
- message: 'OPENAI_API_KEY is not set on the MCP server. Set it to enable TTS.',
+ message: 'No TTS provider configured. Set NVIDIA_API_KEY (free Magpie lane) or OPENAI_API_KEY (paid backstop) on the MCP server.',
};
}
const { sessionId, text } = args || {};
@@ -51,41 +60,80 @@ export const def = {
const voice = args.voice || session?.voice || 'nova';
const model = args.model || 'gpt-4o-mini-tts';
const format = args.format || 'mp3';
+ const language = args.language || 'en-US';
const speed = typeof args.speed === 'number' ? args.speed : 1.0;
- const mime = FORMATS[format];
const t0 = Date.now();
- const r = await fetch('https://api.openai.com/v1/audio/speech', {
- method: 'POST',
- headers: {
- authorization: `Bearer ${OPENAI_API_KEY}`,
- 'content-type': 'application/json',
- },
- body: JSON.stringify({ input: text, voice, model, response_format: format, speed }),
- });
+ const laneErrors = [];
+
+ // Lane 1: free NVIDIA NIM Magpie TTS.
+ if (NVIDIA_API_KEY) {
+ try {
+ const out = await synthesizeNvidiaTts({
+ text, voice, language, format, timeoutMs: NVIDIA_TIMEOUT_MS, apiKey: NVIDIA_API_KEY,
+ });
+ if (session) updateSession(session.id, { lastSpoken: text.slice(0, 200) });
+ return {
+ ok: true,
+ sessionId: session?.id || null,
+ provider: 'nvidia',
+ voice: out.voiceName,
+ model: out.model,
+ format: out.format,
+ mime: out.contentType,
+ sizeBytes: out.audio.length,
+ durationMs: Date.now() - t0,
+ audio: `data:${out.contentType};base64,${out.audio.toString('base64')}`,
+ text,
+ };
+ } catch (e) {
+ laneErrors.push(`nvidia: ${e?.code || 'error'} — ${e?.message || 'failed'}`);
+ }
+ }
+
+ // Lane 2: OpenAI paid backstop.
+ if (!OPENAI_API_KEY) {
+ return { ok: false, error: 'tts_failed', message: `All TTS lanes failed: ${laneErrors.join('; ')}` };
+ }
+ const mime = FORMATS[format];
+ let r;
+ try {
+ r = await fetch('https://api.openai.com/v1/audio/speech', {
+ method: 'POST',
+ headers: {
+ authorization: `Bearer ${OPENAI_API_KEY}`,
+ 'content-type': 'application/json',
+ },
+ body: JSON.stringify({ input: text, voice, model, response_format: format, speed }),
+ signal: AbortSignal.timeout(NVIDIA_TIMEOUT_MS),
+ });
+ } catch (e) {
+ laneErrors.push(`openai: ${e?.message || 'fetch failed'}`);
+ return { ok: false, error: 'tts_failed', message: `All TTS lanes failed: ${laneErrors.join('; ')}` };
+ }
if (!r.ok) {
const errText = await r.text().catch(() => '');
+ laneErrors.push(`openai: ${r.status} ${errText.slice(0, 500)}`);
return {
ok: false,
error: 'tts_failed',
status: r.status,
- message: errText.slice(0, 500),
+ message: `All TTS lanes failed: ${laneErrors.join('; ')}`,
};
}
const buf = Buffer.from(await r.arrayBuffer());
- const base64 = buf.toString('base64');
- const dataUrl = `data:${mime};base64,${base64}`;
if (session) updateSession(session.id, { lastSpoken: text.slice(0, 200) });
return {
ok: true,
sessionId: session?.id || null,
+ provider: 'openai',
voice,
model,
format,
mime,
sizeBytes: buf.length,
durationMs: Date.now() - t0,
- audio: dataUrl,
+ audio: `data:${mime};base64,${buf.toString('base64')}`,
text,
};
},
diff --git a/pages/status.html b/pages/status.html
new file mode 100644
index 000000000..5d600ae00
--- /dev/null
+++ b/pages/status.html
@@ -0,0 +1,361 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="utf-8" />
+ <title>Status — three.ws</title>
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <meta name="theme-color" content="#000000" />
+ <meta
+ name="description"
+ content="Live operational status and 90-day uptime history for the three.ws platform, API, and x402 paid-API surfaces."
+ />
+
+ <meta property="og:type" content="website" />
+ <meta property="og:url" content="https://three.ws/status" />
+ <meta property="og:title" content="Status — three.ws" />
+ <meta
+ property="og:description"
+ content="Live operational status and 90-day uptime history for the three.ws platform."
+ />
+ <meta property="og:image" content="https://three.ws/og-image.png" />
+ <meta property="og:image:width" content="1200" />
+ <meta property="og:image:height" content="630" />
+ <meta name="twitter:card" content="summary_large_image" />
+ <meta name="twitter:image" content="https://three.ws/og-image.png" />
+
+ <link rel="icon" href="/favicon.ico" sizes="any" />
+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
+ <link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png" />
+ <link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png" />
+ <link rel="apple-touch-icon" href="/apple-touch-icon.png" />
+ <link rel="manifest" href="/site.webmanifest" />
+ <link rel="stylesheet" href="/style.css" />
+ <link rel="stylesheet" href="/nav.css" />
+ <link rel="stylesheet" href="/footer.css" />
+ <link rel="stylesheet" href="/fonts/fonts.css" />
+ <script defer src="/footer-newsletter.js"></script>
+
+ <style>
+ .st-wrap {
+ max-width: 880px;
+ margin: 0 auto;
+ padding: calc(var(--space-md) * 2) var(--space-md) calc(var(--space-md) * 4);
+ }
+ .st-crumb {
+ font: var(--text-sm) var(--font-body);
+ color: var(--ink-dim);
+ margin: 0 0 var(--space-md);
+ }
+ .st-crumb a {
+ color: inherit;
+ }
+ .st-title {
+ font-family: var(--font-display);
+ font-size: clamp(1.6rem, 4vw, 2.2rem);
+ margin: 0 0 var(--space-md);
+ }
+
+ .st-banner {
+ display: flex;
+ align-items: center;
+ gap: 0.75rem;
+ border: 1px solid var(--stroke-strong);
+ border-radius: var(--radius-lg);
+ padding: 1rem 1.25rem;
+ margin-bottom: calc(var(--space-md) * 1.5);
+ background: var(--surface-glass);
+ font-family: var(--font-display);
+ font-size: 1.05rem;
+ transition: border-color 0.3s ease;
+ }
+ .st-banner .st-dot {
+ width: 12px;
+ height: 12px;
+ }
+ .st-banner[data-state='ok'] {
+ border-color: rgba(74, 222, 128, 0.35);
+ }
+ .st-banner[data-state='down'] {
+ border-color: rgba(248, 113, 113, 0.45);
+ }
+
+ .st-dot {
+ width: 9px;
+ height: 9px;
+ border-radius: 50%;
+ background: var(--ink-dim);
+ flex: none;
+ transition: background 0.3s ease;
+ }
+ .st-dot[data-state='ok'] {
+ background: var(--success);
+ box-shadow: 0 0 8px rgba(74, 222, 128, 0.5);
+ }
+ .st-dot[data-state='down'] {
+ background: var(--danger);
+ box-shadow: 0 0 8px rgba(248, 113, 113, 0.5);
+ }
+
+ .st-meta {
+ color: var(--ink-dim);
+ font: var(--text-sm) var(--font-body);
+ margin: 0 0 calc(var(--space-md) * 1.5);
+ }
+
+ .st-card {
+ border: 1px solid var(--stroke);
+ border-radius: var(--radius-lg);
+ background: var(--surface-1);
+ padding: 1rem 1.25rem;
+ margin-bottom: var(--space-md);
+ transition:
+ border-color 0.2s ease,
+ background 0.2s ease;
+ }
+ .st-card:hover {
+ border-color: var(--stroke-strong);
+ background: var(--surface-2);
+ }
+ .st-card-head {
+ display: flex;
+ align-items: center;
+ gap: 0.6rem;
+ flex-wrap: wrap;
+ }
+ .st-card-head h2 {
+ font-family: var(--font-display);
+ font-size: 1rem;
+ margin: 0;
+ flex: 1 1 auto;
+ }
+ .st-stats {
+ display: flex;
+ gap: 1rem;
+ color: var(--ink-dim);
+ font: var(--text-sm) var(--font-mono, monospace);
+ white-space: nowrap;
+ }
+ .st-stats strong {
+ color: var(--ink);
+ font-weight: 600;
+ }
+
+ /* 90-day uptime bar — one cell per day, oldest → newest */
+ .st-bar {
+ display: flex;
+ gap: 2px;
+ margin-top: 0.85rem;
+ height: 28px;
+ }
+ .st-cell {
+ flex: 1 1 0;
+ border-radius: 2px;
+ background: var(--surface-3);
+ transition: transform 0.12s ease;
+ }
+ .st-cell:hover,
+ .st-cell:focus-visible {
+ transform: scaleY(1.25);
+ outline: none;
+ }
+ .st-cell[data-band='up'] {
+ background: var(--success);
+ opacity: 0.85;
+ }
+ .st-cell[data-band='degraded'] {
+ background: var(--warn);
+ }
+ .st-cell[data-band='down'] {
+ background: var(--danger);
+ }
+ .st-bar-labels {
+ display: flex;
+ justify-content: space-between;
+ color: var(--ink-dim);
+ font: var(--text-sm) var(--font-body);
+ margin-top: 0.35rem;
+ }
+
+ /* Loading skeleton */
+ .st-skel .st-card-head h2,
+ .st-skel .st-stats,
+ .st-skel .st-bar {
+ background: var(--surface-2);
+ border-radius: var(--radius-md);
+ color: transparent;
+ animation: st-pulse 1.4s ease-in-out infinite;
+ }
+ @keyframes st-pulse {
+ 0%,
+ 100% {
+ opacity: 0.5;
+ }
+ 50% {
+ opacity: 1;
+ }
+ }
+ @media (prefers-reduced-motion: reduce) {
+ .st-skel .st-card-head h2,
+ .st-skel .st-stats,
+ .st-skel .st-bar {
+ animation: none;
+ }
+ .st-cell:hover {
+ transform: none;
+ }
+ }
+
+ .st-note {
+ border: 1px solid var(--stroke);
+ border-radius: var(--radius-lg);
+ background: var(--surface-1);
+ color: var(--ink-dim);
+ padding: 1rem 1.25rem;
+ font: var(--text-sm) var(--font-body);
+ }
+ .st-note a {
+ color: var(--ink);
+ }
+ .st-error {
+ border-color: rgba(248, 113, 113, 0.35);
+ }
+
+ @media (max-width: 480px) {
+ .st-stats {
+ flex-basis: 100%;
+ gap: 0.75rem;
+ }
+ }
+ </style>
+ </head>
+ <body>
+ <header><div id="nav-container"></div></header>
+
+ <main class="st-wrap">
+ <p class="st-crumb"><a href="/">Home</a> / Status</p>
+ <h1 class="st-title">Platform status</h1>
+
+ <div class="st-banner" id="st-banner" role="status" aria-live="polite">
+ <span class="st-dot" id="st-banner-dot" aria-hidden="true"></span>
+ <span id="st-banner-text">Checking platform status…</span>
+ </div>
+ <p class="st-meta" id="st-meta">
+ Probed every 5 minutes from outside our infrastructure.
+ <a href="/api/status" style="color: inherit">JSON feed</a> ·
+ <a href="/changelog" style="color: inherit">Changelog</a>
+ </p>
+
+ <section id="st-services" aria-label="Service status list">
+ <!-- skeletons swapped out by render() -->
+ <article class="st-card st-skel" aria-hidden="true">
+ <div class="st-card-head"><h2>loading</h2><div class="st-stats">…</div></div>
+ <div class="st-bar"></div>
+ </article>
+ <article class="st-card st-skel" aria-hidden="true">
+ <div class="st-card-head"><h2>loading</h2><div class="st-stats">…</div></div>
+ <div class="st-bar"></div>
+ </article>
+ <article class="st-card st-skel" aria-hidden="true">
+ <div class="st-card-head"><h2>loading</h2><div class="st-stats">…</div></div>
+ <div class="st-bar"></div>
+ </article>
+ </section>
+ </main>
+
+ <script type="module">
+ const banner = document.getElementById('st-banner');
+ const bannerDot = document.getElementById('st-banner-dot');
+ const bannerText = document.getElementById('st-banner-text');
+ const meta = document.getElementById('st-meta');
+ const list = document.getElementById('st-services');
+
+ const fmtPct = (v) => (v == null ? '—' : `${v}%`);
+ const band = (uptime) =>
+ uptime == null ? null : uptime >= 99.5 ? 'up' : uptime >= 95 ? 'degraded' : 'down';
+
+ function render(data) {
+ const probed = data.services.filter((s) => s.operational !== null);
+ const down = probed.filter((s) => !s.operational);
+ if (data.monitoring === 'warming-up') {
+ bannerText.textContent = 'Monitoring is warming up — first probes land within minutes.';
+ } else if (down.length === 0) {
+ banner.dataset.state = 'ok';
+ bannerDot.dataset.state = 'ok';
+ bannerText.textContent = 'All systems operational';
+ } else {
+ banner.dataset.state = 'down';
+ bannerDot.dataset.state = 'down';
+ bannerText.textContent = `${down.length} of ${probed.length} services disrupted: ${down
+ .map((s) => s.label)
+ .join(', ')}`;
+ }
+ if (data.checkedAt) {
+ const ago = Math.max(0, Math.round((Date.now() - data.checkedAt) / 60000));
+ meta.firstChild.textContent = `Probed every 5 minutes from outside our infrastructure — last check ${
+ ago === 0 ? 'under a minute' : `${ago} min`
+ } ago. `;
+ }
+
+ list.innerHTML = '';
+ for (const s of data.services) {
+ const card = document.createElement('article');
+ card.className = 'st-card';
+
+ const days = s.history.length;
+ const cells = s.history
+ .map((h) => {
+ const b = band(h.uptime);
+ const label =
+ h.uptime == null ? `${h.date}: no data` : `${h.date}: ${h.uptime}% uptime`;
+ return `<span class="st-cell" ${b ? `data-band="${b}"` : ''} role="img" tabindex="0" aria-label="${label}" title="${label}"></span>`;
+ })
+ .join('');
+
+ card.innerHTML = `
+ <div class="st-card-head">
+ <span class="st-dot" data-state="${s.operational === null ? '' : s.operational ? 'ok' : 'down'}" aria-hidden="true"></span>
+ <h2>${s.label}</h2>
+ <div class="st-stats">
+ <span><strong>${fmtPct(s.uptime90d ?? s.uptime24h)}</strong> uptime</span>
+ <span><strong>${s.avgLatency24hMs == null ? '—' : `${s.avgLatency24hMs}ms`}</strong> avg</span>
+ </div>
+ </div>
+ ${
+ days > 0
+ ? `<div class="st-bar" role="group" aria-label="${s.label} daily uptime, last ${days} days">${cells}</div>
+ <div class="st-bar-labels"><span>${days} days ago</span><span>today</span></div>`
+ : `<div class="st-bar-labels"><span>History appears after the first day of monitoring.</span></div>`
+ }`;
+ list.appendChild(card);
+ }
+ }
+
+ function renderError() {
+ bannerText.textContent = 'Could not load status data.';
+ list.innerHTML = `<div class="st-note st-error">
+ The status feed at <a href="/api/status">/api/status</a> did not respond.
+ That can itself indicate an incident — try again in a minute, or check
+ <a href="https://x.com/trythreews" rel="noopener">@trythreews</a> for updates.
+ </div>`;
+ }
+
+ async function load() {
+ try {
+ const res = await fetch('/api/status', { headers: { accept: 'application/json' } });
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
+ render(await res.json());
+ } catch {
+ renderError();
+ }
+ }
+ load();
+ // Live page: refresh on the probe cadence without requiring a reload.
+ setInterval(load, 5 * 60 * 1000);
+ </script>
+
+ <script src="/nav.js" defer></script>
+ <script src="/brand.js" defer></script>
+ <div id="footer-container"></div>
+ <script src="/footer.js"></script>
+ </body>
+</html>
diff --git a/public/changelog.json b/public/changelog.json
index 9aa1ae6ac..c325be342 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,11 +1,21 @@
{
- "generated_at": "2026-06-11T10:51:55.342Z",
+ "generated_at": "2026-06-11T10:55:52.340Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
"url": "https://three.ws"
},
"entries": [
+ {
+ "date": "2026-06-11",
+ "type": "launch",
+ "title": "Status",
+ "summary": "Live operational status and 90-day uptime history for the platform, API, and x402 surfaces — probed every 5 minutes.",
+ "link": "/status",
+ "tags": [
+ "launch"
+ ]
+ },
{
"date": "2026-06-11",
"type": "update",
@@ -122,6 +132,28 @@
"feature"
]
},
+ {
+ "date": "2026-06-11",
+ "type": "update",
+ "title": "Pluggable memory backends + a portable snapshot format for the agent SDK",
+ "summary": "Agent developers can now plug a custom memory backend — a vector database, an episodic event log, or their own API — behind a named mode with Memory.registerBackend, no forking required. All built-in modes (local, remote, ipfs, encrypted-ipfs, none) are unchanged. We also formalized a memory/0.1 snapshot contract: memory.snapshot() returns a JSON-safe object and Memory.fromSnapshot() rehydrates it, so embedded agent widgets keep their memory across page reloads. Documented in the Memory spec, agent manifest, and README.",
+ "link": null,
+ "tags": [
+ "sdk",
+ "docs"
+ ]
+ },
+ {
+ "date": "2026-06-11",
+ "type": "update",
+ "title": "Public status page with live uptime monitoring",
+ "summary": "three.ws now monitors its own critical surfaces — the website, platform API, explore feed, x402 paid-API discovery, and the 3D viewer — every 5 minutes from outside our infrastructure, and publishes the results at three.ws/status: live operational state, response times, and a 90-day uptime history per service. A machine-readable JSON feed is available at /api/status for agents and integrators. Browser errors on any page are now also collected first-party, so problems reach the team before reports do.",
+ "link": "/status",
+ "tags": [
+ "feature",
+ "infra"
+ ]
+ },
{
"date": "2026-06-11",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index c7fe23a0f..771e564cc 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -6,6 +6,14 @@
<atom:link href="https://three.ws/changelog.xml" rel="self" type="application/rss+xml"/>
<description>What's new on three.ws — features, improvements, and releases, newest first.</description>
<language>en</language>
+ <item>
+ <title>Status</title>
+ <link>https://three.ws/status</link>
+ <guid isPermaLink="false">2026-06-11:Status</guid>
+ <pubDate>Thu, 11 Jun 2026 12:00:00 GMT</pubDate>
+ <category>launch</category>
+ <description>Live operational status and 90-day uptime history for the platform, API, and x402 surfaces — probed every 5 minutes.</description>
+ </item>
<item>
<title>Accurate uptime on the x402 Provider Hub</title>
<link>https://three.ws/changelog</link>
@@ -94,6 +102,22 @@
<category>feature</category>
<description>Two new skills in the marketplace under the new Wallet category: MetaMask Agent Wallet and MetaMask Agent Workflows. Install them on any agent to let it check balances, transfer tokens, swap, bridge across chains, trade perps and prediction markets, and manage Aave positions through MetaMask's mm CLI — each user signs in with their own MetaMask Agent Wallet, so keys stay with you, never with three.ws. Platform chat agents pick the skills up automatically.</description>
</item>
+ <item>
+ <title>Pluggable memory backends + a portable snapshot format for the agent SDK</title>
+ <link>https://three.ws/changelog</link>
+ <guid isPermaLink="false">2026-06-11:Pluggable memory backends + a portable snapshot format for the agent SDK</guid>
+ <pubDate>Thu, 11 Jun 2026 12:00:00 GMT</pubDate>
+ <category>sdk</category>
+ <description>Agent developers can now plug a custom memory backend — a vector database, an episodic event log, or their own API — behind a named mode with Memory.registerBackend, no forking required. All built-in modes (local, remote, ipfs, encrypted-ipfs, none) are unchanged. We also formalized a memory/0.1 snapshot contract: memory.snapshot() returns a JSON-safe object and Memory.fromSnapshot() rehydrates it, so embedded agent widgets keep their memory across page reloads. Documented in the Memory spec, agent manifest, and README.</description>
+ </item>
+ <item>
+ <title>Public status page with live uptime monitoring</title>
+ <link>https://three.ws/status</link>
+ <guid isPermaLink="false">2026-06-11:Public status page with live uptime monitoring</guid>
+ <pubDate>Thu, 11 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>three.ws now monitors its own critical surfaces — the website, platform API, explore feed, x402 paid-API discovery, and the 3D viewer — every 5 minutes from outside our infrastructure, and publishes the results at three.ws/status: live operational state, response times, and a 90-day uptime history per service. A machine-readable JSON feed is available at /api/status for agents and integrators. Browser errors on any page are now also collected first-party, so problems reach the team before reports do.</description>
+ </item>
<item>
<title>Scheduled jobs restored after dependency outage</title>
<link>https://three.ws/changelog</link>
diff --git a/public/features.json b/public/features.json
index b15d149a6..1cecd0fc2 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-11T10:51:55.332Z",
+ "generated_at": "2026-06-11T10:55:52.326Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
@@ -966,6 +966,16 @@
"indexable": true,
"tags": [],
"showcase": false
+ },
+ {
+ "path": "/status",
+ "title": "Status",
+ "description": "Live operational status and 90-day uptime history for the platform, API, and x402 surfaces — probed every 5 minutes.",
+ "added": "2026-06-11",
+ "auth": null,
+ "indexable": true,
+ "tags": [],
+ "showcase": false
}
]
},
diff --git a/public/footer.html b/public/footer.html
index 63260cfa8..9b320a868 100644
--- a/public/footer.html
+++ b/public/footer.html
@@ -71,6 +71,7 @@
<div class="h-footer-link-col">
<h4 class="h-footer-link-heading">Developers</h4>
<a href="/docs">Docs</a>
+ <a href="/status">Status</a>
<a href="/support">Support</a>
<a href="/sitemap">Sitemap</a>
<a href="https://github.com/nirholas/three.ws" target="_blank" rel="noopener">GitHub</a>
diff --git a/public/llms-full.txt b/public/llms-full.txt
index a30d181c6..8c800580e 100644
--- a/public/llms-full.txt
+++ b/public/llms-full.txt
@@ -596,6 +596,12 @@ URL: https://three.ws/tutorials
Step-by-step build guides.
+### Status
+
+URL: https://three.ws/status
+
+Live operational status and 90-day uptime history for the platform, API, and x402 surfaces — probed every 5 minutes.
+
## Blog
Long-form announcements, launches, and writing from three.ws.
diff --git a/public/llms.txt b/public/llms.txt
index 75ae0ad7c..4dd066083 100644
--- a/public/llms.txt
+++ b/public/llms.txt
@@ -125,6 +125,7 @@ Docs, tutorials, and reference.
- [Docs · SDK](https://three.ws/docs/sdk): JavaScript / Node SDK for three.ws.
- [Docs · Listings & Distribution](https://three.ws/docs/listings): Cloud marketplaces and ecosystem directories where three.ws is listed (Alibaba Cloud, BNB Chain Dappbay, and more).
- [Tutorials](https://three.ws/tutorials): Step-by-step build guides.
+- [Status](https://three.ws/status): Live operational status and 90-day uptime history for the platform, API, and x402 surfaces — probed every 5 minutes.
## Blog
diff --git a/public/sitemap/index.html b/public/sitemap/index.html
index d0803f7b3..3cb8dedbd 100644
--- a/public/sitemap/index.html
+++ b/public/sitemap/index.html
@@ -771,6 +771,13 @@
<span class="sm-desc">Step-by-step build guides.</span>
</a>
</li>
+ <li>
+ <a href="/status">
+ <span class="sm-title">Status</span>
+ <span class="sm-path">/status</span>
+ <span class="sm-desc">Live operational status and 90-day uptime history for the platform, API, and x402 surfaces — probed every 5 minutes.</span>
+ </a>
+ </li>
</ul>
</section>
diff --git a/scripts/bundle-api.mjs b/scripts/bundle-api.mjs
index 490a62643..86d94f15c 100644
--- a/scripts/bundle-api.mjs
+++ b/scripts/bundle-api.mjs
@@ -85,6 +85,12 @@ const EXTERNALS = [
// no longer traces that ~50 MB tree once per function across the ~360 routes
// that import http.js (the 45-min build timeout, deploy 5vphtZz6S). If you
// re-add the SDK, read api/_lib/sentry.js's header first.
+ // @grpc/grpc-js + @grpc/proto-loader power the free NVIDIA Magpie TTS lane
+ // (api/_lib/tts-nvidia.js → api/tts/speak.js only). Pure JS (no native
+ // addon), but grpc-js's CJS build does lazy internal requires that esbuild's
+ // ESM output mangles; external lets Node load it natively, and NFT traces
+ // the ~6 MB tree exactly once (single importing route).
+ '@grpc/*',
'@asamuzakjp/*',
'@csstools/*',
'@neynar/*',
diff --git a/scripts/generate-riva-tts-descriptor.mjs b/scripts/generate-riva-tts-descriptor.mjs
new file mode 100644
index 000000000..cc39fa5e5
--- /dev/null
+++ b/scripts/generate-riva-tts-descriptor.mjs
@@ -0,0 +1,60 @@
+#!/usr/bin/env node
+// Regenerates api/_lib/riva-protos/descriptor.js (and the avatar-agent-mcp
+// mirror) from the vendored NVIDIA Riva .proto sources.
+//
+// node scripts/generate-riva-tts-descriptor.mjs
+//
+// Why a generated descriptor instead of loading the .proto files at runtime:
+// api/ routes are esbuild-bundled in place on Vercel (scripts/bundle-api.mjs),
+// so a runtime fs read of a .proto would need fragile includeFiles +
+// import.meta.url path math that differs between dev (api/_lib/…) and the
+// bundled output (api/tts/…). A checked-in JS module bundles cleanly, needs no
+// filesystem at runtime, and is loaded via @grpc/proto-loader's fromJSON().
+//
+// The descriptor is parsed with keepCase:true so the gRPC surface uses the
+// snake_case field names from the proto (text, language_code, sample_rate_hz,
+// voice_name) — same names NVIDIA's docs and the probe transcript use.
+
+import { readFile, writeFile } from 'fs/promises';
+import { fileURLToPath } from 'url';
+import { dirname, resolve } from 'path';
+import { createRequire } from 'module';
+
+const require = createRequire(import.meta.url);
+const protobuf = require('protobufjs');
+
+const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');
+const PROTO_DIR = resolve(ROOT, 'api/_lib/riva-protos');
+const SOURCES = ['riva_common.proto', 'riva_audio.proto', 'riva_tts.proto'];
+const OUTPUTS = [
+ resolve(PROTO_DIR, 'descriptor.js'),
+ resolve(ROOT, 'packages/avatar-agent-mcp/src/lib/riva-protos/descriptor.js'),
+];
+
+const root = new protobuf.Root();
+for (const name of SOURCES) {
+ const source = await readFile(resolve(PROTO_DIR, name), 'utf8');
+ protobuf.parse(source, root, { keepCase: true });
+}
+root.resolveAll();
+
+// Sanity: the exact surface api/_lib/tts-nvidia.js depends on must exist.
+root.lookupService('nvidia.riva.tts.RivaSpeechSynthesis');
+root.lookupType('nvidia.riva.tts.SynthesizeSpeechRequest');
+root.lookupType('nvidia.riva.tts.SynthesizeSpeechResponse');
+root.lookupEnum('nvidia.riva.AudioEncoding');
+
+const banner = `// GENERATED FILE — do not edit by hand.
+// Regenerate with: node scripts/generate-riva-tts-descriptor.mjs
+// protobufjs JSON descriptor for the NVIDIA Riva TTS service, parsed
+// (keepCase) from the vendored protos in api/_lib/riva-protos/*.proto,
+// themselves from https://github.com/nvidia-riva/common (riva/proto/).
+// SPDX-FileCopyrightText: Copyright (c) 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+// SPDX-License-Identifier: MIT
+`;
+
+const body = `${banner}export default ${JSON.stringify(root.toJSON(), null, '\t')};\n`;
+for (const out of OUTPUTS) {
+ await writeFile(out, body);
+ console.log(`wrote ${out}`);
+}
diff --git a/scripts/verify-nvidia-tts.mjs b/scripts/verify-nvidia-tts.mjs
new file mode 100644
index 000000000..4510c1b9f
--- /dev/null
+++ b/scripts/verify-nvidia-tts.mjs
@@ -0,0 +1,124 @@
+#!/usr/bin/env node
+// Live verification for the free NVIDIA Magpie TTS lane (task T2.1).
+//
+// node scripts/verify-nvidia-tts.mjs # full check (needs NVIDIA_API_KEY in .env.local)
+// node scripts/verify-nvidia-tts.mjs --quick # skip the voice-map sweep
+//
+// 1. Synthesizes a short sentence through api/_lib/tts-nvidia.js and asserts
+// real audio came back (RIFF/WAVE magic, duration > 0). Prints latency.
+// 2. Sweeps every mapped Magpie persona + the opus path so the voice map is
+// proven against the live model, not assumed.
+// 3. Forces the NIM lane to fail (bad key) and runs the real /api/tts/speak
+// handler to prove the failover ORDER: nvidia attempted first, OpenAI
+// backstop attempted second, clean JSON error when both fail.
+//
+// Everything stays in memory — no scratch audio files are written.
+
+import { config as dotenv } from 'dotenv';
+import { Readable } from 'node:stream';
+
+dotenv({ path: new URL('../.env.local', import.meta.url) });
+
+const quick = process.argv.includes('--quick');
+if (!process.env.NVIDIA_API_KEY) {
+ console.error('[tts] NVIDIA_API_KEY missing from environment/.env.local — cannot live-verify');
+ process.exit(1);
+}
+
+const { synthesizeNvidiaTts, VOICE_TO_MAGPIE } = await import('../api/_lib/tts-nvidia.js');
+
+function assert(cond, msg) {
+ if (!cond) {
+ console.error(`[tts] FAIL — ${msg}`);
+ process.exit(1);
+ }
+}
+
+function wavDurationSeconds(buf) {
+ return (buf.length - 44) / (44100 * 2); // mono s16 @ 44100
+}
+
+// ── 1. One real sentence through the module ────────────────────────────────
+{
+ const t0 = Date.now();
+ const out = await synthesizeNvidiaTts({
+ text: 'Hello from three dot W S. The free NVIDIA voice lane is live.',
+ voice: 'nova',
+ format: 'mp3', // mp3 is the platform default — NIM serves it as WAV
+ });
+ const ms = Date.now() - t0;
+ assert(Buffer.isBuffer(out.audio), 'module did not return a Buffer');
+ assert(out.audio.subarray(0, 4).toString('ascii') === 'RIFF', `bad magic: ${out.audio.subarray(0, 4)}`);
+ assert(out.audio.subarray(8, 12).toString('ascii') === 'WAVE', 'no WAVE marker');
+ assert(out.contentType === 'audio/wav' && out.format === 'wav', 'content-type/format not truthful');
+ assert(out.model === 'magpie-tts-multilingual', `model: ${out.model}`);
+ const dur = wavDurationSeconds(out.audio);
+ assert(dur > 0, `duration ${dur}`);
+ console.log(
+ `[tts] ✓ synthesize ok — voice ${out.voiceName}, ${out.audio.length} bytes, ${dur.toFixed(2)}s audio, latency ${ms}ms`,
+ );
+}
+
+// ── 2. Voice-map sweep + opus path ─────────────────────────────────────────
+if (!quick) {
+ const personas = new Map(); // persona → one representative OpenAI voice name
+ for (const [openaiVoice, persona] of Object.entries(VOICE_TO_MAGPIE)) {
+ if (!personas.has(persona)) personas.set(persona, openaiVoice);
+ }
+ for (const [persona, openaiVoice] of personas) {
+ const t0 = Date.now();
+ const out = await synthesizeNvidiaTts({ text: 'Quick voice check.', voice: openaiVoice, format: 'wav' });
+ assert(out.audio.length > 44 && out.audio.subarray(0, 4).toString('ascii') === 'RIFF',
+ `persona ${persona} returned no audio`);
+ console.log(`[tts] ✓ ${openaiVoice} → ${out.voiceName} (${out.audio.length} bytes, ${Date.now() - t0}ms)`);
+ }
+ const opus = await synthesizeNvidiaTts({ text: 'Opus container check.', voice: 'nova', format: 'opus' });
+ assert(opus.audio.subarray(0, 4).toString('ascii') === 'OggS', `opus magic: ${opus.audio.subarray(0, 4)}`);
+ assert(opus.contentType === 'audio/ogg' && opus.format === 'opus', 'opus content-type/format not truthful');
+ console.log(`[tts] ✓ opus path ok (${opus.audio.length} bytes, OggS magic)`);
+}
+
+// ── 3. Failover order through the real handler (forced NIM failure) ────────
+{
+ process.env.NVIDIA_API_KEY = 'nvapi-deliberately-invalid-for-failover-check';
+ if (!process.env.OPENAI_API_KEY) process.env.OPENAI_API_KEY = 'sk-invalid-local-failover-check';
+
+ const handler = (await import('../api/tts/speak.js')).default;
+ const body = Buffer.from(JSON.stringify({ text: 'Failover order check.', voice: 'nova' }));
+ const req = Readable.from([body]);
+ req.method = 'POST';
+ req.url = '/api/tts/speak';
+ req.headers = { 'content-type': 'application/json', 'content-length': String(body.length) };
+ const chunks = [];
+ const res = {
+ statusCode: 200,
+ _h: {},
+ writableEnded: false,
+ headersSent: false,
+ setHeader(k, v) { this._h[k.toLowerCase()] = v; },
+ getHeader(k) { return this._h[k.toLowerCase()]; },
+ write(c) { chunks.push(Buffer.from(c)); },
+ end(c) { if (c) chunks.push(Buffer.from(c)); this.writableEnded = true; },
+ };
+ await handler(req, res);
+ const payload = Buffer.concat(chunks);
+
+ if (res.statusCode === 200) {
+ // A working local OpenAI key served the backstop — order is still proven:
+ // NIM was forced invalid, headers must say OpenAI served.
+ assert(res._h['x-tts-model'] !== 'magpie-tts-multilingual', 'NIM claimed to serve with an invalid key');
+ console.log(`[tts] ✓ failover — NIM failed, OpenAI backstop SERVED (model ${res._h['x-tts-model']})`);
+ } else {
+ assert(res.statusCode === 502, `expected 502 when both lanes fail, got ${res.statusCode}`);
+ const err = JSON.parse(payload.toString('utf8'));
+ const detail = err.error_description || '';
+ const iNvidia = detail.indexOf('nvidia:');
+ const iOpenai = detail.indexOf('openai:');
+ assert(iNvidia !== -1, `nvidia lane missing from error: ${detail}`);
+ assert(iOpenai !== -1, `openai lane was never attempted: ${detail}`);
+ assert(iNvidia < iOpenai, `lane order wrong: ${detail}`);
+ console.log(`[tts] ✓ failover order — nvidia first, openai second, clean 502: ${detail.slice(0, 160)}…`);
+ }
+}
+
+console.log('[tts] PASS');
diff --git a/specs/AGENT_MANIFEST.md b/specs/AGENT_MANIFEST.md
index 10fa65a3f..72a033100 100644
--- a/specs/AGENT_MANIFEST.md
+++ b/specs/AGENT_MANIFEST.md
@@ -93,7 +93,7 @@ Everything is optional except `manifest.json` and a `body` reference.
// Memory — persistent state
"memory": {
- "mode": "local", // "local" | "ipfs" | "encrypted-ipfs" | "none"
+ "mode": "local", // "local" | "remote" | "ipfs" | "encrypted-ipfs" | "none" | a registered custom backend
"index": "memory/MEMORY.md",
"maxTokens": 8192, // budget for memory context injection
},
@@ -145,7 +145,7 @@ Skills load lazily. The `<agent-3d>` element emits `skill:loaded` events as each
### `memory`
-`local` persists in `localStorage` keyed by agentId. `ipfs` pins after each write (slow, durable). `encrypted-ipfs` wraps with the owner wallet's pubkey. See [MEMORY_SPEC.md](./MEMORY_SPEC.md).
+`local` persists in `localStorage` keyed by agentId. `remote` persists per-agent via `/api/agent-memory` (owner-only). `ipfs` pins after each write (slow, durable). `encrypted-ipfs` wraps with the owner wallet's pubkey. Any other value names a backend registered via `Memory.registerBackend` (vector store, episodic log, your own API). See [MEMORY_SPEC.md](./MEMORY_SPEC.md).
### `tools`
diff --git a/specs/MEMORY_SPEC.md b/specs/MEMORY_SPEC.md
index f531456ea..effc26675 100644
--- a/specs/MEMORY_SPEC.md
+++ b/specs/MEMORY_SPEC.md
@@ -128,6 +128,55 @@ Same as `ipfs` but the content is encrypted to the owner's wallet pubkey (ECIES
Agent is stateless across sessions. Useful for demos, kiosks, one-shot interactions.
+### Custom modes
+
+Any `memory.mode` value that is not one of the five built-ins resolves to a backend you registered via `Memory.registerBackend` — see [Custom backends](#custom-backends). If no backend matches, the runtime warns once and falls back to `local`, so a typo can never break the embed.
+
+## Custom backends
+
+You can plug an arbitrary store — a vector database, an episodic event log, your own API — behind a named mode without forking the `Memory` class. Register it once at startup; from then on `memory.mode: "<name>"` (or `<agent-3d memory="<name>">`) routes through it.
+
+```js
+import { Memory } from 'https://three.ws/agent-3d/latest/agent-3d.js';
+
+Memory.registerBackend('vector', {
+ // REQUIRED. Hydrate persisted state. Receives the full Memory.load opts
+ // (namespace, manifestURI, fetchFn, plus anything extra you pass through).
+ // Return any subset of { files, timeline, index }.
+ async load({ namespace }) {
+ const rows = await myVectorStore.fetchAll(namespace);
+ const files = Object.fromEntries(rows.map((r) => [r.filename, r.markdown]));
+ return { files };
+ },
+
+ // OPTIONAL. Called after every write() and note(). Inspect memory.files
+ // (a Map) and memory.timeline (an array) and ship them to your store.
+ async persist(memory) {
+ for (const [filename, markdown] of memory.files) {
+ await myVectorStore.upsert(memory.namespace, { filename, markdown });
+ }
+ await myEpisodicLog.replace(memory.namespace, memory.timeline);
+ },
+
+ // OPTIONAL. Real semantic search. Return ranked { file, meta, body, score }
+ // hits. If it throws, Memory silently falls back to substring matching, so
+ // recall never hard-fails mid-conversation.
+ async recall(query, memory, { limit = 5 } = {}) {
+ const matches = await myVectorStore.search(memory.namespace, query, limit);
+ return matches.map((m) => ({ file: m.filename, meta: m.meta, body: m.body, score: m.score }));
+ },
+});
+```
+
+Contract notes:
+
+- `load` is the only required hook. A backend with just `load` is read-through; add `persist` to make it durable, `recall` to make search semantic.
+- `persist` is fire-and-forget on `write`/`note` (so those stay synchronous, matching `local`/`remote`); it is awaited on `agent.memory.save()`. Make it idempotent.
+- Built-in mode names (`none`, `local`, `remote`, `ipfs`, `encrypted-ipfs`) are reserved — `registerBackend` throws if you try to shadow one.
+- `Memory.backends()` lists registered names; `Memory.unregisterBackend(name)` removes one.
+
+The lighter-weight extension point — keeping built-in storage but swapping only the ranker — is `manifest.json → memory.retriever` (see [Retrieval](#retrieval)). Reach for a full backend when you also own where the bytes live.
+
## Retrieval
The runtime budgets `memory.maxTokens` (default 8192) per turn and fills it with:
@@ -176,11 +225,43 @@ Explicit user request ("forget that I..."): delete the file, update `MEMORY.md`,
Automatic decay (per frontmatter `decay`): retrieval layer down-weights; files are not deleted without user confirmation.
+## Snapshot contract
+
+`agent.memory.snapshot()` returns a stable, JSON-safe object — the `memory/0.1` contract — that fully describes an agent's memory at a point in time. It is synchronous, so embedded widgets can serialize/deserialize across page reloads, `postMessage` between frames, or stash state in `sessionStorage`.
+
+```jsonc
+{
+ "version": "memory/0.1",
+ "mode": "local", // the storage mode this snapshot came from
+ "namespace": "agent-uuid",
+ "index": "# Memory\n\n## User\n- [Role](user_role.md) — …",
+ "files": { "user_role.md": "---\nname: Role\n…", /* … */ },
+ "timeline": [ { "ts": "2026-04-14T12:03:12Z", "type": "waved", "style": "casual" } ]
+}
+```
+
+Rehydrate with `Memory.fromSnapshot`. Overrides win over the snapshot's own values, so you can restore into a fresh agent id:
+
+```js
+// Embedded widget — survive a reload:
+sessionStorage.setItem('agent-mem', JSON.stringify(agent.memory.snapshot()));
+
+// …after reload:
+const restored = Memory.fromSnapshot(JSON.parse(sessionStorage.getItem('agent-mem')));
+// or graft onto a new identity:
+const forked = Memory.fromSnapshot(snap, { mode: 'remote', namespace: newAgentId });
+```
+
+If a snapshot omits `index` but carries `files`, `fromSnapshot` rebuilds the index automatically.
+
## Export / import
+`export()` is the async alias for `snapshot()` and returns the same `memory/0.1` shape; `import()` merges another agent's snapshot in (last-write-wins on the timeline, additive on files):
+
```js
-const blob = await agent.memory.export(); // tarball of memory/
-await otherAgent.memory.import(blob); // merges with conflict resolution
+const blob = await agent.memory.export(); // === agent.memory.snapshot()
+await otherAgent.memory.import(blob); // merge (default)
+await otherAgent.memory.import(blob, { strategy: 'replace' }); // overwrite
```
Enables memory-as-inheritance: fork an agent, carry the memories forward.
diff --git a/src/memory/index.js b/src/memory/index.js
index a06d0c8ab..35bd21060 100644
--- a/src/memory/index.js
+++ b/src/memory/index.js
@@ -17,6 +17,13 @@ import { log } from '../shared/log.js';
const FRONTMATTER_RE = /^---\n([\s\S]*?)\n---\n?([\s\S]*)$/;
+// Built-in modes — reserved names a custom backend may not shadow.
+const RESERVED_MODES = new Set(['none', 'local', 'remote', 'ipfs', 'encrypted-ipfs']);
+
+// Registry of custom backends: mode name -> backend definition.
+// See Memory.registerBackend and specs/MEMORY_SPEC.md → "Custom backends".
+const BACKENDS = new Map();
+
function parseFrontmatter(text) {
const m = text.match(FRONTMATTER_RE);
if (!m) return { meta: {}, body: text };
@@ -45,31 +52,72 @@ function pack({ nonce, ciphertext }) {
}
export class Memory {
- constructor({ mode = 'local', namespace, index = {}, files = {}, timeline = [], cryptoKey = null, remoteIds = {} } = {}) {
+ constructor({ mode = 'local', namespace, index = {}, files = {}, timeline = [], cryptoKey = null, remoteIds = {}, backend = null } = {}) {
this.mode = mode;
this.namespace = namespace;
this.files = new Map(Object.entries(files));
this.timeline = timeline;
- this.indexText = index.text || '';
+ // `index` accepts either the legacy `{ text }` shape or a bare string
+ // (the snapshot contract), so a snapshot round-trips cleanly.
+ this.indexText = typeof index === 'string' ? index : index?.text || '';
this.cryptoKey = cryptoKey;
// remote mode: filename -> backend entry id, for upsert round-trip
this._remoteIds = new Map(Object.entries(remoteIds));
+ // Custom backend definition when `mode` resolves to a registered backend;
+ // null for built-in modes. Drives _persist / recall / save delegation.
+ this._backend = backend;
this._dirty = false;
}
+ /**
+ * Register a custom memory backend so `mode: "<name>"` resolves to it —
+ * the documented way to plug a vector store, episodic log, or any external
+ * store without forking the Memory class.
+ *
+ * @param {string} name - Mode name used in the manifest / `<agent-3d memory>`.
+ * May not shadow a built-in mode (none/local/remote/ipfs/encrypted-ipfs).
+ * @param {Object} backend
+ * @param {(opts) => Promise<{files?, timeline?, index?}>} backend.load -
+ * Hydrate persisted state. Receives the full `Memory.load` opts
+ * (`namespace`, `manifestURI`, `fetchFn`, plus any extras you pass).
+ * @param {(memory: Memory) => void|Promise<void>} [backend.persist] -
+ * Called after every `write` and `note`. Inspect `memory.files`
+ * (Map) and `memory.timeline` (array) to ship state to your store.
+ * @param {(query: string, memory: Memory, opts) => Promise<Array>} [backend.recall] -
+ * Semantic search. Return ranked `{ file, meta, body, score }` hits.
+ * Falls back to the built-in substring matcher if it throws.
+ */
+ static registerBackend(name, backend) {
+ if (RESERVED_MODES.has(name))
+ throw new Error(`"${name}" is a built-in memory mode and cannot be overridden`);
+ if (!backend || typeof backend.load !== 'function')
+ throw new Error('memory backend must implement load(opts)');
+ BACKENDS.set(name, backend);
+ }
+
+ static unregisterBackend(name) {
+ return BACKENDS.delete(name);
+ }
+
+ static backends() {
+ return [...BACKENDS.keys()];
+ }
+
/**
* Load a Memory instance for the given mode. See file header for the
* mode table. Unknown modes warn once and fall back to `local`.
*
* @param {Object} opts
- * @param {'none'|'local'|'remote'|'ipfs'|'encrypted-ipfs'} [opts.mode]
+ * @param {'none'|'local'|'remote'|'ipfs'|'encrypted-ipfs'|string} [opts.mode] -
+ * A built-in mode, or the name of a backend registered via registerBackend.
* @param {string} opts.namespace - Stable id (usually agent UUID)
* @param {string} [opts.manifestURI] - Required for ipfs / encrypted-ipfs
* @param {typeof fetch} [opts.fetchFn] - Override fetch (tests / SSR)
* @param {() => Promise<CryptoKey>} [opts.deriveKey] - Required for encrypted-ipfs
* @returns {Promise<Memory>}
*/
- static async load({ mode = 'local', namespace, manifestURI, fetchFn, deriveKey }) {
+ static async load(opts = {}) {
+ const { mode = 'local', namespace, manifestURI, fetchFn, deriveKey } = opts;
if (mode === 'none') return new Memory({ mode: 'none', namespace });
if (mode === 'local') return Memory._loadLocal(namespace);
if (mode === 'remote') return Memory._loadRemote({ namespace, fetchFn });
@@ -78,10 +126,33 @@ export class Memory {
throw new Error('encrypted-ipfs mode requires a deriveKey function');
return Memory._loadIPFS({ mode, namespace, manifestURI, fetchFn, deriveKey });
}
+ const backend = BACKENDS.get(mode);
+ if (backend) return Memory._loadBackend(backend, opts);
log.warn(`[memory] unknown mode "${mode}"; falling back to "local"`);
return Memory._loadLocal(namespace);
}
+ static async _loadBackend(backend, opts) {
+ const { mode, namespace } = opts;
+ let data = {};
+ try {
+ data = (await backend.load(opts)) || {};
+ } catch (e) {
+ log.warn(`[memory] backend "${mode}" load failed; starting empty`, e);
+ }
+ const mem = new Memory({
+ mode,
+ namespace,
+ files: data.files || {},
+ timeline: data.timeline || [],
+ index: data.index || '',
+ backend,
+ });
+ // Backend supplied files but no index — derive one so MEMORY.md is present.
+ if (!mem.indexText && mem.files.size) mem._rebuildIndex();
+ return mem;
+ }
+
static async _loadRemote({ namespace, fetchFn }) {
const f = fetchFn || fetch.bind(globalThis);
if (!namespace) return new Memory({ mode: 'remote', namespace });
@@ -203,7 +274,17 @@ export class Memory {
this._persist();
}
- async recall(query, { limit = 5 } = {}) {
+ async recall(query, opts = {}) {
+ // A registered backend can supply real semantic search (vector store);
+ // fall back to the built-in substring matcher if it errors.
+ if (this._backend?.recall) {
+ try {
+ return await this._backend.recall(query, this, opts);
+ } catch (e) {
+ log.warn('[memory] backend recall failed; using substring fallback', e);
+ }
+ }
+ const { limit = 5 } = opts;
// Placeholder: naive substring match. Real impl: embeddings via runtime.
const q = query.toLowerCase();
const hits = [];
@@ -268,6 +349,18 @@ export class Memory {
}
_persist() {
+ // Custom backend owns persistence — fire-and-forget so write()/note()
+ // stay synchronous, matching local/remote semantics.
+ if (this._backend?.persist) {
+ try {
+ Promise.resolve(this._backend.persist(this)).catch((e) =>
+ log.warn('[memory] backend persist failed', e),
+ );
+ } catch (e) {
+ log.warn('[memory] backend persist failed', e);
+ }
+ return;
+ }
if (this.mode !== 'local' || !this.namespace) return;
const key = `agent:${this.namespace}:memory`;
const data = {
@@ -313,6 +406,12 @@ export class Memory {
// Encrypt all files and pin to IPFS. Returns { cids, memoryCid }.
// For local mode, falls back to synchronous _persist(). Noop for other modes.
async save() {
+ // Custom backend: await its persist so callers can rely on durability.
+ if (this._backend?.persist) {
+ await this._backend.persist(this);
+ this._dirty = false;
+ return;
+ }
if (this.mode === 'local') {
this._persist();
return;
@@ -384,15 +483,50 @@ export class Memory {
return parts.join('\n');
}
- async export() {
+ /**
+ * Canonical serializable snapshot — the `memory/0.1` contract. Synchronous
+ * and JSON-safe, so embedded widgets can persist it to sessionStorage or
+ * postMessage it across reloads, then rehydrate with Memory.fromSnapshot.
+ *
+ * @returns {{version, mode, namespace, index, files, timeline}}
+ */
+ snapshot() {
return {
version: 'memory/0.1',
+ mode: this.mode,
+ namespace: this.namespace,
index: this.indexText,
files: Object.fromEntries(this.files),
timeline: this.timeline,
};
}
+ /**
+ * Rehydrate a Memory from a snapshot() blob. `mode`/`namespace` overrides
+ * win over the snapshot's own values (e.g. restoring into a fresh agent id).
+ *
+ * @param {ReturnType<Memory['snapshot']>} snapshot
+ * @param {{mode?: string, namespace?: string}} [overrides]
+ * @returns {Memory}
+ */
+ static fromSnapshot(snapshot = {}, { mode, namespace } = {}) {
+ const mem = new Memory({
+ mode: mode || snapshot.mode || 'local',
+ namespace: namespace || snapshot.namespace,
+ index: snapshot.index || '',
+ files: snapshot.files || {},
+ timeline: snapshot.timeline || [],
+ });
+ if (!mem.indexText && mem.files.size) mem._rebuildIndex();
+ return mem;
+ }
+
+ // Async alias for snapshot() — retained for back-compat with the
+ // export()/import() pair documented in MEMORY_SPEC.md.
+ async export() {
+ return this.snapshot();
+ }
+
async import(blob, { strategy = 'merge' } = {}) {
if (strategy === 'replace') {
this.files = new Map(Object.entries(blob.files || {}));
diff --git a/tests/memory-modes.test.js b/tests/memory-modes.test.js
index 2dda05601..e9ac00d7c 100644
--- a/tests/memory-modes.test.js
+++ b/tests/memory-modes.test.js
@@ -148,3 +148,97 @@ describe('Memory.load — unknown mode fallback', () => {
expect(mem.read('x')?.body.trim()).toBe('ok');
});
});
+
+// ── custom backend registry ──────────────────────────────────────────────────
+
+describe('Memory.registerBackend', () => {
+ afterEach(() => {
+ Memory.unregisterBackend('vector');
+ });
+
+ it('refuses to shadow a built-in mode and validates the backend shape', () => {
+ expect(() => Memory.registerBackend('local', { load() {} })).toThrow(/built-in/);
+ expect(() => Memory.registerBackend('vector', {})).toThrow(/load/);
+ expect(Memory.backends()).not.toContain('vector');
+ });
+
+ it('hydrates via the backend load hook and reports the custom mode', async () => {
+ const load = vi.fn().mockResolvedValue({
+ files: { 'user_role.md': '---\nname: role\ntype: user\n---\n\nseeded' },
+ });
+ Memory.registerBackend('vector', { load });
+
+ const mem = await Memory.load({ mode: 'vector', namespace: 'agent-9', extra: 'passed' });
+ expect(mem.mode).toBe('vector');
+ expect(Memory.backends()).toContain('vector');
+ // Full opts object reaches the backend (namespace + arbitrary extras).
+ expect(load.mock.calls[0][0]).toMatchObject({ namespace: 'agent-9', extra: 'passed' });
+ expect(mem.read('user_role')?.body.trim()).toBe('seeded');
+ // Index is derived from hydrated files when the backend omits one.
+ expect(mem.indexText).toContain('user_role.md');
+ });
+
+ it('routes writes and notes through the persist hook', async () => {
+ const persist = vi.fn();
+ Memory.registerBackend('vector', { load: () => ({}), persist });
+
+ const mem = await Memory.load({ mode: 'vector', namespace: 'agent-9' });
+ mem.write('feedback_tone', { name: 't', description: 'd', type: 'feedback', body: 'b' });
+ mem.note('waved', { style: 'casual' });
+ await new Promise((r) => setTimeout(r, 0)); // flush fire-and-forget persist
+
+ expect(persist).toHaveBeenCalledTimes(2);
+ expect(persist.mock.calls[0][0]).toBe(mem); // receives the live Memory
+ // localStorage is never touched for a custom backend.
+ expect(globalThis.localStorage.store.size).toBe(0);
+ });
+
+ it('delegates recall to the backend and falls back on error', async () => {
+ const recall = vi.fn().mockResolvedValue([{ file: 'x.md', score: 1 }]);
+ Memory.registerBackend('vector', { load: () => ({}), recall });
+
+ const mem = await Memory.load({ mode: 'vector', namespace: 'agent-9' });
+ const hits = await mem.recall('how does the user prefer feedback', { limit: 3 });
+ expect(recall).toHaveBeenCalledWith('how does the user prefer feedback', mem, { limit: 3 });
+ expect(hits).toEqual([{ file: 'x.md', score: 1 }]);
+
+ // A throwing backend recall must not break the agent — substring fallback.
+ recall.mockRejectedValueOnce(new Error('vector store down'));
+ vi.spyOn(log, 'warn').mockImplementation(() => {});
+ mem.write('feedback_tone', { name: 't', description: 'direct critique', type: 'feedback', body: 'direct' });
+ const fallback = await mem.recall('direct');
+ expect(fallback[0]?.file).toBe('feedback_tone.md');
+ });
+});
+
+// ── snapshot contract ────────────────────────────────────────────────────────
+
+describe('Memory snapshot/fromSnapshot', () => {
+ it('round-trips files, timeline, and the index through a JSON snapshot', async () => {
+ const mem = await Memory.load({ mode: 'local', namespace: 'agent-snap' });
+ mem.write('user_role', { name: 'role', description: 'who', type: 'user', body: 'hello' });
+ mem.note('waved', { style: 'casual' });
+
+ // Snapshot must survive a real JSON serialization (embed/postMessage path).
+ const snap = JSON.parse(JSON.stringify(mem.snapshot()));
+ expect(snap.version).toBe('memory/0.1');
+ expect(snap.index).toContain('user_role.md');
+
+ const restored = Memory.fromSnapshot(snap);
+ expect(restored.mode).toBe('local');
+ expect(restored.namespace).toBe('agent-snap');
+ expect(restored.read('user_role')?.body.trim()).toBe('hello');
+ expect(restored.indexText).toContain('user_role.md');
+ expect(restored.timeline.at(-1)?.type).toBe('waved');
+ });
+
+ it('rebuilds the index when the snapshot omits it, and honors overrides', () => {
+ const restored = Memory.fromSnapshot(
+ { files: { 'user_role.md': '---\nname: role\ntype: user\n---\n\nbody' } },
+ { mode: 'none', namespace: 'fresh-id' },
+ );
+ expect(restored.mode).toBe('none');
+ expect(restored.namespace).toBe('fresh-id');
+ expect(restored.indexText).toContain('user_role.md');
+ });
+});
diff --git a/vercel.json b/vercel.json
index 4fbab23b5..b6c4ad3ee 100644
--- a/vercel.json
+++ b/vercel.json
@@ -83,14 +83,14 @@
"strict-transport-security": "max-age=63072000; includeSubDomains; preload",
"x-content-type-options": "nosniff",
"referrer-policy": "strict-origin-when-cross-origin",
- "content-security-policy": "base-uri 'self'; object-src 'none'; script-src 'self' 'unsafe-inline' 'unsafe-eval' blob: https://cdn.jsdelivr.net https://cdnjs.cloudflare.com https://unpkg.com https://esm.sh https://ajax.googleapis.com https://s3.tradingview.com https://platform.twitter.com https://3d-agent.vercel.app https://three.ws https://3d.irish; worker-src 'self' blob:; frame-ancestors *"
+ "content-security-policy": "base-uri 'self'; object-src 'none'; script-src 'self' 'unsafe-inline' 'unsafe-eval' blob: https://cdn.jsdelivr.net https://cdnjs.cloudflare.com https://unpkg.com https://esm.sh https://ajax.googleapis.com https://s3.tradingview.com https://platform.twitter.com https://3d-agent.vercel.app https://three.ws https://3d.irish; worker-src 'self' blob:; frame-ancestors *; report-uri /api/client-errors"
},
"continue": true
},
{
"src": "/(login|register|forgot-password|reset-password|account|settings|wallet|pay|paywall|vanity-wallet|eth-vanity|evm-wallet|dashboard|dashboard-next|dashboard-classic)(/.*)?$",
"headers": {
- "content-security-policy": "frame-ancestors 'self'; base-uri 'self'; object-src 'none'; script-src 'self' 'unsafe-inline' 'unsafe-eval' blob: https://cdn.jsdelivr.net https://cdnjs.cloudflare.com https://unpkg.com https://esm.sh https://ajax.googleapis.com https://s3.tradingview.com https://platform.twitter.com https://3d-agent.vercel.app https://three.ws https://3d.irish; worker-src 'self' blob:",
+ "content-security-policy": "frame-ancestors 'self'; base-uri 'self'; object-src 'none'; script-src 'self' 'unsafe-inline' 'unsafe-eval' blob: https://cdn.jsdelivr.net https://cdnjs.cloudflare.com https://unpkg.com https://esm.sh https://ajax.googleapis.com https://s3.tradingview.com https://platform.twitter.com https://3d-agent.vercel.app https://three.ws https://3d.irish; worker-src 'self' blob:; report-uri /api/client-errors",
"x-frame-options": "SAMEORIGIN"
},
"continue": true
@@ -608,7 +608,7 @@
{
"src": "/walk-embed/?",
"headers": {
- "content-security-policy": "frame-ancestors *; base-uri 'self'; object-src 'none'",
+ "content-security-policy": "frame-ancestors *; base-uri 'self'; object-src 'none'; report-uri /api/client-errors",
"x-content-type-options": "nosniff",
"referrer-policy": "strict-origin-when-cross-origin",
"cross-origin-resource-policy": "cross-origin"
@@ -725,7 +725,7 @@
{
"src": "/embed/avatar",
"headers": {
- "content-security-policy": "frame-ancestors *; base-uri 'self'; object-src 'none'",
+ "content-security-policy": "frame-ancestors *; base-uri 'self'; object-src 'none'; report-uri /api/client-errors",
"x-content-type-options": "nosniff",
"referrer-policy": "strict-origin-when-cross-origin",
"permissions-policy": "microphone=(self), camera=(self), xr-spatial-tracking=*",
@@ -736,7 +736,7 @@
{
"src": "/embed/avatar/([a-z0-9_-]{3,30})",
"headers": {
- "content-security-policy": "frame-ancestors *; base-uri 'self'; object-src 'none'",
+ "content-security-policy": "frame-ancestors *; base-uri 'self'; object-src 'none'; report-uri /api/client-errors",
"x-content-type-options": "nosniff",
"referrer-policy": "strict-origin-when-cross-origin",
"permissions-policy": "microphone=(self), camera=(self), xr-spatial-tracking=*",
@@ -771,7 +771,7 @@
{
"src": "/widget",
"headers": {
- "content-security-policy": "frame-ancestors *; base-uri 'self'; object-src 'none'",
+ "content-security-policy": "frame-ancestors *; base-uri 'self'; object-src 'none'; report-uri /api/client-errors",
"x-content-type-options": "nosniff",
"referrer-policy": "strict-origin-when-cross-origin",
"permissions-policy": "microphone=(self), camera=(self), xr-spatial-tracking=*, autoplay=*",
@@ -782,7 +782,7 @@
{
"src": "/widget/",
"headers": {
- "content-security-policy": "frame-ancestors *; base-uri 'self'; object-src 'none'",
+ "content-security-policy": "frame-ancestors *; base-uri 'self'; object-src 'none'; report-uri /api/client-errors",
"x-content-type-options": "nosniff",
"referrer-policy": "strict-origin-when-cross-origin",
"permissions-policy": "microphone=(self), camera=(self), xr-spatial-tracking=*, autoplay=*",
@@ -793,7 +793,7 @@
{
"src": "/widget\\.html$",
"headers": {
- "content-security-policy": "frame-ancestors *; base-uri 'self'; object-src 'none'",
+ "content-security-policy": "frame-ancestors *; base-uri 'self'; object-src 'none'; report-uri /api/client-errors",
"x-content-type-options": "nosniff",
"referrer-policy": "strict-origin-when-cross-origin",
"permissions-policy": "microphone=(self), camera=(self), xr-spatial-tracking=*, autoplay=*",
@@ -1262,6 +1262,14 @@
"src": "/skills/",
"dest": "/skills.html"
},
+ {
+ "src": "/status",
+ "dest": "/status.html"
+ },
+ {
+ "src": "/status/",
+ "dest": "/status.html"
+ },
{
"src": "/marketplace",
"dest": "/marketplace.html"
@@ -1944,7 +1952,7 @@
{
"src": "/agent/([^/]+)/embed",
"headers": {
- "content-security-policy": "frame-ancestors *; base-uri 'self'; object-src 'none'",
+ "content-security-policy": "frame-ancestors *; base-uri 'self'; object-src 'none'; report-uri /api/client-errors",
"x-content-type-options": "nosniff",
"referrer-policy": "strict-origin-when-cross-origin",
"permissions-policy": "microphone=(self), camera=(self), xr-spatial-tracking=*",
@@ -2880,7 +2888,7 @@
{
"src": "/a/(\\d+)/(\\d+)/embed",
"headers": {
- "content-security-policy": "frame-ancestors *; base-uri 'self'; object-src 'none'",
+ "content-security-policy": "frame-ancestors *; base-uri 'self'; object-src 'none'; report-uri /api/client-errors",
"x-content-type-options": "nosniff",
"referrer-policy": "strict-origin-when-cross-origin",
"permissions-policy": "microphone=(self), camera=(self), xr-spatial-tracking=*"
@@ -2982,6 +2990,10 @@
"path": "/api/cron/expire-pending-purchases",
"schedule": "*/5 * * * *"
},
+ {
+ "path": "/api/cron/uptime-check",
+ "schedule": "*/5 * * * *"
+ },
{
"path": "/api/cron/cleanup-csrf-tokens",
"schedule": "17 * * * *"
diff --git a/vite.config.js b/vite.config.js
index 5a5b2e619..8ea2266a3 100644
--- a/vite.config.js
+++ b/vite.config.js
@@ -348,6 +348,7 @@ const appConfig = {
'x-pricing': resolve(__dirname, 'pages/x-pricing.html'),
'avatar-studio-demo': resolve(__dirname, 'pages/avatar-studio-demo.html'),
'gallery-picker': resolve(__dirname, 'pages/gallery-picker.html'),
+ status: resolve(__dirname, 'pages/status.html'),
xr: resolve(__dirname, 'pages/xr.html'),
walk: resolve(__dirname, 'pages/walk.html'),
communities: resolve(__dirname, 'pages/communities.html'),
@@ -632,6 +633,8 @@ const appConfig = {
'/gallery/': resolve(root, 'public/gallery/index.html'),
'/gallery-picker': resolve(root, 'pages/gallery-picker.html'),
'/gallery-picker/': resolve(root, 'pages/gallery-picker.html'),
+ '/status': resolve(root, 'pages/status.html'),
+ '/status/': resolve(root, 'pages/status.html'),
'/marketplace': resolve(root, 'pages/marketplace.html'),
'/marketplace/': resolve(root, 'pages/marketplace.html'),
'/marketplace/tools': resolve(root, 'pages/marketplace.html'),