Console

Create a realtime conversation

WSS/v1/realtime

Establish a continuous two-way realtime session over WebSocket, stream in voice, camera, or screen frames, and receive streamed text and voice responses. It supports natural interruptions and delegates complex reasoning and long-running tasks to your own backend, continuing to talk with the user while they run.

Connection and authentication

Upgrade an HTTP GET request to WebSocket. Connect to wss://api.mosi.cn/v1/realtime with the model query parameter specifying the model; place the API Key only in the Authorization request header.

FieldTypeRequiredDescription
model: query stringRequired

Model ID. Use the stable ID; snapshot IDs are also supported. Pass it in the model query parameter of the WebSocket URL.

user: query stringOptional

Your own stable end-user ID, URL-encoded. Required when memory_scope=user; use the same user when reconnecting. Example: wss://api.mosi.cn/v1/realtime?model=moss-live-1.0&user=customer_001.

Authorization: HTTP headerRequired

Bearer <API Key>; put it in the Authorization request header of the WebSocket handshake.

Session flow

StageClientServer events and checks
ConnectComplete the WebSocket handshake and send attach_sessionJoin the session after the connection opens
ConfigureTo choose a voice, send change_voice; for a persona, session instructions, or custom tools, send session.update; to change the audio format, send media.configure; client delegation is set in attach_sessionWait for session_attached; if you sent change_voice, wait for voice_changed; if you sent session.update, wait for session.updated and confirm data.error is an empty string; if you sent media.configure, wait for media.configured
Send audio and videoTurn on the microphone and keep uploading audio; enable video as neededReceive voice and frame input
AnswerDisplay text, play voice, and send playback acknowledgementsReceive input.transcript.done, output.transcript.done, and response.ended; the conversation can continue after a voice reply completes or is interrupted
Continue or endKeep sending input, or close the WebSocketThe connection can continue after a turn completes; closing the connection ends the session

Client events

FieldTypeDescription
attach_session: event

Creates a new session or resumes an existing one. Send this event as the first message after connecting.

To reconnect, first close the old connection, then use the original session_id, the same user, and the same creation options; if the session cannot be resumed, create a new one. Your application keeps its own records of tasks and tool executions.

session.update: event

Configures the persona, session instructions, and custom tools. During initialization, finish configuring before enabling audio.

Omitted settings keep their values, and an update that fails validation is not applied. Sending only instructions keeps the current persona; persona=null restores the default persona.

change_voice: event

Switches the voice for the current session. Send it on the same WebSocket after receiving session_attached.

mic_state: event

Turns microphone input on or off.

media.mode: event

Enables the media format with type prefixes before you send video.

media.configure: event

Chooses the audio format, image capture parameters, and playback acknowledgement mode for this connection. You can send it at any time after attach_session, and more than once; if you do not send it, the default format is used; with no fields, it only returns the current settings; send it again after reconnecting. On poor networks, set profile to low to switch to low-bitrate transport.

client_context.update: event

Reports the device's time zone and, optionally, the device location. The assistant uses this time zone to answer with the local time and date and to work out times such as "3 p.m."; if it is not reported, Beijing time is used. We recommend sending it once after the connection is established and again when the time zone or location changes; pass null for context to clear it.

media.output.configure: event

Adjusts the volume and speaking rate of the speech sent on this connection; useful when the user's device speaker is too quiet or too loud, or when the user wants slower speech. Include at least one of the two fields. You can send it at any time after attach_session, and more than once; it takes effect from the next audio chunk (the reply currently playing changes too); if you do not send it, the default volume and normal speaking rate are used; send it again after reconnecting.

video.state: event

Controls camera or screen frames; turning frames off does not end the session.

video.stream_focus: event

Chooses the main frame source to focus on.

playback.chunk.completed: event

Send it after an audio chunk has actually finished playing in full.

playback.completed: event

response.audio.done has been received, and all audio of that reply has actually finished playing.

playback.stopped: event

