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(api): NVIDIA NIM TTS/embed/rerank hardening, knowledge re-embedder migration, uptime+status polish, expanded api test coverage

nirholasb5ab1790920b
diff --git a/api/_lib/alerts.js b/api/_lib/alerts.js
index 149715ed7..0a66bcbb2 100644
--- a/api/_lib/alerts.js
+++ b/api/_lib/alerts.js
@@ -1,3 +1,4 @@
+// @ts-check
// Real-time ops alerts → Telegram. Errors should find the operator, not wait
// to be hunted: serverError()/wrap() report 5xx server faults here and
// api/client-errors.js reports browser errors, so production failures surface
diff --git a/api/_lib/elevenlabs.js b/api/_lib/elevenlabs.js
index 273ee9bf3..1ce0535d8 100644
--- a/api/_lib/elevenlabs.js
+++ b/api/_lib/elevenlabs.js
@@ -1,3 +1,4 @@
+// @ts-check
// Shared ElevenLabs client + helpers.
//
// Centralizes the base URL, the API-key gate, the cached voice catalog, voice
@@ -146,10 +147,17 @@ export async function createClonedVoice({ name, description, files }) {
throw upstreamError(`ElevenLabs returned ${status}`, status, { upstreamBody });
}
- if (!result?.voice_id) throw upstreamError('ElevenLabs response missing voice_id', 502);
+ // SDK ≥2 returns camelCase model fields (voiceId); tolerate the legacy
+ // snake_case wire shape too so an SDK downgrade can't silently break cloning.
+ const raw = /** @type {any} */ (result);
+ const voiceId = raw?.voiceId ?? raw?.voice_id;
+ if (!voiceId) throw upstreamError('ElevenLabs response missing voice_id', 502);
invalidateVoiceCache();
- return { voiceId: result.voice_id, requiresVerification: !!result.requires_verification };
+ return {
+ voiceId,
+ requiresVerification: !!(raw.requiresVerification ?? raw.requires_verification),
+ };
}
/**
diff --git a/api/_lib/http.js b/api/_lib/http.js
index de4b0dc84..fa3be71f5 100644
--- a/api/_lib/http.js
+++ b/api/_lib/http.js
@@ -1,3 +1,4 @@
+// @ts-check
// HTTP helpers for Vercel Node handlers. Keeps handlers small + consistent.
import { webcrypto } from 'node:crypto';
@@ -36,7 +37,7 @@ export function error(res, status, code, message, extra = {}) {
// full server-side log line. Not security-sensitive — just needs to be unique.
function correlationId() {
const b = new Uint8Array(8);
- (globalThis.crypto || webcrypto).getRandomValues(b);
+ /** @type {Crypto} */ (globalThis.crypto || webcrypto).getRandomValues(b);
return Array.from(b, (x) => x.toString(16).padStart(2, '0')).join('');
}
@@ -118,17 +119,13 @@ export function validationError(res, err) {
export async function readJson(req, limit = 1_000_000) {
const ct = req.headers['content-type'] || '';
if (!ct.includes('application/json')) {
- const err = new Error('content-type must be application/json');
- err.status = 415;
- throw err;
+ throw Object.assign(new Error('content-type must be application/json'), { status: 415 });
}
return readBody(req, limit).then((buf) => {
try {
return JSON.parse(buf.toString('utf8'));
} catch {
- const e = new Error('invalid JSON');
- e.status = 400;
- throw e;
+ throw Object.assign(new Error('invalid JSON'), { status: 400 });
}
});
}
@@ -138,7 +135,7 @@ export async function readForm(req, limit = 1_000_000) {
return Object.fromEntries(new URLSearchParams(buf.toString('utf8')));
}
-function readBody(req, limit) {
+export function readBody(req, limit) {
return new Promise((resolve, reject) => {
const chunks = [];
let total = 0;
diff --git a/api/_lib/migrations/2026-06-11-knowledge-embedder-tag.sql b/api/_lib/migrations/2026-06-11-knowledge-embedder-tag.sql
new file mode 100644
index 000000000..2e694a013
--- /dev/null
+++ b/api/_lib/migrations/2026-06-11-knowledge-embedder-tag.sql
@@ -0,0 +1,26 @@
+-- Migration: vector-space tagging for widget knowledge embeddings.
+--
+-- Embeddings from different models are different vector spaces; comparing a
+-- query embedded with model A against passages embedded with model B returns
+-- plausible-looking garbage. Every stored vector (chunk) and document set
+-- (doc) therefore carries an `embedder` tag — '<model>@<dim>' — and query
+-- time embeds the search string with the SAME tag (api/_lib/embeddings.js).
+--
+-- Every row that exists before this migration was embedded with OpenAI
+-- text-embedding-3-small @ 256 dims (the only embedder the platform ever had
+-- on this surface), so the legacy backfill below encodes that assumption
+-- explicitly. Code additionally treats a null tag as the same legacy space
+-- (LEGACY_EMBED_TAG), covering rows written by old code after this runs.
+--
+-- Apply: npm run db:migrate -- --apply --file 2026-06-11-knowledge-embedder-tag.sql
+-- Idempotent.
+
+begin;
+
+alter table widget_knowledge_docs add column if not exists embedder text;
+alter table widget_knowledge_chunks add column if not exists embedder text;
+
+update widget_knowledge_docs set embedder = 'text-embedding-3-small@256' where embedder is null;
+update widget_knowledge_chunks set embedder = 'text-embedding-3-small@256' where embedder is null;
+
+commit;
diff --git a/api/_lib/schema.sql b/api/_lib/schema.sql
index 72beb606c..478667020 100644
--- a/api/_lib/schema.sql
+++ b/api/_lib/schema.sql
@@ -610,10 +610,13 @@ create table if not exists widget_knowledge_docs (
status text not null default 'ready' check (status in ('queued', 'processing', 'ready', 'failed')),
error text,
source_text text, -- held server-side until QStash worker consumes it
+ embedder text, -- vector space tag ('<model>@<dim>'); null = legacy text-embedding-3-small@256
created_at timestamptz not null default now(),
updated_at timestamptz not null default now()
);
+alter table widget_knowledge_docs add column if not exists embedder text;
+
create index if not exists widget_knowledge_docs_widget
on widget_knowledge_docs(widget_id, created_at desc);
create index if not exists widget_knowledge_docs_user
@@ -624,11 +627,15 @@ do $$ begin
for each row execute function set_updated_at();
exception when duplicate_object then null; end $$;
--- ── widget_knowledge_chunks — 512/100-overlap chunks with truncated embeds ──
--- Embedding is text-embedding-3-small @ 256 dims (Matryoshka), stored as a
--- JSONB float array. Retrieval scores via cosine similarity in JS at query
--- time; switch to pgvector if a single widget grows past several thousand
--- chunks.
+-- ── widget_knowledge_chunks — 512/100-overlap chunks with tagged embeds ─────
+-- Embedding is stored as a JSONB float array, produced by the embedder named
+-- in `embedder` ('<model>@<dim>', e.g. 'nvidia/nv-embedqa-e5-v5@1024' on the
+-- free NIM lane or 'text-embedding-3-small@256' on OpenAI; null = legacy
+-- OpenAI rows). Vectors from different embedders are different spaces — query
+-- time embeds the search string with the SAME tag and never compares across
+-- tags (api/_lib/embeddings.js scoreRowsBySpace). Retrieval scores via cosine
+-- similarity in JS at query time; switch to pgvector if a single widget grows
+-- past several thousand chunks.
create table if not exists widget_knowledge_chunks (
id bigserial primary key,
doc_id text not null references widget_knowledge_docs(id) on delete cascade,
@@ -637,9 +644,12 @@ create table if not exists widget_knowledge_chunks (
content text not null,
embedding jsonb not null,
token_count integer not null default 0,
+ embedder text,
created_at timestamptz not null default now()
);
+alter table widget_knowledge_chunks add column if not exists embedder text;
+
create index if not exists widget_knowledge_chunks_widget
on widget_knowledge_chunks(widget_id);
create index if not exists widget_knowledge_chunks_doc
diff --git a/api/_lib/tts-nvidia.js b/api/_lib/tts-nvidia.js
index 90b0eb408..931867aec 100644
--- a/api/_lib/tts-nvidia.js
+++ b/api/_lib/tts-nvidia.js
@@ -82,11 +82,14 @@ export function resolveMagpieVoice(voice, language) {
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).
+// Magpie cannot encode mp3/aac/flac, and its OGGOPUS output over NVCF is
+// length-framed raw Opus packets WITHOUT an Ogg container (live-verified
+// 2026-06-11 — no OggS magic anywhere in the payload), so it is not directly
+// playable either. Every non-pcm request is therefore served as WAV; browser
+// decoders sniff the container, and content-type + x-tts-format stay truthful
+// about what was actually sent. The OpenAI backstop still produces native
+// mp3/opus/aac/flac when it serves.
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' };
}
@@ -135,6 +138,12 @@ function normalizeGrpcError(err) {
// 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.
+//
+// NVCF gotcha (live-observed): authorization is validated when the gRPC
+// stream/connection is established — an already-authenticated warm channel
+// keeps serving even if the key in env later changes. Irrelevant for prod
+// (the key is fixed per deployment), but key-rotation tests must use a fresh
+// process (see scripts/verify-nvidia-tts.mjs).
let clientPromise = null;
async function getClient() {
if (!clientPromise) {
diff --git a/api/client-errors.js b/api/client-errors.js
index bd7836b55..672dc0218 100644
--- a/api/client-errors.js
+++ b/api/client-errors.js
@@ -1,3 +1,4 @@
+// @ts-check
// Ingest endpoint for first-party client-side error reports sent by
// public/error-reporter.js (loaded on every page). Each accepted event is
// logged as one structured "[client-error]" line so browser errors from real
@@ -8,13 +9,13 @@
// and re-truncates everything anyway — the payload is attacker-controllable
// public input, so nothing from it is trusted or echoed back.
-import { cors, json, method, readJson, wrap, error, rateLimited } from './_lib/http.js';
+import { cors, json, method, readJson, readBody, 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']);
+const EVENT_TYPES = new Set(['error', 'unhandledrejection', 'resource', 'manual', 'csp']);
const LIMITS = { message: 500, stack: 4000, url: 500, name: 100, tag: 20 };
function str(value, max) {
@@ -26,6 +27,20 @@ function int(value) {
return Number.isFinite(value) ? Math.trunc(value) : undefined;
}
+// Map both CSP report wire formats onto our event shape:
+// report-uri: { "csp-report": { "violated-directive", "blocked-uri", ... } }
+// report-to: [ { type: "csp-violation", body: { effectiveDirective, blockedURL, ... } } ]
+function cspToEvents(raw) {
+ const reports = Array.isArray(raw) ? raw.map((r) => r?.body || r) : [raw?.['csp-report'] || raw];
+ return reports.filter(Boolean).map((r) => ({
+ type: 'csp',
+ message: `CSP violation: ${r['effective-directive'] || r.effectiveDirective || r['violated-directive'] || r.violatedDirective || 'unknown directive'}`,
+ source: r['blocked-uri'] || r.blockedURL || r['document-uri'] || r.documentURL,
+ line: r['line-number'] ?? r.lineNumber,
+ col: r['column-number'] ?? r.columnNumber,
+ }));
+}
+
function sanitizeEvent(raw) {
if (!raw || typeof raw !== 'object') return null;
const type = EVENT_TYPES.has(raw.type) ? raw.type : null;
@@ -52,9 +67,23 @@ export default wrap(async (req, res) => {
const rl = await limits.clientErrorsIp(ip);
if (!rl.success) return rateLimited(res, rl);
+ // Browsers POST CSP violations (the `report-uri` directive in vercel.json's
+ // CSP headers) with their own content types and shapes; normalize them into
+ // the same event stream so blocked injections and broken third-party embeds
+ // show up next to JS errors in the logs.
+ const contentType = req.headers['content-type'] || '';
+ const isCspReport =
+ contentType.includes('application/csp-report') ||
+ contentType.includes('application/reports+json');
+
let body;
try {
- body = await readJson(req, 64_000);
+ if (isCspReport) {
+ const raw = JSON.parse((await readBody(req, 64_000)).toString('utf8'));
+ body = { events: cspToEvents(raw) };
+ } else {
+ body = await readJson(req, 64_000);
+ }
} catch (err) {
return error(res, err.status || 400, 'validation_error', err.message || 'invalid body');
}
@@ -79,10 +108,11 @@ export default wrap(async (req, res) => {
// filter on "[client-error]" then on message/page substrings.
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 and
- // page the ops channel (sendOpsAlert dedups per message per hour).
- if (event.type !== 'resource') {
+ // Resource 404s and CSP reports stay log-only — they group terribly as
+ // exceptions and extensions trigger CSP constantly. 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' && event.type !== 'csp') {
const synthetic = new Error(event.message);
synthetic.name = event.name || `client.${event.type}`;
if (event.stack) synthetic.stack = event.stack;
diff --git a/api/cron/uptime-check.js b/api/cron/uptime-check.js
index 3978552ed..118371560 100644
--- a/api/cron/uptime-check.js
+++ b/api/cron/uptime-check.js
@@ -1,3 +1,4 @@
+// @ts-check
// GET /api/cron/uptime-check — first-party synthetic uptime monitor.
//
// Every 5 minutes (vercel.json crons) this probes the platform's critical
diff --git a/api/status.js b/api/status.js
index 07b1a6533..2f63607c2 100644
--- a/api/status.js
+++ b/api/status.js
@@ -1,3 +1,4 @@
+// @ts-check
// 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.
diff --git a/api/tts/speak.js b/api/tts/speak.js
index 17869ae2d..e3047bd0a 100644
--- a/api/tts/speak.js
+++ b/api/tts/speak.js
@@ -6,9 +6,9 @@
//
// 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.
+// whenever NVIDIA_API_KEY is set. Note: Magpie emits raw PCM, so every
+// non-pcm request is 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
diff --git a/api/watsonx/embed.js b/api/watsonx/embed.js
index 28f77fdc7..6682c8c23 100644
--- a/api/watsonx/embed.js
+++ b/api/watsonx/embed.js
@@ -12,8 +12,9 @@
// There is no mock path — every vector is a real embedding call. The provider
// chain degrades gracefully so a watsonx outage never blanks the page:
// 1. IBM Granite on watsonx.ai (primary, when WATSONX_* is configured)
-// 2. OpenAI text-embedding-3-small (fallback, when OPENAI_API_KEY is set)
-// 3. 503 `embed_unconfigured` only when NEITHER provider is available, so the
+// 2. The platform's free-first embedding chain (NVIDIA NIM when keyed,
+// OpenAI text-embedding-3-small as the paid backstop)
+// 3. 503 `embed_unconfigured` only when NO provider is available, so the
// client can show an honest "not configured" state instead of inventing
// vectors. Within a single response all vectors come from one provider, so
// `dimensions` is uniform regardless of which tier served the request.
@@ -21,11 +22,14 @@
import { createHash } from 'node:crypto';
import { cors, method, readJson, error, json, wrap, rateLimited } from '../_lib/http.js';
import { watsonxConfig, watsonxEmbed } from '../_lib/watsonx.js';
-import { embed as openaiEmbed, embeddingsConfigured } from '../_lib/embeddings.js';
+import {
+ embedPassages,
+ embeddingsConfigured,
+ defaultIngestEmbedderTag,
+ embedderInfo,
+} from '../_lib/embeddings.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
-const OPENAI_EMBED_MODEL = 'text-embedding-3-small';
-
// watsonx accepts many inputs per call; cap a single request so one caller can't
// submit an unbounded batch. Matches the chunk size used by agent-embeddings.
const MAX_TEXTS = 96;
@@ -107,21 +111,22 @@ export default wrap(async function handler(req, res) {
}
const cfg = watsonxConfig();
- const openaiReady = embeddingsConfigured();
- if (!cfg.configured && !openaiReady) {
+ const fallbackReady = embeddingsConfigured();
+ if (!cfg.configured && !fallbackReady) {
// No provider at all. No fabricated vectors — tell the client exactly
// what's missing so the UI can render an honest "not configured" state.
return error(
res,
503,
'embed_unconfigured',
- 'No embedding provider is configured. Set WATSONX_API_KEY + WATSONX_PROJECT_ID (IBM Granite) or OPENAI_API_KEY (fallback) to enable embeddings.',
+ 'No embedding provider is configured. Set WATSONX_API_KEY + WATSONX_PROJECT_ID (IBM Granite), NVIDIA_API_KEY (free fallback), or OPENAI_API_KEY (paid fallback) to enable embeddings.',
);
}
- // Provider chain: Granite (primary) → OpenAI (fallback). The first provider
- // that returns a full batch wins; a watsonx outage transparently falls
- // through so /constellation keeps rendering.
+ // Provider chain: Granite (primary) → the platform free-first embedding
+ // chain (NIM, then OpenAI). The first provider that returns a full batch
+ // wins; a watsonx outage transparently falls through so /constellation
+ // keeps rendering.
let result = null;
let lastError = null;
@@ -143,10 +148,14 @@ export default wrap(async function handler(req, res) {
}
}
- if (!result && openaiReady) {
+ if (!result && fallbackReady) {
+ // These texts are peers laid out against each other (not query-vs-corpus),
+ // so they all embed as 'passage' — one consistent space per response.
+ const fallbackTag = defaultIngestEmbedderTag();
+ const fallback = embedderInfo(fallbackTag);
try {
- result = await embedBatch(texts, OPENAI_EMBED_MODEL, async (inputs) => {
- const vecs = await openaiEmbed(inputs);
+ result = await embedBatch(texts, fallback.model, async (inputs) => {
+ const vecs = await embedPassages(fallbackTag, inputs);
return {
vectors: vecs.map((v) => Array.from(v)),
dimensions: vecs[0]?.length ?? 0,
diff --git a/jsconfig.json b/jsconfig.json
new file mode 100644
index 000000000..efc83959f
--- /dev/null
+++ b/jsconfig.json
@@ -0,0 +1,27 @@
+{
+ "//": "Type-checking ratchet for the vanilla-JS codebase. `npm run typecheck` runs tsc --noEmit over the include list; with checkJs off, ONLY files that opt in with a `// @ts-check` first-line pragma are type-checked (imports are still parsed for inference). Ratchet rule: new files get the pragma; when you bring an existing file clean, add `// @ts-check` to it — never remove the pragma from a file that has it. It already caught a real bug (elevenlabs.js reading voice_id off a camelCase SDK model).",
+ "compilerOptions": {
+ "target": "es2023",
+ "module": "nodenext",
+ "moduleResolution": "nodenext",
+ "checkJs": false,
+ "allowJs": true,
+ "noEmit": true,
+ "strict": false,
+ "strictNullChecks": false,
+ "skipLibCheck": true,
+ "resolveJsonModule": true,
+ "types": ["node"]
+ },
+ "include": [
+ "api/_lib/http.js",
+ "api/_lib/alerts.js",
+ "api/_lib/cache.js",
+ "api/_lib/sentry.js",
+ "api/_lib/elevenlabs.js",
+ "api/client-errors.js",
+ "api/status.js",
+ "api/cron/uptime-check.js",
+ "public/error-reporter.js"
+ ]
+}
diff --git a/package-lock.json b/package-lock.json
index a128b7115..4f85b5a54 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -161,6 +161,7 @@
"knip": "^6.16.1",
"playwright": "^1.45.1",
"prettier": "^3.8.4",
+ "typescript": "^5.9.3",
"vite": "^7.3.2",
"vite-plugin-node-polyfills": "^0.28.0",
"vite-plugin-pwa": "^1.3.0",
diff --git a/package.json b/package.json
index 233df2f1e..3c7390d0f 100644
--- a/package.json
+++ b/package.json
@@ -118,7 +118,8 @@
"pump:refresh-idls": "node scripts/refresh-pump-idls.mjs",
"seed:skills": "node scripts/seed-skills.js",
"install:sdk": "npm install --prefix agent-payments-sdk && npm run build --prefix agent-payments-sdk && npm install ./agent-payments-sdk",
- "claude": "./scripts/claude.sh"
+ "claude": "./scripts/claude.sh",
+ "typecheck": "tsc -p jsconfig.json"
},
"dependencies": {
"@0xsplits/splits-sdk": "^6.5.0",
@@ -256,6 +257,7 @@
"knip": "^6.16.1",
"playwright": "^1.45.1",
"prettier": "^3.8.4",
+ "typescript": "^5.9.3",
"vite": "^7.3.2",
"vite-plugin-node-polyfills": "^0.28.0",
"vite-plugin-pwa": "^1.3.0",
diff --git a/packages/avatar-agent-mcp/src/lib/tts-nvidia.js b/packages/avatar-agent-mcp/src/lib/tts-nvidia.js
index f053e66f1..e9f7ac397 100644
--- a/packages/avatar-agent-mcp/src/lib/tts-nvidia.js
+++ b/packages/avatar-agent-mcp/src/lib/tts-nvidia.js
@@ -60,10 +60,12 @@ export function resolveMagpieVoice(voice, language) {
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.
+// Magpie cannot encode mp3/aac/flac, and its OGGOPUS output over NVCF is
+// length-framed raw Opus packets WITHOUT an Ogg container (live-verified
+// 2026-06-11), so it is not directly playable either. Every non-pcm request
+// is therefore served as WAV; the returned mime/format always describe the
+// actual bytes. The OpenAI backstop still produces native formats.
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' };
}
@@ -109,7 +111,9 @@ function normalizeGrpcError(err) {
// 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.
+// server starts fast for users who never call speak. NVCF gotcha: auth is
+// validated at stream/connection setup, so an authenticated warm channel
+// keeps serving even if the key changes mid-process.
let clientPromise = null;
async function getClient() {
if (!clientPromise) {
diff --git a/packages/avatar-agent-mcp/src/tools/speak.js b/packages/avatar-agent-mcp/src/tools/speak.js
index e09ec7aa8..7c9421dc4 100644
--- a/packages/avatar-agent-mcp/src/tools/speak.js
+++ b/packages/avatar-agent-mcp/src/tools/speak.js
@@ -5,7 +5,7 @@
// 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
+// emits raw PCM, so every non-pcm request is 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.
@@ -33,14 +33,14 @@ export const def = {
name: 'speak',
title: 'Avatar speaks (TTS)',
description:
- '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.',
+ '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 (non-pcm 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('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).'),
+ format: z.enum(Object.keys(FORMATS)).optional().describe('Audio format (default mp3; the free NVIDIA lane serves every non-pcm request 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).'),
},
diff --git a/public/error-reporter.js b/public/error-reporter.js
index 38c128ede..c50b6968d 100644
--- a/public/error-reporter.js
+++ b/public/error-reporter.js
@@ -1,3 +1,4 @@
+// @ts-check
// First-party client-side error reporting. Captures uncaught exceptions,
// unhandled promise rejections, and failed resource loads on every page, then
// batches them to POST /api/client-errors where they land in the Vercel
@@ -14,8 +15,11 @@
// exception-proof.
(() => {
'use strict';
- if (window.__threeErrorReporter) return;
- window.__threeErrorReporter = true;
+ // Untyped view of window for our private globals (__threeErrQ, __threeErrCap)
+ // shared with the inline bootstrap injected by vite.config.js.
+ const win = /** @type {any} */ (window);
+ if (win.__threeErrorReporter) return;
+ win.__threeErrorReporter = true;
const ENDPOINT = '/api/client-errors';
const MAX_EVENTS_PER_PAGE = 25; // hard cap so an error loop can't flood the API
@@ -222,7 +226,7 @@
// Drain events the inline bootstrap queued before this file loaded, then
// take over its queue so the bootstrap's listeners feed us directly.
- const bootQueue = (window.__threeErrQ = window.__threeErrQ || []);
+ const bootQueue = (win.__threeErrQ = win.__threeErrQ || []);
const backlog = bootQueue.splice(0);
bootQueue.push = (raw) => {
handleRaw(raw);
@@ -232,14 +236,14 @@
// Standalone usage (a page that includes this file without the Vite-injected
// bootstrap): install the listeners ourselves.
- if (!window.__threeErrCap) {
- window.__threeErrCap = 1;
+ if (!win.__threeErrCap) {
+ win.__threeErrCap = 1;
window.addEventListener('error', handleRaw, true);
window.addEventListener('unhandledrejection', handleRaw);
}
// Manual reporting hook for app code: window.reportClientError(err, { ...context })
- window.reportClientError = (err, context) => {
+ win.reportClientError = (err, context) => {
try {
const isError = err instanceof Error;
enqueue({
diff --git a/scripts/build-vercel.mjs b/scripts/build-vercel.mjs
index 565a9ff8f..5120ad95c 100644
--- a/scripts/build-vercel.mjs
+++ b/scripts/build-vercel.mjs
@@ -148,6 +148,11 @@ async function ensureSDKDist() {
}
async function prebuild() {
+ // Type gate first: with GitHub Actions unavailable on this account, the
+ // deploy build is the only automated checkpoint, so a type error in a
+ // ratcheted file (see jsconfig.json) fails the deploy instead of shipping.
+ // Cheap (~5s) and has already caught a real prod bug (elevenlabs voice_id).
+ await run('typecheck', 'npx tsc -p jsconfig.json');
await Promise.all([
run('build:news', 'node scripts/build-news.mjs'),
run('build:skill-metadata', 'node scripts/build-skill-metadata.mjs'),
diff --git a/scripts/reembed-widget-knowledge.mjs b/scripts/reembed-widget-knowledge.mjs
new file mode 100644
index 000000000..426b10896
--- /dev/null
+++ b/scripts/reembed-widget-knowledge.mjs
@@ -0,0 +1,274 @@
+#!/usr/bin/env node
+// Re-embed all stored widget knowledge chunks into the free NVIDIA NIM
+// embedding space (nvidia/nv-embedqa-e5-v5@1024), safely.
+//
+// Why: rows embedded with OpenAI text-embedding-3-small@256 can only be
+// queried while an OpenAI key serves — and the platform's free-first policy
+// wants retrieval off the paid lane entirely. This migrates every chunk to
+// the NIM space using the same access layer the API uses (api/_lib/db.js +
+// api/_lib/embeddings.js), so what the script writes is exactly what
+// retrieval reads.
+//
+// Safety properties:
+// • Resume-safe + idempotent — each chunk row carries an `embedder` tag;
+// a re-run only touches rows still outside the target space, and a crash
+// mid-run loses nothing.
+// • Atomic per document set — a doc's `embedder` tag flips only after every
+// chunk in it is verified migrated. Retrieval routes per-chunk tag, so
+// even mid-migration every chunk is queried in its own (correct) space.
+// • Throttled, with exponential backoff on 429/5xx/network errors — the
+// free tier is credit-metered and rate-limited.
+// • --dry-run prints counts and cost/time estimates and writes NOTHING.
+//
+// Usage:
+// node scripts/reembed-widget-knowledge.mjs --dry-run
+// node scripts/reembed-widget-knowledge.mjs [--widget wdgt_x] [--batch 64] [--throttle-ms 400]
+//
+// Requires DATABASE_URL (+ NVIDIA_API_KEY for a real run) from .env.local /
+// .env / the environment. Run AFTER the T3.1 tagging schema is deployed
+// (api/_lib/migrations/2026-06-11-knowledge-embedder-tag.sql).
+
+import { readFileSync } from 'node:fs';
+import { resolve, dirname } from 'node:path';
+import { fileURLToPath, pathToFileURL } from 'node:url';
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+const root = resolve(__dirname, '..');
+
+function loadEnvFile(path) {
+ let raw;
+ try {
+ raw = readFileSync(path, 'utf8');
+ } catch {
+ return;
+ }
+ for (const line of raw.split('\n')) {
+ const m = line.match(/^\s*([A-Z0-9_]+)\s*=\s*(.*?)\s*$/i);
+ if (!m) continue;
+ const [, k, v] = m;
+ if (process.env[k]) continue;
+ process.env[k] = v.replace(/^["']|["']$/g, '');
+ }
+}
+loadEnvFile(resolve(root, '.env.local'));
+loadEnvFile(resolve(root, '.env'));
+
+const { NIM_EMBED_TAG, embedderConfigured, embedPassages } = await import(
+ '../api/_lib/embeddings.js'
+);
+
+// Free-tier pacing defaults: 64 chunks per request (well under the probed
+// 512-input batch ceiling), a polite gap between requests, and a generous
+// per-request latency assumption for the dry-run time estimate.
+const DEFAULT_BATCH = 64;
+const DEFAULT_THROTTLE_MS = 400;
+const EST_REQUEST_SECONDS = 1.0;
+
+export function parseCliArgs(argv) {
+ const args = { dryRun: false, widget: null, batch: DEFAULT_BATCH, throttleMs: DEFAULT_THROTTLE_MS };
+ for (let i = 0; i < argv.length; i++) {
+ const a = argv[i];
+ if (a === '--dry-run') args.dryRun = true;
+ else if (a === '--widget') args.widget = argv[++i] || null;
+ else if (a === '--batch') args.batch = Math.max(1, Math.min(512, Number(argv[++i]) || DEFAULT_BATCH));
+ else if (a === '--throttle-ms') args.throttleMs = Math.max(0, Number(argv[++i]) || 0);
+ else throw new Error(`unknown argument: ${a}`);
+ }
+ return args;
+}
+
+/**
+ * Survey every knowledge doc and classify what the migration would do to it.
+ * Read-only — this is the whole of --dry-run.
+ */
+export async function planMigration(sql, { targetTag, widgetId = null }) {
+ const rows = await sql`
+ select d.id, d.widget_id, d.title, d.status, d.embedder as doc_embedder,
+ count(c.id)::int as total_chunks,
+ count(c.id) filter (where c.embedder is distinct from ${targetTag})::int as pending_chunks,
+ coalesce(sum(c.token_count) filter (where c.embedder is distinct from ${targetTag}), 0)::int as pending_tokens
+ from widget_knowledge_docs d
+ left join widget_knowledge_chunks c on c.doc_id = d.id
+ where ${widgetId}::text is null or d.widget_id = ${widgetId}
+ group by d.id, d.widget_id, d.title, d.status, d.embedder
+ order by d.widget_id, d.id
+ `;
+ return rows.map((d) => ({ ...d, ...classifyDoc(d, targetTag) }));
+}
+
+/** Decide the action for one surveyed doc. Pure — unit-tested directly. */
+export function classifyDoc(doc, targetTag) {
+ if (doc.status !== 'ready') return { action: 'skip', reason: `status=${doc.status}` };
+ if (!Number(doc.total_chunks)) return { action: 'skip', reason: 'no chunks stored' };
+ if (!Number(doc.pending_chunks)) {
+ return doc.doc_embedder === targetTag
+ ? { action: 'done', reason: 'already migrated' }
+ : { action: 'flip', reason: 'all chunks migrated; doc tag stale (resumed run)' };
+ }
+ return { action: 'migrate', reason: `${doc.pending_chunks}/${doc.total_chunks} chunks pending` };
+}
+
+/**
+ * Retry `fn` on rate limits (429), upstream 5xx, and network-level failures
+ * with exponential backoff. Never retries hard 4xx/config errors.
+ */
+export async function withBackoff(fn, { attempts = 6, baseMs = 2000, sleep, log = () => {} } = {}) {
+ for (let attempt = 0; ; attempt++) {
+ try {
+ return await fn();
+ } catch (err) {
+ const status = err?.status;
+ const retriable =
+ status === 429 ||
+ (typeof status === 'number' && status >= 500) ||
+ (status === undefined && err?.code !== 'no_embedder' && err?.code !== 'unknown_embedder');
+ if (!retriable || attempt >= attempts - 1) throw err;
+ const delayMs = Math.min(60_000, baseMs * 2 ** attempt) + Math.floor(Math.random() * 250);
+ log(` ${status === 429 ? 'rate limited' : `retryable error (${status ?? err?.code ?? 'network'})`} — backing off ${delayMs}ms (attempt ${attempt + 1}/${attempts})`);
+ await sleep(delayMs);
+ }
+ }
+}
+
+/**
+ * Migrate one document set. Re-embeds only chunks whose tag differs from the
+ * target (idempotent / resume point is the per-row tag), then flips the doc
+ * tag iff a verification count confirms zero chunks remain outside the target
+ * space — the set-level flip is atomic with respect to retrieval semantics.
+ */
+export async function migrateDoc(
+ { sql, embedBatchFn, sleep, log = () => {} },
+ doc,
+ { targetTag, batch = DEFAULT_BATCH, throttleMs = DEFAULT_THROTTLE_MS },
+) {
+ let migrated = 0;
+ for (;;) {
+ const pending = await sql`
+ select id, content from widget_knowledge_chunks
+ where doc_id = ${doc.id} and embedder is distinct from ${targetTag}
+ order by chunk_index
+ limit ${batch}
+ `;
+ if (!pending.length) break;
+
+ const vectors = await withBackoff(
+ () => embedBatchFn(pending.map((r) => String(r.content))),
+ { sleep, log },
+ );
+ for (let i = 0; i < pending.length; i++) {
+ await sql`
+ update widget_knowledge_chunks
+ set embedding = ${JSON.stringify(Array.from(vectors[i]))}::jsonb,
+ embedder = ${targetTag}
+ where id = ${pending[i].id}
+ `;
+ }
+ migrated += pending.length;
+ if (throttleMs) await sleep(throttleMs);
+ }
+
+ const [{ remaining }] = await sql`
+ select count(*)::int as remaining from widget_knowledge_chunks
+ where doc_id = ${doc.id} and embedder is distinct from ${targetTag}
+ `;
+ if (Number(remaining) === 0) {
+ await sql`update widget_knowledge_docs set embedder = ${targetTag} where id = ${doc.id}`;
+ return { migrated, flipped: true };
+ }
+ return { migrated, flipped: false };
+}
+
+export function summarizePlan(plan, { batch = DEFAULT_BATCH, throttleMs = DEFAULT_THROTTLE_MS } = {}) {
+ const by = (action) => plan.filter((d) => d.action === action);
+ const pendingChunks = plan.reduce((s, d) => s + Number(d.pending_chunks || 0), 0);
+ const pendingTokens = plan.reduce((s, d) => s + Number(d.pending_tokens || 0), 0);
+ const requests = plan.reduce((s, d) => s + Math.ceil(Number(d.pending_chunks || 0) / batch), 0);
+ const estSeconds = Math.ceil(requests * (EST_REQUEST_SECONDS + throttleMs / 1000));
+ return {
+ docs: plan.length,
+ migrate: by('migrate').length,
+ flip: by('flip').length,
+ done: by('done').length,
+ skip: by('skip').length,
+ pendingChunks,
+ pendingTokens,
+ requests,
+ estSeconds,
+ };
+}
+
+async function main() {
+ const args = parseCliArgs(process.argv.slice(2));
+ const targetTag = NIM_EMBED_TAG;
+
+ if (!process.env.DATABASE_URL) {
+ console.error('DATABASE_URL not set (.env.local / .env / environment)');
+ process.exit(1);
+ }
+ if (!args.dryRun && !embedderConfigured(targetTag)) {
+ console.error('NVIDIA_API_KEY not set — required to embed into the NIM space. (--dry-run works without it.)');
+ process.exit(1);
+ }
+
+ const { sql } = await import('../api/_lib/db.js');
+ const host = new URL(process.env.DATABASE_URL).host;
+ console.log(`${args.dryRun ? 'DRY RUN — surveying' : 'Migrating'} widget knowledge on ${host}`);
+ console.log(`target space: ${targetTag}${args.widget ? ` · widget: ${args.widget}` : ''} · batch ${args.batch} · throttle ${args.throttleMs}ms\n`);
+
+ const plan = await planMigration(sql, { targetTag, widgetId: args.widget });
+ const totals = summarizePlan(plan, { batch: args.batch, throttleMs: args.throttleMs });
+
+ for (const d of plan) {
+ if (d.action === 'done') continue;
+ console.log(`[${d.action.padEnd(7)}] ${d.id} (${d.widget_id}) "${String(d.title).slice(0, 60)}" — ${d.reason}`);
+ }
+ console.log(
+ `\n${totals.docs} docs: ${totals.migrate} to migrate, ${totals.flip} tag-flip only, ` +
+ `${totals.done} already migrated, ${totals.skip} skipped`,
+ );
+ console.log(
+ `${totals.pendingChunks} chunks to re-embed (~${totals.pendingTokens} tokens) ` +
+ `→ ~${totals.requests} NIM requests, est. ~${totals.estSeconds}s (free tier: $0; ~${totals.requests} metered credits)`,
+ );
+
+ if (args.dryRun) {
+ console.log('\nDRY RUN — nothing was written.');
+ return;
+ }
+
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+ const embedBatchFn = (texts) => embedPassages(targetTag, texts);
+ const log = (msg) => console.log(msg);
+
+ let migratedChunks = 0;
+ let flippedDocs = 0;
+ let incomplete = 0;
+ for (const d of plan) {
+ if (d.action === 'done' || d.action === 'skip') continue;
+ console.log(`→ ${d.id} (${d.widget_id}): ${d.reason}`);
+ const result = await migrateDoc(
+ { sql, embedBatchFn, sleep, log },
+ d,
+ { targetTag, batch: args.batch, throttleMs: args.throttleMs },
+ );
+ migratedChunks += result.migrated;
+ if (result.flipped) flippedDocs++;
+ else {
+ incomplete++;
+ console.warn(` ! ${d.id} still has unmigrated chunks — tag NOT flipped (safe to re-run)`);
+ }
+ }
+
+ console.log(`\nDone: ${migratedChunks} chunks re-embedded, ${flippedDocs} document sets flipped to ${targetTag}.`);
+ if (incomplete) {
+ console.warn(`${incomplete} sets incomplete — re-run this script to resume.`);
+ process.exitCode = 2;
+ }
+}
+
+if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
+ main().catch((err) => {
+ console.error('reembed failed:', err?.message || err);
+ process.exit(1);
+ });
+}
diff --git a/scripts/verify-nvidia-tts.mjs b/scripts/verify-nvidia-tts.mjs
index 4510c1b9f..379735c67 100644
--- a/scripts/verify-nvidia-tts.mjs
+++ b/scripts/verify-nvidia-tts.mjs
@@ -10,16 +10,28 @@
// 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.
+// backstop attempted second, clean JSON error when both fail. This runs in
+// a CHILD PROCESS because NVCF authorizes at gRPC stream/connection setup —
+// a warm channel that already authenticated keeps serving even after the
+// key in env changes, so an in-process key swap proves nothing.
//
// Everything stays in memory — no scratch audio files are written.
import { config as dotenv } from 'dotenv';
import { Readable } from 'node:stream';
+import { spawnSync } from 'node:child_process';
+import { fileURLToPath } from 'node:url';
+// dotenv never overrides vars already present, so the bogus key injected by
+// the parent for --failover-only survives this load.
dotenv({ path: new URL('../.env.local', import.meta.url) });
+// .env.local can carry prod flags; clear them so the critical rate limiter
+// doesn't fail closed (no local Redis) when we exercise the real handler.
+delete process.env.NODE_ENV;
+delete process.env.VERCEL_ENV;
const quick = process.argv.includes('--quick');
+const failoverOnly = process.argv.includes('--failover-only');
if (!process.env.NVIDIA_API_KEY) {
console.error('[tts] NVIDIA_API_KEY missing from environment/.env.local — cannot live-verify');
process.exit(1);
@@ -39,7 +51,7 @@ function wavDurationSeconds(buf) {
}
// ── 1. One real sentence through the module ────────────────────────────────
-{
+if (!failoverOnly) {
const t0 = Date.now();
const out = await synthesizeNvidiaTts({
text: 'Hello from three dot W S. The free NVIDIA voice lane is live.',
@@ -60,7 +72,7 @@ function wavDurationSeconds(buf) {
}
// ── 2. Voice-map sweep + opus path ─────────────────────────────────────────
-if (!quick) {
+if (!quick && !failoverOnly) {
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);
@@ -72,17 +84,33 @@ if (!quick) {
`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)`);
+ // Opus requests are served as WAV on the NIM lane (NVCF Magpie's OGGOPUS
+ // output is containerless raw packets — see resolveMagpieFormat); the
+ // served format/content-type must say so truthfully.
+ const opus = await synthesizeNvidiaTts({ text: 'Format truthfulness check.', voice: 'nova', format: 'opus' });
+ assert(opus.audio.subarray(0, 4).toString('ascii') === 'RIFF', `opus→wav magic: ${opus.audio.subarray(0, 4)}`);
+ assert(opus.contentType === 'audio/wav' && opus.format === 'wav', 'opus→wav labels not truthful');
+ console.log(`[tts] ✓ opus request truthfully served as WAV (${opus.audio.length} bytes)`);
}
// ── 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';
-
+if (!failoverOnly) {
+ // Fresh process so the bogus key is the FIRST thing the gRPC channel ever
+ // authenticates with (see header note on NVCF connection-level auth).
+ const r = spawnSync(process.execPath, [fileURLToPath(import.meta.url), '--failover-only'], {
+ env: {
+ ...process.env,
+ NVIDIA_API_KEY: 'nvapi-deliberately-invalid-for-failover-check',
+ OPENAI_API_KEY: process.env.OPENAI_API_KEY || 'sk-invalid-local-failover-check',
+ },
+ stdio: 'inherit',
+ timeout: 120_000,
+ });
+ if (r.status !== 0) {
+ console.error('[tts] FAIL — failover child exited with', r.status);
+ process.exit(1);
+ }
+} else {
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]);
@@ -121,4 +149,4 @@ if (!quick) {
}
}
-console.log('[tts] PASS');
+if (!failoverOnly) console.log('[tts] PASS');
diff --git a/src/agent-identity.js b/src/agent-identity.js
index 4f515403b..262d5b1b1 100644
--- a/src/agent-identity.js
+++ b/src/agent-identity.js
@@ -332,8 +332,12 @@ function _makeEmbedFn(agentId) {
body: JSON.stringify({ text }),
});
if (!resp.ok) throw new Error(`embed ${resp.status}`);
- const { embedding } = await resp.json();
- return embedding;
+ // The endpoint serves a free-first provider chain, so the model can
+ // differ between calls (NIM up vs. fallen back to Voyage). Pass the
+ // model through: AgentMemory only cosine-compares vectors from the
+ // same model — different models are different vector spaces.
+ const { embedding, model } = await resp.json();
+ return { vector: embedding, model: model || null };
};
}
diff --git a/src/agent-memory.js b/src/agent-memory.js
index 79acb144c..56f3aab0f 100644
--- a/src/agent-memory.js
+++ b/src/agent-memory.js
@@ -18,6 +18,22 @@ export const MEMORY_TYPES = {
REFERENCE: 'reference',
};
+// Entries persisted before embeddings carried a model tag were produced by the
+// Voyage-only /api/agents/:id/embed endpoint. Encoding that here lets recall()
+// keep comparing them — but only against queries embedded by the same model.
+const LEGACY_EMBED_MODEL = 'voyage-3-lite';
+
+// embedFn may return a bare vector (number[]) or { vector, model } — the
+// platform's _makeEmbedFn passes the model through because the embed endpoint
+// is a provider chain and vectors from different models must never be
+// cosine-compared. Bare vectors get model null ("unspecified custom space").
+function _normalizeEmbedResult(res) {
+ if (Array.isArray(res)) return { vector: res, model: null };
+ if (res && Array.isArray(res.vector)) return { vector: res.vector, model: res.model ?? null };
+ if (res && Array.isArray(res.embedding)) return { vector: res.embedding, model: res.model ?? null };
+ return null;
+}
+
/**
* @typedef {Object} MemoryEntry
* @property {string} id
@@ -33,7 +49,8 @@ export const MEMORY_TYPES = {
export class AgentMemory {
/**
* @param {string} agentId
- * @param {{ backendSync?: boolean, embedFn?: (text: string) => Promise<number[]> }} [opts]
+ * @param {{ backendSync?: boolean,
+ * embedFn?: (text: string) => Promise<number[] | { vector: number[], model?: string|null }> }} [opts]
*/
constructor(agentId, { backendSync = false, embedFn = null } = {}) {
this.agentId = agentId;
@@ -71,7 +88,13 @@ export class AgentMemory {
this._scheduleSync(mem);
// Fire-and-forget embedding generation
if (this.embedFn) {
- this.embedFn(mem.content).then((vec) => { mem.embedding = vec; }).catch(() => {});
+ this.embedFn(mem.content).then((res) => {
+ const norm = _normalizeEmbedResult(res);
+ if (norm) {
+ mem.embedding = norm.vector;
+ mem.embeddingModel = norm.model;
+ }
+ }).catch(() => {});
}
return id;
}
@@ -120,18 +143,24 @@ export class AgentMemory {
return true;
});
- const queryVec = await this.embedFn(queryText).catch(() => null);
- if (!queryVec) return this.query({ type, limit });
+ const queryRes = await this.embedFn(queryText).then(_normalizeEmbedResult).catch(() => null);
+ if (!queryRes) return this.query({ type, limit });
+ const queryModel = queryRes.model;
+ // Same-space rule: only cosine-compare entries embedded by the SAME
+ // model as the query. Entries from another model's vector space (e.g.
+ // stored before a provider failover) score garbage against this query,
+ // so they take the substring path instead of a fake similarity.
const withEmbedding = [];
const withoutEmbedding = [];
for (const m of active) {
- if (m.embedding) withEmbedding.push(m);
+ const entryModel = 'embeddingModel' in m ? m.embeddingModel : LEGACY_EMBED_MODEL;
+ if (m.embedding && entryModel === queryModel) withEmbedding.push(m);
else withoutEmbedding.push(m);
}
const scored = withEmbedding
- .map((m) => ({ entry: m, score: cosineSim(queryVec, m.embedding) }))
+ .map((m) => ({ entry: m, score: cosineSim(queryRes.vector, m.embedding) }))
.filter((x) => x.score >= minScore)
.sort((a, b) => b.score - a.score);
@@ -354,8 +383,12 @@ export class AgentMemory {
// ── Helpers ──────────────────────────────────────────────────────────────────
export function cosineSim(a, b) {
+ // Mismatched lengths are by definition different vector spaces — never
+ // compare a shared prefix. Zero vectors have no direction; score 0, not NaN.
+ if (!a || !b || a.length !== b.length) return 0;
let dot = 0, na = 0, nb = 0;
for (let i = 0; i < a.length; i++) { dot += a[i] * b[i]; na += a[i] * a[i]; nb += b[i] * b[i]; }
+ if (!na || !nb) return 0;
return dot / (Math.sqrt(na) * Math.sqrt(nb));
}
diff --git a/tasks/nvidia-nim/PLAN.md b/tasks/nvidia-nim/PLAN.md
index e6c6125f2..36a4ad5ce 100644
--- a/tasks/nvidia-nim/PLAN.md
+++ b/tasks/nvidia-nim/PLAN.md
@@ -45,7 +45,7 @@ Status legend: `[ ]` not started · `[~]` in progress (note who/when in Worklog)
- [ ] **T1.5** [14-deploy-smoke-changelog.md](14-deploy-smoke-changelog.md) — deploy + prod smoke + changelog
### Phase 2 — Speech back online
-- [ ] **T2.1** [20-tts-lane.md](20-tts-lane.md) — free TTS lane in `api/tts/speak.js` (NIM first, OpenAI backstop)
+- [x] **T2.1** [20-tts-lane.md](20-tts-lane.md) — free TTS lane in `api/tts/speak.js` (NIM first, OpenAI backstop) — live-verified end-to-end incl. failover order (see Worklog 2026-06-11)
- [ ] **T2.2** [21-tts-verify.md](21-tts-verify.md) — every speech surface verified in prod + changelog
### Phase 3 — Widget RAG back online
@@ -100,6 +100,43 @@ Status legend: `[ ]` not started · `[~]` in progress (note who/when in Worklog)
## Worklog (append-only; newest at top)
+- **2026-06-11** — **T2.1 (free NIM TTS lane) — DONE, live-verified end-to-end.** Decision
+ gate per the probe: gRPC-only is fine — built the Node gRPC client. **Dependency/bundling
+ decision:** added `@grpc/grpc-js` + `@grpc/proto-loader` (pure JS, no native addon) to
+ root deps; vendored the Riva protos (`riva_tts/audio/common.proto`, MIT, SPDX headers
+ preserved) under `api/_lib/riva-protos/` and check in a **generated protobufjs JSON
+ descriptor** (`descriptor.js`, regenerated by `scripts/generate-riva-tts-descriptor.mjs`)
+ loaded via `protoLoader.fromJSON` — no runtime `.proto` fs reads, so it survives the
+ in-place esbuild bundling without includeFiles tricks. `@grpc/*` added to bundle-api
+ EXTERNALS (CJS lazy-require pattern; NFT traces it once — only speak.js imports it);
+ bundled the route with the exact prod flags into a temp outfile and import-loaded it: clean.
+ New `api/_lib/tts-nvidia.js`: cached TLS channel to `grpc.nvcf.nvidia.com:443`, per-call
+ metadata (`function-id` 877104f7…, bearer key), non-streaming `Synthesize`, LINEAR_PCM
+ 44.1 kHz → WAV-wrapped server-side, gRPC code → platform error map. `api/tts/speak.js`
+ restructured free-first: NIM lane (30 s per-attempt budget, full buffer before any byte
+ is written → failover always clean) → OpenAI backstop (now also has a timeout) → 502
+ with both lane errors in attempt order; 503 only when NEITHER key set; validation/limits
+ unchanged; `x-tts-voice`/`x-tts-model`/`x-tts-format`/content-type always truthful. MCP
+ twin `packages/avatar-agent-mcp` (tools/speak.js) mirrors the chain via its own copy
+ `src/lib/tts-nvidia.js` + descriptor (published standalone, can't import across the repo;
+ noted in both headers), deps added, v1.0.3→1.1.0. **Voice map (live-verified, every
+ persona 200'd):** alloy→Mia, ash→Jason, ballad→Leo, coral→Sofia, echo→Ray, fable→Leo,
+ nova→Aria, onyx→Ray, sage→Mia, shimmer→Sofia, verse→Jason (all as
+ `Magpie-Multilingual.EN-US.<P>`; bare-tag + region language aliases for the 9 langs).
+ **Live numbers** (`scripts/verify-nvidia-tts.mjs`): full sentence → 4.46 s WAV in
+ **1.3–2.1 s**; short phrase **~370–430 ms**; forced-bad-key failover proven in a child
+ process: nvidia attempted first (gRPC 7 PermissionDenied), openai second, clean 502.
+ **Three upstream surprises** (recorded in probes/tts.md addenda): subvoice ids need an
+ UPPERCASE language tag (`EN-US.Aria`; lowercase → INVALID_ARGUMENT); NVCF "OGGOPUS" is
+ length-framed raw Opus packets with NO Ogg container (unplayable → every non-pcm request
+ is served as WAV, truthfully labeled; OpenAI backstop still emits native formats); NVCF
+ validates auth at stream/connection setup, so a warm authenticated channel keeps serving
+ after a key swap — key-failure tests must use a fresh process. New
+ `tests/api/tts-speak.test.js` (15 cases: chain order both surfaces, transport-layer
+ mocks only, voice/lang mapping, header truthfulness, 503/502 semantics, pcm/opus
+ handling, validation) — green; agents-voice + chat-plugin-tool + all-modules-load (518
+ tests) green; avatar-agent-mcp node:test suite green. Changelog entry deferred to T2.2
+ (prod verification owns the holder-visible announcement).
- **2026-06-11** — **T1.3 (NIM FLUX lane) — DONE, live-verified.** With the restored
`NVIDIA_API_KEY` in `.env.local`, ran `scripts/verify-nim-flux.mjs` (new, reusable —
live + `--degrade` modes): a real "teapot" generation through `textToImage()` served by
diff --git a/tasks/nvidia-nim/probes/tts.md b/tasks/nvidia-nim/probes/tts.md
index 0282ef088..3e989956a 100644
--- a/tasks/nvidia-nim/probes/tts.md
+++ b/tasks/nvidia-nim/probes/tts.md
@@ -123,3 +123,24 @@ before building T2.1.
- List functions: `GET https://api.nvcf.nvidia.com/v2/nvcf/functions` (Bearer key).
- Synthesize: Python snippet above, or grpc-js against the same host/metadata.
- Verified: 4.37 s mono 16-bit 44.1 kHz WAV from Magpie multilingual. Scratch deleted.
+
+---
+
+## T2.1 addenda (2026-06-11, live-verified while building the lane)
+
+- **Subvoice ids are upper-cased.** `voice_name` must be
+ `Magpie-Multilingual.EN-US.Aria` — a lowercase language tag
+ (`…en-US.Aria`) fails with `INVALID_ARGUMENT: subvoice requested not found`.
+ Full live subvoice map via `GetRivaSynthesisConfig` (same metadata): personas
+ Mia/Jason/Aria/Leo/Sofia/Ray + Pascal/Diego/Louise/Isabela exist under EN-US;
+ every language exposes a large persona cross-product.
+- **OGGOPUS over NVCF is NOT an Ogg container.** The response is length-framed
+ raw Opus packets (no `OggS` magic anywhere) — not directly playable. The
+ production lane serves WAV for every non-pcm request instead.
+- **Auth is per-connection, not per-call.** NVCF validates the bearer when the
+ gRPC stream/connection is established (`failed to open stateful work request:
+ PermissionDenied` on a fresh channel with a bad key) — but a warm channel
+ that already authenticated keeps serving after the key in env changes.
+ Key-failure tests need a fresh process.
+- **Observed latency (Codespace → grpc.nvcf.nvidia.com):** ~370–430 ms for a
+ short phrase, ~1.3–2.1 s for a full sentence (4.5 s audio), per-call.
diff --git a/tests/api/client-errors.test.js b/tests/api/client-errors.test.js
index 38a04385c..201e23e85 100644
--- a/tests/api/client-errors.test.js
+++ b/tests/api/client-errors.test.js
@@ -26,16 +26,21 @@ vi.mock('../../api/_lib/sentry.js', () => ({
captureMessage: vi.fn(),
}));
+const sendOpsAlert = vi.fn();
+vi.mock('../../api/_lib/alerts.js', () => ({
+ sendOpsAlert: (...args) => sendOpsAlert(...args),
+}));
+
const { default: handler } = await import('../../api/client-errors.js');
-function makeReq({ method = 'POST', body = null, raw = null } = {}) {
+function makeReq({ method = 'POST', body = null, raw = null, contentType } = {}) {
const payload = raw ?? (body ? JSON.stringify(body) : '');
const req = Readable.from(payload ? [Buffer.from(payload)] : []);
req.method = method;
req.url = '/api/client-errors';
req.headers = {
host: 'localhost',
- 'content-type': 'application/json',
+ 'content-type': contentType || 'application/json',
'user-agent': 'TestBrowser/1.0',
};
return req;
@@ -85,6 +90,7 @@ let consoleError;
beforeEach(() => {
state.rateLimited = false;
captureException.mockClear();
+ sendOpsAlert.mockClear();
consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
});
afterEach(() => {
@@ -180,6 +186,68 @@ describe('api/client-errors', () => {
expect(body.received).toBe(25);
});
+ it('pages the ops channel for JS errors but not resource events', async () => {
+ await invoke({
+ body: {
+ page: 'https://three.ws/play',
+ events: [
+ errorEvent(),
+ { type: 'resource', tag: 'img', message: 'failed to load img', source: 'https://three.ws/x.png' },
+ ],
+ },
+ });
+ expect(sendOpsAlert).toHaveBeenCalledTimes(1);
+ expect(sendOpsAlert.mock.calls[0][0]).toContain('client error on https://three.ws/play');
+ });
+
+ it('ingests report-uri CSP reports (application/csp-report)', async () => {
+ const { status, body } = await invoke({
+ contentType: 'application/csp-report',
+ raw: JSON.stringify({
+ 'csp-report': {
+ 'document-uri': 'https://three.ws/play',
+ 'violated-directive': 'script-src',
+ 'effective-directive': 'script-src',
+ 'blocked-uri': 'https://evil.example/x.js',
+ 'line-number': 7,
+ },
+ }),
+ });
+ expect(status).toBe(202);
+ expect(body.received).toBe(1);
+ const logged = JSON.parse(
+ consoleError.mock.calls.find(([tag]) => tag === '[client-error]')[1],
+ );
+ expect(logged.type).toBe('csp');
+ expect(logged.message).toBe('CSP violation: script-src');
+ expect(logged.source).toBe('https://evil.example/x.js');
+ // CSP stays log-only: no Sentry, no ops page.
+ expect(captureException).not.toHaveBeenCalled();
+ expect(sendOpsAlert).not.toHaveBeenCalled();
+ });
+
+ it('ingests report-to CSP reports (application/reports+json)', async () => {
+ const { status, body } = await invoke({
+ contentType: 'application/reports+json',
+ raw: JSON.stringify([
+ {
+ type: 'csp-violation',
+ body: {
+ documentURL: 'https://three.ws/',
+ effectiveDirective: 'object-src',
+ blockedURL: 'https://evil.example/applet',
+ },
+ },
+ ]),
+ });
+ expect(status).toBe(202);
+ expect(body.received).toBe(1);
+ const logged = JSON.parse(
+ consoleError.mock.calls.find(([tag]) => tag === '[client-error]')[1],
+ );
+ expect(logged.message).toBe('CSP violation: object-src');
+ });
+
it('returns 429 with Retry-After when the IP is rate limited', async () => {
state.rateLimited = true;
const { status, body, res } = await invoke({ body: { events: [errorEvent()] } });
diff --git a/tests/api/embeddings.test.js b/tests/api/embeddings.test.js
new file mode 100644
index 000000000..82f8c1aec
--- /dev/null
+++ b/tests/api/embeddings.test.js
@@ -0,0 +1,290 @@
+// Tests for api/_lib/embeddings.js — the multi-provider embedding module with
+// vector-space tagging. Pins the four invariants the widget RAG stack leans
+// on: (1) free-first provider selection (NIM leads, OpenAI is the paid
+// backstop), (2) every embed call is bound to an explicit embedder tag and the
+// NIM lane carries the REQUIRED input_type + respects the 512-token cap,
+// (3) untagged legacy rows resolve to OpenAI text-embedding-3-small@256,
+// (4) cross-space comparison is impossible: scoreRowsBySpace refuses spaces
+// no provider can serve, and cosine scores mismatched dimensions as 0.
+
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+
+import {
+ NIM_EMBED_TAG,
+ OPENAI_EMBED_TAG,
+ LEGACY_EMBED_TAG,
+ embeddingsConfigured,
+ defaultIngestEmbedderTag,
+ resolveEmbedderTag,
+ embedderInfo,
+ embedderConfigured,
+ embedWith,
+ embedPassages,
+ embedQuery,
+ scoreRowsBySpace,
+ cosine,
+} from '../../api/_lib/embeddings.js';
+
+const NIM_URL = 'https://integrate.api.nvidia.com/v1/embeddings';
+const OPENAI_URL = 'https://api.openai.com/v1/embeddings';
+
+const fetchMock = vi.fn();
+
+function okEmbeddings(vectors) {
+ return {
+ ok: true,
+ status: 200,
+ json: async () => ({ data: vectors.map((embedding, index) => ({ index, embedding })) }),
+ text: async () => '',
+ };
+}
+
+function clearKeys() {
+ delete process.env.NVIDIA_API_KEY;
+ delete process.env.OPENAI_API_KEY;
+}
+
+beforeEach(() => {
+ clearKeys();
+ fetchMock.mockReset();
+ vi.stubGlobal('fetch', fetchMock);
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+ clearKeys();
+});
+
+function lastBody() {
+ return JSON.parse(fetchMock.mock.calls.at(-1)[1].body);
+}
+
+describe('provider configuration (free-first)', () => {
+ it('reports unconfigured and no default when no key is present', () => {
+ expect(embeddingsConfigured()).toBe(false);
+ expect(defaultIngestEmbedderTag()).toBe(null);
+ });
+
+ it('prefers the free NIM lane when its key is present', () => {
+ process.env.NVIDIA_API_KEY = 'nvapi-test';
+ process.env.OPENAI_API_KEY = 'sk-test';
+ expect(embeddingsConfigured()).toBe(true);
+ expect(defaultIngestEmbedderTag()).toBe(NIM_EMBED_TAG);
+ });
+
+ it('falls back to OpenAI for new ingests only when NIM is keyless', () => {
+ process.env.OPENAI_API_KEY = 'sk-test';
+ expect(defaultIngestEmbedderTag()).toBe(OPENAI_EMBED_TAG);
+ });
+});
+
+describe('embedder tag resolution (vector-space identity)', () => {
+ it('treats untagged legacy rows as OpenAI text-embedding-3-small@256', () => {
+ expect(LEGACY_EMBED_TAG).toBe(OPENAI_EMBED_TAG);
+ expect(resolveEmbedderTag(null)).toBe(LEGACY_EMBED_TAG);
+ expect(resolveEmbedderTag('')).toBe(LEGACY_EMBED_TAG);
+ expect(resolveEmbedderTag(undefined)).toBe(LEGACY_EMBED_TAG);
+ });
+
+ it('refuses unknown tags — an unknown space can never be queried', () => {
+ expect(resolveEmbedderTag('mystery-model@4096')).toBe(null);
+ expect(embedderInfo('mystery-model@4096')).toBe(null);
+ expect(embedderConfigured('mystery-model@4096')).toBe(false);
+ });
+
+ it('exposes model id + dimension for known tags', () => {
+ expect(embedderInfo(NIM_EMBED_TAG)).toMatchObject({
+ model: 'nvidia/nv-embedqa-e5-v5',
+ dim: 1024,
+ free: true,
+ });
+ expect(embedderInfo(OPENAI_EMBED_TAG)).toMatchObject({
+ model: 'text-embedding-3-small',
+ dim: 256,
+ });
+ });
+
+ it('embedderConfigured tracks the provider key for the tag, not any key', () => {
+ process.env.NVIDIA_API_KEY = 'nvapi-test';
+ expect(embedderConfigured(NIM_EMBED_TAG)).toBe(true);
+ expect(embedderConfigured(OPENAI_EMBED_TAG)).toBe(false);
+ expect(embedderConfigured(null)).toBe(false); // legacy = OpenAI, no key
+ });
+});
+
+describe('embedWith — NIM lane', () => {
+ beforeEach(() => {
+ process.env.NVIDIA_API_KEY = 'nvapi-test';
+ });
+
+ it('sends model, inputs, and the REQUIRED input_type for passages', async () => {
+ fetchMock.mockResolvedValueOnce(okEmbeddings([[0.1, 0.2], [0.3, 0.4]]));
+ const out = await embedPassages(NIM_EMBED_TAG, ['one', 'two']);
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ expect(fetchMock.mock.calls[0][0]).toBe(NIM_URL);
+ expect(lastBody()).toEqual({
+ model: 'nvidia/nv-embedqa-e5-v5',
+ input: ['one', 'two'],
+ input_type: 'passage',
+ });
+ expect(out).toHaveLength(2);
+ expect(out[0]).toBeInstanceOf(Float64Array);
+ });
+
+ it('embeds search strings with input_type query', async () => {
+ fetchMock.mockResolvedValueOnce(okEmbeddings([[0.5, 0.6]]));
+ const vec = await embedQuery(NIM_EMBED_TAG, 'what is three.ws?');
+ expect(lastBody().input_type).toBe('query');
+ expect(Array.from(vec)).toEqual([0.5, 0.6]);
+ });
+
+ it('rejects an invalid inputType before any network call', async () => {
+ await expect(embedWith(NIM_EMBED_TAG, ['x'], 'document')).rejects.toMatchObject({
+ code: 'embedder_error',
+ });
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it('retries an over-length 400 once with inputs truncated under the 512-token cap', async () => {
+ const oversized = 'x'.repeat(9000);
+ fetchMock
+ .mockResolvedValueOnce({
+ ok: false,
+ status: 400,
+ text: async () => '{"error":"Input length 4032 exceeds maximum allowed token size 512"}',
+ })
+ .mockResolvedValueOnce(okEmbeddings([[1, 0]]));
+ const out = await embedPassages(NIM_EMBED_TAG, [oversized]);
+ expect(out).toHaveLength(1);
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ const retryInput = JSON.parse(fetchMock.mock.calls[1][1].body).input[0];
+ expect(retryInput.length).toBeLessThanOrEqual(512 * 3);
+ });
+
+ it('does not retry-loop: a second over-length 400 surfaces as an error', async () => {
+ const reject400 = {
+ ok: false,
+ status: 400,
+ text: async () => 'Input length 9999 exceeds maximum allowed token size 512',
+ };
+ fetchMock.mockResolvedValueOnce(reject400).mockResolvedValueOnce(reject400);
+ await expect(embedPassages(NIM_EMBED_TAG, ['x'.repeat(9000)])).rejects.toMatchObject({
+ code: 'embedder_error',
+ status: 400,
+ });
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ });
+
+ it('surfaces upstream failures with status for backoff routing', async () => {
+ fetchMock.mockResolvedValueOnce({ ok: false, status: 429, text: async () => 'slow down' });
+ await expect(embedPassages(NIM_EMBED_TAG, ['x'])).rejects.toMatchObject({
+ code: 'embedder_error',
+ status: 429,
+ });
+ });
+
+ it('sorts response rows by index so vectors align with inputs', async () => {
+ fetchMock.mockResolvedValueOnce({
+ ok: true,
+ status: 200,
+ json: async () => ({
+ data: [
+ { index: 1, embedding: [2, 2] },
+ { index: 0, embedding: [1, 1] },
+ ],
+ }),
+ });
+ const out = await embedPassages(NIM_EMBED_TAG, ['a', 'b']);
+ expect(Array.from(out[0])).toEqual([1, 1]);
+ expect(Array.from(out[1])).toEqual([2, 2]);
+ });
+});
+
+describe('embedWith — OpenAI lane', () => {
+ it('requests the Matryoshka-truncated 256 dimensions', async () => {
+ process.env.OPENAI_API_KEY = 'sk-test';
+ fetchMock.mockResolvedValueOnce(okEmbeddings([[0.1]]));
+ await embedPassages(OPENAI_EMBED_TAG, ['hello']);
+ expect(fetchMock.mock.calls[0][0]).toBe(OPENAI_URL);
+ expect(lastBody()).toEqual({
+ model: 'text-embedding-3-small',
+ input: ['hello'],
+ dimensions: 256,
+ });
+ });
+
+ it('throws no_embedder when the tag is known but its key is absent', async () => {
+ process.env.NVIDIA_API_KEY = 'nvapi-test';
+ await expect(embedPassages(OPENAI_EMBED_TAG, ['x'])).rejects.toMatchObject({
+ code: 'no_embedder',
+ });
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it('throws unknown_embedder for a tag this build does not know', async () => {
+ await expect(embedPassages('mystery@1', ['x'])).rejects.toMatchObject({
+ code: 'unknown_embedder',
+ });
+ });
+});
+
+describe('scoreRowsBySpace — same-space routing, cross-space refusal', () => {
+ it('embeds the query in each servable space and scores strictly within it', async () => {
+ process.env.NVIDIA_API_KEY = 'nvapi-test';
+ process.env.OPENAI_API_KEY = 'sk-test';
+ // NIM query vector [1,0]; OpenAI query vector [0,1].
+ fetchMock.mockImplementation(async (url, init) => {
+ const body = JSON.parse(init.body);
+ return okEmbeddings([body.model.startsWith('nvidia/') ? [1, 0] : [0, 1]]);
+ });
+ const rows = [
+ { id: 1, embedder: NIM_EMBED_TAG, embedding: [1, 0] }, // matches NIM query
+ { id: 2, embedder: null, embedding: [0, 1] }, // legacy → OpenAI space, matches
+ { id: 3, embedder: NIM_EMBED_TAG, embedding: [0, 1] }, // orthogonal in NIM space
+ ];
+ const { scored, needsReembed } = await scoreRowsBySpace(rows, 'question?');
+ expect(needsReembed).toEqual([]);
+ expect(fetchMock).toHaveBeenCalledTimes(2); // one query embed per space
+ const byId = Object.fromEntries(scored.map((r) => [r.id, r]));
+ expect(byId[1].score).toBeCloseTo(1, 6);
+ expect(byId[2].score).toBeCloseTo(1, 6);
+ expect(byId[2].embedder).toBe(LEGACY_EMBED_TAG); // legacy normalized, not guessed
+ expect(byId[3].score).toBeCloseTo(0, 6);
+ });
+
+ it('refuses to score rows whose space no configured provider can serve', async () => {
+ process.env.NVIDIA_API_KEY = 'nvapi-test'; // OpenAI NOT configured
+ fetchMock.mockResolvedValue(okEmbeddings([[1, 0]]));
+ const rows = [
+ { id: 1, embedder: NIM_EMBED_TAG, embedding: [1, 0] },
+ { id: 2, embedder: null, embedding: [0.9, 0.1] }, // legacy OpenAI space
+ { id: 3, embedder: 'retired-model@999', embedding: [0.9, 0.1] },
+ ];
+ const { scored, needsReembed } = await scoreRowsBySpace(rows, 'q');
+ expect(scored.map((r) => r.id)).toEqual([1]);
+ expect(needsReembed).toEqual(
+ expect.arrayContaining([
+ { embedder: LEGACY_EMBED_TAG, chunks: 1 },
+ { embedder: 'retired-model@999', chunks: 1 },
+ ]),
+ );
+ // The legacy rows were never compared against the NIM query vector.
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe('cosine — dimension guard', () => {
+ it('scores identical vectors as 1', () => {
+ expect(cosine([0.1, 0.2, 0.3], [0.1, 0.2, 0.3])).toBeCloseTo(1, 6);
+ });
+
+ it('scores mismatched dimensions as 0 — never compares a shared prefix', () => {
+ // A 1024-dim NIM vector vs a 256-dim OpenAI vector must not produce a
+ // plausible-looking similarity from the overlapping prefix.
+ expect(cosine([1, 1, 1], [1, 1])).toBe(0);
+ });
+
+ it('scores zero vectors as 0, not NaN', () => {
+ expect(cosine([0, 0], [1, 1])).toBe(0);
+ });
+});
diff --git a/tests/api/rerank.test.js b/tests/api/rerank.test.js
new file mode 100644
index 000000000..6393f3c28
--- /dev/null
+++ b/tests/api/rerank.test.js
@@ -0,0 +1,103 @@
+// Tests for api/_lib/rerank.js — the optional NIM rerank stage behind
+// KNOWLEDGE_RERANK_ENABLED. Pins the two contracts retrieval depends on:
+// opt-in gating (retrieval ordering never changes without the flag) and
+// strict fail-open (any upstream problem returns null so cosine order wins).
+
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+
+import { rerankConfigured, rerankPassages } from '../../api/_lib/rerank.js';
+
+const fetchMock = vi.fn();
+
+function clearEnv() {
+ delete process.env.KNOWLEDGE_RERANK_ENABLED;
+ delete process.env.NVIDIA_API_KEY;
+}
+
+beforeEach(() => {
+ clearEnv();
+ fetchMock.mockReset();
+ vi.stubGlobal('fetch', fetchMock);
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+ clearEnv();
+});
+
+function enable() {
+ process.env.KNOWLEDGE_RERANK_ENABLED = '1';
+ process.env.NVIDIA_API_KEY = 'nvapi-test';
+}
+
+describe('rerankConfigured', () => {
+ it('is off by default, even with the NVIDIA key present', () => {
+ expect(rerankConfigured()).toBe(false);
+ process.env.NVIDIA_API_KEY = 'nvapi-test';
+ expect(rerankConfigured()).toBe(false);
+ });
+
+ it('requires BOTH the opt-in flag and the key', () => {
+ process.env.KNOWLEDGE_RERANK_ENABLED = '1';
+ expect(rerankConfigured()).toBe(false);
+ process.env.NVIDIA_API_KEY = 'nvapi-test';
+ expect(rerankConfigured()).toBe(true);
+ });
+});
+
+describe('rerankPassages', () => {
+ it('returns null without touching the network when not configured', async () => {
+ expect(await rerankPassages('q', ['a', 'b'])).toBe(null);
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it('posts the probed body shape and returns candidate indexes best-first', async () => {
+ enable();
+ fetchMock.mockResolvedValueOnce({
+ ok: true,
+ json: async () => ({
+ rankings: [
+ { index: 2, logit: 3.7 },
+ { index: 0, logit: -1.2 },
+ { index: 1, logit: -14.6 },
+ ],
+ }),
+ });
+ const order = await rerankPassages('capital of France?', ['p0', 'p1', 'p2']);
+ expect(order).toEqual([2, 0, 1]);
+ const [url, init] = fetchMock.mock.calls[0];
+ expect(url).toBe('https://ai.api.nvidia.com/v1/retrieval/nvidia/reranking');
+ expect(JSON.parse(init.body)).toEqual({
+ model: 'nvidia/rerank-qa-mistral-4b',
+ query: { text: 'capital of France?' },
+ passages: [{ text: 'p0' }, { text: 'p1' }, { text: 'p2' }],
+ });
+ });
+
+ it('skips degenerate inputs (fewer than two passages)', async () => {
+ enable();
+ expect(await rerankPassages('q', ['only one'])).toBe(null);
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it('fails open on an upstream error status', async () => {
+ enable();
+ fetchMock.mockResolvedValueOnce({ ok: false, status: 429, json: async () => ({}) });
+ expect(await rerankPassages('q', ['a', 'b'])).toBe(null);
+ });
+
+ it('fails open on a network throw', async () => {
+ enable();
+ fetchMock.mockRejectedValueOnce(new Error('socket hang up'));
+ expect(await rerankPassages('q', ['a', 'b'])).toBe(null);
+ });
+
+ it('rejects a partial or garbled ranking instead of reordering with it', async () => {
+ enable();
+ fetchMock.mockResolvedValueOnce({
+ ok: true,
+ json: async () => ({ rankings: [{ index: 0, logit: 1 }, { index: 7, logit: 0 }] }),
+ });
+ expect(await rerankPassages('q', ['a', 'b'])).toBe(null);
+ });
+});
diff --git a/tests/api/tts-speak.test.js b/tests/api/tts-speak.test.js
new file mode 100644
index 000000000..b8d82e1a0
--- /dev/null
+++ b/tests/api/tts-speak.test.js
@@ -0,0 +1,371 @@
+// Tests for the TTS free-first provider chain (task T2.1).
+//
+// Policy under test (api/_lib/llm.js doctrine applied to speech):
+// • NVIDIA NIM Magpie (free, gRPC) leads whenever NVIDIA_API_KEY is set —
+// and OpenAI is NEVER called when it serves.
+// • OpenAI is the paid backstop: attempted only after the NIM lane fails or
+// is unconfigured.
+// • 503 only when NO lane is configured; 502 (with both lanes' errors, in
+// attempt order) when every configured lane fails.
+// • x-tts-voice / x-tts-model / x-tts-format / content-type always describe
+// the bytes actually served (Magpie emits PCM → non-pcm requests become
+// WAV).
+//
+// Transport-layer mocks only: the gRPC client (@grpc/grpc-js) and global
+// fetch. No live calls. Same chain is asserted on the MCP twin
+// (packages/avatar-agent-mcp/src/tools/speak.js).
+
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { Readable } from 'node:stream';
+
+// Shared with the hoisted vi.mock factories below.
+const grpcState = vi.hoisted(() => ({
+ // (req, metadata, opts, cb) — set per test.
+ synthesize: null,
+ calls: [], // { request, metadata }
+ clients: [], // constructor args, to prove the channel target
+}));
+
+vi.mock('@grpc/grpc-js', () => {
+ class Metadata {
+ constructor() {
+ this.map = {};
+ }
+ set(k, v) {
+ this.map[k] = v;
+ }
+ get(k) {
+ return this.map[k];
+ }
+ }
+ class RivaSpeechSynthesis {
+ constructor(host, creds, opts) {
+ grpcState.clients.push({ host, creds, opts });
+ }
+ synthesize(request, metadata, opts, cb) {
+ grpcState.calls.push({ request, metadata });
+ grpcState.synthesize(request, metadata, opts, cb);
+ }
+ }
+ const grpc = {
+ Metadata,
+ credentials: { createSsl: () => ({ ssl: true }) },
+ loadPackageDefinition: () => ({ nvidia: { riva: { tts: { RivaSpeechSynthesis } } } }),
+ };
+ return { default: grpc };
+});
+
+vi.mock('@grpc/proto-loader', () => ({
+ default: { fromJSON: () => ({ mockPackageDefinition: true }) },
+}));
+
+const ORIGINAL_FETCH = globalThis.fetch;
+const ENV_KEYS = ['NVIDIA_API_KEY', 'OPENAI_API_KEY'];
+const ORIGINAL_ENV = Object.fromEntries(ENV_KEYS.map((k) => [k, process.env[k]]));
+
+// Synthetic little-endian s16 PCM (clearly not RIFF) the mock lane returns.
+const PCM_BYTES = Buffer.alloc(2000, 0x42);
+const OPENAI_MP3_BYTES = Buffer.from('openai-mp3-bytes-fixture');
+
+function grpcSuccess() {
+ grpcState.synthesize = (_req, _md, _opts, cb) => cb(null, { audio: PCM_BYTES });
+}
+
+function grpcFailure(code = 16, details = 'auth denied') {
+ grpcState.synthesize = (_req, _md, _opts, cb) => {
+ const err = new Error(details);
+ err.code = code;
+ err.details = details;
+ cb(err);
+ };
+}
+
+function stubOpenAi(status = 200, body = OPENAI_MP3_BYTES) {
+ const calls = [];
+ globalThis.fetch = vi.fn(async (url, opts = {}) => {
+ const u = String(url);
+ calls.push({ url: u, body: opts.body ? JSON.parse(opts.body) : null });
+ if (!u.includes('api.openai.com')) throw new Error(`unexpected fetch in test: ${u}`);
+ if (status !== 200) {
+ return new Response(JSON.stringify({ error: { message: 'insufficient_quota' } }), { status });
+ }
+ return new Response(body, { status: 200, headers: { 'content-type': 'audio/mpeg' } });
+ });
+ return calls;
+}
+
+let ipCounter = 0;
+function makeReq(body, headers = {}) {
+ const buf = Buffer.from(JSON.stringify(body));
+ const req = Readable.from([buf]);
+ req.method = 'POST';
+ req.url = '/api/tts/speak';
+ req.headers = {
+ 'content-type': 'application/json',
+ 'content-length': String(buf.length),
+ // Unique IP per request so the in-memory per-IP limiter never trips.
+ 'x-vercel-forwarded-for': `10.0.0.${++ipCounter}`,
+ ...headers,
+ };
+ return req;
+}
+
+function makeRes() {
+ const chunks = [];
+ return {
+ 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;
+ },
+ body() {
+ return Buffer.concat(chunks);
+ },
+ json() {
+ return JSON.parse(this.body().toString('utf8'));
+ },
+ };
+}
+
+async function callSpeak(body, headers) {
+ const handler = (await import('../../api/tts/speak.js')).default;
+ const res = makeRes();
+ await handler(makeReq(body, headers), res);
+ return res;
+}
+
+beforeEach(() => {
+ grpcState.synthesize = () => {
+ throw new Error('grpc synthesize called without a test stub');
+ };
+ grpcState.calls.length = 0;
+ process.env.NVIDIA_API_KEY = 'nvapi-test-key';
+ process.env.OPENAI_API_KEY = 'sk-test-openai';
+ globalThis.fetch = vi.fn(async (url) => {
+ throw new Error(`unexpected fetch in test: ${url}`);
+ });
+});
+
+afterEach(() => {
+ globalThis.fetch = ORIGINAL_FETCH;
+ for (const k of ENV_KEYS) {
+ if (ORIGINAL_ENV[k] === undefined) delete process.env[k];
+ else process.env[k] = ORIGINAL_ENV[k];
+ }
+});
+
+describe('POST /api/tts/speak — free-first chain', () => {
+ it('NIM serves and OpenAI is never called; headers describe the actual audio', async () => {
+ grpcSuccess();
+ const res = await callSpeak({ text: 'Hello there', voice: 'nova', format: 'mp3' });
+
+ expect(res.statusCode).toBe(200);
+ // mp3 was requested, but the free lane emits PCM → served as WAV, truthfully.
+ expect(res.getHeader('content-type')).toBe('audio/wav');
+ expect(res.getHeader('x-tts-model')).toBe('magpie-tts-multilingual');
+ expect(res.getHeader('x-tts-voice')).toBe('Magpie-Multilingual.EN-US.Aria');
+ expect(res.getHeader('x-tts-format')).toBe('wav');
+ const body = res.body();
+ expect(body.subarray(0, 4).toString('ascii')).toBe('RIFF');
+ expect(body.subarray(8, 12).toString('ascii')).toBe('WAVE');
+ expect(body.length).toBe(44 + PCM_BYTES.length);
+ // Paid backstop untouched.
+ expect(globalThis.fetch).not.toHaveBeenCalled();
+ // The gRPC request carried the probe-verified NVCF contract.
+ expect(grpcState.calls).toHaveLength(1);
+ const { request, metadata } = grpcState.calls[0];
+ expect(request).toMatchObject({
+ text: 'Hello there',
+ language_code: 'en-US',
+ encoding: 'LINEAR_PCM',
+ sample_rate_hz: 44100,
+ voice_name: 'Magpie-Multilingual.EN-US.Aria',
+ });
+ expect(metadata.map['function-id']).toBe('877104f7-e885-42b9-8de8-f6e4c6303969');
+ expect(metadata.map['authorization']).toBe('Bearer nvapi-test-key');
+ expect(grpcState.clients.at(-1).host).toBe('grpc.nvcf.nvidia.com:443');
+ });
+
+ it('fails over to OpenAI when the NIM lane errors, with truthful headers', async () => {
+ grpcFailure(8, 'free tier exhausted');
+ const calls = stubOpenAi();
+ const res = await callSpeak({ text: 'Backstop please', voice: 'shimmer', format: 'mp3' });
+
+ expect(res.statusCode).toBe(200);
+ expect(grpcState.calls).toHaveLength(1); // NIM attempted first
+ expect(calls).toHaveLength(1);
+ expect(calls[0].url).toContain('api.openai.com/v1/audio/speech');
+ expect(calls[0].body).toMatchObject({ voice: 'shimmer', model: 'gpt-4o-mini-tts', response_format: 'mp3' });
+ expect(res.getHeader('content-type')).toBe('audio/mpeg');
+ expect(res.getHeader('x-tts-model')).toBe('gpt-4o-mini-tts');
+ expect(res.getHeader('x-tts-voice')).toBe('shimmer');
+ expect(res.getHeader('x-tts-format')).toBe('mp3');
+ expect(res.body().equals(OPENAI_MP3_BYTES)).toBe(true);
+ });
+
+ it('goes straight to OpenAI when NVIDIA_API_KEY is absent', async () => {
+ delete process.env.NVIDIA_API_KEY;
+ const calls = stubOpenAi();
+ const res = await callSpeak({ text: 'No free lane today' });
+
+ expect(res.statusCode).toBe(200);
+ expect(grpcState.calls).toHaveLength(0);
+ expect(calls).toHaveLength(1);
+ expect(res.getHeader('x-tts-model')).toBe('gpt-4o-mini-tts');
+ });
+
+ it('returns 503 not_configured only when NO lane is configured', async () => {
+ delete process.env.NVIDIA_API_KEY;
+ delete process.env.OPENAI_API_KEY;
+ const res = await callSpeak({ text: 'anyone there?' });
+
+ expect(res.statusCode).toBe(503);
+ expect(res.json().error).toBe('not_configured');
+ expect(grpcState.calls).toHaveLength(0);
+ expect(globalThis.fetch).not.toHaveBeenCalled();
+ });
+
+ it('returns a clean 502 with both lane errors, in attempt order, when everything fails', async () => {
+ grpcFailure(16, 'bad key');
+ stubOpenAi(429);
+ const res = await callSpeak({ text: 'Total outage' });
+
+ expect(res.statusCode).toBe(502);
+ const detail = res.json().error_description;
+ const iNvidia = detail.indexOf('nvidia:');
+ const iOpenai = detail.indexOf('openai:');
+ expect(iNvidia).toBeGreaterThanOrEqual(0);
+ expect(iOpenai).toBeGreaterThan(iNvidia); // nvidia attempted first
+ expect(detail).toContain('invalid_key');
+ expect(detail).toContain('429');
+ });
+
+ it('serves pcm requests raw (no WAV header) with audio/pcm content-type', async () => {
+ grpcSuccess();
+ const res = await callSpeak({ text: 'raw please', format: 'pcm' });
+
+ expect(res.statusCode).toBe(200);
+ expect(res.getHeader('content-type')).toBe('audio/pcm');
+ expect(res.getHeader('x-tts-format')).toBe('pcm');
+ expect(res.body().equals(PCM_BYTES)).toBe(true);
+ });
+
+ it('serves opus requests as WAV on the NIM lane (NVCF emits containerless opus), truthfully labeled', async () => {
+ grpcSuccess();
+ const res = await callSpeak({ text: 'opus request', format: 'opus' });
+
+ expect(res.statusCode).toBe(200);
+ expect(grpcState.calls[0].request.encoding).toBe('LINEAR_PCM');
+ expect(res.getHeader('content-type')).toBe('audio/wav');
+ expect(res.getHeader('x-tts-format')).toBe('wav');
+ expect(res.body().subarray(0, 4).toString('ascii')).toBe('RIFF');
+ });
+
+ it('keeps request validation: empty text is a 400 before any lane is tried', async () => {
+ const res = await callSpeak({ text: ' ' });
+
+ expect(res.statusCode).toBe(400);
+ expect(grpcState.calls).toHaveLength(0);
+ expect(globalThis.fetch).not.toHaveBeenCalled();
+ });
+});
+
+describe('voice + language mapping (api/_lib/tts-nvidia.js)', () => {
+ it('maps every platform voice name to a live-verified en-US Magpie persona', async () => {
+ const { VOICE_TO_MAGPIE, resolveMagpieVoice } = await import('../../api/_lib/tts-nvidia.js');
+ const platformVoices = ['alloy', 'ash', 'ballad', 'coral', 'echo', 'fable', 'nova', 'onyx', 'sage', 'shimmer', 'verse'];
+ // Personas confirmed against the live GetRivaSynthesisConfig subvoice list.
+ const livePersonas = new Set(['Mia', 'Jason', 'Aria', 'Leo', 'Sofia', 'Ray']);
+ for (const v of platformVoices) {
+ expect(livePersonas.has(VOICE_TO_MAGPIE[v]), `${v} maps to a live persona`).toBe(true);
+ expect(resolveMagpieVoice(v)).toBe(`Magpie-Multilingual.EN-US.${VOICE_TO_MAGPIE[v]}`);
+ }
+ });
+
+ it('upper-cases the language tag in the subvoice id (server rejects lowercase)', async () => {
+ const { resolveMagpieVoice } = await import('../../api/_lib/tts-nvidia.js');
+ expect(resolveMagpieVoice('nova', 'ja-JP')).toBe('Magpie-Multilingual.JA-JP.Aria');
+ expect(resolveMagpieVoice('nova', 'ja')).toBe('Magpie-Multilingual.JA-JP.Aria');
+ });
+
+ it('falls back to en-US for unknown languages and passes raw Magpie ids through', async () => {
+ const { resolveMagpieVoice, resolveMagpieLanguage } = await import('../../api/_lib/tts-nvidia.js');
+ expect(resolveMagpieLanguage('en-GB')).toBe('en-US');
+ expect(resolveMagpieLanguage('xx-YY')).toBe('en-US');
+ expect(resolveMagpieVoice('Magpie-Multilingual.ES-US.Diego.Happy')).toBe('Magpie-Multilingual.ES-US.Diego.Happy');
+ });
+
+ it('unknown voice names get the default persona instead of failing', async () => {
+ const { resolveMagpieVoice } = await import('../../api/_lib/tts-nvidia.js');
+ expect(resolveMagpieVoice('definitely-not-a-voice')).toBe('Magpie-Multilingual.EN-US.Sofia');
+ });
+});
+
+describe('MCP twin (packages/avatar-agent-mcp speak tool) — same chain', () => {
+ // config.js binds env at import time, so reset modules and re-import per test.
+ async function freshTool() {
+ vi.resetModules();
+ return (await import('../../packages/avatar-agent-mcp/src/tools/speak.js')).def;
+ }
+
+ it('NIM serves: provider nvidia, wav data URL, OpenAI never called', async () => {
+ grpcSuccess();
+ const tool = await freshTool();
+ const out = await tool.handler({ text: 'MCP says hi', voice: 'onyx' });
+
+ expect(out.ok).toBe(true);
+ expect(out.provider).toBe('nvidia');
+ expect(out.model).toBe('magpie-tts-multilingual');
+ expect(out.voice).toBe('Magpie-Multilingual.EN-US.Ray');
+ expect(out.format).toBe('wav');
+ expect(out.mime).toBe('audio/wav');
+ expect(out.audio.startsWith('data:audio/wav;base64,')).toBe(true);
+ const decoded = Buffer.from(out.audio.split(',')[1], 'base64');
+ expect(decoded.subarray(0, 4).toString('ascii')).toBe('RIFF');
+ expect(globalThis.fetch).not.toHaveBeenCalled();
+ });
+
+ it('NIM failure falls over to OpenAI with truthful provider fields', async () => {
+ grpcFailure(14, 'upstream unavailable');
+ const calls = stubOpenAi();
+ const tool = await freshTool();
+ const out = await tool.handler({ text: 'MCP backstop', voice: 'nova', format: 'mp3' });
+
+ expect(out.ok).toBe(true);
+ expect(out.provider).toBe('openai');
+ expect(out.model).toBe('gpt-4o-mini-tts');
+ expect(out.voice).toBe('nova');
+ expect(out.mime).toBe('audio/mpeg');
+ expect(calls).toHaveLength(1);
+ });
+
+ it('both lanes failing returns tts_failed with the attempt order; no key at all is not_configured', async () => {
+ grpcFailure(16, 'bad key');
+ stubOpenAi(401);
+ let tool = await freshTool();
+ const failed = await tool.handler({ text: 'MCP outage' });
+ expect(failed.ok).toBe(false);
+ expect(failed.error).toBe('tts_failed');
+ expect(failed.message.indexOf('nvidia:')).toBeGreaterThanOrEqual(0);
+ expect(failed.message.indexOf('openai:')).toBeGreaterThan(failed.message.indexOf('nvidia:'));
+
+ delete process.env.NVIDIA_API_KEY;
+ delete process.env.OPENAI_API_KEY;
+ tool = await freshTool();
+ const unconfigured = await tool.handler({ text: 'MCP unconfigured' });
+ expect(unconfigured.ok).toBe(false);
+ expect(unconfigured.error).toBe('not_configured');
+ });
+});
diff --git a/tests/api/uptime-status.test.js b/tests/api/uptime-status.test.js
new file mode 100644
index 000000000..e2096b446
--- /dev/null
+++ b/tests/api/uptime-status.test.js
@@ -0,0 +1,181 @@
+// Tests for the first-party uptime pipeline:
+// api/cron/uptime-check.js — probes targets, stores snapshots + daily
+// aggregates, alerts on failure and recovery
+// api/status.js — public aggregation the /status page renders
+// All upstreams (fetch, cache, alerts, rate limits) are mocked; the contract
+// under test is storage shape, aggregation math, auth, and alert behavior.
+
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+
+const cache = new Map();
+vi.mock('../../api/_lib/cache.js', () => ({
+ cacheGet: vi.fn(async (k) => (cache.has(k) ? cache.get(k) : null)),
+ cacheSet: vi.fn(async (k, v) => {
+ // JSON round-trip like real Redis, so handlers can't rely on references.
+ cache.set(k, JSON.parse(JSON.stringify(v)));
+ }),
+ cacheDel: vi.fn(async (k) => cache.delete(k)),
+ cacheBackend: () => 'memory',
+}));
+
+const sendOpsAlert = vi.fn();
+vi.mock('../../api/_lib/alerts.js', () => ({
+ sendOpsAlert: (...args) => sendOpsAlert(...args),
+}));
+
+vi.mock('../../api/_lib/rate-limit.js', () => ({
+ limits: { publicIp: vi.fn(async () => ({ success: true })) },
+ clientIp: vi.fn(() => '127.0.0.1'),
+}));
+
+const upstream = { failIds: new Set() };
+const realFetch = global.fetch;
+
+const { default: cronHandler, UPTIME_TARGETS } = await import('../../api/cron/uptime-check.js');
+const { default: statusHandler } = await import('../../api/status.js');
+
+function makeRes() {
+ return {
+ statusCode: 200,
+ headers: {},
+ body: '',
+ writableEnded: false,
+ setHeader(k, v) {
+ this.headers[k.toLowerCase()] = v;
+ },
+ end(chunk) {
+ if (chunk !== undefined) this.body += chunk;
+ this.writableEnded = true;
+ },
+ };
+}
+
+async function runCron({ secret = 'test-secret' } = {}) {
+ const res = makeRes();
+ await cronHandler(
+ {
+ method: 'GET',
+ url: '/api/cron/uptime-check',
+ headers: secret ? { authorization: `Bearer ${secret}` } : {},
+ },
+ res,
+ );
+ return { status: res.statusCode, body: res.body ? JSON.parse(res.body) : null };
+}
+
+async function runStatus() {
+ const res = makeRes();
+ await statusHandler({ method: 'GET', url: '/api/status', headers: {} }, res);
+ return { status: res.statusCode, body: res.body ? JSON.parse(res.body) : null, res };
+}
+
+beforeEach(() => {
+ cache.clear();
+ upstream.failIds.clear();
+ sendOpsAlert.mockClear();
+ process.env.CRON_SECRET = 'test-secret';
+ global.fetch = vi.fn(async (url) => {
+ const u = new URL(String(url));
+ const target = UPTIME_TARGETS.find((t) => u.pathname + u.search === t.path);
+ const fail = target && upstream.failIds.has(target.id);
+ return { ok: !fail, status: fail ? 503 : 200 };
+ });
+ return () => {
+ global.fetch = realFetch;
+ };
+});
+
+describe('api/cron/uptime-check', () => {
+ it('rejects a missing or wrong cron secret', async () => {
+ expect((await runCron({ secret: 'wrong' })).status).toBe(401);
+ expect((await runCron({ secret: null })).status).toBe(401);
+ delete process.env.CRON_SECRET;
+ expect((await runCron({})).status).toBe(503);
+ });
+
+ it('probes every target and stores a snapshot + daily aggregate', async () => {
+ const { status, body } = await runCron();
+ expect(status).toBe(200);
+ expect(body.ok).toBe(true);
+ expect(Object.keys(body.results).sort()).toEqual(UPTIME_TARGETS.map((t) => t.id).sort());
+
+ const snaps = cache.get('uptime:snapshots');
+ expect(snaps).toHaveLength(1);
+ const daily = cache.get('uptime:daily');
+ expect(daily).toHaveLength(1);
+ for (const t of UPTIME_TARGETS) {
+ expect(daily[0].targets[t.id]).toMatchObject({ n: 1, up: 1 });
+ }
+ expect(sendOpsAlert).not.toHaveBeenCalled();
+ });
+
+ it('alerts on a down target and announces recovery', async () => {
+ upstream.failIds.add('api');
+ const down = await runCron();
+ expect(down.body.ok).toBe(false);
+ expect(down.body.down).toBe(1);
+ expect(sendOpsAlert).toHaveBeenCalledTimes(1);
+ expect(sendOpsAlert.mock.calls[0][0]).toContain('DOWN');
+
+ sendOpsAlert.mockClear();
+ upstream.failIds.clear();
+ await runCron();
+ expect(sendOpsAlert).toHaveBeenCalledTimes(1);
+ expect(sendOpsAlert.mock.calls[0][0]).toContain('RECOVERED');
+ });
+
+ it('caps the snapshot window and accumulates daily counts', async () => {
+ await runCron();
+ await runCron();
+ await runCron();
+ expect(cache.get('uptime:snapshots')).toHaveLength(3);
+ const daily = cache.get('uptime:daily');
+ expect(daily).toHaveLength(1);
+ expect(daily[0].targets.site).toMatchObject({ n: 3, up: 3 });
+ });
+});
+
+describe('api/status', () => {
+ it('reports warming-up with no probe data', async () => {
+ const { status, body } = await runStatus();
+ expect(status).toBe(200);
+ expect(body.ok).toBe(true);
+ expect(body.monitoring).toBe('warming-up');
+ expect(body.services).toHaveLength(UPTIME_TARGETS.length);
+ for (const s of body.services) {
+ expect(s.operational).toBeNull();
+ expect(s.uptime24h).toBeNull();
+ }
+ });
+
+ it('aggregates uptime and latency from probe history', async () => {
+ upstream.failIds.add('explore');
+ await runCron();
+ upstream.failIds.clear();
+ await runCron();
+
+ const { body } = await runStatus();
+ expect(body.monitoring).toBe('active');
+ const explore = body.services.find((s) => s.id === 'explore');
+ expect(explore.operational).toBe(true); // latest probe is green
+ expect(explore.uptime24h).toBe(50);
+ expect(explore.uptime90d).toBe(50);
+ expect(explore.history).toHaveLength(1);
+ const site = body.services.find((s) => s.id === 'site');
+ expect(site.uptime24h).toBe(100);
+ expect(body.ok).toBe(true);
+ });
+
+ it('flags the platform not-ok while a service is down', async () => {
+ upstream.failIds.add('api');
+ await runCron();
+ const { body } = await runStatus();
+ expect(body.ok).toBe(false);
+ expect(body.services.find((s) => s.id === 'api').operational).toBe(false);
+ });
+
+ it('is publicly cacheable', async () => {
+ const { res } = await runStatus();
+ expect(res.headers['cache-control']).toContain('max-age=60');
+ });
+});
diff --git a/tests/api/widget-knowledge-embedder.test.js b/tests/api/widget-knowledge-embedder.test.js
new file mode 100644
index 000000000..f0bfe2689
--- /dev/null
+++ b/tests/api/widget-knowledge-embedder.test.js
@@ -0,0 +1,223 @@
+// Tests for the embedder-tagging plumbing in api/widgets/[id]/_knowledge.js:
+// ingest stamps the free-first embedder tag on the doc and every chunk,
+// the retrieval debugger surfaces an actionable needs_reembed 503 instead of
+// ever crossing vector spaces, and the QStash worker re-resolves a stale tag
+// to a servable embedder before re-embedding.
+
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+
+const NIM_TAG = 'nvidia/nv-embedqa-e5-v5@1024';
+const LEGACY_TAG = 'text-embedding-3-small@256';
+
+// ── Mocks (registered before importing _knowledge.js) ───────────────────────
+
+const sqlQueue = [];
+const sqlCalls = [];
+const sqlMock = vi.fn((strings, ...params) => {
+ sqlCalls.push({ text: Array.isArray(strings) ? strings.join('$') : String(strings), params });
+ const next = sqlQueue.shift();
+ if (next instanceof Error) return Promise.reject(next);
+ return Promise.resolve(next ?? []);
+});
+sqlMock.transaction = vi.fn(async (queries) => Promise.all(queries));
+vi.mock('../../api/_lib/db.js', () => ({ sql: sqlMock }));
+
+// Mutable embedding-provider state each test configures.
+const mockEmbedState = {
+ defaultTag: NIM_TAG,
+ configured: new Set([NIM_TAG]),
+ scoreResult: { scored: [], needsReembed: [] },
+};
+const embedPassagesMock = vi.fn(async (_tag, texts) =>
+ texts.map(() => Float64Array.from([1, 0, 0, 0])),
+);
+vi.mock('../../api/_lib/embeddings.js', () => ({
+ NIM_EMBED_TAG: NIM_TAG,
+ OPENAI_EMBED_TAG: LEGACY_TAG,
+ LEGACY_EMBED_TAG: LEGACY_TAG,
+ embeddingsConfigured: () => mockEmbedState.configured.size > 0,
+ embedderConfigured: (tag) => mockEmbedState.configured.has(tag || LEGACY_TAG),
+ defaultIngestEmbedderTag: () => mockEmbedState.defaultTag,
+ resolveEmbedderTag: (tag) => {
+ const t = tag || LEGACY_TAG;
+ return t === NIM_TAG || t === LEGACY_TAG ? t : null;
+ },
+ embedPassages: embedPassagesMock,
+ scoreRowsBySpace: vi.fn(async () => mockEmbedState.scoreResult),
+}));
+
+vi.mock('../../api/_lib/rerank.js', () => ({
+ rerankConfigured: () => false,
+ rerankPassages: vi.fn(),
+}));
+
+vi.mock('../../api/_lib/text-extract.js', () => ({ fetchAndExtract: vi.fn() }));
+vi.mock('../../api/_lib/qstash.js', () => ({
+ qstashEnabled: () => false,
+ publishJob: vi.fn(),
+}));
+vi.mock('../../api/_lib/env.js', () => ({ env: { APP_ORIGIN: 'https://three.ws' } }));
+
+const { ingestKnowledge, testRetrieval, processQueuedDoc } = await import(
+ '../../api/widgets/[id]/_knowledge.js'
+);
+
+beforeEach(() => {
+ sqlQueue.length = 0;
+ sqlCalls.length = 0;
+ sqlMock.mockClear();
+ embedPassagesMock.mockClear();
+ mockEmbedState.defaultTag = NIM_TAG;
+ mockEmbedState.configured = new Set([NIM_TAG]);
+ mockEmbedState.scoreResult = { scored: [], needsReembed: [] };
+});
+
+function findCall(snippet) {
+ return sqlCalls.find((c) => c.text.includes(snippet));
+}
+
+describe('ingestKnowledge — embedder tagging', () => {
+ it('stamps the free-first embedder tag on the doc and every chunk', async () => {
+ sqlQueue.push([{ n: 0 }]); // doc count
+ sqlQueue.push([]); // doc insert
+ // chunk inserts run via sql.transaction (mock resolves them), then:
+ sqlQueue.push([]); // status=ready update
+
+ const out = await ingestKnowledge({
+ widgetId: 'wdgt_x',
+ userId: 'user-1',
+ input: { source_type: 'text', content: 'three.ws is an agent platform. '.repeat(4), title: 'About' },
+ });
+
+ expect(out.status).toBe('ready');
+ // Chunks embedded as passages, in the NIM space.
+ expect(embedPassagesMock).toHaveBeenCalledTimes(1);
+ expect(embedPassagesMock.mock.calls[0][0]).toBe(NIM_TAG);
+ // Doc row carries the tag…
+ const docInsert = findCall('insert into widget_knowledge_docs');
+ expect(docInsert.params).toContain(NIM_TAG);
+ // …and so does every chunk row.
+ const chunkInserts = sqlCalls.filter((c) => c.text.includes('insert into widget_knowledge_chunks'));
+ expect(chunkInserts.length).toBeGreaterThan(0);
+ for (const call of chunkInserts) expect(call.params).toContain(NIM_TAG);
+ });
+
+ it('503s with an actionable message when no embedding provider is configured', async () => {
+ mockEmbedState.defaultTag = null;
+ mockEmbedState.configured = new Set();
+ await expect(
+ ingestKnowledge({
+ widgetId: 'wdgt_x',
+ userId: 'user-1',
+ input: { source_type: 'text', content: 'some content here', title: 'T' },
+ }),
+ ).rejects.toMatchObject({ status: 503, code: 'embedder_unavailable' });
+ expect(embedPassagesMock).not.toHaveBeenCalled();
+ });
+});
+
+describe('testRetrieval — same-space routing and cross-space refusal', () => {
+ it('returns space-scored results with each chunk’s embedder tag', async () => {
+ const rows = [
+ { id: 1, doc_id: 'wkd_a', chunk_index: 0, content: 'alpha content', embedding: [1, 0], token_count: 3, embedder: NIM_TAG, title: 'Doc', source_url: null, source_type: 'text' },
+ ];
+ sqlQueue.push(rows);
+ mockEmbedState.scoreResult = {
+ scored: rows.map((r) => ({ ...r, score: 0.91 })),
+ needsReembed: [],
+ };
+ const out = await testRetrieval({ widgetId: 'wdgt_x', query: 'alpha?', topK: 5 });
+ expect(out.results).toHaveLength(1);
+ expect(out.results[0]).toMatchObject({ id: 1, embedder: NIM_TAG, score: 0.91 });
+ expect(out.reranked).toBe(false);
+ expect(out.needs_reembed).toBeUndefined();
+ });
+
+ it('refuses with a designed needs_reembed 503 when no stored space is servable', async () => {
+ sqlQueue.push([
+ { id: 1, doc_id: 'wkd_a', chunk_index: 0, content: 'legacy', embedding: [1, 0], token_count: 2, embedder: LEGACY_TAG, title: 'Doc', source_url: null, source_type: 'text' },
+ ]);
+ mockEmbedState.scoreResult = {
+ scored: [],
+ needsReembed: [{ embedder: LEGACY_TAG, chunks: 1 }],
+ };
+ await expect(testRetrieval({ widgetId: 'wdgt_x', query: 'anything' })).rejects.toMatchObject({
+ status: 503,
+ code: 'needs_reembed',
+ });
+ await expect(
+ (async () => {
+ sqlQueue.push([{ id: 1, doc_id: 'wkd_a', chunk_index: 0, content: 'legacy', embedding: [1, 0], token_count: 2, embedder: LEGACY_TAG, title: 'Doc', source_url: null, source_type: 'text' }]);
+ return testRetrieval({ widgetId: 'wdgt_x', query: 'anything' });
+ })(),
+ ).rejects.toThrow(/reembed-widget-knowledge\.mjs/);
+ });
+
+ it('serves what it can and reports the rest when spaces are mixed', async () => {
+ const nimRow = { id: 1, doc_id: 'wkd_a', chunk_index: 0, content: 'served', embedding: [1, 0], token_count: 2, embedder: NIM_TAG, title: 'Doc', source_url: null, source_type: 'text' };
+ sqlQueue.push([nimRow, { ...nimRow, id: 2, embedder: LEGACY_TAG }]);
+ mockEmbedState.scoreResult = {
+ scored: [{ ...nimRow, score: 0.8 }],
+ needsReembed: [{ embedder: LEGACY_TAG, chunks: 1 }],
+ };
+ const out = await testRetrieval({ widgetId: 'wdgt_x', query: 'served?' });
+ expect(out.results.map((r) => r.id)).toEqual([1]);
+ expect(out.needs_reembed).toEqual([{ embedder: LEGACY_TAG, chunks: 1 }]);
+ });
+
+ it('503s when no embedding provider exists at all', async () => {
+ mockEmbedState.configured = new Set();
+ await expect(testRetrieval({ widgetId: 'wdgt_x', query: 'q' })).rejects.toMatchObject({
+ status: 503,
+ code: 'embedder_unavailable',
+ });
+ });
+});
+
+describe('processQueuedDoc — worker re-resolves the embedder', () => {
+ it('re-embeds with the current default when the queued tag is no longer servable', async () => {
+ // Doc queued under the legacy OpenAI tag, but only NIM is configured now.
+ sqlQueue.push([
+ { id: 'wkd_a', widget_id: 'wdgt_x', source_text: 'fresh knowledge text for the worker', status: 'queued', chunk_count: 1, embedder: LEGACY_TAG },
+ ]);
+ sqlQueue.push([]); // status=processing
+ sqlQueue.push([]); // delete partial chunks
+ // chunk inserts via transaction, then:
+ sqlQueue.push([]); // ready update
+
+ const out = await processQueuedDoc({ docId: 'wkd_a', widgetId: 'wdgt_x' });
+ expect(out.status).toBe('ready');
+ expect(embedPassagesMock.mock.calls[0][0]).toBe(NIM_TAG);
+ // The ready update writes the tag that was ACTUALLY used.
+ const readyUpdate = findCall("status = 'ready'");
+ expect(readyUpdate.params).toContain(NIM_TAG);
+ });
+
+ it('keeps the queued tag when its provider can still serve', async () => {
+ mockEmbedState.configured = new Set([NIM_TAG, LEGACY_TAG]);
+ sqlQueue.push([
+ { id: 'wkd_a', widget_id: 'wdgt_x', source_text: 'fresh knowledge text for the worker', status: 'queued', chunk_count: 1, embedder: LEGACY_TAG },
+ ]);
+ sqlQueue.push([]); // status=processing
+ sqlQueue.push([]); // delete partial chunks
+ sqlQueue.push([]); // ready update
+
+ await processQueuedDoc({ docId: 'wkd_a', widgetId: 'wdgt_x' });
+ expect(embedPassagesMock.mock.calls[0][0]).toBe(LEGACY_TAG);
+ });
+
+ it('fails the doc cleanly when nothing can embed', async () => {
+ mockEmbedState.defaultTag = null;
+ mockEmbedState.configured = new Set();
+ sqlQueue.push([
+ { id: 'wkd_a', widget_id: 'wdgt_x', source_text: 'text body for the doc', status: 'queued', chunk_count: 1, embedder: NIM_TAG },
+ ]);
+ sqlQueue.push([]); // failed update
+ await expect(processQueuedDoc({ docId: 'wkd_a', widgetId: 'wdgt_x' })).rejects.toMatchObject({
+ status: 503,
+ code: 'embedder_unavailable',
+ });
+ const failedUpdate = findCall("status = 'failed'");
+ expect(failedUpdate).toBeTruthy();
+ });
+});
diff --git a/tests/api/widgets.test.js b/tests/api/widgets.test.js
index 5204989c2..e0aa79918 100644
--- a/tests/api/widgets.test.js
+++ b/tests/api/widgets.test.js
@@ -61,17 +61,36 @@ vi.mock('../../api/_lib/avatars.js', () => ({
}));
// Embeddings — keep tests offline. Configured=true so we exercise the test
-// branch's validation; embed() returns a fixed vector if invoked.
-vi.mock('../../api/_lib/embeddings.js', () => ({
- embeddingsConfigured: () => true,
- embed: vi.fn(async (texts) => texts.map(() => Float64Array.from([1, 0, 0, 0]))),
- cosine: (a, b) => {
+// branch's validation; the embed fns return a fixed vector if invoked.
+vi.mock('../../api/_lib/embeddings.js', () => {
+ const NIM_EMBED_TAG = 'nvidia/nv-embedqa-e5-v5@1024';
+ const LEGACY_EMBED_TAG = 'text-embedding-3-small@256';
+ const fixedVectors = (texts) => texts.map(() => Float64Array.from([1, 0, 0, 0]));
+ const cosine = (a, b) => {
+ if (!a || !b || a.length !== b.length) return 0;
let dot = 0, na = 0, nb = 0;
- const n = Math.min(a.length, b.length);
- for (let i = 0; i < n; i++) { dot += a[i] * b[i]; na += a[i] ** 2; nb += b[i] ** 2; }
+ for (let i = 0; i < a.length; i++) { dot += a[i] * b[i]; na += a[i] ** 2; nb += b[i] ** 2; }
return na && nb ? dot / Math.sqrt(na * nb) : 0;
- },
-}));
+ };
+ return {
+ NIM_EMBED_TAG,
+ OPENAI_EMBED_TAG: LEGACY_EMBED_TAG,
+ LEGACY_EMBED_TAG,
+ embeddingsConfigured: () => true,
+ embedderConfigured: () => true,
+ defaultIngestEmbedderTag: () => NIM_EMBED_TAG,
+ resolveEmbedderTag: (tag) => tag || LEGACY_EMBED_TAG,
+ embedderInfo: (tag) => ({ tag: tag || LEGACY_EMBED_TAG, model: 'mock-embedder', dim: 4 }),
+ embedWith: vi.fn(async (_tag, texts) => fixedVectors(texts)),
+ embedPassages: vi.fn(async (_tag, texts) => fixedVectors(texts)),
+ embedQuery: vi.fn(async () => Float64Array.from([1, 0, 0, 0])),
+ scoreRowsBySpace: vi.fn(async (rows) => ({
+ scored: rows.map((r) => ({ ...r, embedder: r.embedder || LEGACY_EMBED_TAG, score: 1 })),
+ needsReembed: [],
+ })),
+ cosine,
+ };
+});
// ── Import handlers AFTER mocks are registered ───────────────────────────────