# Internal media WebSocket

Private VoIP UAT uses `https://192.168.1.69:9445` and `wss://192.168.1.69:9445/v1/live-sessions/<id>/audio`. The complete deployed connection, schema, timeout and tool acknowledgement contract is below. The default remains mock; approved agent runtime configuration may select real OpenAI. Read `/v1/agent-handoffs/<approved-agentId>` for safe effective-provider metadata.

Create `POST /v1/live-sessions` with `tenantId`, `agentId`, `callId`, caller/called numbers, direction, optional `userId`, and mode (`voice` default or `transcription`). Response contains the service session id, status, audio format and relative WebSocket path. Provider secrets and provider event formats never appear in it.

Upgrade `/v1/live-sessions/:id/audio` with bearer service authentication and `x-tenant-id`. One connection per session; no session reconnect. A disconnect ends the provider connection and releases quota reservations. A closed session may be inspected for 60 seconds, then is removed from memory.

Send JSON text frames, maximum 64 KiB. Audio is raw mono signed 16-bit little-endian PCM at 24,000 samples/sec, base64 encoded, without container headers. Use 20 ms frames (960 bytes), ordered continuously. Complete 16-bit samples are mandatory. The VoIP media adapter must decode G.711/other codecs and resample before forwarding; this service does not perform DSP conversion. Returned audio uses the same PCM format.

Incoming events:

```json
{"type":"session.start"}
{"type":"audio.append","audio":"<base64 PCM>"}
{"type":"audio.commit"}
{"type":"audio.interrupt","itemId":"<last played item>","playedMs":240}
{"type":"session.end"}
```

`session.start` announces media attachment and emits `session.started`; the provider has already connected during HTTP creation. The greeting starts only after this media event, so it cannot disappear before attachment. Repeated starts are rejected. Voice uses provider server VAD for response creation; commit is useful for explicitly ended input turns. Transcription-only mode needs caller-side VAD/turn commit because its model does not support server VAD. Silence/input should stay below the maximum call budget. Binary frames and unknown properties are rejected.

Outgoing events always include `sessionId` and `callId`:

| Type                 | Fields / meaning                                                                          |
| -------------------- | ----------------------------------------------------------------------------------------- |
| `session.started`    | Session details                                                                           |
| `audio.delta`        | `audio` base64 PCM, optional `itemId` for playback tracking                               |
| `audio.clear`        | Immediately flush queued AI playback on barge-in                                          |
| `transcript.partial` | `text`, optional `itemId`; provisional content                                            |
| `transcript.final`   | `text`, `endedAt`, optional `startedAt`/`itemId`; persisted caller turn                   |
| `agent.text`         | Completed assistant utterance                                                             |
| `tool.request`       | Validated telephony `actionId`, name, tenant/call, payload, status=requested              |
| `session.error`      | Normalized `error.code`, safe message, optional requestId                                 |
| `session.ended`      | reason: completed, media_disconnected, SESSION_EXPIRED, AI_UNAVAILABLE, or INTERNAL_ERROR |

On interruption, stop local playback immediately, flush pending audio, and send `audio.interrupt` with the provider-neutral item identifier from audio.delta and the actual played millisecond count. The adapter cancels generation and truncates unheard audio. Server speech detection also emits audio.clear; the platform should return the played position in an interrupt message. Missing position permits cancellation but cannot precisely truncate unheard conversation history.

The service closes slow consumers after a 1 MiB outbound queue and caps the input event queue at 100 frames. Provider failures emit `session.error` and `session.ended` with AI_UNAVAILABLE. The platform must then choose its fallback route. Timing fields are included only when known; this release does not infer exact word/audio alignment or live speaker identities.

## Exact private UAT connection

The existing `text.input` event requires `{ "type": "text.input", "text": "<nonempty question, max2000 characters>" }` and session.start first. It is permitted only by a real OpenAI agent's runtime textInputMaxTurns policy; the temporary [Gaskells UAT profile](gaskells-uat.md) allows six sequential questions, while existing mock profiles reject it. Real responses emit `agent.done` with status completed/failed/incomplete/cancelled after usage is metered; await this before the next turn, including after the audio greeting. The seven client and eleven server event schemas are unchanged by the agent-handoff implementation. A disabled tool policy exposes no tools; an unexpected provider tool call ends safely with TOOL_FAILED and no action.

Trust the handoff CA `voiceai-wrapper-lan-ca.crt`, whose certificate SAN is `IP:192.168.1.69`. Normal hostname and certificate verification is required. Every HTTP business request and WSS upgrade must send `Authorization: Bearer <token from protected env>` and `x-tenant-id: voip-staging`. No query parameters are used or required. Never put a token in a URL, and never send x-admin-key for this identity. The tenant header asserts the credential's fixed tenant; it cannot select another tenant.