Reports actual progress after playback has stopped. First acknowledge the chunks that finished playing, then report the partial duration of the current unfinished chunk.

conversation.item.create: event

Submits a tool execution result. On failure, also send back a failure description the model can use.

response.create: event

Has the model continue its reply using tool results already submitted. Use it to continue answering after a tool call; in ordinary voice conversations, the model responds automatically.

session.thinking.append: event

Sends facts or progress.

session.commentary.append: event

Sends progress or results that can be expressed to the user.

session.instructions.append: event

Appends session-level instructions.

session.delegation.cancel: event

Requests cancellation of the specified delegation. Your application is also responsible for stopping its own executor or device operations.

ping: event

Optional connection keepalive event; send it at your application's keepalive interval.

Server events

FieldTypeDescription
session_attached: event

The session is ready. Save the session ID and continue with the actual configuration returned.

session.updated: event

Result of processing the session configuration. Check data.error first, then decide whether to start input.

voice_changed: event

Notification that the voice was set; data.name is the voice ID set for the current session.

media.configured: event

Response to media.configure, containing the settings currently in effect for this connection; decode subsequent downstream speech according to its output_audio.

client_context.updated: event

Response to client_context.update.

media.output.configured: event

Response to media.output.configure; when the user asks during the conversation for slower or faster speech, the server also sends this event to tell your application the new speaking rate.

input.speech.started: event

Notification that user voice activity started. Your application can use it to update the user's speaking state; stopping playback and acknowledgements still follow the interruption events.

input.speech.stopped: event

Notification that user voice activity stopped, used to update the user's speaking state. Handle the model reply and the connection state through their own events.

session.closing: event

The server may send this notification before the connection closes. Your application handles the connection closing through the WebSocket close event.

input.transcript.updated: event

The current user transcript was updated.

input.transcript.done: event

The current user transcript was confirmed.

input.transcript.revised: event

Revises a confirmed user transcript. Update the history entry by turn instead of adding a new conversation entry.

output.transcript.updated: event

The model transcript was updated.

output.transcript.done: event

The final model transcript on the normal completion path.

response.audio.started: event

The corresponding reply started outputting audio.

response.audio.context: event

Association information for the next binary audio chunk. Save it and pair it with the PCM frame that follows.

response.audio.done: event

All audio for the corresponding reply has been sent. You still need to wait for the local player to finish.

response.audio.stop: event

Stop playback of the specified reply immediately and clear its queued audio. Keep receiving new replies.

response.ended: event

This reply has ended, and the connection can still be used. Normal completion, an abort before any audio was spoken, or a failure can be reported through this event.

response.interrupted: event

A reply that was already speaking was interrupted, or playback failed. This event is the final state of that reply; your application ends the reply based on it.

response.function_call_arguments.done: event

The complete tool call arguments are ready. Choose the tool by name, parse arguments, and run it.

response.done: event

Summary of tool call output. It may contain the same call as the arguments-done event, so deduplicate by call_id; it does not mean the tool has run or that voice playback has finished.

conversation.item.created: event

The tool result has been received; next, send response.create to continue the reply.

session.delegation.created: event

A task needs to be run by your application. Save delegation.id and prepare the call from objective and context; keep handling realtime audio while the task runs asynchronously.

session.thinking.appended: event

Confirms that the server has accepted this update. Audio playback state is tracked by the player and playback acknowledgements.

session.commentary.appended: event

Confirms that the server has accepted this update. Audio playback state is tracked by the player and playback acknowledgements.

session.instructions.appended: event

Confirms that the server has accepted this update. Audio playback state is tracked by the player and playback acknowledgements.

session.delegation.cancelled: event

The delegation has been marked as cancelled. Your application should stop the actual execution and discard old results not yet sent back.

pong: event

The public keepalive response uses {action, data}, with all time fields inside data.

error: event

Request or session error. Handle the corresponding request according to the error code, and continue the session or reconnect depending on the connection state.

Custom tool calls

Define tools in session.update.session.tools; your application runs them. Custom tools work in both client and none modes.

