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.

Agent voice-in: free NVIDIA Riva ASR lane closes the avatar voice loop

nirholas7359f4fda879
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 3d83a354e..04bead04c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -38,6 +38,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **Social recovery & inheritance — a funded agent that never dies with its owner** — Your agent's wallet is custodial and real-money funded, so "I lost access" or "the owner is gone" should never mean the funds are lost forever. You can now name guardians (real three.ws accounts you trust) and a beneficiary, and set how many guardians must agree. If you ever lose access, that threshold of guardians approving — plus a 48-hour safety window only you can cancel — hands control of the agent and its wallet back to you. An optional dead-man's switch passes the agent to your beneficiary if you go silent past a period you choose, but only after a generous, cancellable grace window and an explicit confirmation — and you abort the whole thing instantly just by showing up (a login, a trade, or tapping "I'm here"). Crucially, no private key is ever exported or exposed: recovery and inheritance only change who owns the agent, and the same encrypted, server-held key keeps signing for the new owner. Every step is time-locked, reversible until commit, and written to your custody trail; the wallet is frozen against autonomous spending during any contested process so it can never be drained out from under you. Guardians act from a new Guardian console — the agents you're trusted to protect, where you approve a recovery or confirm an inheritance without ever touching anyone's funds. (`/guardian`) `[feature, security]`
- **Steadier 3D generation and token stats when free providers get busy** — Two backend reliability fixes. The free image step behind text→3D now shrugs off a brief blip from NVIDIA's gateway — if it answers with a fast, transient hiccup, we retry once before handing off, so fewer prompts have to fall through to a slower backup and fewer fail outright. (A real timeout still hands off immediately, so nothing waits twice.) Separately, live token stats lean on several market-data sources; when one hits its monthly quota we already pause it, but each fresh server instance used to re-discover that the hard way and waste another doomed call. That pause is now shared across the whole fleet, so the moment one instance sees a source is exhausted, none of the others retry it — quieter, faster, and no wasted quota. `[fix, infra]`
- **Talk to your agent and it trades — the Conversational Wallet** — Your avatar's wallet now takes voice and text commands. Tell your agent "tip 0.1 SOL to vault.sol", "snipe that mint with half a SOL", "sell half my $THREE", or "withdraw 2 SOL to my Phantom" — it parses your intent with Claude, shows you exactly what it will do next to your own words (real quote, USD value, fees, network), and waits for an explicit "yes" or a tap before anything moves. Confirmed trades come back with a real on-chain signature and explorer link, and the avatar celebrates the moment it lands. Every action runs the same owner-only, spend-limit-gated, audited path as the rest of the wallet — visitors can chat but can never move funds, by any phrasing. A wrong hearing is caught at the read-back, "cancel" is always one word away, and there's a full keyboard path with no mic required. `[feature]`
+- **Talk to your avatar — a new free speech-to-text lane closes the voice loop** — Your avatar could already speak for free; now it can listen for free too. A new /api/asr endpoint turns spoken audio into text using NVIDIA's hosted Riva recognition on the same free key that already powers avatar voices, 3D generation, and chat — so voice-in costs nothing extra. Until now, talking to an avatar relied on the browser's built-in recognizer, which only exists in Chrome and Edge and quietly sends your microphone to Google; the new lane is server-side and works the same everywhere. It's purely additive: when the lane isn't switched on, voice keeps working exactly as before — nothing changes for anyone. Send a short WAV, PCM, FLAC, or Ogg clip and get back the transcript, the language detected, and optional word-level timestamps, all metered fairly so it can't be abused. `[feature]`
- **The in-chat skill purchase card is smoother, fully keyboard-friendly, and shows the right price every time** — The payment card that appears when you unlock a paid skill inside an embedded agent got a polish-and-correctness pass. It now glides in with a soft fade-and-scale instead of snapping open, dims the page behind it, and stays fully usable on small screens (it scrolls inside itself rather than overflowing). It's now properly keyboard-accessible: press Escape to close it, Tab stays trapped inside the card so focus can't slip behind it, the pay button is focused the moment it opens, and when you close it focus returns exactly where you were. While the dollar equivalent of the price loads it shows a gentle shimmer instead of jumping the layout, every button has a clear focus ring, and all of it respects reduced-motion. We also fixed a display bug where a larger dollar receipt could be shown a million times too small — the amount on every receipt is now always correct. (`/marketplace`) `[improvement, fix]`
- **The walking companion, page narrator, and 3D tour are smoother, kinder to your battery, and never start on a blank canvas** — The three avatars that walk and talk over a page got a polish pass focused on the moments before and around them. The corner companion now greets you with a soft loading shimmer instead of an empty box while its 3D body streams in, and the guided tour opens with an honest 'waking your guide' loader — a real readiness cue, never a fake bar — instead of a frozen page. All four 3D surfaces (the corner companion, the full-page walk playground, the drop-in page narrator, and the feature tour) now pause their animation the instant you switch to another tab, and the page narrator also pauses when it scrolls out of view — so a living avatar never quietly burns your laptop battery in a background tab. The narrator's mute button now shows the correct state from the very first frame, the tour's loader always clears cleanly when you exit, and several small resource leaks (timers and drag handlers left running after a companion or narrator was dismissed) are fixed. Reduced-motion preferences are honored throughout. (`/walk`) `[improvement, fix]`
- **three.ws opens cleanly inside in-app browsers** — Opening a three.ws link from inside the X (Twitter) app, and other in-app browsers that sandbox local storage, could throw an error before the page finished setting up its language — leaving some visitors on a broken first screen. Language preference now degrades gracefully when storage is blocked instead of failing, so the site loads normally everywhere. We also quieted a class of harmless background network blips (an expired draft model link, a dropped request) that were being logged as errors even though the viewer already shows its designed "couldn't load" card and recovers. `[fix]`
diff --git a/api/_lib/asr-nvidia.js b/api/_lib/asr-nvidia.js
new file mode 100644
index 000000000..fcc385357
--- /dev/null
+++ b/api/_lib/asr-nvidia.js
@@ -0,0 +1,231 @@
+// Free NVIDIA NIM ASR lane — Riva speech-to-text over NVCF gRPC.
+//
+// This is the voice-IN sibling of api/_lib/tts-nvidia.js (voice-OUT). It closes
+// the avatar voice loop: Magpie TTS already gives every avatar a free voice;
+// this lane gives users a free, cross-browser way to TALK to the avatar,
+// replacing the browser-only window.webkitSpeechRecognition path (Chrome/Edge
+// only, ships user audio to Google) with server-side Riva recognition.
+//
+// Like Magpie, Riva ASR is hosted as an NVCF gRPC function on
+// grpc.nvcf.nvidia.com:443, selected by a `function-id` metadata entry with the
+// nvapi key as a bearer `authorization` metadata entry. The wire contract is
+// the standard Riva SpeechRecognition service; the proto definitions are
+// vendored under ./riva-protos/ and loaded from a generated JSON descriptor
+// (asr-descriptor.js — kept separate from the TTS descriptor) so no .proto file
+// needs to exist on the serverless filesystem (api/ routes are esbuild-bundled
+// in place — scripts/bundle-api.mjs).
+//
+// ── Function id is configuration, never a guessed constant ───────────────────
+// Unlike Magpie's id (live-probed and pinned), the hosted ASR model a deployment
+// wants can vary (Parakeet CTC/RNN-T, Canary multilingual, different versions),
+// so the NVCF function id is read from NVIDIA_ASR_FUNCTION_ID. Discover the live
+// id for your account with `node scripts/verify-nvidia-asr.mjs --list`, which
+// enumerates GET api.nvcf.nvidia.com/v2/nvcf/functions and prints the ASR
+// candidates. Until it is set, nvidiaAsrConfigured() returns false and callers
+// treat the lane as absent — no fake default, no silent misroute.
+//
+// Error codes match the established provider contract (tts-nvidia.js):
+// invalid_key / rate_limited / invalid_argument / timeout /
+// provider_unreachable / provider_error / not_configured.
+
+import { env } from './env.js';
+import asrDescriptor from './riva-protos/asr-descriptor.js';
+
+export const NVIDIA_ASR_HOST = 'grpc.nvcf.nvidia.com:443';
+const DEFAULT_TIMEOUT_MS = 30_000;
+
+// Riva ASR's offline Recognize accepts mono audio in one of these container/
+// codec encodings (riva_audio.proto AudioEncoding). We expose friendly aliases
+// so the endpoint can map a request format onto the proto enum. LINEAR_PCM is
+// the cross-browser default: every browser can produce raw 16-bit PCM via Web
+// Audio even where MediaRecorder codecs differ.
+export const ASR_ENCODINGS = new Map([
+ ['pcm', 'LINEAR_PCM'], ['wav', 'LINEAR_PCM'], ['linear_pcm', 'LINEAR_PCM'], ['linear16', 'LINEAR_PCM'],
+ ['flac', 'FLAC'],
+ ['opus', 'OGGOPUS'], ['ogg', 'OGGOPUS'], ['oggopus', 'OGGOPUS'],
+ ['mulaw', 'MULAW'], ['ulaw', 'MULAW'],
+ ['alaw', 'ALAW'],
+]);
+
+export function resolveAsrEncoding(encoding) {
+ if (!encoding) return 'LINEAR_PCM';
+ return ASR_ENCODINGS.get(String(encoding).toLowerCase()) || 'LINEAR_PCM';
+}
+
+export function nvidiaAsrConfigured() {
+ return Boolean(env.NVIDIA_API_KEY && env.NVIDIA_ASR_FUNCTION_ID);
+}
+
+// Parse a RIFF/WAVE header → { sampleRateHz, channels, pcm } so a WAV upload can
+// be handed to Riva as raw LINEAR_PCM with the correct rate. Riva's LINEAR_PCM
+// expects header-less little-endian s16 samples; passing the 44-byte RIFF header
+// through prepends ~44 bytes of garbage to the first samples and skews the rate
+// the model is told. Returns null when the bytes are not a WAV (caller then
+// trusts the explicitly-supplied rate/encoding).
+export function parseWav(buf) {
+ if (!Buffer.isBuffer(buf) || buf.length < 44) return null;
+ if (buf.toString('ascii', 0, 4) !== 'RIFF' || buf.toString('ascii', 8, 12) !== 'WAVE') return null;
+ // Walk the chunk list rather than assuming the canonical 44-byte layout —
+ // some encoders insert a LIST/fact chunk before `data`.
+ let offset = 12;
+ let sampleRateHz = 0;
+ let channels = 1;
+ let pcm = null;
+ while (offset + 8 <= buf.length) {
+ const id = buf.toString('ascii', offset, offset + 4);
+ const size = buf.readUInt32LE(offset + 4);
+ const body = offset + 8;
+ if (id === 'fmt ' && body + 16 <= buf.length) {
+ channels = buf.readUInt16LE(body + 2) || 1;
+ sampleRateHz = buf.readUInt32LE(body + 4);
+ } else if (id === 'data') {
+ pcm = buf.subarray(body, Math.min(body + size, buf.length));
+ }
+ // Chunks are word-aligned: an odd size carries a trailing pad byte.
+ offset = body + size + (size & 1);
+ }
+ if (!pcm || !sampleRateHz) return null;
+ return { sampleRateHz, channels, pcm };
+}
+
+// gRPC status code → platform error code (numeric codes so the mapping does not
+// depend on the grpc-js import being resolved). Mirrors tts-nvidia.js.
+function normalizeGrpcError(err) {
+ const code = typeof err?.code === 'number' ? err.code : null;
+ const map = {
+ 3: 'invalid_argument', // bad encoding/rate/language/audio
+ 4: 'timeout', // DEADLINE_EXCEEDED
+ 7: 'invalid_key', // PERMISSION_DENIED
+ 8: 'rate_limited', // RESOURCE_EXHAUSTED (credit-metered free tier)
+ 14: 'provider_unreachable', // UNAVAILABLE
+ 16: 'invalid_key', // UNAUTHENTICATED
+ };
+ const normalized = new Error(
+ `NVIDIA Riva ASR failed${code !== null ? ` (gRPC ${code})` : ''}: ${err?.details || err?.message || 'unknown error'}`,
+ );
+ normalized.code = (code !== null && map[code]) || 'provider_error';
+ normalized.grpcCode = code;
+ return normalized;
+}
+
+// One cached client per warm lambda (the TLS channel is keyless — auth rides in
+// per-call metadata). @grpc/grpc-js is imported lazily so non-ASR importers do
+// not pay for the dependency at cold start. See tts-nvidia.js for the NVCF
+// warm-channel auth caveat that the verify script works around.
+let clientPromise = null;
+async function getClient() {
+ if (!clientPromise) {
+ clientPromise = (async () => {
+ const [{ default: grpc }, { default: protoLoader }] = await Promise.all([
+ import('@grpc/grpc-js'),
+ import('@grpc/proto-loader'),
+ ]);
+ const definition = protoLoader.fromJSON(asrDescriptor, {
+ keepCase: true,
+ longs: Number,
+ enums: String,
+ defaults: true,
+ oneofs: true,
+ });
+ const pkg = grpc.loadPackageDefinition(definition);
+ const Recognition = pkg.nvidia.riva.asr.RivaSpeechRecognition;
+ return {
+ grpc,
+ client: new Recognition(NVIDIA_ASR_HOST, grpc.credentials.createSsl(), {
+ 'grpc.max_send_message_length': 64 * 1024 * 1024,
+ }),
+ };
+ })().catch((e) => {
+ clientPromise = null; // a failed init must not poison the warm lambda
+ throw e;
+ });
+ }
+ return clientPromise;
+}
+
+// Transcribe a single utterance on the free NIM lane via the offline Recognize
+// RPC (unary — fits a serverless function; no streaming socket to babysit).
+//
+// { audio: Buffer, encoding?, sampleRateHz?, language?, maxAlternatives?,
+// automaticPunctuation?, wordTimeOffsets?, model?, timeoutMs?, apiKey? }
+// → { text, confidence, words, language, model, audioProcessed }
+//
+// `audio` is raw bytes in `encoding`. When a WAV is passed as LINEAR_PCM the
+// caller should strip the header first (parseWav) — this function trusts the
+// encoding/rate it is given.
+//
+// Throws Error with .code ∈ not_configured | invalid_key | rate_limited |
+// invalid_argument | timeout | provider_unreachable | provider_error.
+export async function transcribeNvidiaAsr({
+ audio,
+ encoding = 'LINEAR_PCM',
+ sampleRateHz = 16000,
+ language = 'en-US',
+ maxAlternatives = 1,
+ automaticPunctuation = true,
+ wordTimeOffsets = false,
+ model = '',
+ timeoutMs = DEFAULT_TIMEOUT_MS,
+ apiKey,
+} = {}) {
+ const key = apiKey || env.NVIDIA_API_KEY;
+ const functionId = env.NVIDIA_ASR_FUNCTION_ID;
+ if (!key || !functionId) {
+ const err = new Error(
+ !key ? 'NVIDIA_API_KEY not set' : 'NVIDIA_ASR_FUNCTION_ID not set (run scripts/verify-nvidia-asr.mjs --list to discover it)',
+ );
+ err.code = 'not_configured';
+ throw err;
+ }
+ const bytes = Buffer.isBuffer(audio) ? audio : Buffer.from(audio || []);
+ if (!bytes.length) {
+ const err = new Error('no audio bytes to transcribe');
+ err.code = 'invalid_argument';
+ throw err;
+ }
+
+ const { grpc, client } = await getClient();
+ const metadata = new grpc.Metadata();
+ metadata.set('function-id', functionId);
+ metadata.set('authorization', `Bearer ${key}`);
+
+ const response = await new Promise((resolveCall, rejectCall) => {
+ client.recognize(
+ {
+ config: {
+ encoding: ASR_ENCODINGS.get(String(encoding).toLowerCase()) || encoding,
+ sample_rate_hertz: sampleRateHz,
+ language_code: language,
+ max_alternatives: maxAlternatives,
+ enable_automatic_punctuation: automaticPunctuation,
+ enable_word_time_offsets: wordTimeOffsets,
+ ...(model ? { model } : {}),
+ },
+ audio: bytes,
+ },
+ metadata,
+ { deadline: new Date(Date.now() + timeoutMs) },
+ (err, res) => (err ? rejectCall(normalizeGrpcError(err)) : resolveCall(res)),
+ );
+ });
+
+ // Riva returns sequential results; the offline path currently yields one.
+ // Concatenate the top alternative of each result into a single transcript so
+ // the caller gets the complete utterance regardless of internal segmentation.
+ const results = Array.isArray(response?.results) ? response.results : [];
+ const tops = results.map((r) => r?.alternatives?.[0]).filter(Boolean);
+ const text = tops.map((a) => a.transcript || '').join(' ').trim();
+ const confidence = tops.length ? tops.reduce((s, a) => s + (a.confidence || 0), 0) / tops.length : 0;
+ const words = wordTimeOffsets
+ ? tops.flatMap((a) => (Array.isArray(a.words) ? a.words : []).map((w) => ({
+ word: w.word,
+ startMs: w.start_time,
+ endMs: w.end_time,
+ confidence: w.confidence,
+ })))
+ : [];
+ const audioProcessed = results.reduce((m, r) => Math.max(m, r?.audio_processed || 0), 0);
+ const detectedLang = tops[0]?.language_code?.[0] || language;
+
+ return { text, confidence, words, language: detectedLang, model: model || 'riva-asr', audioProcessed };
+}
diff --git a/api/_lib/env.js b/api/_lib/env.js
index b04b360ec..142a2ea76 100644
--- a/api/_lib/env.js
+++ b/api/_lib/env.js
@@ -271,6 +271,16 @@ export const env = {
return opt('NVIDIA_API_KEY');
},
+ // NVCF function id for the hosted Riva ASR model (Parakeet/Canary) used by the
+ // free speech-to-text lane (api/_lib/asr-nvidia.js, api/asr.js). Unlike the
+ // pinned Magpie TTS id, the ASR model/version a deployment wants varies, so
+ // the id is configuration — discover the live id for your account with
+ // `node scripts/verify-nvidia-asr.mjs --list`. When unset the ASR lane reports
+ // itself unconfigured and callers fall back to the browser SpeechRecognition.
+ get NVIDIA_ASR_FUNCTION_ID() {
+ return opt('NVIDIA_ASR_FUNCTION_ID');
+ },
+
// IBM watsonx.ai (Granite foundation models) — selectable brain in
// /api/chat and /api/brain/chat. Requires the API key AND a project (or
// space) id; the shared client in _lib/watsonx.js exchanges the key for an
diff --git a/api/_lib/rate-limit.js b/api/_lib/rate-limit.js
index 9db48ec76..cc4af7c8b 100644
--- a/api/_lib/rate-limit.js
+++ b/api/_lib/rate-limit.js
@@ -643,6 +643,15 @@ export const limits = {
getLimiter('tts:speak:user', { limit: 40, window: '1 h', critical: true }).limit(userId),
ttsSpeakIp: (ip) =>
getLimiter('tts:speak:ip', { limit: 10, window: '1 h', critical: true }).limit(ip),
+ // NVIDIA Riva ASR (api/asr) — free upstream but credit-metered, and each call
+ // streams an audio clip the server holds in memory, so meter per principal.
+ // Authenticated users get a generous bucket; anonymous callers (keyed by IP) a
+ // tighter one. Critical so a missing Redis in prod fails closed rather than
+ // leaving an open transcription drain.
+ asrUser: (userId) =>
+ getLimiter('asr:user', { limit: 60, window: '1 h', critical: true }).limit(userId),
+ asrIp: (ip) =>
+ getLimiter('asr:ip', { limit: 15, window: '1 h', critical: true }).limit(ip),
// /brain multi-LLM proxy. Paid flagship models (Claude/GPT-4o) run on the
// server keys, so meter per principal: authenticated users get a generous
// per-user bucket, anonymous callers a tighter per-IP one. Both critical so a
diff --git a/api/_lib/riva-protos/asr-descriptor.js b/api/_lib/riva-protos/asr-descriptor.js
new file mode 100644
index 000000000..3cd0adc52
--- /dev/null
+++ b/api/_lib/riva-protos/asr-descriptor.js
@@ -0,0 +1,476 @@
+// GENERATED FILE — do not edit by hand.
+// Regenerate with: node scripts/generate-riva-asr-descriptor.mjs
+// protobufjs JSON descriptor for the NVIDIA Riva ASR service, parsed
+// (keepCase) from the vendored protos in api/_lib/riva-protos/*.proto,
+// themselves from https://github.com/nvidia-riva/common (riva/proto/).
+// SPDX-FileCopyrightText: Copyright (c) 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+// SPDX-License-Identifier: MIT
+export default {
+ "nested": {
+ "nvidia": {
+ "nested": {
+ "riva": {
+ "options": {
+ "cc_enable_arenas": true,
+ "go_package": "nvidia.com/riva_speech"
+ },
+ "nested": {
+ "RequestId": {
+ "fields": {
+ "value": {
+ "type": "string",
+ "id": 1
+ }
+ }
+ },
+ "AudioEncoding": {
+ "values": {
+ "ENCODING_UNSPECIFIED": 0,
+ "LINEAR_PCM": 1,
+ "FLAC": 2,
+ "MULAW": 3,
+ "OGGOPUS": 4,
+ "ALAW": 20
+ }
+ },
+ "asr": {
+ "options": {
+ "cc_enable_arenas": true,
+ "go_package": "nvidia.com/riva_speech"
+ },
+ "nested": {
+ "RivaSpeechRecognition": {
+ "methods": {
+ "Recognize": {
+ "requestType": "RecognizeRequest",
+ "responseType": "RecognizeResponse"
+ },
+ "StreamingRecognize": {
+ "requestType": "StreamingRecognizeRequest",
+ "requestStream": true,
+ "responseType": "StreamingRecognizeResponse",
+ "responseStream": true
+ },
+ "GetRivaSpeechRecognitionConfig": {
+ "requestType": "RivaSpeechRecognitionConfigRequest",
+ "responseType": "RivaSpeechRecognitionConfigResponse"
+ }
+ }
+ },
+ "RivaSpeechRecognitionConfigRequest": {
+ "fields": {
+ "model_name": {
+ "type": "string",
+ "id": 1
+ }
+ }
+ },
+ "RivaSpeechRecognitionConfigResponse": {
+ "fields": {
+ "model_config": {
+ "rule": "repeated",
+ "type": "Config",
+ "id": 1
+ }
+ },
+ "nested": {
+ "Config": {
+ "fields": {
+ "model_name": {
+ "type": "string",
+ "id": 1
+ },
+ "parameters": {
+ "keyType": "string",
+ "type": "string",
+ "id": 2
+ }
+ }
+ }
+ }
+ },
+ "RecognizeRequest": {
+ "fields": {
+ "config": {
+ "type": "RecognitionConfig",
+ "id": 1
+ },
+ "audio": {
+ "type": "bytes",
+ "id": 2
+ },
+ "id": {
+ "type": "RequestId",
+ "id": 100
+ }
+ }
+ },
+ "StreamingRecognizeRequest": {
+ "oneofs": {
+ "streaming_request": {
+ "oneof": [
+ "streaming_config",
+ "audio_content"
+ ]
+ }
+ },
+ "fields": {
+ "streaming_config": {
+ "type": "StreamingRecognitionConfig",
+ "id": 1
+ },
+ "audio_content": {
+ "type": "bytes",
+ "id": 2
+ },
+ "runtime_config": {
+ "keyType": "string",
+ "type": "string",
+ "id": 3
+ },
+ "id": {
+ "type": "RequestId",
+ "id": 100
+ }
+ }
+ },
+ "EndpointingConfig": {
+ "oneofs": {
+ "_start_history": {
+ "oneof": [
+ "start_history"
+ ]
+ },
+ "_start_threshold": {
+ "oneof": [
+ "start_threshold"
+ ]
+ },
+ "_stop_history": {
+ "oneof": [
+ "stop_history"
+ ]
+ },
+ "_stop_threshold": {
+ "oneof": [
+ "stop_threshold"
+ ]
+ },
+ "_stop_history_eou": {
+ "oneof": [
+ "stop_history_eou"
+ ]
+ },
+ "_stop_threshold_eou": {
+ "oneof": [
+ "stop_threshold_eou"
+ ]
+ }
+ },
+ "fields": {
+ "start_history": {
+ "type": "int32",
+ "id": 1,
+ "options": {
+ "proto3_optional": true
+ }
+ },
+ "start_threshold": {
+ "type": "float",
+ "id": 2,
+ "options": {
+ "proto3_optional": true
+ }
+ },
+ "stop_history": {
+ "type": "int32",
+ "id": 3,
+ "options": {
+ "proto3_optional": true
+ }
+ },
+ "stop_threshold": {
+ "type": "float",
+ "id": 4,
+ "options": {
+ "proto3_optional": true
+ }
+ },
+ "stop_history_eou": {
+ "type": "int32",
+ "id": 5,
+ "options": {
+ "proto3_optional": true
+ }
+ },
+ "stop_threshold_eou": {
+ "type": "float",
+ "id": 6,
+ "options": {
+ "proto3_optional": true
+ }
+ }
+ }
+ },
+ "RecognitionConfig": {
+ "oneofs": {
+ "_endpointing_config": {
+ "oneof": [
+ "endpointing_config"
+ ]
+ }
+ },
+ "fields": {
+ "encoding": {
+ "type": "AudioEncoding",
+ "id": 1
+ },
+ "sample_rate_hertz": {
+ "type": "int32",
+ "id": 2
+ },
+ "language_code": {
+ "type": "string",
+ "id": 3
+ },
+ "max_alternatives": {
+ "type": "int32",
+ "id": 4
+ },
+ "profanity_filter": {
+ "type": "bool",
+ "id": 5
+ },
+ "speech_contexts": {
+ "rule": "repeated",
+ "type": "SpeechContext",
+ "id": 6
+ },
+ "audio_channel_count": {
+ "type": "int32",
+ "id": 7
+ },
+ "enable_word_time_offsets": {
+ "type": "bool",
+ "id": 8
+ },
+ "enable_automatic_punctuation": {
+ "type": "bool",
+ "id": 11
+ },
+ "enable_separate_recognition_per_channel": {
+ "type": "bool",
+ "id": 12
+ },
+ "model": {
+ "type": "string",
+ "id": 13
+ },
+ "verbatim_transcripts": {
+ "type": "bool",
+ "id": 14
+ },
+ "diarization_config": {
+ "type": "SpeakerDiarizationConfig",
+ "id": 19
+ },
+ "custom_configuration": {
+ "keyType": "string",
+ "type": "string",
+ "id": 24
+ },
+ "endpointing_config": {
+ "type": "EndpointingConfig",
+ "id": 25,
+ "options": {
+ "proto3_optional": true
+ }
+ }
+ }
+ },
+ "StreamingRecognitionConfig": {
+ "fields": {
+ "config": {
+ "type": "RecognitionConfig",
+ "id": 1
+ },
+ "interim_results": {
+ "type": "bool",
+ "id": 2
+ }
+ }
+ },
+ "SpeakerDiarizationConfig": {
+ "fields": {
+ "enable_speaker_diarization": {
+ "type": "bool",
+ "id": 1
+ },
+ "max_speaker_count": {
+ "type": "int32",
+ "id": 2
+ }
+ }
+ },
+ "SpeechContext": {
+ "fields": {
+ "phrases": {
+ "rule": "repeated",
+ "type": "string",
+ "id": 1
+ },
+ "boost": {
+ "type": "float",
+ "id": 4
+ }
+ }
+ },
+ "RecognizeResponse": {
+ "fields": {
+ "results": {
+ "rule": "repeated",
+ "type": "SpeechRecognitionResult",
+ "id": 1
+ },
+ "id": {
+ "type": "RequestId",
+ "id": 100
+ }
+ }
+ },
+ "SpeechRecognitionResult": {
+ "fields": {
+ "alternatives": {
+ "rule": "repeated",
+ "type": "SpeechRecognitionAlternative",
+ "id": 1
+ },
+ "channel_tag": {
+ "type": "int32",
+ "id": 2
+ },
+ "audio_processed": {
+ "type": "float",
+ "id": 3
+ }
+ }
+ },
+ "SpeechRecognitionAlternative": {
+ "fields": {
+ "transcript": {
+ "type": "string",
+ "id": 1
+ },
+ "confidence": {
+ "type": "float",
+ "id": 2
+ },
+ "words": {
+ "rule": "repeated",
+ "type": "WordInfo",
+ "id": 3
+ },
+ "language_code": {
+ "rule": "repeated",
+ "type": "string",
+ "id": 4
+ }
+ }
+ },
+ "WordInfo": {
+ "fields": {
+ "start_time": {
+ "type": "int32",
+ "id": 1
+ },
+ "end_time": {
+ "type": "int32",
+ "id": 2
+ },
+ "word": {
+ "type": "string",
+ "id": 3
+ },
+ "confidence": {
+ "type": "float",
+ "id": 4
+ },
+ "speaker_tag": {
+ "type": "int32",
+ "id": 5
+ },
+ "language_code": {
+ "type": "string",
+ "id": 6
+ }
+ }
+ },
+ "StreamingRecognizeResponse": {
+ "fields": {
+ "results": {
+ "rule": "repeated",
+ "type": "StreamingRecognitionResult",
+ "id": 1
+ },
+ "id": {
+ "type": "RequestId",
+ "id": 100
+ }
+ }
+ },
+ "PipelineStates": {
+ "fields": {
+ "vad_probabilities": {
+ "rule": "repeated",
+ "type": "float",
+ "id": 1
+ }
+ }
+ },
+ "StreamingRecognitionResult": {
+ "oneofs": {
+ "_pipeline_states": {
+ "oneof": [
+ "pipeline_states"
+ ]
+ }
+ },
+ "fields": {
+ "alternatives": {
+ "rule": "repeated",
+ "type": "SpeechRecognitionAlternative",
+ "id": 1
+ },
+ "is_final": {
+ "type": "bool",
+ "id": 2
+ },
+ "stability": {
+ "type": "float",
+ "id": 3
+ },
+ "channel_tag": {
+ "type": "int32",
+ "id": 5
+ },
+ "audio_processed": {
+ "type": "float",
+ "id": 6
+ },
+ "pipeline_states": {
+ "type": "PipelineStates",
+ "id": 7,
+ "options": {
+ "proto3_optional": true
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+};
diff --git a/api/_lib/riva-protos/riva_asr.proto b/api/_lib/riva-protos/riva_asr.proto
new file mode 100644
index 000000000..a60399c9a
--- /dev/null
+++ b/api/_lib/riva-protos/riva_asr.proto
@@ -0,0 +1,451 @@
+// SPDX-FileCopyrightText: Copyright (c) 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+// SPDX-License-Identifier: MIT
+
+// Copyright 2019 Google LLC.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+syntax = "proto3";
+
+package nvidia.riva.asr;
+
+option cc_enable_arenas = true;
+option go_package = "nvidia.com/riva_speech";
+
+import "riva/proto/riva_audio.proto";
+import "riva/proto/riva_common.proto";
+
+/*
+ * The RivaSpeechRecognition service provides two mechanisms for converting
+ * speech to text.
+ */
+service RivaSpeechRecognition {
+ // Recognize expects a RecognizeRequest and returns a RecognizeResponse. This
+ // request will block until the audio is uploaded, processed, and a transcript
+ // is returned.
+ rpc Recognize(RecognizeRequest) returns (RecognizeResponse) {}
+ // StreamingRecognize is a non-blocking API call that allows audio data to be
+ // fed to the server in chunks as it becomes available. Depending on the
+ // configuration in the StreamingRecognizeRequest, intermediate results can be
+ // sent back to the client. Recognition ends when the stream is closed by the
+ // client.
+ rpc StreamingRecognize(stream StreamingRecognizeRequest)
+ returns (stream StreamingRecognizeResponse) {}
+
+ // Enables clients to request the configuration of the current ASR service, or
+ // a specific model within the service.
+ rpc GetRivaSpeechRecognitionConfig(RivaSpeechRecognitionConfigRequest)
+ returns (RivaSpeechRecognitionConfigResponse) {}
+}
+
+/*
+ * RivaSpeechRecognitionConfigRequest
+ */
+
+message RivaSpeechRecognitionConfigRequest {
+ // If model is specified only return config for model, otherwise return all
+ // configs.
+ string model_name = 1;
+}
+
+message RivaSpeechRecognitionConfigResponse {
+ message Config {
+ string model_name = 1;
+ map<string, string> parameters = 2;
+ }
+
+ repeated Config model_config = 1;
+}
+
+/*
+ * RecognizeRequest is used for batch processing of a single audio recording.
+ */
+message RecognizeRequest {
+ // Provides information to recognizer that specifies how to process the
+ // request.
+ RecognitionConfig config = 1;
+ // The raw audio data to be processed. The audio bytes must be encoded as
+ // specified in `RecognitionConfig`.
+ bytes audio = 2;
+
+ // The ID to be associated with the request. If provided, this will be
+ // returned in the corresponding response.
+ RequestId id = 100;
+}
+
+/*
+ * A StreamingRecognizeRequest is used to configure and stream audio content to
+ * the Riva ASR Service. The first message sent must include only a
+ * StreamingRecognitionConfig. Subsequent messages sent in the stream must
+ * contain only raw bytes of the audio to be recognized.
+ */
+message StreamingRecognizeRequest {
+ // The streaming request, which is either a streaming config or audio content.
+ oneof streaming_request {
+ // Provides information to the recognizer that specifies how to process the
+ // request. The first `StreamingRecognizeRequest` message must contain a
+ // `streaming_config` message.
+ StreamingRecognitionConfig streaming_config = 1;
+ // The audio data to be recognized. Sequential chunks of audio data are sent
+ // in sequential `StreamingRecognizeRequest` messages. The first
+ // `StreamingRecognizeRequest` message must not contain `audio` data
+ // and all subsequent `StreamingRecognizeRequest` messages must contain
+ // `audio` data. The audio bytes must be encoded as specified in
+ // `RecognitionConfig`.
+ bytes audio_content = 2;
+ }
+
+ // Per-chunk runtime configuration passed alongside audio_content messages.
+ // This is an OPTIONAL parameter which should be used when client needs to
+ // tune server configuration during an ongoing session.
+ // Supported keys:
+ // "force_eou" = "true" : Forces an immediate end-of-utterance for the
+ // current stream, emitting a final transcript without ending the stream.
+ // Unlike closing the stream (is_last), the stream remains open and
+ // subsequent audio continues as a new utterance. Only supported for
+ // cache-aware RNNT models.
+ map<string, string> runtime_config = 3;
+
+ // The ID to be associated with the request. If provided, this will be
+ // returned in the corresponding responses.
+ RequestId id = 100;
+}
+
+/*
+ * EndpointingConfig is used for configuring different fields related to start
+ * or end of utterance
+ */
+message EndpointingConfig {
+ // `start_history` is the size of the window, in milliseconds, used to
+ // detect start of utterance.
+ // `start_threshold` is the percentage threshold used to detect start of
+ // utterance. (0.0 to 1.0)
+ // If `start_threshold` of `start_history` ms of the acoustic model output
+ // have non-blank tokens, start of utterance is detected.
+ optional int32 start_history = 1;
+ optional float start_threshold = 2;
+
+ // `stop_history` is the size of the window, in milliseconds, used to
+ // detect end of utterance.
+ // `stop_threshold` is the percentage threshold used to detect end of
+ // utterance. (0.0 to 1.0)
+ // If `stop_threshold` of `stop_history` ms of the acoustic model output have
+ // non-blank tokens, end of utterance is detected and decoder will be reset.
+ optional int32 stop_history = 3;
+ optional float stop_threshold = 4;
+
+ // `stop_history_eou` and `stop_threshold_eou` are used for 2-pass end of utterance.
+ // `stop_history_eou` is the size of the window, in milliseconds, used to
+ // trigger 1st pass of end of utterance and generate a partial transcript
+ // with stability of 1. (stop_history_eou < stop_history)
+ // `stop_threshold_eou` is the percentage threshold used to trigger 1st
+ // pass of end of utterance. (0.0 to 1.0)
+ // If `stop_threshold_eou` of `stop_history_eou` ms of the acoustic model
+ // output have non-blank tokens, 1st pass of end of utterance is triggered.
+ optional int32 stop_history_eou = 5;
+ optional float stop_threshold_eou = 6;
+}
+
+// Provides information to the recognizer that specifies how to process the
+// request
+message RecognitionConfig {
+ // The encoding of the audio data sent in the request.
+ //
+ // All encodings support only 1 channel (mono) audio.
+ AudioEncoding encoding = 1;
+
+ // The sample rate in hertz (Hz) of the audio data sent in the
+ // `RecognizeRequest` or `StreamingRecognizeRequest` messages.
+ // The Riva server will automatically down-sample/up-sample the audio to
+ // match the ASR acoustic model sample rate. The sample rate value below 8kHz
+ // will not produce any meaningful output.
+ int32 sample_rate_hertz = 2;
+
+ // Required. The language of the supplied audio as a
+ // [BCP-47](https://www.rfc-editor.org/rfc/bcp/bcp47.txt) language tag.
+ // Example: "en-US".
+ string language_code = 3;
+
+ // Maximum number of recognition hypotheses to be returned.
+ // Specifically, the maximum number of `SpeechRecognizeAlternative` messages
+ // within each `SpeechRecognizeResult`.
+ // The server may return fewer than `max_alternatives`.
+ // If omitted, will return a maximum of one.
+ int32 max_alternatives = 4;
+
+ // A custom field that enables profanity filtering for the generated
+ // transcripts. If set to 'true', the server filters out profanities,
+ // replacing all but the initial character in each filtered word with
+ // asterisks. For example, "x**". If set to `false` or omitted, profanities
+ // will not be filtered out. The default is `false`.
+ bool profanity_filter = 5;
+
+ // Array of SpeechContext.
+ // A means to provide context to assist the speech recognition. For more
+ // information, see SpeechContext section
+ repeated SpeechContext speech_contexts = 6;
+
+ // The number of channels in the input audio data.
+ // If `0` or omitted, defaults to one channel (mono).
+ // Note: Only single channel audio input is supported as of now.
+ int32 audio_channel_count = 7;
+
+ // If `true`, the top result includes a list of words and the start and end
+ // time offsets (timestamps), and confidence scores for those words. If
+ // `false`, no word-level time offset information is returned. The default
+ // is `false`.
+ bool enable_word_time_offsets = 8;
+
+ // If 'true', adds punctuation to recognition result hypotheses. The
+ // default 'false' value does not add punctuation to result hypotheses.
+ bool enable_automatic_punctuation = 11;
+
+ // This needs to be set to `true` explicitly and `audio_channel_count` > 1
+ // to get each channel recognized separately. The recognition result will
+ // contain a `channel_tag` field to state which channel that result belongs
+ // to. If this is not true, we will only recognize the first channel. The
+ // request is billed cumulatively for all channels recognized:
+ // `audio_channel_count` multiplied by the length of the audio.
+ // Note: This field is not yet supported.
+ bool enable_separate_recognition_per_channel = 12;
+
+ // Which model to select for the given request.
+ // If empty, Riva will select the right model based on the other
+ // RecognitionConfig parameters. The model should correspond to the name
+ // passed to `riva-build` with the `--name` argument
+ string model = 13;
+
+ // The verbatim_transcripts flag enables or disable inverse text
+ // normalization. 'true' returns exactly what was said, with no
+ // denormalization. 'false' applies inverse text normalization, also this is
+ // the default
+ bool verbatim_transcripts = 14;
+
+ // Config to enable speaker diarization and set additional
+ // parameters. For non-streaming requests, the diarization results will be
+ // provided only in the top alternative of the FINAL SpeechRecognitionResult.
+ SpeakerDiarizationConfig diarization_config = 19;
+
+ // Custom fields for passing request-level
+ // configuration options to plugins used in the
+ // model pipeline.
+ map<string, string> custom_configuration = 24;
+
+ // Config for tuning start or end of utterance parameters.
+ // If empty, Riva will use default values or custom values if specified in riva-build arguments.
+ optional EndpointingConfig endpointing_config = 25;
+}
+
+// Provides information to the recognizer that specifies how to process the
+// request
+message StreamingRecognitionConfig {
+ // Provides information to the recognizer that specifies how to process the
+ // request
+ RecognitionConfig config = 1;
+
+ // If `true`, interim results (tentative hypotheses) may be
+ // returned as they become available (these interim results are indicated with
+ // the `is_final=false` flag).
+ // If `false` or omitted, only `is_final=true` result(s) are returned.
+ bool interim_results = 2;
+}
+
+// Config to enable speaker diarization.
+message SpeakerDiarizationConfig {
+ // If 'true', enables speaker detection for each recognized word in
+ // the top alternative of the recognition result using a speaker_tag provided
+ // in the WordInfo.
+ bool enable_speaker_diarization = 1;
+
+ // Maximum number of speakers in the conversation. This gives flexibility by
+ // allowing the system to automatically determine the correct number of
+ // speakers. If not set, the default value is 8.
+ int32 max_speaker_count = 2;
+}
+
+// Provides "hints" to the speech recognizer to favor specific words and phrases
+// in the results.
+message SpeechContext {
+ // A list of strings containing words and phrases "hints" so that
+ // the speech recognition is more likely to recognize them. This can be used
+ // to improve the accuracy for specific words and phrases, for example, if
+ // specific commands are typically spoken by the user. This can also be used
+ // to add additional words to the vocabulary of the recognizer.
+ repeated string phrases = 1;
+
+ // Hint Boost. Positive value will increase the probability that a specific
+ // phrase will be recognized over other similar sounding phrases. The higher
+ // the boost, the higher the chance of false positive recognition as well.
+ // Though `boost` can accept a wide range of positive values, most use cases
+ // are best served with values between 0 and 20. We recommend using a binary
+ // search approach to finding the optimal value for your use case.
+ float boost = 4;
+}
+
+// The only message returned to the client by the `Recognize` method. It
+// contains the result as zero or more sequential `SpeechRecognitionResult`
+// messages.
+message RecognizeResponse {
+ // Sequential list of transcription results corresponding to
+ // sequential portions of audio. Currently only returns one transcript.
+ repeated SpeechRecognitionResult results = 1;
+
+ // The ID associated with the request
+ RequestId id = 100;
+}
+
+// A speech recognition result corresponding to the latest transcript
+message SpeechRecognitionResult {
+ // May contain one or more recognition hypotheses (up to the
+ // maximum specified in `max_alternatives`).
+ // These alternatives are ordered in terms of accuracy, with the top (first)
+ // alternative being the most probable, as ranked by the recognizer.
+ repeated SpeechRecognitionAlternative alternatives = 1;
+
+ // For multi-channel audio, this is the channel number corresponding to the
+ // recognized result for the audio from that channel.
+ // For audio_channel_count = N, its output values can range from '1' to 'N'.
+ int32 channel_tag = 2;
+
+ // Length of audio processed so far in seconds
+ float audio_processed = 3;
+}
+
+// Alternative hypotheses (a.k.a. n-best list).
+message SpeechRecognitionAlternative {
+ // Transcript text representing the words that the user spoke.
+ string transcript = 1;
+
+ // The confidence estimate. A higher number indicates an estimated greater
+ // likelihood that the recognized word is correct. This field is set only for
+ // a non-streaming result or, for a streaming result where is_final=true.
+ // This field is not guaranteed to be accurate and users should not rely on
+ // it to be always provided. Although confidence can currently be roughly
+ // interpreted as a natural-log probability, the estimate computation varies
+ // with difference configurations, and is subject to change. The default of
+ // 0.0 is a sentinel value indicating confidence was not set.
+ float confidence = 2;
+
+ // A list of word-specific information for each recognized word. Only
+ // populated if is_final=true
+ repeated WordInfo words = 3;
+
+ // List of language codes detected in the transcript.
+ repeated string language_code = 4;
+}
+
+// Word-specific information for recognized words.
+message WordInfo {
+ // Time offset relative to the beginning of the audio in ms
+ // and corresponding to the start of the spoken word.
+ // This field is only set if `enable_word_time_offsets=true` and only
+ // in the top hypothesis.
+ int32 start_time = 1;
+
+ // Time offset relative to the beginning of the audio in ms
+ // and corresponding to the end of the spoken word.
+ // This field is only set if `enable_word_time_offsets=true` and only
+ // in the top hypothesis.
+ int32 end_time = 2;
+
+ // The word corresponding to this set of information.
+ string word = 3;
+
+ // The confidence estimate. A higher number indicates an estimated greater
+ // likelihood that the recognized word is correct. This field is set only for
+ // a non-streaming result or, for a streaming result where is_final=true.
+ // This field is not guaranteed to be accurate and users should not rely on
+ // it to be always provided. Although confidence can currently be roughly
+ // interpreted as a natural-log probability, the estimate computation varies
+ // with difference configurations, and is subject to change. The default of
+ // 0.0 is a sentinel value indicating confidence was not set.
+ float confidence = 4;
+
+ // Output only. A distinct integer value is assigned for every speaker within
+ // the audio. This field specifies which one of those speakers was detected to
+ // have spoken this word. Value ranges from '1' to diarization_speaker_count.
+ // speaker_tag is set if enable_speaker_diarization = 'true' and only in the
+ // top alternative.
+ int32 speaker_tag = 5;
+
+ // The language code of the word.
+ string language_code = 6;
+}
+
+// `StreamingRecognizeResponse` is the only message returned to the client by
+// `StreamingRecognize`. A series of zero or more `StreamingRecognizeResponse`
+// messages are streamed back to the client.
+//
+// Here are few examples of `StreamingRecognizeResponse`s
+//
+// 1. results { alternatives { transcript: "tube" } stability: 0.01 }
+//
+// 2. results { alternatives { transcript: "to be a" } stability: 0.01 }
+//
+// 3. results { alternatives { transcript: "to be or not to be"
+// confidence: 0.92 }
+// alternatives { transcript: "to bee or not to bee" }
+// is_final: true }
+//
+
+message StreamingRecognizeResponse {
+ // This repeated list contains the latest transcript(s) corresponding to
+ // audio currently being processed.
+ // Currently one result is returned, where each result can have multiple
+ // alternatives
+ repeated StreamingRecognitionResult results = 1;
+
+ // The ID associated with the request
+ RequestId id = 100;
+}
+
+message PipelineStates {
+ // Neural VAD probabilities
+ repeated float vad_probabilities = 1;
+}
+
+// A streaming speech recognition result corresponding to a portion of the audio
+// that is currently being processed.
+message StreamingRecognitionResult {
+ // May contain one or more recognition hypotheses (up to the
+ // maximum specified in `max_alternatives`).
+ // These alternatives are ordered in terms of accuracy, with the top (first)
+ // alternative being the most probable, as ranked by the recognizer.
+ repeated SpeechRecognitionAlternative alternatives = 1;
+
+ // If `false`, this `StreamingRecognitionResult` represents an
+ // interim result that may change. If `true`, this is the final time the
+ // speech service will return this particular `StreamingRecognitionResult`,
+ // the recognizer will not return any further hypotheses for this portion of
+ // the transcript and corresponding audio.
+ bool is_final = 2;
+
+ // An estimate of the likelihood that the recognizer will not
+ // change its guess about this interim result. Values range from 0.0
+ // (completely unstable) to 1.0 (completely stable).
+ // This field is only provided for interim results (`is_final=false`).
+ // The default of 0.0 is a sentinel value indicating `stability` was not set.
+ float stability = 3;
+
+ // For multi-channel audio, this is the channel number corresponding to the
+ // recognized result for the audio from that channel.
+ // For audio_channel_count = N, its output values can range from '1' to 'N'.
+ int32 channel_tag = 5;
+
+ // Length of audio processed so far in seconds
+ float audio_processed = 6;
+
+ // Message for pipeline states
+ optional PipelineStates pipeline_states = 7;
+}
\ No newline at end of file
diff --git a/api/asr.js b/api/asr.js
new file mode 100644
index 000000000..f5f419a74
--- /dev/null
+++ b/api/asr.js
@@ -0,0 +1,184 @@
+// POST /api/asr — free speech-to-text (voice IN) for the avatar voice loop.
+//
+// The companion to /api/tts/speak (voice OUT): Magpie TTS gives every avatar a
+// free voice; this endpoint lets users TALK to the avatar with a real,
+// cross-browser recognizer instead of the browser-only
+// window.webkitSpeechRecognition (Chrome/Edge only, ships audio to Google,
+// absent in Firefox and many embeds).
+//
+// Lane: NVIDIA NIM Riva ASR (free, gRPC — api/_lib/asr-nvidia.js). There is no
+// paid backstop wired here on purpose: when the lane is unconfigured the client
+// keeps its existing browser-SpeechRecognition path, so this endpoint is purely
+// additive — nothing depends on it and nothing breaks when it is absent.
+//
+// Request: raw audio bytes as the body, with the encoding given by Content-Type
+// audio/wav | audio/x-wav → WAV (header parsed, sent as LINEAR_PCM)
+// audio/L16 | audio/pcm → raw 16-bit little-endian PCM (set ?rate)
+// audio/flac → FLAC
+// audio/ogg → Ogg/Opus
+// or a JSON body { audio: <base64>, format?, language?, sampleRate?, words? }.
+// Query/JSON params: language (BCP-47, default en-US), rate (PCM sample rate),
+// words ("1" for word-level timestamps), model (override Riva model name).
+//
+// Response: { text, confidence, language, model, durationSec, words? }.
+
+import { cors, method, readBody, readJson, error, json, wrap, rateLimited } from './_lib/http.js';
+import { getSessionUser, authenticateBearer, extractBearer } from './_lib/auth.js';
+import { limits, clientIp } from './_lib/rate-limit.js';
+import {
+ transcribeNvidiaAsr,
+ nvidiaAsrConfigured,
+ resolveAsrEncoding,
+ parseWav,
+} from './_lib/asr-nvidia.js';
+
+export const maxDuration = 30;
+
+// 8 MiB of audio — generous for a spoken utterance (~4 min of 16 kHz mono PCM,
+// far more once compressed) while bounding the in-memory buffer per request.
+const MAX_AUDIO_BYTES = 8 * 1024 * 1024;
+const ASR_TIMEOUT_MS = 25_000;
+
+// Content-Type → friendly encoding alias understood by resolveAsrEncoding.
+// WebM/Opus (Chrome's MediaRecorder default) is intentionally absent: Riva does
+// not accept the WebM container, so we reject it with actionable guidance rather
+// than silently mislabel it as Ogg and emit garbage transcripts.
+function encodingFromContentType(ct) {
+ const type = String(ct || '').split(';')[0].trim().toLowerCase();
+ switch (type) {
+ case 'audio/wav':
+ case 'audio/x-wav':
+ case 'audio/wave':
+ return 'wav';
+ case 'audio/l16':
+ case 'audio/pcm':
+ case 'audio/x-pcm':
+ return 'pcm';
+ case 'audio/flac':
+ case 'audio/x-flac':
+ return 'flac';
+ case 'audio/ogg':
+ case 'audio/opus':
+ return 'opus';
+ default:
+ return null;
+ }
+}
+
+export default wrap(async function handler(req, res) {
+ if (cors(req, res, { methods: 'POST,OPTIONS' })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ if (!nvidiaAsrConfigured()) {
+ return error(
+ res,
+ 503,
+ 'not_configured',
+ 'Speech-to-text is not configured (set NVIDIA_API_KEY and NVIDIA_ASR_FUNCTION_ID — discover the id with scripts/verify-nvidia-asr.mjs --list)',
+ );
+ }
+
+ // Metered: free upstream but credit-limited, and each call holds an audio clip
+ // in memory. Authenticated callers get a per-user budget; anonymous a tight
+ // per-IP one. Mirrors the TTS metering policy.
+ const session = await getSessionUser(req);
+ const bearer = session ? null : await authenticateBearer(extractBearer(req));
+ const userId = session?.id ?? bearer?.userId ?? null;
+ if (userId) {
+ const rl = await limits.asrUser(userId);
+ if (!rl.success) return rateLimited(res, rl, 'ASR rate limit exceeded, try again later');
+ } else {
+ const rl = await limits.asrIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl, 'ASR rate limit exceeded, sign in for a higher limit');
+ }
+
+ const url = new URL(req.url, 'http://localhost');
+ const q = url.searchParams;
+ const contentType = req.headers['content-type'] || '';
+ const isJson = contentType.split(';')[0].trim().toLowerCase() === 'application/json';
+
+ // Pull audio + params from whichever transport was used.
+ let audio;
+ let format;
+ let language = q.get('language') || q.get('lang') || 'en-US';
+ let sampleRate = Number(q.get('rate') || q.get('sampleRate')) || 0;
+ let wantWords = q.get('words') === '1' || q.get('words') === 'true';
+ let model = q.get('model') || '';
+
+ try {
+ if (isJson) {
+ const body = await readJson(req, Math.ceil(MAX_AUDIO_BYTES * 1.4)); // base64 inflates ~33%
+ const b64 = typeof body.audio === 'string' ? body.audio.replace(/^data:[^,]*,/, '') : '';
+ if (!b64) return error(res, 400, 'bad_request', 'audio (base64) is required');
+ audio = Buffer.from(b64, 'base64');
+ format = body.format || 'wav';
+ if (typeof body.language === 'string') language = body.language;
+ if (Number(body.sampleRate)) sampleRate = Number(body.sampleRate);
+ if (body.words === true || body.words === '1') wantWords = true;
+ if (typeof body.model === 'string') model = body.model;
+ } else {
+ format = encodingFromContentType(contentType);
+ if (!format) {
+ return error(
+ res,
+ 415,
+ 'unsupported_media_type',
+ `Unsupported audio Content-Type "${contentType.split(';')[0] || 'none'}". Send audio/wav, audio/pcm (with ?rate=), audio/flac, or audio/ogg — WebM/Opus must be decoded to PCM/WAV client-side first.`,
+ );
+ }
+ audio = await readBody(req, MAX_AUDIO_BYTES);
+ }
+ } catch (e) {
+ if (e?.status === 413) return error(res, 413, 'payload_too_large', 'audio exceeds the 8 MB limit');
+ return error(res, e?.status || 400, 'bad_request', e?.message || 'could not read request body');
+ }
+
+ if (!audio?.length) return error(res, 400, 'bad_request', 'no audio bytes received');
+
+ let encoding = resolveAsrEncoding(format);
+
+ // A WAV carries its own sample rate and a 44-byte header Riva's LINEAR_PCM
+ // must not see — strip to raw PCM and trust the header's rate. Non-WAV inputs
+ // keep their declared encoding and the supplied (or default) rate.
+ if (encoding === 'LINEAR_PCM') {
+ const wav = parseWav(audio);
+ if (wav) {
+ audio = wav.pcm;
+ sampleRate = wav.sampleRateHz;
+ } else if (!sampleRate) {
+ // Raw PCM with no declared rate — 16 kHz is the Riva model default and
+ // the most common capture rate; the client can override with ?rate=.
+ sampleRate = 16000;
+ }
+ } else if (!sampleRate) {
+ sampleRate = 16000;
+ }
+
+ try {
+ const out = await transcribeNvidiaAsr({
+ audio,
+ encoding,
+ sampleRateHz: sampleRate,
+ language,
+ wordTimeOffsets: wantWords,
+ model,
+ timeoutMs: ASR_TIMEOUT_MS,
+ });
+ return json(res, 200, {
+ text: out.text,
+ confidence: out.confidence,
+ language: out.language,
+ model: out.model,
+ durationSec: out.audioProcessed,
+ ...(wantWords ? { words: out.words } : {}),
+ }, { 'cache-control': 'no-store' });
+ } catch (e) {
+ const code = e?.code || 'provider_error';
+ const status =
+ code === 'rate_limited' ? 429 :
+ code === 'invalid_argument' ? 400 :
+ code === 'not_configured' ? 503 :
+ 502;
+ return error(res, status, code, `Speech recognition failed: ${e?.message || 'unknown error'}`);
+ }
+});
diff --git a/data/changelog.json b/data/changelog.json
index a8d992af2..2a88c3540 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,14 @@
{
"$comment": "Curated changelog entries for three.ws — the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.",
"entries": [
+ {
+ "date": "2026-06-23",
+ "title": "Talk to your avatar — a new free speech-to-text lane closes the voice loop",
+ "summary": "Your avatar could already speak for free; now it can listen for free too. A new /api/asr endpoint turns spoken audio into text using NVIDIA's hosted Riva recognition on the same free key that already powers avatar voices, 3D generation, and chat — so voice-in costs nothing extra. Until now, talking to an avatar relied on the browser's built-in recognizer, which only exists in Chrome and Edge and quietly sends your microphone to Google; the new lane is server-side and works the same everywhere. It's purely additive: when the lane isn't switched on, voice keeps working exactly as before — nothing changes for anyone. Send a short WAV, PCM, FLAC, or Ogg clip and get back the transcript, the language detected, and optional word-level timestamps, all metered fairly so it can't be abused.",
+ "tags": [
+ "feature"
+ ]
+ },
{
"date": "2026-06-23",
"title": "Skill-sale earnings now show up in your agent's Earn tab",
diff --git a/public/changelog.json b/public/changelog.json
index 0f4bad5ee..38664e099 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-23T05:03:23.255Z",
+ "generated_at": "2026-06-23T05:06:30.997Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -336,6 +336,16 @@
"feature"
]
},
+ {
+ "date": "2026-06-23",
+ "type": "update",
+ "title": "Talk to your avatar — a new free speech-to-text lane closes the voice loop",
+ "summary": "Your avatar could already speak for free; now it can listen for free too. A new /api/asr endpoint turns spoken audio into text using NVIDIA's hosted Riva recognition on the same free key that already powers avatar voices, 3D generation, and chat — so voice-in costs nothing extra. Until now, talking to an avatar relied on the browser's built-in recognizer, which only exists in Chrome and Edge and quietly sends your microphone to Google; the new lane is server-side and works the same everywhere. It's purely additive: when the lane isn't switched on, voice keeps working exactly as before — nothing changes for anyone. Send a short WAV, PCM, FLAC, or Ogg clip and get back the transcript, the language detected, and optional word-level timestamps, all metered fairly so it can't be abused.",
+ "link": null,
+ "tags": [
+ "feature"
+ ]
+ },
{
"date": "2026-06-23",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index 79f8155fc..fe5b75e5e 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -262,6 +262,14 @@
<category>feature</category>
<description>Your avatar's wallet now takes voice and text commands. Tell your agent &quot;tip 0.1 SOL to vault.sol&quot;, &quot;snipe that mint with half a SOL&quot;, &quot;sell half my $THREE&quot;, or &quot;withdraw 2 SOL to my Phantom&quot; — it parses your intent with Claude, shows you exactly what it will do next to your own words (real quote, USD value, fees, network), and waits for an explicit &quot;yes&quot; or a tap before anything moves. Confirmed trades come back with a real on-chain signature and explorer link, and the avatar celebrates the moment it lands. Every action runs the same owner-only, spend-limit-gated, audited path as the rest of the wallet — visitors can chat but can never move funds, by any phrasing. A wrong hearing is caught at the read-back, &quot;cancel&quot; is always one word away, and there's a full keyboard path with no mic required.</description>
</item>
+ <item>
+ <title>Talk to your avatar — a new free speech-to-text lane closes the voice loop</title>
+ <link>https://three.ws/changelog</link>
+ <guid isPermaLink="false">2026-06-23:Talk to your avatar — a new free speech-to-text lane closes the voice loop</guid>
+ <pubDate>Tue, 23 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>Your avatar could already speak for free; now it can listen for free too. A new /api/asr endpoint turns spoken audio into text using NVIDIA's hosted Riva recognition on the same free key that already powers avatar voices, 3D generation, and chat — so voice-in costs nothing extra. Until now, talking to an avatar relied on the browser's built-in recognizer, which only exists in Chrome and Edge and quietly sends your microphone to Google; the new lane is server-side and works the same everywhere. It's purely additive: when the lane isn't switched on, voice keeps working exactly as before — nothing changes for anyone. Send a short WAV, PCM, FLAC, or Ogg clip and get back the transcript, the language detected, and optional word-level timestamps, all metered fairly so it can't be abused.</description>
+ </item>
<item>
<title>The in-chat skill purchase card is smoother, fully keyboard-friendly, and shows the right price every time</title>
<link>https://three.ws/marketplace</link>
diff --git a/public/features.json b/public/features.json
index ace0e8250..225f1343b 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-23T05:03:23.222Z",
+ "generated_at": "2026-06-23T05:06:30.818Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/scripts/generate-riva-asr-descriptor.mjs b/scripts/generate-riva-asr-descriptor.mjs
new file mode 100644
index 000000000..017e257f0
--- /dev/null
+++ b/scripts/generate-riva-asr-descriptor.mjs
@@ -0,0 +1,63 @@
+#!/usr/bin/env node
+// Regenerates api/_lib/riva-protos/asr-descriptor.js from the vendored NVIDIA
+// Riva .proto sources.
+//
+// node scripts/generate-riva-asr-descriptor.mjs
+//
+// This is the ASR sibling of scripts/generate-riva-tts-descriptor.mjs. It is
+// kept SEPARATE — a distinct generator writing a distinct descriptor file — so
+// the proven TTS descriptor (descriptor.js, consumed by api/_lib/tts-nvidia.js)
+// is never regenerated or perturbed when the ASR surface changes. The two
+// lanes share the same vendored riva_audio.proto / riva_common.proto but own
+// their service descriptors independently.
+//
+// Why a generated descriptor instead of loading the .proto files at runtime:
+// api/ routes are esbuild-bundled in place on Vercel (scripts/bundle-api.mjs),
+// so a runtime fs read of a .proto would need fragile includeFiles +
+// import.meta.url path math that differs between dev (api/_lib/…) and the
+// bundled output (api/asr.js). A checked-in JS module bundles cleanly, needs no
+// filesystem at runtime, and is loaded via @grpc/proto-loader's fromJSON().
+//
+// The descriptor is parsed with keepCase:true so the gRPC surface uses the
+// snake_case field names from the proto (config, sample_rate_hertz,
+// language_code, max_alternatives) — the same names NVIDIA's docs use.
+
+import { readFile, writeFile } from 'fs/promises';
+import { fileURLToPath } from 'url';
+import { dirname, resolve } from 'path';
+import { createRequire } from 'module';
+
+const require = createRequire(import.meta.url);
+const protobuf = require('protobufjs');
+
+const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');
+const PROTO_DIR = resolve(ROOT, 'api/_lib/riva-protos');
+const SOURCES = ['riva_common.proto', 'riva_audio.proto', 'riva_asr.proto'];
+const OUTPUT = resolve(PROTO_DIR, 'asr-descriptor.js');
+
+const root = new protobuf.Root();
+for (const name of SOURCES) {
+ const source = await readFile(resolve(PROTO_DIR, name), 'utf8');
+ protobuf.parse(source, root, { keepCase: true });
+}
+root.resolveAll();
+
+// Sanity: the exact surface api/_lib/asr-nvidia.js depends on must exist.
+root.lookupService('nvidia.riva.asr.RivaSpeechRecognition');
+root.lookupType('nvidia.riva.asr.RecognizeRequest');
+root.lookupType('nvidia.riva.asr.RecognizeResponse');
+root.lookupType('nvidia.riva.asr.RecognitionConfig');
+root.lookupEnum('nvidia.riva.AudioEncoding');
+
+const banner = `// GENERATED FILE — do not edit by hand.
+// Regenerate with: node scripts/generate-riva-asr-descriptor.mjs
+// protobufjs JSON descriptor for the NVIDIA Riva ASR service, parsed
+// (keepCase) from the vendored protos in api/_lib/riva-protos/*.proto,
+// themselves from https://github.com/nvidia-riva/common (riva/proto/).
+// SPDX-FileCopyrightText: Copyright (c) 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+// SPDX-License-Identifier: MIT
+`;
+
+const body = `${banner}export default ${JSON.stringify(root.toJSON(), null, '\t')};\n`;
+await writeFile(OUTPUT, body);
+console.log(`wrote ${OUTPUT}`);
diff --git a/scripts/verify-nvidia-asr.mjs b/scripts/verify-nvidia-asr.mjs
new file mode 100644
index 000000000..1a3cd269b
--- /dev/null
+++ b/scripts/verify-nvidia-asr.mjs
@@ -0,0 +1,107 @@
+#!/usr/bin/env node
+// Live verification for the free NVIDIA Riva ASR lane (voice IN).
+//
+// node scripts/verify-nvidia-asr.mjs --list # enumerate NVCF functions and
+// # print the ASR candidates +
+// # their ids (needs NVIDIA_API_KEY)
+// node scripts/verify-nvidia-asr.mjs # full round-trip check (needs
+// # NVIDIA_API_KEY + NVIDIA_ASR_FUNCTION_ID)
+//
+// The function id for the hosted ASR model is deployment configuration, not a
+// pinned constant (Parakeet/Canary, multiple versions). `--list` discovers the
+// live id for your account by enumerating
+// GET https://api.nvcf.nvidia.com/v2/nvcf/functions
+// and printing every function whose name looks like speech recognition. Copy the
+// id into NVIDIA_ASR_FUNCTION_ID (.env.local / vercel env), then run the script
+// with no args to prove the lane end to end.
+//
+// The full check is a self-contained round-trip across BOTH free lanes: it
+// synthesizes a known sentence through the Magpie TTS lane (api/_lib/tts-nvidia.js)
+// to get real spoken audio, transcribes it back through the Riva ASR lane
+// (api/_lib/asr-nvidia.js), and asserts the transcript recovers the spoken words.
+// No fixture audio files are needed and nothing is written to disk.
+
+import { config as dotenv } from 'dotenv';
+
+dotenv({ path: new URL('../.env.local', import.meta.url) });
+// .env.local can carry prod flags; clear them so nothing fails closed locally.
+delete process.env.NODE_ENV;
+delete process.env.VERCEL_ENV;
+
+const listOnly = process.argv.includes('--list');
+
+if (!process.env.NVIDIA_API_KEY) {
+ console.error('[asr] NVIDIA_API_KEY missing from environment/.env.local — cannot verify');
+ process.exit(1);
+}
+
+const NVCF_FUNCTIONS_URL = 'https://api.nvcf.nvidia.com/v2/nvcf/functions';
+const ASR_NAME_HINT = /(asr|speech.?recognition|recognize|parakeet|canary|conformer|citrinet)/i;
+
+async function listFunctions() {
+ const res = await fetch(NVCF_FUNCTIONS_URL, {
+ headers: { authorization: `Bearer ${process.env.NVIDIA_API_KEY}`, accept: 'application/json' },
+ });
+ if (!res.ok) {
+ const detail = await res.text().catch(() => '');
+ throw new Error(`NVCF function list returned ${res.status}: ${detail.slice(0, 300)}`);
+ }
+ const data = await res.json();
+ const functions = Array.isArray(data?.functions) ? data.functions : [];
+ const asr = functions.filter((f) => ASR_NAME_HINT.test(`${f?.name || ''} ${f?.id || ''}`));
+ console.log(`[asr] ${functions.length} NVCF functions visible; ${asr.length} look like ASR:\n`);
+ for (const f of asr) {
+ console.log(` ${f.id} ${f.status || ''} ${f.name || ''}${f.versionId ? ` (v ${f.versionId})` : ''}`);
+ }
+ if (!asr.length) {
+ console.log(' (none matched — list every function with: curl -H "Authorization: Bearer $NVIDIA_API_KEY" ' + NVCF_FUNCTIONS_URL + ')');
+ } else {
+ console.log('\n[asr] set NVIDIA_ASR_FUNCTION_ID to one of the ids above, then re-run without --list.');
+ }
+}
+
+async function roundTrip() {
+ if (!process.env.NVIDIA_ASR_FUNCTION_ID) {
+ console.error('[asr] NVIDIA_ASR_FUNCTION_ID missing — run with --list to discover it first');
+ process.exit(1);
+ }
+ const { synthesizeNvidiaTts } = await import('../api/_lib/tts-nvidia.js');
+ const { transcribeNvidiaAsr, parseWav } = await import('../api/_lib/asr-nvidia.js');
+
+ const sentence = 'the quick brown fox jumps over the lazy dog';
+ console.log(`[asr] synthesizing reference audio via Magpie TTS: "${sentence}"`);
+ const t0 = Date.now();
+ const tts = await synthesizeNvidiaTts({ text: sentence, voice: 'nova', format: 'wav' });
+ if (!tts.audio?.length || tts.audio.toString('ascii', 0, 4) !== 'RIFF') {
+ throw new Error('TTS did not return a WAV — cannot build the ASR reference clip');
+ }
+ console.log(`[asr] ${tts.audio.length} bytes of WAV in ${Date.now() - t0} ms`);
+
+ const wav = parseWav(tts.audio);
+ if (!wav) throw new Error('could not parse the synthesized WAV header');
+
+ console.log('[asr] transcribing it back through Riva ASR…');
+ const t1 = Date.now();
+ const out = await transcribeNvidiaAsr({
+ audio: wav.pcm,
+ encoding: 'LINEAR_PCM',
+ sampleRateHz: wav.sampleRateHz,
+ language: 'en-US',
+ });
+ console.log(`[asr] transcript in ${Date.now() - t1} ms: "${out.text}" (confidence ${out.confidence.toFixed(3)})`);
+
+ const got = out.text.toLowerCase();
+ const recovered = ['quick', 'brown', 'fox', 'lazy', 'dog'].filter((w) => got.includes(w));
+ if (recovered.length < 3) {
+ throw new Error(`transcript recovered only ${recovered.length}/5 key words — lane is not producing real recognition`);
+ }
+ console.log(`[asr] PASS — recovered ${recovered.length}/5 key words; round-trip across both free lanes works.`);
+}
+
+try {
+ if (listOnly) await listFunctions();
+ else await roundTrip();
+} catch (e) {
+ console.error(`[asr] FAIL — ${e?.message || e}`);
+ process.exit(1);
+}