Allowed: GET an identity-approved agent handoff, POST live-sessions, GET/DELETE own live session, own media WSS, GET own usage and GET own call transcript. Agent listing/CRUD remains forbidden. Anonymous/invalid auth is401; wrong tenant/forbidden operation403; unapproved agent or foreign session/transcript404. Only operators configure agent runtimes and server credentials. HTTP error shape is `{ "error": { "code": "...", "message": "...", "requestId": "..." } }`.

Create with `POST /v1/live-sessions`, Content-Type application/json:

```json
{
  "tenantId": "voip-staging",
  "agentId": "9eb68eb3-2aa4-4040-a33b-eb431b34cae7",
  "callId": "unique-uat-call-id",
  "caller": "mock-caller",
  "called": "mock-destination",
  "direction": "inbound",
  "mode": "voice"
}
```

Required tenantId, agentId, callId, caller, called, direction. Optional userId, mode (voice default, or transcription). IDs match `^[A-Za-z0-9_-]{1,100}$`; caller/called are nonempty strings up to2000 characters. Direction inbound/outbound. Use fresh call IDs, no customer data. The service returns201:

```json
{
  "id": "<generated UUID>",
  "tenantId": "voip-staging",
  "callId": "unique-uat-call-id",
  "agentId": "9eb68eb3-2aa4-4040-a33b-eb431b34cae7",
  "mode": "voice",
  "status": "ready",
  "audioFormat": { "encoding": "pcm16le", "channels": 1, "sampleRate": 24000 },
  "websocketPath": "/v1/live-sessions/<generated UUID>/audio"
}
```

Connect to the returned path using session id, never callId. GET returns the same shape; DELETE returns status closed and is idempotent within the60-second in-memory inspection window. Sessions do not survive restart. Default staging limits:30 seconds from HTTP creation (the approved Gaskells UAT profile explicitly overrides this to120 seconds), two concurrent calls,60 daily/600 monthly minutes, one-day transcript retention.

## Machine-readable JSON schemas and ordered events

[realtime-events.json](realtime-events.json) is draft-07 JSON Schema. `definitions.client` contains seven variants; `definitions.server` contains eleven. Generate using `node scripts/protocol-schema.js --write`; validate with `node scripts/protocol-schema.js`. Client schemas are generated directly from the runtime validators. All event objects reject unknown properties. Additional PCM-length and interrupt-pair semantic checks apply.

One UTF-8 JSON object per text message, max65536 bytes including JSON. No binary messages. No sequence or timestamp fields are required or accepted from the client. Wire arrival order is processing order; no replay or reorder protocol.

| Client type     | Required fields besides type                                           | Optional fields                                         | Semantics                                                                                                                                          |
| --------------- | ---------------------------------------------------------------------- | ------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- |
| session.start   | none                                                                   | none                                                    | Send once first. Emits session.started and starts greeting. Repeated start rejected. Legacy audio before start is accepted but starts no greeting. |
| audio.append    | audio: valid base64, max64000 chars                                    | none                                                    | Raw PCM complete samples, min2bytes, even length. Smallest valid silence is `{"type":"audio.append","audio":"AAA="}`.                              |
| audio.commit    | none                                                                   | none                                                    | Commit input turn; mock emits final transcript, assistant text/audio and permitted callback request.                                               |
| audio.interrupt | none                                                                   | itemId: nonempty string up to2000; playedMs: integer>=0 | Both fields together or neither. Stop generation/flush playback. With itemId, position permits truncation in real provider mode.                   |
| tool.result     | actionId: nonempty string up to2000; status: rejected/completed/failed | message: string up to2000                               | Consumer result for a pending action only.                                                                                                         |
| session.end     | none                                                                   | none                                                    | End, settle usage, emit session.ended, close1000.                                                                                                  |

Server events all include type/sessionId/callId, including media validation errors. Optional fields are omitted, not null. Internal usage/provider function events are not forwarded directly.