Do not block WebSocket sending and receiving or audio processing while running tools. Tools are synchronous by default: the model's reply for this turn waits for the tool result, the wait has an upper limit, and a timeout is treated as no result received. Declare tools that may take longer than about 2 seconds to run (querying your backend, placing orders, approvals, calling third-party services) as async tools; see "Async tools": the user can keep talking, and the assistant continues answering after the result is sent back.

Tool definition

FieldTypeRequiredDescription
type: stringRequired

Set to function.

name: stringRequired

Starts with a letter or underscore and contains only letters, digits, and underscores, up to 64 characters; names must be unique within the list. If a name cannot be used, the configuration confirmation returns an error.

description: stringRequired

Non-empty; describe the purpose and when to use the tool.

parameters: objectOptional

JSON Schema of the parameters; if omitted, an object with no properties is used. Your application validates the arguments before running the tool.

execution_mode: stringOptional

Execution mode; defaults to sync. See "Async tools".

read_only: booleanOptional

Whether the tool is read-only. It must be true for async_query and false for async_effect; otherwise the whole session.update is rejected.

sync tools can set it too: true marks a read-only query, which is run again after the user says something new or a write operation happens in between; within the same turn, queries with the same arguments reuse the previous result.

Define a tool
{
  "action": "session.update",
  "session": {
    "tools": [
      {
        "type": "function",
        "name": "get_order_status",
        "description": "Look up the current status of the specified order",
        "parameters": {
          "type": "object",
          "properties": {
            "order_id": {
              "type": "string"
            }
          },
          "required": [
            "order_id"
          ]
        }
      }
    ]
  }
}

session.updated confirms the configuration succeeded → receive response.function_call_arguments.done → your application runs the tool → send the result back with conversation.item.create → receive conversation.item.created → send response.create to continue the reply.

response.done may also contain the same call; deduplicate by call_id and run each call once. Updating the tool list replaces it entirely; pass tools: [] to clear it.

Keep the tool list stable

  • Use the same tool definitions for all sessions of the same application, with names, order, descriptions, and parameters unchanged word for word.
  • Do not put dynamic information such as the user, time, or order number in tool descriptions; put it in session instructions or tool results.
  • Finish configuring with a single session.update before enabling audio; avoid changing the tool list in the middle of a session.

Send back tool results and continue answering

After running the tool, submit the result with the same call_id. output is text or a JSON string.

Send back the tool result
{
  "action": "conversation.item.create",
  "item": {
    "type": "function_call_output",
    "call_id": "<received call_id>",
    "output": "{\"status\":\"shipped\"}"
  }
}

You then receive the corresponding result confirmation:

Result confirmation
{
  "action": "conversation.item.created",
  "data": {
    "type": "conversation.item.created",
    "item": {
      "id": "<item_id>",
      "type": "function_call_output",
      "call_id": "<received call_id>"
    }
  }
}

Then send response.create to ask the model to continue answering:

Continue answering
{
  "action": "response.create",
  "response": {
    "call_ids": [
      "<confirmed call_id>"
    ]
  }
}

response.done summarizes function call output. Run each call_id once; custom tools work in both client and none modes.

Async tools

A sync tool makes the model's reply for this turn wait until the result comes back, and the user can only wait in the meantime. For tools that may take longer than about 2 seconds to run, add execution_mode to the tool definition: use async_query for read-only queries and async_effect for operations with side effects.

Declare an async tool
{
  "action": "session.update",
  "session": {
    "tools": [
      {
        "type": "function",
        "name": "lookup_inventory",
        "description": "Look up the current inventory",
        "parameters": {"type": "object", "properties": {"sku": {"type": "string"}}, "required": ["sku"]},
        "execution_mode": "async_query"
      }
    ]
  }
}
  1. When the model calls an async tool, the server sends response.function_call_arguments.done as usual, with execution_mode, task_id, revision, and arguments_sha256. The assistant first briefly tells the user it is working on it, the turn then ends, and the user can keep talking.
  2. Your application runs the call outside the WebSocket send/receive and audio loop.
  3. When you have the result, send conversation.item.create with the same call_id; after you receive conversation.item.created, send response.create (with that call in call_ids), and the server starts a new reply that tells the user the result.

