> Every Taji docs page as Markdown: https://docs.taji.is/llms.txt

# Gemini: how it works

Gemini Live is Google's realtime speech model API: one WebSocket carries your audio in and the model's speech, transcripts and function calls out. Taji takes from it one thing, a voice: it hears the open microphone, speaks the conversation's replies, and hands your requests to your desk's agent. The plugin is one crate, `taji-gemini`, built from `plugins/gemini/src/lib.rs`. It implements `taji_plugin::voice::Voice`, the kernel holds its one socket to `generativelanguage.googleapis.com`, and it serves no market data, places no orders and feeds no hub product.

Voice is the one exception to [0002](https://github.com/TajiAI/Taji/blob/main/docs/decisions/0002-taji-embeds-no-model.md): Taji calls no model API, voice aside. The boundary that exception keeps is the shape of this crate. The voice model is a relay, not a second agent. Its whole tool set is six dispatch tools (`send`, `read`, `stop`, `open_desk`, `set_progress_updates`, `hang_up`, `Tool::ALL` in `engine/crates/taji-plugin/src/voice.rs`). It reads no quote, holds none of the agent's eight MCP tools, and places and approves nothing. Every request with trading meaning goes, as your words, to the agent your own platform runs. The key is yours, sealed in your vault, and Google bills it, not Taji.

## The vendor

All facts here come from Google's Gemini API docs, fetched 2026-12-02. The `ai.google.dev` paths now redirect (301) to `aistudio.google.com`, which is where each link below points.

**Hosts.** One environment, with no sandbox. The Live socket is `wss://generativelanguage.googleapis.com/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent`, API version `v1beta` ([Live API reference](https://aistudio.google.com/api-reference/live)). REST calls go to `https://generativelanguage.googleapis.com/v1beta/…`.

**Auth.** A Gemini API key belongs to a Google Cloud project, and the project carries billing, collaborators and permissions. The REST docs pass the key in an `x-goog-api-key` header ([API keys](https://aistudio.google.com/docs/api-key.md)). The WebSocket guide passes it as a `key` query parameter on the socket URL: "Authentication is handled by including your API key as a query parameter in the WebSocket URL" ([Get started with the WebSocket API](https://aistudio.google.com/docs/live-api/get-started-websocket)). The key page states no expiry, but says Google blocks unrestricted keys left dormant for an extended period, from 2026-05-07. It warns never to put a key in a web or mobile client.

For a client-side app Google offers ephemeral tokens: `POST /v1beta/auth_tokens` mints a token for `BidiGenerateContentConstrained`, by default valid 30 minutes, able to open a new session for 60 seconds, and good for one use ([Live API reference](https://aistudio.google.com/api-reference/live)).

**The Live protocol.** Each message is JSON. The first client message is `setup`; the server answers `setupComplete`. After that:

| Direction | Message | What it carries |
|---|---|---|
| client | `realtimeInput.audio` | a `Blob`: base64 `data` and a `mimeType` such as `audio/pcm;rate=16000` |
| client | `clientContent` | turns of text, with `turnComplete` |
| client | `toolResponse` | `functionResponses`, each `id`, `name`, `response` |
| server | `serverContent` | `modelTurn.parts[].inlineData` (audio), `inputTranscription`, `outputTranscription`, `interrupted`, `generationComplete`, `turnComplete` |
| server | `toolCall` | `functionCalls`, each `id`, `name`, `args` |
| server | `toolCallCancellation` | the `ids` of calls the server dropped |
| server | `goAway` | `timeLeft` before the connection is "terminated as ABORTED" |
| server | `sessionResumptionUpdate` | `newHandle`, `resumable` |

`setup`'s fields are `model`, `generationConfig`, `systemInstruction`, `tools`, `realtimeInputConfig`, `sessionResumption`, `contextWindowCompression`, `inputAudioTranscription`, `outputAudioTranscription`, `proactivity`, `historyConfig` and `labels`. The reference says input transcription is sent "independently with no guaranteed ordering".

**Audio.** Input is "raw 16-bit PCM audio, 16kHz, little-endian", and the API resamples another rate if the `mimeType` names it. Output "always uses a sample rate of 24kHz" ([Live API capabilities](https://aistudio.google.com/docs/live-api/capabilities)).

**Turn detection.** "By default, the model automatically performs VAD on a continuous audio input stream." Its silence threshold defaults to "approximately 800ms". The default `activityHandling` is `START_OF_ACTIVITY_INTERRUPTS`: your speech cancels the generation, and "Only the information already sent to the client is retained in the session history". With detection disabled, the client sends `activityStart` and `activityEnd` itself.

**Function calling.** The Live API has no automatic tool handling: the client must answer each call with a `toolResponse`. "On `gemini-4-live` and `gemini-3.8-live`, function calling runs asynchronously (`NON_BLOCKING`) by default", and a declaration's `behavior: BLOCKING` keeps the synchronous mode ([Tool use](https://aistudio.google.com/docs/live-api/tools)). With thinking at `LOW` or above only `NON_BLOCKING` is allowed, and `BLOCKING` or `scheduling` returns an error ([Live thinking](https://aistudio.google.com/docs/live-api/thinking.md)). The `FunctionDeclaration` schema defines `BLOCKING` as "the system will wait to receive the function response before continuing the conversation" and `NON_BLOCKING` as "the system will not wait". A response's `scheduling` (`INTERRUPT`, `WHEN_IDLE`, `SILENT`, default `WHEN_IDLE`) is "Only applicable to NON_BLOCKING function calls" ([Function declarations](https://aistudio.google.com/api-reference/caching#FunctionDeclaration)). The Tool use page does not describe `toolCallCancellation`.

**Sessions.** A connection lasts "around 10 minutes". Without compression, an audio-only session is capped at 15 minutes. `contextWindowCompression` with a sliding window allows sessions of unlimited length. With `sessionResumption` on, the server sends handles; a handle passed in a new connection's `setup` resumes the session, and stays valid 2 hours after the session last ended ([Session management](https://aistudio.google.com/docs/live-api/session-management)). The reference defines `sessionResumption.handle` as "The handle of a previous session. If not present then a new session is created", `SessionResumptionUpdate.newHandle` as the "New handle that represents a state that can be resumed. Empty if `resumable`=false", and `GoAway.timeLeft` as "The remaining time before the connection will be terminated as ABORTED" ([Live API reference](https://aistudio.google.com/api-reference/live)).

**The model.** `gemini-4-live`, released 2026-12-02, "replaces both Gemini 3.8 Live and Gemini 3.8 Live Extended Thinking with a single `gemini-4-live` endpoint": 131,072 input and 65,536 output tokens, with function calling, Google Search grounding and optional thinking ([Gemini 4 Live](https://aistudio.google.com/docs/models/gemini-4-live)). Google's migration is to "change the model string to `models/gemini-4-live` and omit `thinking_level` (or set `MINIMAL`)"; "turn lifecycle and `turnComplete` signals remain identical" ([Live thinking](https://aistudio.google.com/docs/live-api/thinking.md)). `gemini-3.8-live` has no shutdown date yet ([Deprecations](https://aistudio.google.com/docs/deprecations.md)). Native audio models answer only in the `AUDIO` modality. Proactive audio is permanently enabled, and setting `proactive_audio: false` "returns an error"; affective dialog is removed. The reference says of proactive audio: "If enabled, the model can reject responding to the last prompt", such as out-of-context speech.

**Models list.** `GET /v1beta/models` with `pageSize` (default 50, at most 1000) and `pageToken`; it answers `models` and `nextPageToken` ([List models](https://aistudio.google.com/api-reference/models/list-models)).

**Limits and errors.** Rate limits apply per project, not per key, and rise with the project's usage tier: Tier 1 is an active billing account, Tier 2 $100 paid plus 3 days, Tier 3 $1,000 plus 30 days ([Rate limits](https://aistudio.google.com/docs/rate-limits)). `gemini-4-live` is limited in tokens per minute alone (Tier 1 250K, Tier 2 600K, Tier 3 15M), and no Live concurrent-session limit is listed. The error page ([API errors](https://aistudio.google.com/docs/api-errors.md)) lists, among others: 401 a missing, invalid or expired key; 402 "Your Prepay credit balance is depleted", not to be retried; 403 a key lacking permission; 429 a per-minute limit (retry with backoff) or the daily quota.

**What Taji does not use:**

- **Google Search grounding and every other built-in tool.** The voice may declare only `Tool::ALL`. A searching voice would answer market questions itself, which 0002 rules out.
- **Ephemeral tokens.** The kernel holds the socket, so the key never needs to reach a client ([0005](https://github.com/TajiAI/Taji/blob/main/docs/decisions/0005-no-key-reaches-a-client.md)).
- **Client-side turn detection** (`realtimeInputConfig`, `activityStart`, `activityEnd`). The `Voice` contract asks for "the provider's own turn detection on the open microphone". Tuning the detector waits on a repro.
- **Non-blocking calls and `scheduling`.** Every declaration is `BLOCKING` (below), and `scheduling` applies only to non-blocking calls.
- **A chosen language or thinking level** (`speechConfig.languageCode`, `thinkingLevel`). Taji takes Google's defaults.
- **Image and video input, text output.** Voice is audio both ways. Not yet built.
- **`usageMetadata`, `generationComplete`, `proactivity`, `historyConfig`.** The arm ignores them. Showing a session's spend is not yet built.

## Code map

- `plugins/gemini/src/lib.rs`: the whole arm. Read `impl Voice for Gemini` first, then `State::on_event`.
  - `Gemini`: the two URLs, `live` (the socket, without `?key=`) and `models`; `Default` points at Google and a test points them at a local server.
  - `MODEL`, `INPUT_HZ`, `OUTPUT_HZ`, `INPUT_MIME`: `gemini-4-live`, 16 kHz in, 24 kHz out.
  - `setup_frame`: the `setup` message: the model, `AUDIO` output, the instructions, the six tools, each `BLOCKING`, both transcriptions, resumption and the sliding window.
  - `Gemini::open`: connect with the key in the query, send `setup`, wait for `setupComplete`.
  - `Voice::run`: the loop. It selects between the kernel's `Input`, Google's frames and the pending `goAway`'s timer, and reconnects once a `goAway` is due (`State::swap_due`) or on a lost connection that has a handle.
  - `Gemini::resume`: the reconnect after an unplanned loss or a failed swap, one attempt after each of `RECONNECT_WAITS` not yet used.
  - `State`: the turn bookkeeping. `on_input` sends audio, results, cuts and Tells; `on_event` routes Google's messages to `on_tool_call` and `on_content`; `begin`, `cut` and `flush` keep the `Began`/`Done` rules over the SDK's `voice::Turns`, which also opens a reconnect.
  - `Turn`: one turn's `told`, `cut`, `over`, its pending calls and the responses held for one `toolResponse`.
  - `response_of`: the kernel's result string as a function response object.
  - `refusal`, `connect_error`, `sanitize`: Google's errors as `Failed`, with the key masked.
  - `next_ws_event`: a text or binary frame as JSON, or a close as `Failed`.
- `plugins/gemini/tests/scripted.rs`: offline tests against a local `tokio-tungstenite` server replaying Live message sequences, and a `wiremock` models list.
- `plugins/gemini/tests/live.rs`: ignored tests against Google, keyed by `GEMINI_API_KEY`.
- `plugins/gemini/taji-plugin.toml`: identity, the `gemini` link form, its step, field and refusal words.
- `plugins/gemini/Cargo.toml`: depends on `taji-plugin` with its `voice` feature, `tokio-tungstenite`, `reqwest`, `base64` and `serde_json`, and on no other Taji crate.
- `plugins/gemini/README.md`: the page for the person linking, and the measured behaviour.

## How it plugs into Taji

**The trait.** `Gemini` implements `Plugin`, whose `build` calls `b.voice(Self::default())`, and `Voice` (`engine/crates/taji-plugin/src/voice.rs`):

| Method | Gemini's answer |
|---|---|
| `id`, `name` | `gemini`, `Gemini` |
| `fields` | `key` |
| `format` | 16,000 Hz in, 24,000 Hz out, PCM s16le mono |
| `link` | `GET /v1beta/models?pageSize=1` with `x-goog-api-key`; any 2xx links |
| `voices` | the nine prebuilt voices, Kore first, each with Google's descriptor |
| `run` | one Live session for as long as the kernel's `hears` stays open, reconnecting inside on a quiet `goAway` and on a lost connection |

`Voice::run`'s doc comment holds eight turn rules, and the arm exists to keep them: each turn opens with `Began { spoken }` and closes with one `Done`, in order; a turn that began while a Tell was unanswered is marked not spoken (fail closed); after a cut, nothing of an older turn but its `Done`; no `Done` between a `Call` and its `Result`; a Tell waits until no turn runs; a swap that ends a running turn is `Reconnecting`, that turn's `Done`, `Reconnected`, and nothing else between them.

The plugin has no `FACTS`, `VenueFacts` or `OFFER` statics: it is no data source or venue. `engine/crates/taji-open/src/lib.rs` composes it with `.add(taji_gemini::Gemini::default)`, after OpenAI's arm.

**The link form.** The manifest's one `[[link]]` is the form `gemini` (kind `fields`, group `Voice`), with one step and one secret field `key`; the step text is [the manifest](https://github.com/TajiAI/Taji/blob/main/plugins/gemini/taji-plugin.toml)'s. It posts `voice/link` with `{"provider": "gemini"}`. Its refusal words are `invalid_key` and `no_credit`; the kernel turns each into the manifest's sentence (`Sealed::word_sentence` in `engine/crates/taji/src/wire/sealed.rs`).

**The kernel side.** `engine/crates/taji/src/wire/voice.rs` owns everything that is not Gemini:

- the link: it calls `Voice::link`, seals the fields under vault record `voice_gemini`, and writes `voice.json`;
- the session: `/ws/voice` is open to the window's scopes alone (`get("ws/voice", WINDOW)` in `engine/crates/taji/src/wire/routes.rs`), so your agent cannot open the microphone; a kernel runs one session, and a newer `start` ends the older `replaced`;
- the tools: `run_tool` runs each call against the bound conversation (`crate::agent::Agent`);
- the gate: only `read` runs in a turn your speech did not begin; any other call there is answered "Only the user's own speech can do that.";
- the replies: the relay watches the bound chat and tells the voice each answer, card, question and failure as a cue line (`[answer to "…"]`, `[waiting on the user]`, `[failed]`);
- the captions, the timers and the session's end.

The window's end is `ui/src/agent/voice.ts`: it captures the microphone with echo cancellation on, resamples it to `ready.input_hz` in `ui/src/agent/voice.worklet.ts`, and plays the kernel's audio at `output_hz`.

**Surfaces.**

| Taji surface | Gemini call | Made in |
|---|---|---|
| `POST /verb/voice/link` (`provider: "gemini"`) | `GET /v1beta/models?pageSize=1` | `Voice::link` |
| `GET /read/voice`, Gemini's row | none: the kernel's slot | `engine/crates/taji/src/wire/voice.rs` |
| `/ws/voice` `start` → `ready` | the socket, `setup`, `setupComplete` | `Gemini::open` |
| `/ws/voice` client `audio` | `realtimeInput.audio` | `State::on_input` |
| kernel `audio` and `caption` (`you`, `voice`) | `serverContent` audio and transcriptions | `State::on_content` |
| kernel `cut` | `serverContent.interrupted` | `State::on_content`, `State::cut` |
| the six tools | `toolCall`, then `toolResponse` | `State::on_tool_call`, `State::on_input` |
| an `agent` caption, spoken | `clientContent` with the cue line | `State::flush` |
| kernel `ended` `provider` | a close or socket error with no handle, a refusal, or a spent `RECONNECT_WAITS` | `next_ws_event`, `Gemini::resume` |
| `POST /verb/voice/unlink` | none: the sealed record is deleted | `engine/crates/taji/src/wire/voice.rs` |

The routes' full contracts are the `voice` rows of the `//!` header of `engine/crates/taji/src/wire/mod.rs`.

**One spoken turn, from the microphone to the dispatched act and back.** You say "Buy one share of Apple" on desk Main.

1. **Start.** The window opens `/ws/voice` and sends `start` with its desk. `Voices::serve` checks the scope, unseals `voice_gemini` (`armed`), binds the desk's conversation (`bind`), and spawns `Gemini::run` with `INSTRUCTIONS` as the system instruction. `run` opens the socket with `?key=`, sends `setup` and waits for `setupComplete`. The kernel frames `ready` with `input_hz` 16000 and `output_hz` 24000, and the window asks for the microphone.
2. **The microphone.** Every 40 ms the worklet posts 16 kHz samples; the window sends each as a binary `audio` frame. `Session::audio` passes it as `Input::Audio`, and `on_input` sends it as `realtimeInput.audio`, base64, `audio/pcm;rate=16000`. Audio streams from `ready` to the socket's end, silence included.
3. **Google ends your utterance.** Its detector hears about 800 ms of silence. `inputTranscription` deltas arrive as `Output::Heard`, and the kernel captions them `you`.
4. **The model calls `send`.** A `toolCall` arrives with `send` and `args` `{"text": "Buy 1 AAPL"}`. With no turn live, `begin` emits `Began { spoken: true }`; `on_tool_call` records the call as pending and emits `Output::Call`. A name outside `Tool::ALL` is answered "Unknown tool." and never reaches the kernel.
5. **The kernel dispatches.** `Session::output` sees a spoken turn and queues the call; `start` runs it on a blocking task. `run_tool` calls `Agent::hand_off`, which puts a question into the bound chat with `origin.channel` `voice` and a `taji://voice` mention. The mention carries, on the call's first hand-off to this chat, `VOICE_INSTRUCTIONS` (`engine/crates/taji/src/agent.rs`): the text came from speech, your own words in the transcript win, and an order is read back and placed only once you confirm. It also carries what was said since the last hand-off, up to 12 lines and 2,000 characters. Your agent, over ACP on your platform's sign-in, now owns the request. An order it places follows the account's approvals ([0008](https://github.com/TajiAI/Taji/blob/main/docs/decisions/0008-live-orders-wait-for-approval.md)); the voice can approve nothing.
6. **The result goes back.** `run_tool` answers "Working on it; the answer comes as an [answer] line." The kernel hands it back as `Input::Result`. Once every call of that `toolCall` has its result, the arm sends one `toolResponse`, the string wrapped as `{"result": …}`.
7. **Gemini speaks.** `modelTurn` audio parts become `Output::Audio`, framed `audio` with 24 kHz PCM, and the window plays them. `outputTranscription` becomes `Output::Spoke`, captioned `voice`. A `turnComplete` that came while the call waited was held; the one after the response ends the turn with `Done`.
8. **The agent's reply.** Later the agent answers in the chat. The relay turns it into an `[answer to "Buy 1 AAPL"] …` cue, at most 1,000 characters of answer (`ANSWER_CHARS`), captions it `agent`, and, once no turn runs, passes it as `Input::Tell`. `State::flush` emits `Began { spoken: false }` and sends it as `clientContent`; Gemini speaks it in the first person, as its own words, and ends the turn. In that told turn only `read` runs. If the agent parks an approval, the cue is `[waiting on the user] approval: …` and the voice says approving happens only in Taji's window.

If you speak during step 7, Google sends `interrupted`: the arm emits `Output::Interrupted`, the kernel frames `cut`, the window stops playback, and nothing more of that turn reaches you.

## Why it is built this way

- **A voice, not a model, inside Taji.** 0002 lets voice call a model only as a relay to your own agent; its Alternatives reject a text model between the voice and your agent. Hence the six tools, `INSTRUCTIONS` forbidding the voice to answer market questions itself, and no built-in Google tool.
- **Only your speech can act.** A Tell carries the agent's text, and a reply could carry an instruction. So a turn not begun by your speech may only `read` (`a_turn_a_tell_began_may_read_and_nothing_else` in `engine/crates/taji/src/wire/voice.rs`), and rule 2 of `Voice::run` fails closed: a turn beginning while a Tell is unanswered counts as told, since the arm cannot tell whose turn Google started. The README's measured section shows the cost: a request spoken in that instant is not handed over, and you say it again.
- **The kernel holds the socket.** The key is unsealed in the kernel and sent only to Google; no client or process plugin sees it ([0005](https://github.com/TajiAI/Taji/blob/main/docs/decisions/0005-no-key-reaches-a-client.md), and the Voice section of [security](https://docs.taji.is/architecture/security.md)). This is also why ephemeral tokens are unneeded.
- **The key goes in the query string.** That is how Google's WebSocket guide authenticates the socket. The URL lives only inside `run`; every error that might echo it passes `sanitize`, and the crate never logs a key, audio or a transcript.
- **Google's own turn detection.** The `Voice` contract leaves detection to the provider, and the measured defaults (about 800 ms of silence, barge-in on) are what the README records. `setup` sends no `realtimeInputConfig` so the defaults stand.
- **`responseModalities` sits in `generationConfig`.** The WebSocket guide's example puts it at the top of `setup`; Google refused that with close 1007 "Cannot find field" (the comment on `setup_frame`). The reference's form works.
- **Blocking calls.** Rule 5 of `Voice::run` holds a turn's output until every `Call` has its `Result`, and the kernel's results ("Not sent. Do not say it happened.") must reach the model before it speaks of the outcome. `gemini-4-live` defaults to `NON_BLOCKING`, which goes on speaking, so `setup_frame` declares each tool `BLOCKING`. Google refuses `BLOCKING` once thinking is above `MINIMAL`, so `setup` names no thinking level.
- **A held `turnComplete`.** Google can send `turnComplete` while a call waits on its result. Rule 3 forbids a `Done` between a `Call` and its `Result`, so the arm keeps the turn open until the tool response starts the generation whose own `turnComplete` ends it.
- **One `toolResponse` per `toolCall`.** The arm holds results until every call of a `toolCall` is answered, then sends them together (`a_tool_call_is_answered_in_one_tool_response_and_its_turn_complete_is_held`). Why one message rather than one per result is not on record.
- **Cut calls are answered, not dropped.** On `Input::Cut` the arm answers every waiting call with "The user interrupted.", so Google's turn reaches `turnComplete` and the next can begin. On Google's own `interrupted` it sends nothing, since the server discards those calls itself.
- **Reconnects stay inside `run`.** The `Voice` contract keeps "a provider's reconnects and resumption" inside the arm. A connection lasts about ten minutes, so on `goAway` the arm opens a new one with the newest resumable handle, closing the old one after. It does not swap at once: Google does not document that a resume keeps partial input, so the old socket keeps serving until no turn runs and no `inputTranscription` arrived for `Gemini::quiet` (1 s), or until 5 s of the `goAway`'s `timeLeft` remain. `timeLeft` is a protobuf `Duration`, which JSON writes as seconds ending in `s` (`"10s"`, `"3.5s"`); the [reference](https://aistudio.google.com/api-reference/live) types it `Duration` and the [session-management page](https://aistudio.google.com/docs/live-api/session-management) gives no format, so a frame with no parsable `timeLeft` swaps at the first quiet moment only. The kernel sees a swap only when it ends a running turn: `Reconnecting`, the `Done` of each turn running, `Reconnected` (rule 8). The turns end rather than carry over because a running generation does not continue on the new connection, and the kernel's cut path (`Reconnecting` cuts like an interruption) already drops the turn's calls; the arm drops them too, so a late `Result` sends nothing.
- **A lost connection resumes on the handle, or ends the session.** A close, a socket error or a failed send while a resumption handle is held emits `Reconnecting` (always: the connection was lost, so the user's speech goes nowhere), ends every running turn, then reopens on the handle after each of `RECONNECT_WAITS` (0.5, 1, 2, 4 and 8 s) and emits `Reconnected`. Audio the kernel sent meanwhile waits in `hears` and reaches the new session in order; Google acknowledges no audio, so what the dead socket had not delivered is not replayed. With no handle there is no context to resume and the loss ends `run`, as before. `Failed::Word` (a key or credit failure) and `Failed::Refused` (a 1007 or 1008 close) are never retried: waiting cannot fix them. A spent list returns the last error. The list is walked across reconnects: it starts again from 0.5 s only once a connection has stayed up `Reconnect::steady` (30 s), so an open that succeeds and then closes each time still waits 0.5, 1, 2, 4, 8 s and then ends `run`.
- **A chosen voice and the desk's vocabulary.** `setup.voice` is sent as `generationConfig.speechConfig.voiceConfig.prebuiltVoiceConfig.voiceName`; `VOICES` is a static list, and Google's one-word descriptors are the `tone`. `setup.vocabulary` is sent as `inputAudioTranscription.customVocabulary` when it is not empty. `Input::Played` is ignored: Gemini has no truncate. Both are re-sent on every reconnect, since `setup_frame` is built from the same `Setup`.
- **A sliding context window.** Without it an audio session ends at 15 minutes; the README measured that it lifts the limit.
- **Both transcriptions on.** The kernel needs text for captions and for the transcript each hand-off carries. Your own words in that transcript are what lets `VOICE_INSTRUCTIONS` tell the agent to trust them over the voice's wording.
- **`link` is a models read.** `Voice::link` must prove the key "with one authenticated call that opens no session", so linking bills no audio. The README records the cost: it proves the key, not its credit.
- **One pinned model.** `MODEL` is `gemini-4-live`, and a picker is not yet built.
- **A plugin on the SDK alone.** The crate depends on `taji-plugin` and no kernel crate ([0003](https://github.com/TajiAI/Taji/blob/main/docs/decisions/0003-plugin-on-sdk-alone.md)).

## Constraints and limits

The numbers measured against Google are the README's, under its [Use](https://docs.taji.is/catalog/gemini.md#use) section: the detector's silence, interruptions, reconnects, compression, noise and the models read.

- **Failures map onto `Failed`:**

  | Where | What fails | Result |
  |---|---|---|
  | `link` or the socket upgrade | 401, `API_KEY_INVALID` or "API key not valid" | the word `invalid_key` |
  | `link` or the socket upgrade | 402 or "credit balance is depleted" | the word `no_credit` |
  | `link` or the socket upgrade | another 4xx but 429 | `Failed::Refused` with Google's text, key masked |
  | `link` or the socket upgrade | 429, 5xx, transport | `Failed::Unreached` |
  | a live socket | close 1007 or 1008 | as a 400: one of the words if the reason names it, else `Refused` |
  | a live socket | any other close, a socket error, a lost send | `Failed::Unreached`; with a resumption handle held, the arm reconnects first and returns this only once `RECONNECT_WAITS` is spent |
  | `key` | no `key` field | `Failed::Refused("Gemini needs an API key.")` |

  When `run` returns an error the kernel ends the session `ended` `provider` with that sentence and sets the row's `error`; it never restarts a voice session. You turn voice on again.
- **Rate limits.** The arm reads no rate limit and retries nothing: a 429 at connect ends the session. Google's error page names no `Retry-After` or retry delay for a 429, only "Wait and retry with exponential backoff" for a per-minute limit and waiting for the reset for the daily quota. Limits are per project and by tier.
- **Reconnects.** A `goAway` reconnects at the first moment no turn runs and no input transcription arrived in the last second, or once 5 s of its `timeLeft` remain; a lost connection with a handle waits 0.5 s first, then 1, 2, 4 and 8 s between attempts, starting again from 0.5 s only after a connection has stayed up 30 s. A turn running at either ends with its `Done`, its calls dropped, between `Reconnecting` and `Reconnected`; a `Tell` waits until the new session is up. With no resumable handle yet, a `goAway`'s new connection starts without the conversation's context, and a lost connection ends `run`. A `goAway` whose reopen fails with `Unreached` takes the same waits on the same handle, with `Reconnecting` and `Reconnected` around them whether or not a turn was running. A refused reconnect ends `run`.
- **Barge-in and history.** Google keeps in its history all it sent, not what the window played, so after an interruption the model may believe you heard more than you did. Truncating it to what was played is not yet built.
- **Kernel timers** (`engine/crates/taji/src/wire/voice.rs`):
  - a call has `CALL_TIME`, the agent's 60 s `ASK_WAIT` plus 5 s; past it the voice is told the call is unfinished, and its late result is told as a `[late result] <tool>: <output>` line;
  - a turn with nothing exchanged for 30 s (`TURN_IDLE`) is cut;
  - a turn may make 8 calls per desk it reaches (`DESK_CALLS`) before it is cut.
- **Audio back-pressure.** The kernel keeps 16 slots of the arm's input queue for results, cuts and Tells (`HEARD_ROOM`). While the arm is not reading, during a reconnect, live audio past that is dropped rather than stalling the session.
- **Noise and other people.** The microphone is always open, and proactive audio, which lets the model decline speech not meant for it, is always on and cannot be turned off. 3.8 Live answered a remark to someone else 1 run of 3 and 4 Live 0 of 3 (`a_cough_and_a_remark_to_someone_else_are_not_answered` in `tests/live.rs`); instruction wording did not close it on 3.8. A turn Gemini keeps silent still carries a transcript (`<!-- no speech output -->`), which the next hand-off's transcript keeps.
- **What reaches Google.** Everything the microphone hears while voice is on, the cue lines, and the results of `read`: the conversation's last six messages, 400 characters each, and whether the agent is working or waiting for approval.

## Examples

Each comes from a test body, its values made up, in `plugins/gemini/tests/scripted.rs` unless it names another source. Function call ids and resumption handles are masked `pN`; the key is shown as `…`.

**The link** (`link_reads_the_models_and_maps_an_invalid_key_and_no_credit`). `POST /verb/voice/link` with `{"provider": "gemini", "key": …}` makes the arm call:

```
GET /v1beta/models?pageSize=1     x-goog-api-key: …
→ 200 {"models": []}                                   links
→ 400 {"error": {"code": 400, "message": "API key not valid. Please pass a valid API key.",
       "status": "INVALID_ARGUMENT",
       "details": [{"@type": "type.googleapis.com/google.rpc.ErrorInfo", "reason": "API_KEY_INVALID", …}]}}
                                                       Failed::Word("invalid_key")
→ 402 {"error": {"code": 402, "message": "Your Prepay credit balance is depleted.", "status": "RESOURCE_EXHAUSTED"}}
                                                       Failed::Word("no_credit")
```

**The link form** (`engine/crates/taji/tests/fixtures/wire/link-forms.json`, trimmed). `GET /read/link/forms` serves `{"form": "gemini", "group": "Voice", "kind": "fields", "fields": [{"name": "key", "kind": "secret", "label": "API key", …}], "post": {"route": "voice/link", "body": {"provider": "gemini"}}, "refusals": {"invalid_key": "Google did not accept that API key. …", "no_credit": "Google's prepay credit balance is depleted. …"}, …}`.

**The setup** (`the_setup_leaves_turn_detection_to_google_and_a_spoken_turn_begins_spoken`). The socket opens on `…BidiGenerateContent?key=…` and the arm's first message is:

```json
{"setup": {
  "model": "models/gemini-4-live",
  "generationConfig": {"responseModalities": ["AUDIO"]},
  "systemInstruction": {"parts": [{"text": "Speak briefly and call dispatch tools."}]},
  "tools": [{"functionDeclarations": [
    {"name": "send", "description": "Hand a request to the agent in the bound conversation on the current desk.",
     "parametersJsonSchema": {"type": "object", "properties": {"text": {"type": "string"},
       "delivery": {"type": "string", "enum": ["steer", "queue"], "default": "steer"}},
       "required": ["text"], "additionalProperties": false},
     "behavior": "BLOCKING"},
    {"name": "read", …}, {"name": "stop", …}, {"name": "open_desk", …}]}],
  "inputAudioTranscription": {}, "outputAudioTranscription": {},
  "sessionResumption": {}, "contextWindowCompression": {"slidingWindow": {}}}}
```

The test's instruction stands in for `INSTRUCTIONS`, and `setup` has no `realtimeInputConfig`.

**A spoken turn** (the same test). After `setupComplete`, the arm sends a microphone chunk as `{"realtimeInput": {"audio": {"data": …, "mimeType": "audio/pcm;rate=16000"}}}`, the data base64. Google answers:

```
{"serverContent": {"inputTranscription": {"text": "What is AAPL?"}}}      → Heard("What is AAPL?")
{"serverContent": {"modelTurn": {"parts": [{"inlineData":
   {"mimeType": "audio/pcm;rate=24000", "data": "MjxGUA=="}}]}}}          → Began { spoken: true }, Audio([50, 60, 70, 80])
{"serverContent": {"outputTranscription": {"text": "Checking now."}}}     → Spoke("Checking now.")
{"serverContent": {"generationComplete": true}}                         → nothing
{"serverContent": {"turnComplete": true}}                               → Done
```

**A tool call** (`a_tool_call_is_answered_in_one_tool_response_and_its_turn_complete_is_held`). Google sends:

```json
{"toolCall": {"functionCalls": [
  {"id": "p1", "name": "open_desk", "args": {"name": "Main"}},
  {"id": "p2", "name": "send", "args": {"text": "check AAPL"}}]}}
```

then `{"serverContent": {"turnComplete": true}}`, which the arm holds. It emits `Began { spoken: true }` and the two `Call`s. The kernel answers `Result { call: "p1", output: "Opened Main." }` and `Result { call: "p2", output: "{\"error\":\"Not sent. Do not say it happened.\"}" }`, and only then does the arm send:

```json
{"toolResponse": {"functionResponses": [
  {"id": "p1", "name": "open_desk", "response": {"result": "Opened Main."}},
  {"id": "p2", "name": "send", "response": {"error": "Not sent. Do not say it happened."}}]}}
```

**A told turn** (`a_tell_begins_a_told_turn_with_client_content`). The kernel passes `Input::Tell("[answer to \"q\"] AAPL is 200.")` with no turn live. The arm emits `Began { spoken: false }` and sends:

```json
{"clientContent": {"turns": [{"role": "user", "parts": [{"text": "[answer to \"q\"] AAPL is 200."}]}],
                   "turnComplete": true}}
```

Google's audio and `{"outputTranscription": {"text": "Apple is 200."}}` come back as `Audio`, `Spoke("Apple is 200.")`, then `Done`.

**A reconnect** (`a_session_outlives_one_go_away_with_its_context`). Google sends `{"sessionResumptionUpdate": {"newHandle": "p3", "resumable": true}}`, later `{"newHandle": "", "resumable": false}` (ignored), then `{"newHandle": "p4", "resumable": true}` and `{"goAway": {"timeLeft": "10s"}}`. The arm opens a second socket whose `setup` carries `"sessionResumption": {"handle": "p4"}` and the same instruction, closes the first, and the microphone's next chunk is the new socket's first message. With no turn running and no speech in the last second the kernel sees nothing; while the user is mid-sentence the swap waits for a quiet second (`a_go_away_during_input_transcription_keeps_the_old_socket_until_quiet`). In `a_close_mid_turn_resumes_on_the_handle_and_keeps_waiting_audio_in_order` Google closes the socket instead, mid-reply, after handle `p3`: the arm emits `Reconnecting`, `Done`, waits 0.5 s, opens a socket whose `setup` carries `{"handle": "p3"}`, emits `Reconnected`, and the chunks that arrived meanwhile are that socket's first messages, in order.

**The kernel's side of a send** (`a_send_puts_the_hand_off_and_its_answer_is_told_once_after_the_turn` in `engine/crates/taji/src/wire/voice.rs`, with a scripted stand-in arm `alpha`, so its rates are its own). `/ws/voice` frames `{"type": "ready", "provider": "alpha", "name": "Alpha", "desk": "d1", "session": …, "input_hz": 24000, "output_hz": 24000, "seq": 1}`; the chat gets the prompt `Buy 1 AAPL` with `"channel":"voice"`; the captions run `you` "buy one apple", `voice` "Sending.", then `agent` with `from` "Claude Code".

**Google's own frames for a real turn.** No capture yet. The live suite asserts on `Output`s and prints only `CELL` and `ORDER` lines; recording the frames of `spoken_question_begins_spoken_and_ends_with_its_done` would make one.

## Testing

- **The arm, offline:** `cargo test -p taji-gemini`. No key and no network: a local WebSocket server plays Live and `wiremock` plays the models list. The tests cover the setup and URLs, spoken and told turns, a held `turnComplete`, interruptions and cuts with calls waiting, a late result, a cancelled call, an unknown tool, `goAway` with and without a turn running or speech arriving, a close mid-turn resumed on the handle, a close with no handle, a word or a refusal not retried, a close naming an invalid key (with the key kept out of the error), and the link's refusals.
- **The kernel's session**, against a scripted arm: `cargo test -p taji --lib wire::voice`. It covers link and unlink, the spoken-only gate, Tells and their order, cards and approvals, cuts, timers, binds and replacements.
- **The tool set:** `cargo test -p taji-plugin --features voice the_voice_model_has_only_the_dispatch_tools`.
- **Live:** `cargo test -p taji-gemini --test live -- --ignored --test-threads=1 --nocapture`, with `GEMINI_API_KEY` in your environment or the repo's `.env`, billed to that key. Speech comes from macOS `say`, or a PCM or WAV file named by `VOICE_LIVE_PCM`. The tests: `link_proves_key`, `spoken_question_begins_spoken_and_ends_with_its_done`, `speech_mid_answer_interrupts_it_and_is_answered`, `speech_while_a_call_waits_ends_every_turn`, and `a_cough_and_a_remark_to_someone_else_are_not_answered`, which fails some runs until a remark to someone else goes unanswered.
- **The walk:** `engine/crates/taji/scripts/voice_walk.py <port> link|say|steer|stop|order --provider gemini`, against a headless kernel you started as `AGENTS.md` says, never your own Taji. Its header lists what each step speaks and checks; `order` runs only on `taji_sim` and skips while any live account is linked.

## References

Google's Gemini API docs, each fetched 2026-12-02:

- [Live API WebSocket reference](https://aistudio.google.com/api-reference/live)
- [Get started with the WebSocket API](https://aistudio.google.com/docs/live-api/get-started-websocket)
- [Live API capabilities](https://aistudio.google.com/docs/live-api/capabilities)
- [Session management](https://aistudio.google.com/docs/live-api/session-management)
- [Tool use](https://aistudio.google.com/docs/live-api/tools)
- [Function declarations](https://aistudio.google.com/api-reference/caching#FunctionDeclaration)
- [Gemini 4 Live](https://aistudio.google.com/docs/models/gemini-4-live)
- [Live thinking](https://aistudio.google.com/docs/live-api/thinking.md)
- [Deprecations](https://aistudio.google.com/docs/deprecations.md)
- [List models](https://aistudio.google.com/api-reference/models/list-models)
- [API keys](https://aistudio.google.com/docs/api-key.md)
- [Rate limits](https://aistudio.google.com/docs/rate-limits)
- [API errors](https://aistudio.google.com/docs/api-errors.md)

In Taji: [0002](https://github.com/TajiAI/Taji/blob/main/docs/decisions/0002-taji-embeds-no-model.md), [0005](https://github.com/TajiAI/Taji/blob/main/docs/decisions/0005-no-key-reaches-a-client.md), [security](https://docs.taji.is/architecture/security.md), [the README](https://docs.taji.is/catalog/gemini.md), [the manifest](https://github.com/TajiAI/Taji/blob/main/plugins/gemini/taji-plugin.toml).
