Choose Task Voice for explicit audio input and a Task result, Realtime RTC for live publications and subscriptions, or OneSay Agent for a spoken conversation with an Agent in a Room. All use the OneSay JavaScript SDK; their lifecycles are separate. The SDK is in preview, and it is not on npm.
Install
-
Prerequisite: an account in the trial. You need a OneSay account enrolled in the trial; the Console, Device provisioning and every access token depend on it. Sign up in OneSay Cloud: each Project you create in the Organization OneSay Cloud makes for you gets its Test Environment enrolled in the trial when it is created. Sign up at
https://cloud.onesay.com/cloud/sign-up/. -
Prerequisite: access to the repository. OneSay has given your GitHub account read-only access to the SDK's repository. The repository is private; to ask for that access, write to
sdk@onesay.comwith your GitHub account name. -
Install the release named
v0.2.0, the one this guide describes, in your project with thenpmcommand in the Installation section of the repository's README at that release.That command fetches the release over HTTPS with your Git credentials, which must have the access from step 2 (for example a GitHub personal access token in your Git credential helper). The README's shorter form fetches over SSH and needs an SSH key on your GitHub account. The release carries its built files, so installing runs no build and no install script. If Git answers
Repository not found, your GitHub account does not have the access yet, or your Git credentials are not those of that account.The README at
v0.2.0was written before Production opened: it says Production is not offered yet and showsenvironment: "custom"withsetCustomEndpoints. Follow this guide instead and useenvironment: "production". The release's environment table (SDK_ENVIRONMENTS) already holds the Production addresses below. -
Use Node.js 22.12 or later; Node.js 24 is the tested version. The Task Voice and RTC clients use the global
WebSocket, which Node.js 22 and later provide (Node.js 20 has none).
Where this code can run today. In a browser and in Node.js alike,
tokenProviderreturns a person's short-lived Human access token; an API key (osp_) is refused. Today that token comes only from signing in to OneSay Cloud: signing in from your own page or program is not offered yet, and there is no step yet that gives the token to your own code, so the code below cannot yet run outside OneSay Cloud. To run the same chains now, sign in to OneSay Cloud and use the Console sections below (Task Voice and the AI Agent). To plan your own page or service, write tosdk@onesay.com.
JavaScript + Task Voice
With the package in your project, create a client for the Production environment. The package loads from an ES module with import, or, from v0.1.9, from CommonJS with require("@onesay/sdk"). require loads the package's ES module build, which Node.js 22.12 and later do without a flag (the tested version is Node.js 24); to compile CommonJS with --module nodenext, use TypeScript 5.8 or later. The steps below use top-level await, so run them in an ES module ("type": "module" in your package.json, or a .mjs or .mts file).
import { OneSayClient } from "@onesay/sdk";
const client = new OneSayClient({ environment: "production", tokenProvider });environment: "production" uses the addresses the SDK's environment table (SDK_ENVIRONMENTS) names for it: https://api.onesay.com/v1 and wss://realtime.onesay.com/v1. To reach another regional node, call setCustomEndpoints with the addresses from your configuration and use environment: "custom".
The program under Run a dictation from Node.js below runs these steps from start to end. In the SDK's repository,
examples/node-raw-pcm.ts and examples/canonical-pcm.ts show the PCM framing on its own and send no request; its
docs/QUICKSTART.md covers an AI Agent call, under OneSay Agent.
Supply current
Project/Environment and Source bindings, short-lived credentials through the
SDK's token providers, and already captured 16 kHz mono PCM s16le. The Task
client owns WSS/OSAF framing, sequence, ACK, backpressure, replay/resume and
cancellation; it does not capture audio or request microphone permission. A
Room created for a Task does not start an RTC session or an Agent.
A Task voice session runs in this order:
- Choose the Test Project Environment.
- In a browser, provide a short-lived access token through
tokenProvider; never embed anosp_*credential. - Obtain a single-use Realtime ticket from the Control API
(
createRealtimeConnection) for the intended Room and Project Environment. - Connect with
onesay.realtime.v1, open an Audio SignalStream, and send 16 kHz mono PCM s16le frames that your application captured. An AudioWorklet is one optional way to capture them in a browser. - The server sends
task.started, thenaudio.ackandartifact.deltawhile audio flows. Keep each frame until a contiguousaudio.ackcovers it. - Send
signal.end. The server answers withsignal.ended,artifact.finalizedandtask.completed; wait for that terminal Task state.
The Task language is optional. Leave it empty or set "auto" and the speech
Provider detects the language; the results then report the language as
"auto". Set a language code such as "zh-CN" to fix the language.
A ticket can be used once. A second connection with the same ticket is
refused with close code 1008 ticket_invalid, even while the first connection
is still open; request a new ticket instead.
Run a dictation from Node.js
This program runs one dictation of a recorded file from Node.js 24 with the SDK's public API only. It creates a microphone Source
and a Room, takes a single-use ticket, opens an Audio SignalStream over Task WSS, creates a dictation.v1 Task, sends the file in
40 ms frames, prints the final text and closes the Room. Three steps need the Human's confirmation (Consent), room.create,
signal.open and room.close: the program prints each request's presentation and goes on only when you type allow. It first
reads your user ID (getCurrentUser) and creates the Source (createSource), both callable through client.control.request from
v0.1.10; this guide describes v0.2.0. It reads the server's events while it sends the audio: the server acknowledges every 40 ms
frame (audio.ack), and events left unread would fill the client's event queue after a few minutes of audio. Save it as dictate.mjs in your project.
// dictate.mjs: one Task Voice dictation of a recorded file (16 kHz mono PCM s16le) from Node.js 24.
import { readFile } from "node:fs/promises";
import { createInterface } from "node:readline/promises";
import { OneSayClient, RealtimeClient, SPEC_SHA256, buildRealtimeConnectPlan, createConsentRequest, decideConsentRequest,
normalizeConsentAction } from "@onesay/sdk";
const { ONESAY_PROJECT_ID: project_id, ONESAY_ENVIRONMENT_ID: environment_id, ONESAY_ACCESS_TOKEN } = process.env;
const missing = ["ONESAY_PROJECT_ID", "ONESAY_ENVIRONMENT_ID", "ONESAY_ACCESS_TOKEN"]
.filter(name => !process.env[name]).concat(process.argv[2] ? [] : ["the audio file (for example: node dictate.mjs speech.pcm)"]);
if (missing.length) { console.error(`dictate.mjs: missing ${missing.join(", ")}`); process.exit(2); } // before any request
const environment = "production";
const tokenProvider = async () => ONESAY_ACCESS_TOKEN; // a short-lived Human access token; never an osp_ key
const client = new OneSayClient({ environment, tokenProvider });
const key = () => crypto.randomUUID();
const call = async (operationId, input = {}) => (await client.control.request({ operationId, environment, ...input })).data;
const CROCKFORD = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
const newId = prefix => prefix + [...crypto.getRandomValues(new Uint8Array(26))].map((b, i) => CROCKFORD[i === 0 ? b % 8 : b % 32]).join("");
const prompt = createInterface({ input: process.stdin, output: process.stdout });
// Consent: the Human reads the request's presentation and decides.
async function confirm(action_id, input, actorId) {
const action = await normalizeConsentAction({ action_id, input });
const context = () => ({ environment, idempotencyKey: key() });
const { data: request } = await createConsentRequest({ actor_principal_id: actorId, delegation_id: null,
scope: { kind: "project_environment", project_id, environment_id }, registry_digest: SPEC_SHA256, action }, context(), { tokenProvider });
console.log(JSON.stringify(request.presentation, null, 2));
const decision = (await prompt.question(`Type allow to confirm ${action_id}: `)).trim() === "allow" ? "allow" : "deny";
await decideConsentRequest(request.id, { decision, request_digest: request.request_digest, wording_version: request.wording_version },
context(), { tokenProvider });
if (decision !== "allow") throw new Error(`${action_id} was not confirmed`);
}
try { // a failure prints one line with its public error code
const pcm = await readFile(process.argv[2]);
const me = await call("getCurrentUser");
const source = process.env.ONESAY_SOURCE_ID ? { id: process.env.ONESAY_SOURCE_ID } // reuse a microphone Source of yours
: await call("createSource", { idempotencyKey: key(),
body: { project_id, environment_id, profile: "sensor.microphone", display_name: "dictate.mjs", device_id: null } });
console.log("source", source.id);
const roomInput = { project_id, environment_id, name: "Dictation", max_participants: 2, ttl_seconds: 900, metadata: {} };
await confirm("room.create", roomInput, me.id);
const room = await call("createRoom", { idempotencyKey: key(), body: roomInput });
const realtime = new RealtimeClient({ maxQueuedEvents: 4096 });
const send = (type, data) => realtime.sendControl(type, `msg_${key().replaceAll("-", "").slice(0, 16)}`, data);
async function until(type) { // the next event of this type; audio.ack, artifact.delta and the others are passed over
for (;;) {
const event = await realtime.nextEvent(60_000);
if (event.type === type) return event.data;
if (/\.failed$|^error$|^connection\.closing$/u.test(event.type)) throw new Error(`${event.type}: ${event.data?.error?.code ?? event.data?.code}`);
}
}
try {
const ticket = await call("createRealtimeConnection", { idempotencyKey: key(), body: { room_id: room.id, protocol_version: "1",
requested_grants: ["livekit.room_join", "source.use", "livekit.publish:microphone", "task.dictation.create", "task.cancel", "artifact.subscribe"] } });
await realtime.connect(buildRealtimeConnectPlan(environment, new URL(ticket.websocket_url).searchParams.get("ticket")));
await until("connection.welcome");
send("room.join", { display_name: "dictate.mjs" });
const { participant_id } = await until("room.joined");
const open = { kind: "audio", source_id: source.id, format: { codec: "pcm_s16le", sample_rate: 16000, channels: 1 },
client_signal_stream_id: `dictate-${Date.now()}` };
await confirm("signal.open", { ...open, room_id: room.id, participant_id }, me.id);
send("signal.open", open);
const { signal_stream_id, stream_handle } = await until("signal.opened");
send("task.create", { profile: "dictation.v1", client_task_id: `dictate-${Date.now()}`,
inputs: [{ id: newId("tin_"), ordinal: 0, role: "primary", kind: "signal_stream", signal_stream_id }],
config: { language: "zh", formatting: "natural", punctuation: "auto" } }); // "en" for English
await until("task.created");
const finalized = until("artifact.finalized"); // read events while sending: every frame gets an audio.ack
let failure;
finalized.catch(error => { failure = error; });
let sequence = 0;
for (let offset = 0; offset < pcm.length && !failure; offset += 1280, sequence += 1) { // 640 samples, 40 ms per frame
realtime.sendAudio({ streamHandle: stream_handle, sequence, sampleStart: BigInt(offset / 2),
payload: new Uint8Array(pcm.subarray(offset, offset + 1280)) });
await new Promise(resolve => setTimeout(resolve, 40));
}
if (failure) throw failure;
send("signal.end", { signal_stream_id, final_sequence: sequence - 1, final_sample_count: pcm.length / 2, reason: "client_completed" });
console.log((await finalized).text);
const completed = await until("task.completed");
console.log(completed.status, completed.usage);
} finally { // close the connection and the Room, also after a failure
await realtime.close(1000, "client_closed").catch(() => {});
try {
await confirm("room.close", { room_id: room.id }, me.id);
await call("closeRoom", { idempotencyKey: key(), path: { room_id: room.id }, body: {} });
console.log("room closed", room.id);
} catch (error) {
console.error(`room ${room.id} not closed (it ends when its ttl_seconds pass): ${error.message}`);
}
}
} catch (error) {
console.error(`dictate.mjs: ${error.code ?? error.message}`);
process.exitCode = 1;
} finally {
prompt.close();
}Reference code today. It runs once a short-lived Human access token can be given to your own code, which is not offered yet (see Where this code can run today above); until then, run the same dictation on OneSay Cloud's Task Voice test page. With such a token, run it with the IDs of your Test Project and Environment (OneSay Cloud shows them):
ONESAY_PROJECT_ID=<PROJECT_ID> ONESAY_ENVIRONMENT_ID=<ENVIRONMENT_ID> ONESAY_ACCESS_TOKEN=<HUMAN_ACCESS_TOKEN> node dictate.mjs speech.pcmIn PowerShell, set the variables first:
$env:ONESAY_PROJECT_ID = "<PROJECT_ID>"; $env:ONESAY_ENVIRONMENT_ID = "<ENVIRONMENT_ID>"; $env:ONESAY_ACCESS_TOKEN = "<HUMAN_ACCESS_TOKEN>"; node dictate.mjs speech.pcmspeech.pcm is raw 16 kHz mono PCM s16le with whole 16-bit samples (an even number of bytes). To make one from a recording, install
FFmpeg and run ffmpeg -i speech.wav -ar 16000 -ac 1 -f s16le speech.pcm. Expected: the
Source's ID, the final text on one line, completed and the Task's usage, then room closed with the Room's ID. The dictation is paid from the money allowance. Without one of the three settings or the file, the program names what is missing and exits with code 2 before it sends anything. When a step is
refused, the program stops with the public error code, for example consent_required for a step you did not allow, or
quota_exceeded, or budget_exceeded when the account has no money left for a Task, or when a Task has used the money set aside for it. capability_not_enabled (403, not retryable) means that the Environment does not have the trial switched on yet: details.required_setup names what it lacks and details.action_id the Action, and trying again does not help; use the Test Environment of a Project you created in OneSay Cloud (the first prerequisite under Install), or contact OneSay. Each run creates a Source unless you set ONESAY_SOURCE_ID to the ID an earlier run printed. The program closes the Room also after a failure; a Room it could not close ends by itself when its ttl_seconds pass.
To read a Task afterwards, client.tasks (the SDK's TaskClient) offers get, list and cancel over the Control API.
Try Task Voice in the Console
To see a Task Voice dictation before you write code, sign in to OneSay Cloud and open its
Task Voice test page (/cloud/tests/task-voice/; see the Console). Choose a
microphone Source and a language, then speak: the page shows the text as it
arrives and the final text with its usage when you stop. It runs the same chain
as the steps above, a OneSay dictation Task over Task WSS/OSAF with the SDK's
Task client, under your signed-in identity in the selected Project and
Environment; the page's own part is capturing the microphone as 16 kHz PCM
frames.
Every step that creates, sends or ends something (the Room, the microphone signal, cancelling a dictation, closing the Room) is first prepared as a Consent request, and it runs only after you allow it in the page; Deny leaves it undone. The server checks each Action again, so the page grants nothing by itself. A dictation is paid from the money allowance. You can cancel a dictation instead of stopping it, and leave and close the Room when you are done.
The section is available to accounts enrolled in the trial. It shows what the chain does; it is not a measure of recognition quality.
HTTP 503 capability_authority_unavailable with retryable: true is not a refusal: the authorization was not refused, so keep it. See
Authentication.
JavaScript + Realtime RTC
Preview: not yet on your own page. The RTC steps below cannot run from your own page yet, for two reasons. The Control API accepts browser requests only from OneSay Cloud's own address, so a request from your page is refused before it reaches OneSay (the change that admits your page's address is in progress). And the short-lived Human token comes only from the OneSay Cloud sign-in (see Where this code can run today above), and there is no test token for trying these steps. Until both change, try a conversation on OneSay Cloud's Voice call test page (
/cloud/tests/voice-call/, see the Console); it does not run this code.
Use @onesay/sdk and its client.rtc.connect facade. As under Task Voice, environment is production:
import { OneSayClient } from "@onesay/sdk";
const client = new OneSayClient({ environment: "production", tokenProvider });A connection needs a Room, an app session and a microphone Source of yours, and a short-lived Human token; keep the token in
memory and never supply a Platform API key or Provider key. There is no list of app sessions to pick from: create the Room and the
app session yourself, in this order, each after the Human's confirmation (Consent) of exactly the input you send. The lines below
continue the program under Run a dictation from Node.js above, after its Source: confirm is its Consent step (in a page, show
the request's presentation to the Human and record their choice instead of reading a terminal), and key, me, source,
tokenProvider and SPEC_SHA256 are its own; applicationId is your Application's ID in OneSay Cloud.
const roomInput = { project_id, environment_id, name: "RTC call", max_participants: 2, ttl_seconds: 900, metadata: {} };
await confirm("room.create", roomInput, me.id);
const room = (await client.control.request({ operationId: "createRoom", environment: "production", idempotencyKey: key(), body: roomInput })).data;
const sessionInput = { application_id: applicationId, device_id: null, environment_id, expected_requirement_revision: null,
expected_report_revision: null, registry_digest: SPEC_SHA256, ttl_seconds: 900 };
await confirm("app.session.create", sessionInput, me.id);
const created = (await client.control.request({ operationId: "createAppSession", environment: "production", idempotencyKey: key(), body: sessionInput })).data;
const appSessionId = created.session?.id ?? created.id;
await confirm("rtc.connection.create", { room_id: room.id, app_session_id: appSessionId, microphone_source_id: source.id }, me.id);
const session = await client.rtc.connect({ roomId: room.id, appSessionId, microphoneSourceId: source.id, idempotencyKey: key() });
const microphone = await session.audio.publishLocalMicrophone();Passing microphoneSourceId covers your microphone during connection admission and returns its ID on session.microphonePublicationId,
so session.audio.publishLocalMicrophone() captures and publishes the browser microphone directly with no extra server call.
Call session.audio.enablePlayback() from a click. In v0.2.0, session.capabilities.autoSubscribe is true under LiveKit's stock
auto-subscribe defaults, so LiveKit delivers every other participant's audio as soon as they publish, an Agent too, with no separate
subscription request.
To mute or unmute one remote participant locally without a server request, read opaque session-scoped handles from session.peers
(or session.onPeersChanged) and call session.audio.setPeerSubscribed(peer, subscribed). To restrict which peers can subscribe to
tracks you publish, call session.audio.setTrackSubscriptionPermissions({ allowAll, allowedPeers }). These join steps' Actions and
inputs (room.create, app.session.create and rtc.connection.create with microphone_source_id) are the ones OneSay Cloud's
Voice call test and Voice room test confirm. Without a decision, a Consent-gated step answers consent_required; after the Human
allows it, run it with the same input. The repository's examples/rtc-browser is a browser page with one button per operation (its
README lists them), and examples/rtc-agents.ts shows an Agent; both need the same Room, app session and Consent first.
RTC connect does not create a Task or Agent; Agent creation and stop are separate authorized operations. Calling session.close()
disconnects locally through LiveKit and does not confirm that the server revoked the connection; use client.rtc.get,
client.rtc.revoke or client.rtc.endPublication out of band when you need durable server state or termination.
If connect fails, read the error's retryable. grant_missing (403) is the server's definite refusal of the join, for example
because the connection was revoked; room_closed means the Room no longer exists. Neither is retryable: do not retry automatically.
Ask for authorization again instead: read the Room and app session back, confirm the Consent again if it is needed, and only then
call connect again. Only client_network_unavailable (retryable) may be retried, with a growing wait between attempts: it means
the network or the server could not be reached. These codes apply in v0.2.0.
If session.audio.publishLocalMicrophone fails, read the error's code. client_permission_denied means the person or the browser
refused the microphone; client_device_not_found means there is no microphone. Neither is retryable: ask
the person to allow the microphone in the browser, or to connect one, then call publishLocalMicrophone again. resource_busy
(retryable) means another capture holds the microphone; any other start failure is client_audio_capture_failed (retryable), also when the
microphone chosen with deviceId is gone: choose another one.
JavaScript + OneSay Agent
A OneSay Agent is a voice participant that joins your Room, listens to the publications you select and answers out
loud. You can interrupt it: speak while it answers, and it stops and listens. To try it without code, sign in to OneSay Cloud and
use its Voice call test page (/cloud/tests/voice-call/; your account must be enabled for the trial; see the
Console). The AI Agent Quickstart walks through it step by step.
In code, connect to the Room as in the RTC section, publish your microphone, then confirm and start the Agent with the explicit input set and a duration (the Consent input is the registry's, in snake_case):
if (!session.microphonePublicationId) {
throw new Error("Connection admission did not return a microphonePublicationId.");
}
const agentInput = { room_id: room.id, app_session_id: appSessionId, mode: "realtime",
publication_ids: [session.microphonePublicationId], max_duration_seconds: 120 };
await confirm("agent.execution.create", agentInput, me.id);
const idempotencyKey = key();
const agent = await client.rtc.agents.create({
roomId: room.id, appSessionId, mode: "realtime", publicationIds: agentInput.publication_ids,
maxDurationSeconds: 120, idempotencyKey,
});maxDurationSeconds is still required, 1 to 1,200 seconds, but it is only recorded: reaching it ends neither the Agent nor the call. The Agent ends when you stop it, when the call ends, or when the money set aside for it at the start runs out; that amount does not come from maxDurationSeconds.
Every call that creates, changes or ends something needs the Human's confirmation (Consent), except ending what is your own (stopping your own Agent, ending your own publication, revoking your own connection): until the Human confirms,
the server answers consent_required. After the confirmation, retry with the same idempotencyKey. How the Human confirms in your app, with createConsentRequest and decideConsentRequest, is shown in the AI Agent Quickstart. The other errors, and
what to do about each, are in Common errors.
Keep the idempotency key: if the response is lost, the same call with the same key returns the same Agent instead of
starting another. Read the Agent with client.rtc.agents.get(roomId, agent.agentExecutionId) at most once every 2
seconds. To hear it, call session.audio.enablePlayback() from a user gesture; you do not select its voice (see the RTC call above). Every Control API request, these reads included, counts toward one request
limit per user that all requests share; a request over it is refused with 429 rate_limited and can be retried a little later. The limit is set per environment.
observedState | Meaning |
|---|---|
pending | Accepted; the Agent is not running yet |
running | The Agent has started |
failed | The Agent ended by itself before you stopped it, or it never joined |
unknown | OneSay cannot confirm what the Agent is doing (it stopped reporting, or ended after your stop) |
stopped | A confirmed stop |
OneSay reports running while the Agent works (also after your stop request). Once the stop is confirmed, a read shows
stopped with effectiveStoppedAt; while effectiveStoppedAt is null, the stop is not confirmed yet. If the Agent has not
joined about a minute after the start, OneSay asks it to join once more; if it still cannot, the execution reads failed
instead of staying pending. unknown can still change to failed if a late report shows the Agent ended by itself first.
desiredState is what you asked for; observedState is what OneSay observed. While you listen, the RTC session's
audio.agentStates reports the Agent's output as initializing, idle, listening, thinking, speaking or
unknown: a low-frequency hint for your interface, never proof of what the Agent did. Stop it with
client.rtc.agents.stop(roomId, agentExecutionId, { idempotencyKey }); it needs no confirmation,
since the Agent is your own. An accepted stop is a request, not proof that the Agent has left.
If the RTC session reconnects (its state goes from reconnecting back to connected; onStateChanged reports each
change), read the Agent again with client.rtc.agents.get. If its observedState is failed or unknown, the Agent
may have ended while you were reconnecting: end your call instead of waiting for it to answer.
On the standard trial, the Agent API's maxDurationSeconds takes up to 1,200 seconds and does not end the call,
and no time limit ends a Device's call: it ends when someone hangs up or the money for it runs out, and a reconnect within the same running call is not refused because of time. This rule has not been verified on a device yet: no Device call longer than about 14 minutes has run since it changed. A conversation also has a cost budget, and a very long answer can be cut off. How many conversations an enrolled account can have is set by the Agent allowance the OneSay team sets for it,
not by a count. A Project's Test Environment gets its trial when the Project is created in the Organization OneSay Cloud makes for you.
To use a Device's microphone as the Agent's input instead of your browser's: use the
device-initiated call (available since ESP32 SDK 0.1.9): the Device starts the Agent call itself, under the standing Delegation its
owner created (set with agent_prof on the ESP32-S3-BOX-3 example), once device-initiated calls are switched on for your Environment
(contact OneSay), and naming the microphone of a Device on ESP32 SDK 0.1.11 from your app returns in a later release. With a
Device on ESP32 SDK 0.1.9 or earlier, you can also start and stop the Agent from your app, with the Device's pub_ id in
publicationIds. On OneSay's service today, the Agent does not hear the Device in a call that a person starts (ESP32 SDK 0.1.9 and earlier). See Start an AI Agent call from an ESP32 board,
A Device as the Agent's microphone and speaker
and Talk to an AI Agent on an ESP32-S3-BOX-3.
To publish a Device's microphone from JavaScript in v0.2.0, name the Device's active microphone Source in the Device's
rtc.connection.create Delegation and confirm that delegated Consent with microphone_source_id; the Device then calls
client.rtc.connect with delegationId and idempotencyKey (without microphoneSourceId in the connect call), reads
session.microphonePublicationId, and calls session.audio.publishLocalMicrophone(). For an ESP32 board, use the ESP32 SDK.