Each revision has a different call_id; deduplicate execution by call_id. Both the model and your application can revise or cancel unfinished tasks:

FieldTypeDescription
session.tool_task.revise: event

Revises the arguments of an unfinished async task. The server reissues the call with a new call_id and revision.

session.tool_task.cancel: event

Cancels an unfinished async task. Operations with side effects that have already been carried out cannot be undone by cancelling.

session.tool_task.updated: event

Response after a successful revision or cancellation.

response.function_call.cancel_requested: event

The server asks you to stop a call: the task was revised or cancelled by the model, or the wait timed out. Stop execution and discard any results that arrive late. This event does not mean your executor or device has stopped.

  • If expected_revision does not match the server, or the arguments do not conform to the schema, the error tool_task_conflict is returned; if the task does not exist, unknown_tool_task is returned.
  • Each session allows up to 128 async tasks (including finished ones), up to 32 revisions per task, and up to 4 running at the same time; a single execution takes at most 120 seconds from dispatch to receiving the result. When capacity is used up, new tasks are rejected; tasks in progress are not evicted.

Client delegation

The backend model, Agent, and tools run in your environment. Enable client when creating the session; if omitted, it is none, which does not affect frontend custom tools.

Enable client delegation
{
  "action": "attach_session",
  "delegation": {
    "type": "client"
  }
}

Confirm session_attached.data.delegation=client → receive session.delegation.created → run asynchronously → send back progress or results → handle the corresponding appended acknowledgements. Keep sending and receiving audio during the task.

EventUse
session.thinking.appendSilently sends back facts or progress for later answers.
session.commentary.appendin_progress sends back progress that can be spoken; completed / failed sends back the final result, including for reasoning tasks.
session.instructions.appendAppends business instructions for the rest of the conversation.

Link tasks by delegation.id and fill in delegation_id when sending back. timeout_ms specifies how long the current reply waits for the result; after the wait ends, the background task keeps running, and your application controls the execution timeout.

After receiving session.delegation.cancelled, mark the task as cancelled, stop the executor, and discard any further progress and results for that task. Your application handles undoing business operations that have already taken place.

A send-back retry reuses the original task result, event_id, and payload. The server deduplicates within the most recent 256 successful event_ids of the current session; for retries outside that window or after a service restart, your application checks the processing state. Each message carries at most 2000 Unicode characters; summarize long results first.

JavaScript SDK and executors

Use @mossai/mosslive to connect Pi or a custom execution framework over your existing realtime connection. Both use the same executor contract.

Install the SDK
npm install @mossai/mosslive@0.1.0

Connect Pi

First create a session with delegation: { type: "client" } enabled, then attach the executor on the same connection. In the example below, ws and sessionId come from the existing connection.

Connect Pi
import { attachDelegation } from '@mossai/mosslive';
import { createPiRunner } from '@mossai/mosslive/pi';

// ws and sessionId come from the existing voice connection; the session must be
// created with delegation: { type: 'client' }.
const run = createPiRunner({
  provider: 'custom',
  model: 'YOUR-BACKEND-MODEL',
  baseUrl: 'https://YOUR-PROVIDER/v1',
  api: 'openai-completions',
  keyEnv: 'CUSTOMER_BACKEND_KEY',
  workspaceRoot: './workspace',
  stateDir: './private-pi-state',
  tools: ['read', 'grep', 'find', 'ls'],
});
const bridge = attachDelegation({ socket: ws, sessionId, run });
// When the app shuts down, await bridge.close(), then close the ws the app owns.

When you create the connection with connectLive, set url to wss://api.mosi.cn/v1/realtime without query parameters, and pass the model separately as model: "moss-live-1.0".

Unified executor contract