| Server type        | Exact additional fields                                                                                        |
| ------------------ | -------------------------------------------------------------------------------------------------------------- |
| session.started    | All session creation fields: id, tenantId, agentId, mode, status=ready, audioFormat, websocketPath.            |
| audio.delta        | audio: base64 PCM; optional itemId.                                                                            |
| audio.clear        | none; immediately flush assistant playback.                                                                    |
| transcript.partial | text; optional itemId. Mock text "Mock caller"; future provider fragments can be deltas, aggregate per item.   |
| transcript.final   | text and endedAt ISO UTC; optional startedAt ISO UTC and itemId. Complete turn supersedes provisional display. |
| agent.text         | text: complete assistant utterance.                                                                            |
| tool.request       | actionId, status=requested, name, tenantId, payload, timeoutMs=5000.                                           |
| tool.completed     | actionId, status=rejected/completed/failed, message.                                                           |
| session.error      | error: code, safe message, optional requestId.                                                                 |
| session.ended      | reason: completed/media_disconnected/SESSION_EXPIRED/AI_UNAVAILABLE/INTERNAL_ERROR.                            |

## Audio pacing and connection recovery

PCM16LE mono24kHz has no WAV/RTP headers. The VoIP adapter must decode/resample G.711/Opus before forwarding. Recommended20ms=960bytes; minimum2bytes, max48000 decoded bytes from the64000-character base64 field. Pace chunks in real time; do not flood. Mock output is960bytes of silence, testing protocol only. Keep an ordered bounded playback queue. On caller barge-in immediately stop and flush, then send audio.interrupt; include itemId/actual playedMs together only when audio.delta supplied itemId. Mock has no itemId so send type only. Flush also on audio.clear.

Native WebSocket ping every20 seconds. Client must pong (Node ws automatically does). Missing pong by the next tick terminates the socket, peer observes1006. No JSON heartbeat event. The effective profile timeout starts at HTTP creation:30 seconds for default staging agents,120 seconds for the approved Gaskells UAT agent. Read maxSessionSeconds from the scoped agent handoff. HTTP rate limit120 requests/minute per observed IP; shared gateway source may aggregate requests. Consumer should set5–10-second handshake timeout and its own fallback deadline.

Close codes:1000 graceful end/expiry/fallback when final event can be sent;1009 message too large;1013 input flood/slow consumer;1011 server failure;1006 abrupt disconnect/heartbeat termination (not sent on wire). Validation usually emits VALIDATION_ERROR and keeps connection open. Provider failure emits AI_PROVIDER_UNAVAILABLE then session.ended AI_UNAVAILABLE. Disconnect ends session, no reattach/reconnect/resume. Second attachment409. After loss, create fresh session and callId; do not blindly replay actions.

## Tool request / acknowledgement contract

Staging agent allows only call.requestCallback. First mock commit emits:

```json
{
  "type": "tool.request",
  "sessionId": "<id>",
  "callId": "<call>",
  "actionId": "<UUID>",
  "status": "requested",
  "name": "call.requestCallback",
  "tenantId": "voip-staging",
  "payload": {
    "callerName": "Mock caller",
    "callerNumber": "mock-caller",
    "message": "UAT callback simulation only",
    "for": "Mock receptionist",
    "priority": "normal"
  },
  "timeoutMs": 5000
}
```

The Voice API persists/emits a request only. It does not call, transfer, or write CRM/calendar/email. VoIP authorizes any future execution. In this UAT respond within5000ms:

```json
{
  "type": "tool.result",
  "actionId": "<same UUID>",
  "status": "rejected",
  "message": "UAT mock only; no external action"
}
```

actionId correlates within this tenant/session. Service persists sanitized result, audits it and emits tool.completed with actionId/status/message. Unknown, duplicate, foreign or expired ID produces VALIDATION_ERROR. Timeout emits/stores failed, "Consumer acknowledgement timed out". Session end fails pending requests. Provider gets status=requested when queued; later consumer acknowledgement is recorded for the consumer and is not injected as a second provider function result. Assistant must never claim requested means executed. Provider tool-call IDs are deduplicated; repeated mock commits do not issue new callback requests.

General call.requestTransfer uses payload `{ "targetType": "extension" | "number", "target": "..." }`, restricted to tenant targets/agent tool list. Disabled for this profile. Callback requires all five payload fields above; priority low/normal/high. No unrestricted external adapters are enabled.

## Scoped transcript and usage

GET `/v1/calls/<callId>/transcript`: callId, serviceIdentityId, text, segments, expiresAt (epoch milliseconds). Segments contain normalized final caller/assistant text events and role caller/assistant. Expired/foreign404. GET `/v1/usage`: only this identity's records, with tenantId/callId/serviceIdentityId/model/operation/quantities/timestamps and reservation fields where applicable. Duration reserved at creation, settled at end. Mock token quantities are synthetic, not real OpenAI spend. Same-tenant identities cannot read each other's session/transcript/usage. Tenant quotas include all identities.