Executor contract
type TaskRunner = (
  task: {
    sessionId: string;
    delegationId: string;
    objective: string;
    purpose: 'task' | 'reasoning';
    context: readonly { role: string; content: string }[];
  },
  context: {
    signal: AbortSignal;
    reportProgress: (text: string, options?: { spoken?: boolean }) => boolean;
    limits?: { maxProgressBytes: number; maxResultChars: number };
  }
) => Promise<string>;

The executor receives a task and returns the final text. Report new progress with reportProgress; when signal signals cancellation, stop the actual work and release resources before settling the Promise.

By default each progress message is limited to 600 UTF-8 bytes; adjust this with maxProgressBytes. The final result is limited to 2000 Unicode characters; summarize longer results with summarizeResult. Each append in the protocol carries at most 2000 Unicode characters.

reportProgress(text) sends back task progress; with { spoken: true } it submits progress the model can speak about. The SDK sends back the final text the executor returns; throw an error when execution fails.

Connect other execution frameworks

Generate an adapter project
npx @mossai/mosslive@0.1.0 init-adapter --directory my-adapter
cd my-adapter
npm install
npm test

The generated project includes an executor template, AGENTS.md, and contract tests. Implement TaskRunner by following the guide, then pass it to attachDelegation({ socket, sessionId, run }).

To manage event dispatch yourself, use createDelegationBridge. When the app exits, close the Bridge and the connection the app owns.

Current protocol values

ItemRequirement
AudioBy default, 16 kHz upstream and 48 kHz downstream, mono PCM S16LE, no WAV header; you can change this with media.configure. Upload continuously at realtime speed and keep sending silence after the user stops speaking; keep capturing during playback to support interruptions.
Media framingAudio-only input can send PCM directly. With tagged-v1 enabled: audio 0x00 + PCM (or an Opus packet table), camera 0x01 + JPEG, screen 0x02 + JPEG; audio keeps the prefix after frames are turned off. Downstream binary messages carry no prefix.
VideoOne binary message per JPEG frame, sharing the WebSocket with audio; no Base64, MP4, or H.264. Capture according to media.configured.video; the default is a long side of 512, quality 0.75, and 1 frame per second. Under load, older frames may be dropped.
Text updatestext is a full snapshot that replaces the display; the user's turn and the model's turn_id link to their respective records. Send playback acknowledgements based on the player's actual playback progress.
Persona and instructionspersona.prompt is up to 8000 Unicode characters; session instructions total up to 16000.
ToolsUp to 128; names up to 64 characters.
Context send-backUp to 2000 Unicode characters per append. Delegation context includes up to the 6 most recent entries, 600 characters each. instructions are up to 16000 Unicode characters.
Delegation recordsUp to 32 per session; finished tasks can be reclaimed, and sending back to an old ID may return unknown_delegation_id.

Error codes

For authentication, permissions, rate limiting, and general HTTP errors during connection, see Error Codes. The following are protocol errors specific to the MOSS-LIVE endpoint.

Error codesAction
memory_scope_requires_userProvide a stable user, or create a session-scoped session.
memory_scope_immutable / invalid_memory_scopeUse a valid memory scope; keep the original setting when resuming a session.
session_option_mismatch / invalid_session_optionCheck the creation options; keep the original settings when reconnecting.
invalid_content / content_too_longContent must be non-empty, and a single item must not exceed 2000 Unicode characters; content over the limit returns content_too_long.
invalid_delegation_id / unknown_delegation_idCheck the delegation ID and the session it belongs to; use null for session-level context.
invalid_statusUse completed, in_progress, or failed for commentary.status.
instructions_fullSession instructions have reached the total limit, and further calls return this error. Tidy up the instructions and reconfigure, or create a new session as your business requires.
unknown_call_idCheck the state of the call for that call_id, and reuse the result of a completed call.
invalid_public_requestReturned when the event name, fields, types, or action/type do not agree; check them and retry. It is also returned when a single session.update submits instructions longer than 16000 Unicode characters, and that configuration does not take effect.
invalid_event_idevent_id must be a string; the current length limit is 256 bytes.
event_id_conflictThe same event_id maps to different requests; check the ID and payload.
delegation_terminalThe delegation has ended; stop sending new progress and results.
delegation_cancel_failedCheck the task ID and status, and confirm whether the executor actually stopped.
presentation_capacityToo many results are waiting to be spoken; keep the completed task results and retry the send-back later.

Simultaneous interpretation

Translates one stream of realtime speech into another language and streams back the source text, the translated text, and the translated speech; it only translates and does not answer the content. It is the same service as realtime conversation, with the same connection method and authentication, at the path /v1/realtime/interpret. Example: wss://api.mosi.cn/v1/realtime/interpret?model=moss-live-1.0&source=en&target=zh.

FieldTypeRequiredDescription
model: query stringRequired

Model ID, the same as for realtime conversation.

target: query stringRequired

Target language code: zh Chinese, en English, ja Japanese, ko Korean, de German, fr French, es Spanish, ru Russian, it Italian, pt Portuguese, tr Turkish, el Greek, id Indonesian, ms Malay.

source: query stringOptional

Source language code, with the same values as target; detected automatically when omitted, and required when bidirectional=1.

bidirectional: query stringOptional

Switch for two-way interpretation.

voice: query stringOptional

Voice ID for the translated speech, that is, the data[].id returned by List Voices; the default voice is used when omitted.

After connecting, send attach_session as the first message, then send media.mode (tagged-v1), and media.configure if needed. Then keep streaming audio at realtime speed (0x00 + 16 kHz PCM16, or 0x00 + an Opus packet table), keep streaming silence when no one is speaking, and close the connection only after response.audio.done for the last sentence arrives. Each connection takes only one speaker; for multiple speakers, use one connection per person.

Client events

Only the following events are accepted; other events return error (invalid_request), and the connection stays open.

FieldTypeDescription
attach_session: event

Creates a session; it is the first message after connecting, and other fields are ignored. Each connection is a new session; resuming is not supported.

media.mode: event

Declares that upstream binary messages carry a type byte; audio is 0x00.

media.configure: event

Chooses the audio format and playback acknowledgement mode, with the same values as media.configure above; video is not used.

playback.chunk.completed: event

Send it after a chunk of translated speech has actually finished playing. Required when playback is client (default), otherwise the next sentence keeps waiting; not needed when it is server.

playback.completed: event

Send it after response.audio.done for a translated sentence has arrived and all its chunks have finished playing.

playback.stopped: event

Send it when the client stops playing a sentence on its own.

mic_state: event

Turns microphone input on or off.

ping: event

Optional connection keepalive event.

Server events

FieldTypeDescription
session_attached: event

The session is established.

media.configured: event

Response to media.configure, with the same fields as media.configured above (without video).

input.speech.started: event

Source speech started.

input.speech.stopped: event

Source speech paused.

input.transcript.updated: event

Realtime snapshot of a source segment; each one is the full text of that segment and replaces the display.

input.transcript.done: event

Final text of a source segment.

response.audio.started: event

Translated speech for a sentence started. One source segment may be translated into several sentences; translated speech may start before the source segment's input.transcript.done.

response.audio.context: event

The binary message that follows is a chunk of this sentence's speech.

output.transcript.updated: event

Progressive snapshot of this sentence's translated text.

output.transcript.done: event

Final translated text of this sentence.

response.audio.done: event

All speech for this sentence has been sent.

response.audio.stop: event

Speech for this sentence stopped midway; discard the part not yet played.

response.ended: event

This sentence has ended.

session.closing: event

Notification before the server closes the connection.

error: event

The request was invalid or a server error occurred.

Errors

  • Invalid query parameters: the handshake returns HTTP 400 and no connection is established.
  • The first message is not attach_session: error (invalid_request) is returned, and the connection is then closed with close code 1008.
  • Concurrency is full or the service is under maintenance: the connection is closed with close code 1013 (reason Session limit or Server draining); reconnect later, increasing the retry interval each time.