# Technical Reference
[Back to README](../README.md)
This document describes the OpenAI-compatible API and its extensions for session selection, progress, replies, and cancellation.
See the [README](../README.md) for initial setup.
Unless stated otherwise, run the examples in this document from the project directory.
## ๐ OpenAI-Compatible Protocol
### HTTP API
| Method and path | Behavior | Authentication |
| --- | --- | --- |
| `GET /health` | Process liveness check that returns `{"status":"ok"}` | None |
| `GET /v1/models` | Lists the single configured model | Bearer |
| `GET /v1/models/{model}` | Returns the configured model's details; other names return 404 | Bearer |
| `POST /v1/chat/completions` | Returns a non-streaming text response, or SSE with `stream: true` | Bearer |
Include `Authorization: Bearer ` for routes under `/v1`.
The proxy key is `api_key` in the `proxy.toml` file generated by `muse-proxy init`.
It is separate from Muse credentials, the Muse SDK token, and an OpenAI API key.
Clients using the same configuration share the same Muse account and persona.
If an `Origin` header is present, its value must match the request destination's scheme, host, and port.
Cross-origin browser requests are rejected with 403. The proxy does not provide CORS access for external websites.
Clients that omit `Origin`, such as ordinary SDK clients and curl, can also use the API.
Starting the proxy, calling `/health`, and retrieving model information do not connect to Muse or read the credential files.
A successful `/health` check does not establish that a connection to Muse will succeed.
There is no Responses API, WebSocket API, Embeddings API, push subscription API, or request status API.
### Input and Compatibility Scope
Only **the last `role: "user"` message** in `messages` is sent to Muse.
Previous conversation history and `system` / `developer` instructions are not resent. Muse manages conversation history and the persona.
If the last user message is empty, too long, or non-text, the proxy returns an error; it does not send an earlier message instead.
| Field | Support |
| --- | --- |
| `model` | Ignored, whether supplied or omitted. Responses always use the configured alias. It is not forwarded to Muse and does not select its underlying model or VM |
| `messages` | An array containing at least one message. The last user message must contain non-whitespace text |
| `content` | A string, or an array of text parts with `type: "text"` / `"input_text"`. Array entries are joined with newlines |
| `stream` | Boolean; defaults to `false` |
| `n` | Omitted or `1` |
| `stream_options.include_usage` | Boolean. When `true` with `stream: true`, adds a `usage: null` chunk before the stream ends |
| `session_id` | Proxy extension; see [Session Selection](#session-id) |
| `temperature`, `top_p`, `max_tokens`, `max_completion_tokens`, penalties, `seed`, etc. | Accepted for compatibility but ignored, without being forwarded to Muse |
Tool calls, images, audio, structured output, custom stop conditions, and token probabilities are unsupported.
`tools` / `functions` must be omitted, `null`, or an empty array; `tool_choice` / `function_call` must be omitted, `null`, or `"none"`;
`modalities` must be omitted, `null`, or `["text"]`.
`audio` must be omitted or `null`; `response_format` must be omitted, `null`, or `{"type":"text"}`;
`stop` must be omitted, `null`, or an empty array; `logprobs` must be omitted, `null`, or `false`. Other values return 400.
Unrecognized fields are ignored. `context_id` cannot be used to select a conversation.
Muse does not provide token usage or cost information, so the proxy does not return estimates.
Non-streaming responses omit `usage`. SSE returns `usage: null` only when `include_usage: true` is specified.
## ๐งพ Extensions to the OpenAI API
The proxy adds the following information and behavior to the
[OpenAI Chat Completions format](https://developers.openai.com/api/reference/python/resources/chat/subresources/completions/methods/create).
See [Input and Compatibility Scope](#openai-compatible-protocol) for the supported standard features.
| Extension | Purpose |
| --- | --- |
| Request `session_id` | Selects a Muse conversation |
| Response `muse_proxy` | Identifies `progress` / `reply` / `cancel`, request IDs, message IDs, sequence numbers, and replacement requests |
| Reply routing within a session | Assigns replies without a request association to the latest accepted request and ends other pending requests with cancel |
| HTTP 200 cancellation responses | Ends a request's wait with HTTP 200, custom metadata, and empty content |
`muse_proxy.kind` identifies the type of received content; it is not an OpenAI-standard `status` field.
This API does not expose a `queued` / `running` / `completed` status enumeration or an endpoint for querying status.
`finish_reason: "stop"` alone cannot distinguish normal completion from cancel.
Clients that handle cancellation must check `muse_proxy.kind`.
### Muse State and Public Notifications
| Event received from Muse | Proxy behavior |
| --- | --- |
| `agent.status` with `activity_text` / `activity_code` | Emits available progress as `kind: "progress"` |
| Reply message `delta.message_done`, etc. | Emits finalized content as `kind: "reply"`; this does not yet end the whole request |
| `task.status: running` | Tracks ongoing work internally; does not emit a separate OpenAI status chunk |
| Root task `task.status: completed` | Completes the whole request after also checking that other work and messages have finished |
| Root task `task.status: cancelled` / `canceled` | Emits `kind: "cancel"` to waiting requests, with a `null` replacement |
| Root task `task.status: failed` / `errored` | Ends with an error |
Progress comes from structured events accepted by the official SDK, rather than guesses based on parsing plain text.
If `activity_text` is absent, the proxy uses `activity_code` as the content.
`activity_code` is a string supplied by Muse, with no guaranteed fixed enumeration. Clients must accept unknown codes.
Consecutive identical progress notifications are deduplicated. Empty, idle, online, and terminal states are not emitted as progress content.
These notifications describe progress reported by Muse; they do not expose the model's internal reasoning.
When requests overlap in the same session, progress goes to the latest accepted pending request.
## ๐ฌ Session Selection
The request body's `session_id` must contain 1โ64 ASCII letters, digits, or hyphens.
With the OpenAI Python SDK, pass it through `extra_body`:
```python
completion = client.chat.completions.create(
model="muse",
messages=[{"role": "user", "content": "Let's continue our previous conversation."}],
extra_body={"session_id": "my-app-chat"},
)
```
Selection precedence is the request's `session_id`, the configured `default_session_id`, then the main chat.
`muse-proxy init` sets `default_session_id = "muse-proxy"`,
but the default in `Settings` itself is `None`. Existing configuration files without this setting use the main chat.
Omitting `session_id` or passing `session_id: null` uses the configured default.
The proxy deterministically derives a UUID v5 from the device identifier and session label, and uses it as the Muse side-chat ID.
The same device identity and label always produce the same UUID, including after a restart.
A UUID-formatted value is normalized and used directly as that UUID.
Muse also has a native `session_id`; accepting arbitrary labels and converting them to UUIDs is a proxy extension.
The label does not set the chat's display name in the Muse app.
A side chat that does not exist yet is created on the first message send, and the proxy starts subscribing to it.
The same user message is not resent to create the chat.
Use these side chats exclusively for the proxy. The proxy subscribes to messages for the corresponding session.
Different `session_id` values do not separate the Muse account or persona being used.
### Deleted Chats and Session ID Reuse
Muse may refuse reuse of a session ID whose chat was deleted.
In an observed case, subscription returned HTTP 404 with `session not found`, and message submission returned HTTP 404 with `chat no longer exists`.
The proxy reported `muse_request_error`; changing the session label allowed a new chat to be created successfully.
Deletion of the original chat is the suspected cause, rather than a confirmed rule about Muse's server behavior.
If this happens, choose a new session label or an unused UUID.
When the request omits `session_id`, change `default_session_id` in `proxy.toml`, for example:
```toml
default_session_id = "muse-proxy-1"
```
Restart the proxy after changing the configuration.
Restarting without changing the label does not help select a new chat: the same device identity and label still produce the same UUID.
If the request explicitly supplies `session_id`, change that value instead; it takes precedence over `default_session_id`.
## ๐ท๏ธ Message Metadata
Each SSE content chunk for progress, replies, or cancellation includes a top-level `muse_proxy` attribute.
For non-streaming REST responses, only cancellation responses include this attribute.
| Field | Type | Meaning |
| --- | --- | --- |
| `kind` | `"progress"` / `"reply"` / `"cancel"` | Notification type |
| `request_id` | String | Target proxy request; matches the Chat Completion `id` and HTTP `x-request-id` |
| `message_id` | String | Muse message ID, or a proxy-generated `musemsg-โฆ` ID for progress, cancel, or other notifications without an available Muse ID |
| `sequence` | Integer | Notification number, starting at 1 within the request; counts progress, replies, and cancel |
| `activity_code` | String; optional | Muse activity code, included only on `progress` when available |
| `superseded_by` | String or `null` | Included only on `cancel`: the replacement proxy request ID, or `null` if unavailable |
`request_id` is a `chatcmpl-โฆ` ID generated by the proxy for each HTTP request.
It is separate from the user message ID returned by Muse when it accepts a send.
`message_id` is also distinct from `request_id`; a single completion can contain multiple reply message IDs.
`superseded_by` identifies the replacement completion ID, not a Muse ID.
`sequence` is not a global persistence cursor.
It does not count role, finish, or usage chunks, keepalive comments, or `[DONE]`.
Progress that is not exposed in a non-streaming REST response is still counted internally, so a REST cancel does not always have `sequence: 1`.
Requests and notifications are not persisted. The proxy provides no retrieval, resume, or deduplication API based on these IDs.
## ๐ก Stream Lifecycle
### Normal Completion
With `stream: true`, the proxy returns the assistant role, progress and replies, `finish_reason: "stop"`, then `[DONE]`.
Each reply is emitted when Muse finalizes a message; the proxy does not forward tokens as they are generated.
Multiple replies use ordinary `delta.content` under the same completion ID. The second and subsequent replies start with `\n\n`.
Progress content ends with `\n\n` and also reaches conventional Chat Completions clients as text content.
**A single message's `message_done` does not end the request.**
The proxy sends the final `stop` and `[DONE]` after the root task completes, tracked tasks and incoming replies finish, and no sends remain in progress.
This completion condition is the same whether or not replies contain association IDs.
The following SSE example contains one progress notification and two replies. Blank lines separate the `data:` lines.
```text
data: {"id":"chatcmpl-example","object":"chat.completion.chunk","created":1792800000,"model":"muse","choices":[{"index":0,"delta":{"role":"assistant","content":""},"finish_reason":null,"logprobs":null}]}
data: {"id":"chatcmpl-example","object":"chat.completion.chunk","created":1792800000,"model":"muse","choices":[{"index":0,"delta":{"content":"Searching.\n\n"},"finish_reason":null,"logprobs":null}],"muse_proxy":{"kind":"progress","request_id":"chatcmpl-example","message_id":"musemsg-progress","sequence":1,"activity_code":"researching"}}
data: {"id":"chatcmpl-example","object":"chat.completion.chunk","created":1792800000,"model":"muse","choices":[{"index":0,"delta":{"content":"Here are the Sapporo results."},"finish_reason":null,"logprobs":null}],"muse_proxy":{"kind":"reply","request_id":"chatcmpl-example","message_id":"muse-reply-1","sequence":2}}
data: {"id":"chatcmpl-example","object":"chat.completion.chunk","created":1792800000,"model":"muse","choices":[{"index":0,"delta":{"content":"\n\nHere are the Hakata results."},"finish_reason":null,"logprobs":null}],"muse_proxy":{"kind":"reply","request_id":"chatcmpl-example","message_id":"muse-reply-2","sequence":3}}
data: {"id":"chatcmpl-example","object":"chat.completion.chunk","created":1792800000,"model":"muse","choices":[{"index":0,"delta":{},"finish_reason":"stop","logprobs":null}]}
data: [DONE]
```
While waiting, the proxy sends an SSE comment, `: keepalive`, approximately every 15 seconds.
It is neither progress nor a reply, and does not extend the request timeout.
With `stream_options.include_usage: true`, a chunk with `choices: [], usage: null` appears between `stop` and `[DONE]`.
With `stream: false`, the proxy omits progress and returns one assistant response containing all replies joined by the same separator.
Repeated notifications with the same reply ID and content already emitted over SSE are not emitted again.
If the content of an already-emitted ID changes, the proxy ends with `muse_protocol_error` because it cannot retract text already sent.
## ๐ Overlapping Requests in One Conversation
Within the same session, another request can be sent to Muse before the previous request receives a reply.
Requests share a connection and subscription, and are recorded in the order that Muse's send API acknowledges them.
An HTTP request's arrival alone does not make it the latest accepted request.
Different sessions use independent connections and can send messages before other sessions finish replying.
Credential refresh is serialized within the proxy; reply waits do not hold an account-wide lock.
Replies are assigned according to these rules:
1. If `reply_to_message_id` or other reply associations can be traced to an accepted user message, return the reply to that request.
2. If the parent ID is empty or refers to the message itself, and cannot identify a request, return the reply to the latest accepted pending request in the same session.
3. In case 2, send cancel to all other accepted pending requests remaining in that session at that point, ending their waits.
4. Do not assign a reply to the latest request when its association cannot be verified, such as a nonempty external parent ID.
This decision is made when a completed reply message is emitted.
Accepting a new request alone does not cancel an older request.
A proxy-generated cancel does not mean Muse semantically decided that the new request replaced the old one.
It is an explicit routing policy used when replies lack a request association.
```text
Request A accepted โโ waiting โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ cancel โ stop โ [DONE]
Request B accepted โโ waiting โโ unassociated reply 1 โโ reply 2 โโ task complete โ stop โ [DONE]
โ Replace A with B โ Continue as ordinary replies to B
```
Even for two independent questions, replies without association IDs are grouped under the latest request.
Use different `session_id` values if each request needs an independent completion.
This replacement policy never cancels requests in a different session.
## โน๏ธ Cancellation
Cancel is an extension that tells the caller of an older request to stop waiting for that request's reply.
For replacement within a session, `superseded_by` contains the latest completion ID receiving the replies.
The older request's SSE stream receives an empty `delta.content` with `kind: "cancel"`, immediately followed by `stop` and `[DONE]`.
The latest request continues receiving replies until the whole task finishes.
```text
data: {"id":"chatcmpl-old","object":"chat.completion.chunk","created":1792800000,"model":"muse","choices":[{"index":0,"delta":{"role":"assistant","content":""},"finish_reason":null,"logprobs":null}]}
data: {"id":"chatcmpl-old","object":"chat.completion.chunk","created":1792800000,"model":"muse","choices":[{"index":0,"delta":{"content":""},"finish_reason":null,"logprobs":null}],"muse_proxy":{"kind":"cancel","request_id":"chatcmpl-old","message_id":"musemsg-cancel","sequence":1,"superseded_by":"chatcmpl-new"}}
data: {"id":"chatcmpl-old","object":"chat.completion.chunk","created":1792800000,"model":"muse","choices":[{"index":0,"delta":{},"finish_reason":"stop","logprobs":null}]}
data: [DONE]
```
A non-streaming cancel returns **HTTP 200, empty assistant content, and `finish_reason: "stop"`**.
Even if some replies have already arrived, a non-streaming REST cancel does not return their content.
```json
{
"id": "chatcmpl-old",
"object": "chat.completion",
"created": 1792800000,
"model": "muse",
"choices": [{"index": 0, "message": {"role": "assistant", "content": ""}, "finish_reason": "stop", "logprobs": null}],
"muse_proxy": {
"kind": "cancel",
"request_id": "chatcmpl-old",
"message_id": "musemsg-cancel",
"sequence": 1,
"superseded_by": "chatcmpl-new"
}
}
```
Muse's own `task.status: cancelled` / `canceled` is also converted to cancel.
These notifications do not identify a replacement request, so `superseded_by` is `null`.
The SDK recognizes these terminal states, but the conditions under which Muse sends them have not been verified.
The same-session routing policy does not depend on receiving these native notifications.
The proxy provides no API for clients to issue cancel notifications or command Muse to stop execution.
An HTTP disconnect or timeout ends the wait for that request, but does not necessarily cancel work already accepted by Muse.
If another request is waiting in the same session, its connection and subscription remain active.
## ๐ Receiving Events with the OpenAI Python SDK
Running the proxy does not require the OpenAI SDK or an OpenAI API key. To use the OpenAI SDK as a client,
point `base_url` to the proxy and supply the proxy's `api_key`.
This example displays progress separately, accumulates replies, and discards the request's accumulated content on cancel.
```python
from openai import OpenAI
from muse_proxy.config import Settings
settings = Settings.from_file("proxy.toml")
with OpenAI(
base_url="http://127.0.0.1:8766/v1",
api_key=settings.api_key,
timeout=settings.request_timeout_seconds + 30,
max_retries=0,
) as client:
reply_parts = []
cancelled = False
with client.chat.completions.create(
model=settings.model,
messages=[{"role": "user", "content": "Find ramen restaurants in Sapporo."}],
extra_body={"session_id": "my-app-chat"},
stream=True,
) as stream:
for chunk in stream:
metadata = chunk.model_dump().get("muse_proxy") or {}
kind = metadata.get("kind")
text = ""
if chunk.choices:
text = chunk.choices[0].delta.content or ""
if kind == "cancel":
cancelled = True
reply_parts.clear()
print("This request has ended. Replacement:", metadata.get("superseded_by"))
elif kind == "progress":
print("Progress:", text.rstrip())
elif kind == "reply":
reply_parts.append(text)
if not cancelled:
print("".join(reply_parts))
```
The official Python SDK's synchronous and asynchronous clients have been tested with mocked HTTP responses using `openai==3.37.0`.
Cancel is returned as an ordinary `ChatCompletionChunk`; it does not raise a dedicated exception or trigger an automatic retry.
The following `stop` and `[DONE]` end iteration normally. The SDK does not yield `[DONE]` itself.
A REST cancel also returns a normal Chat Completion, so inspect `completion.model_dump().get("muse_proxy")`.
**The SDK does not automatically remove content received before cancel.**
Blindly concatenating `delta.content` includes progress in the answer and retains partial content from a canceled request.
Clients must remove partial displays or accumulated content themselves when needed.
With the higher-level `client.chat.completions.stream()`, inspect
`event.chunk.model_dump().get("muse_proxy")` on events with `event.type == "chunk"`.
`content.delta` / `content.done` alone cannot identify cancellation.
Custom attributes on later chunks are not carried into `get_final_completion()`, so do not rely solely on the final result.
## โ๏ธ Configuration and Operations
Start the proxy with `muse-proxy serve --config /path/to/proxy.toml` to load TOML configuration.
`init` also accepts `--config` and never overwrites an existing file.
| Setting | Default | Purpose |
| --- | --- | --- |
| `api_key` | Required; randomly generated by `init` | Proxy Bearer key, at least 16 characters |
| `state_dir` | `data/muse` | Directory containing existing Muse credentials; relative paths resolve against the configuration file, and `~` is supported |
| `host` | `127.0.0.1` | HTTP listening address |
| `port` | `8766` | HTTP listening port |
| `model` | `muse` | Model alias advertised by the API and returned in responses |
| `default_session_id` | `None`; `init` sets `muse-proxy` | Conversation used when the request does not specify one |
| `sdk_token` | Unset | The same Muse SDK token used for pairing |
| `vm_id` | Unset | Muse VM ID or name; when omitted, uses the default VM, or the first listed VM if there is no default |
| `request_timeout_seconds` | `180.0` | Overall response wait limit, including connection and session waits |
| `connect_timeout_seconds` | `30.0` | Wait limit for connecting to Muse or starting a chat subscription |
| `max_request_bytes` | `307200` | HTTP body size limit in bytes: 300 KiB |
| `max_message_chars` | `16000` | Character limit for the last user message |
`MUSE_PROXY_API_KEY` overrides TOML `api_key`, and `MUSEGADGET_SDK_TOKEN` overrides TOML `sdk_token`.
If the SDK token is absent from both the environment and configuration, the proxy reads `state_dir/sdk_token`.
Restart the proxy after changing configuration.
### Terminal logging
`muse-proxy serve` configures logging to stderr at `info` level. No configuration-file changes are required.
The serve-only `--log-level` option accepts these levels, from most to least detailed:
| Level | Output |
| --- | --- |
| `trace` | DEBUG diagnostics plus client HTTP bodies and decoded Muse requests, responses, acknowledgements, and events |
| `debug` | INFO diagnostics plus proxy events and upstream connection phases, without conversation content |
| `info` | Request arrivals, HTTP status and duration, accepted chats, and conversation outcomes |
| `warning` | Request failures and other warnings |
| `error` | Errors and critical failures |
| `critical` | Critical failures only |
```sh
muse-proxy serve --config /path/to/proxy.toml --log-level trace
```
Log lines contain a timestamp, severity, logger name, and diagnostic fields.
Each request receives an internal `http_id` so arrival, HTTP status, and duration can be correlated even if authentication or parsing fails.
This ID is for logs; it does not add a response header or change error responses.
An accepted chat request also logs its generated completion `request_id`, matching the existing `x-request-id` response header.
Conversation outcomes distinguish success, cancellation, and failure. Failures log a sanitized error code and, where available, a parameter name.
The HTTP status alone is insufficient: an SSE failure after headers have been sent still has status 200 and is logged as a failure.
TRACE covers both sides of the proxy.
The `muse_proxy.http` logger adds these client-facing body records:
- `http.request.body`: the submitted JSON after authentication and JSON parsing, before protocol validation. It includes fields ignored by the proxy, such as `model` and earlier conversation history, as well as any submitted `session_id`.
- `http.response.body`: the outgoing JSON response or each SSE frame, including progress, replies, cancellation, errors, `[DONE]`, and keepalives. Records include `format=json|sse`, `sequence`, and a JSON-encoded `body` value. Streaming frames are logged as they are sent without waiting for the entire response.
These records include `http_id` and `request_id`; `request_id` is `-` before a chat request has been accepted.
The `muse_proxy.upstream` logger records Muse communication before it is converted to the client-facing protocol:
| Exchange | TRACE contents |
| --- | --- |
| Muse application requests | Method, path, stream ID, SDK request ID, and outbound JSON, including `/chat/stream` message, device ID, session UUID, and output modality |
| Muse application responses | Original response status and decoded body, including subscription failures; the SDK acknowledgement envelope containing `ok`, `status`, and `response` is also preserved |
| Subscription events | Decoded NDJSON events before proxy routing, including progress, replies, and task state |
| Connection and registration | WebSocket upgrade outcome, registration/control messages, close outcome, and available error/status details |
| VM lookup and token refresh | HTTP method, path, available response status, and SDK-normalized result; `body_availability=sdk_result` distinguishes this from an original response body |
Correlate the accepted HTTP request's `request_id` with upstream records.
The `router_id` identifies a shared Muse connection, `stream_id` identifies an application stream within it, and `upstream_request_id` identifies the SDK's `x-request-id`.
A subscription can carry events for multiple pending requests; those events are observed before the proxy decides which request receives them.
Shared connection and subscription records use `request_id=-`; follow their `router_id` back to the request's route record.
For example, these illustrative records show a Muse refusal and its body on the same application stream:
```text
TRACE muse_proxy.upstream muse.response router_id=router-example request_id=chatcmpl-example upstream_request_id=sdk-request-example stream_id=7 method=POST path=/chat/stream status=400 headers={"content-type":"application/json"}
TRACE muse_proxy.upstream muse.response.body router_id=router-example request_id=chatcmpl-example upstream_request_id=sdk-request-example stream_id=7 method=POST path=/chat/stream format=json sequence=1 body={"error":"Example rejection reason"}
```
The example's status and error text are placeholders; actual records preserve the upstream values after redaction.
The statuses have separate meanings. A WebSocket upgrade status describes establishing the connection.
A Muse application response status describes that operation over the encrypted connection.
The final proxy HTTP status describes the response returned to the external client.
For example, `muse_request_error` with proxy HTTP 502 can follow a Muse application refusal with a different upstream status.
Inspect the original upstream body and SDK acknowledgement instead of treating 502 as Muse's own status.
VM lookup and token refresh use the SDK's HTTP API. The SDK discards some raw HTTP error bodies; TRACE cannot reconstruct them and records the SDK result with an explicit availability marker.
No additional request is sent to collect diagnostics. Logging observes the existing connection and stream without consuming subscription events a second time.
The Muse records show the decoded application protocol, not encrypted wire bytes.
Credential-like fields are recursively redacted. Recognized values include the configured proxy key and SDK token, loaded Muse access/refresh tokens and VM authentication values, and refreshed tokens.
Credential files are not read just for logging. Client headers and query strings are excluded, and credential fields such as private keys are redacted.
Upstream protocol headers use an explicit diagnostic allowlist: `x-request-id`, `content-type`, `accept`, and `x-app-id`. Authentication, cookie, and other upstream headers are excluded.
**TRACE logs contain private conversation text, submitted history, device IDs, and session IDs.**
For client-facing HTTP logs, malformed request bodies and malformed or partial response bodies use omission markers instead of raw text.
Each submitted JSON body, JSON response, or SSE frame has a 1 MiB logging limit.
If an HTTP response body or frame exceeds that limit, an omission marker is logged and remaining response body logging stops.
Excessively nested JSON is also omitted.
Upstream Muse records and buffered application bodies or NDJSON lines also have a 1 MiB logging limit and use size-limit omission markers when exceeded.
These logging limits do not change the actual response, the existing request-size limit, or the subscription's delivery to the proxy.
DEBUG and less detailed levels exclude request and reply bodies and session IDs. Muse refusals log a safe integer upstream status at WARNING when available.
Proxy request diagnostics include recognized route names rather than arbitrary raw paths.
Use `--log-level debug` for proxy diagnostics without conversation content.
Uvicorn stays at `info` for TRACE and DEBUG because server debug logs can include WebSocket handshake headers.
Other selected levels apply to both proxy and server logs.
The root logger and SDK/network logger levels are left unchanged; Uvicorn's normal access log remains disabled.
When embedding `create_app()` without the CLI, configure the `muse_proxy` logger in the hosting application to receive these diagnostics.
For TRACE, use numeric level `5` (also exported as `muse_proxy.logging.TRACE_LEVEL`); DEBUG uses level `10`.
For third-party clients, first verify base URL `http://127.0.0.1:8766/v1` and the proxy Bearer key.
An unrecognized endpoint returns 404; a wrong key returns `invalid_api_key` (401).
Chat requests ignore the client's `model`; only `GET /v1/models/{model}` requires the configured alias and returns `model_not_found` (404) for other names.
If no arrival is logged at `info` level, check the client destination, listener, and reverse proxy.
Browser-based clients may send a cross-origin `Origin` header or an `OPTIONS` preflight request: origin rejection returns 403,
and preflight requests return 405. CORS and additional API routes are not enabled by logging.
### Process and connection state
The CLI runs one process with one worker. Do not use the same credentials concurrently in multiple processes or workers.
Request-to-reply associations live in process memory. Within one process, credential reload, refresh, and saving are serialized;
connections for different sessions can run concurrently. A replacement connection for the same session waits for the old connection's cleanup to finish.
There is no persistent request/reply queue or stream resumption across restarts.
For external access, choose an appropriate listening address and deploy an HTTPS reverse proxy.
## ๐จ Errors, Disconnects, and Retries
Non-streaming REST and input validation errors use the format `{"error":{"message":...,"type":...,"param":...,"code":...}}`.
The main codes are listed below.
| HTTP status | `error.code` | Meaning |
| --- | --- | --- |
| 400 | `invalid_request_error` | Invalid JSON, input, or unsupported parameters |
| 401 | `invalid_api_key` | Invalid proxy Bearer key |
| 403 | `origin_rejected` | Cross-origin request |
| 404 | `model_not_found` | `GET /v1/models/{model}` requested a name other than the configured alias |
| 413 | `body_too_large` | HTTP body exceeds the size limit |
| 429 | `muse_busy` | Too many pending requests |
| 503 | `muse_credentials_error` / `muse_sdk_unavailable` | Required credential files or SDK are unavailable |
| 502 or 503 | `muse_unavailable` | Communication with Muse failed, no Muse is available, or the proxy is shutting down |
| 502 or 503 | `muse_auth_error` | Muse authentication, token refresh, or a related problem |
| 502 | `muse_request_error` / `muse_connection_error` / `muse_protocol_error` | Muse rejected the send, disconnected, or produced a protocol inconsistency |
| 502 | `muse_task_error` / `muse_empty_reply` | Task failure or completion without reply content |
| 504 | `muse_timeout` / `muse_reply_timeout` | Connection or overall wait timed out |
The HTTP statuses in this table apply when the status can still be set, such as non-streaming REST responses or errors before SSE starts.
A valid `stream: true` request first receives HTTP 200 and a role chunk.
Errors discovered while connecting to Muse, including missing credential files, therefore appear inside an HTTP 200 SSE response.
Proxy key and input validation happen before SSE starts, so invalid values produce non-2xx JSON errors.
Framework errors, such as 404 for an unknown route, do not necessarily use this JSON format.
Once SSE has started, the HTTP status cannot change.
The proxy leaves previously emitted progress and content intact, then sends `data: {"error": ...}` followed by `data: [DONE]`.
It does not send the `finish_reason: "stop"` marker for normal completion. Do not treat `[DONE]` alone as proof of success.
The official SDK treats this error frame as an API error.
A request that receives only progress and ends without a reply or cancel is also treated as an error, rather than normal completion.
Chat Completions responses use these headers:
| Header | Value |
| --- | --- |
| `x-request-id` | Proxy-generated completion ID, assigned after request parsing; absent on authentication and input validation failures |
| `x-should-retry` | `false`; also included on the proxy's JSON errors |
| `Cache-Control` | `no-store` |
| `X-Accel-Buffering` | `no` for SSE |
| `WWW-Authenticate` | `Bearer` on 401 errors |
A client-supplied `request_id` or `x-request-id` is never adopted as the proxy request ID.
The proxy never automatically resends a user message.
Muse may already have accepted a message when a disconnect or timeout occurs, so `max_retries=0` is also recommended for client SDKs.
`Idempotency-Key` is not supported for deduplicating retries.
Receiving progress or replies does not extend the overall timeout.
After the caller's HTTP connection closes, the proxy cannot deliver a termination notification to that request.
## ๐ Muse Credentials and Refresh
Initial pairing uses the official Linux SDK. The Ubuntu walkthrough below is a reference recipe
using the same SDK version as this proxy. See the [official Linux SDK guide](https://github.com/facebookincubator/muse-gadget-sdk/blob/main/linux/README.md)
for current requirements, platform details, and setup guidance.
After pairing, normal conversations and token refresh do not require a smartphone, Bluetooth, or BlueZ.
### Initial Pairing: Ubuntu Example
Use Ubuntu 22.04 or later with internet access, Bluetooth LE peripheral support, a sudo-capable account,
and a nearby phone running the Muse app. Obtain a [Muse SDK token](https://gadgets.muse.ai/settings/sdk-tokens) before starting.
Run these commands in a Bash terminal on the Linux machine:
```bash
curl -fsSL \
https://raw.githubusercontent.com/facebookincubator/muse-gadget-sdk/e6fe5174092702ffddae6f90759a38d55a4ebae1/linux/install.sh \
-o musegadget-install.sh
less musegadget-install.sh
bash musegadget-install.sh --from \
'git+https://github.com/facebookincubator/muse-gadget-sdk@e6fe5174092702ffddae6f90759a38d55a4ebae1#subdirectory=linux'
```
The installer prompts for the SDK token with hidden input, installs dependencies, configures BlueZ,
starts the gadget service, and opens pairing for ten minutes.
The gadget service can execute Muse commands as the selected Linux account; review the installer's account-access prompt.
The download URL pins the installer, and `--from` pins the installed SDK.
When the terminal says pairing is open, use the Muse app:
1. Enable **Settings โ Devices โ Developer mode**.
2. Choose **Add Device** and select the `MuseGadgetXXXXXX` name printed in the terminal. Accept the community-device prompt for your device.
3. When asked for Wi-Fi, select the displayed connection. The Linux machine is already online, so no Wi-Fi password is needed.
4. Wait for `Paired.` in the terminal.
If pairing times out before completing, reopen the pairing window with:
```bash
sudo musegadget pair
```
To replace an existing saved pairing, use `sudo musegadget pair --force` instead.
### Transfer Credentials to the Proxy
On the Linux machine, stop and disable the gadget service, then export the three files as your user:
```bash
sudo systemctl disable --now musegadget.service
install -d -m 0700 "$HOME/muse-auth-export"
sudo install -m 0600 -o "$(id -u)" -g "$(id -g)" \
/var/lib/musegadget/identity.json \
/var/lib/musegadget/pairing.json \
/var/lib/musegadget/sdk_token \
"$HOME/muse-auth-export/"
```
Securely transfer `muse-auth-export` to the proxy host, for example over SSH or using a USB drive.
Pairing may take place on a different machine from the one running the proxy.
From the proxy project directory, import the files with the following Bash commands, replacing the source path:
```bash
install -d -m 0700 data/muse
install -m 0600 "/path/to/muse-auth-export"/{identity.json,pairing.json,sdk_token} data/muse/
```
This example uses the default `state_dir = "data/muse"` and a `proxy.toml` in the project directory.
Use your configured `state_dir` if it differs. For an existing proxy installation, stop the proxy before replacing its credentials.
Once the files are in place, start the proxy as described in the [Quick Start](../README.md#quick-start).
| File | Contents |
| --- | --- |
| `identity.json` | Device identity information established during pairing |
| `pairing.json` | Access token, refresh token, connection details, etc. |
| `sdk_token` | SDK token used during pairing; optional if supplied through the environment or configuration |
Keep the original gadget service disabled so it does not use or refresh the same credentials concurrently.
If a saved SDK token hint is present, the same token used for pairing is required.
Changing the proxy's `api_key` does not require pairing with Muse again.
### Automatic Refresh and Storage
Before connecting for a conversation, the proxy refreshes the access token if at least three hours have passed since it was saved.
A 401 from the VM retrieval API also triggers a forced refresh for subsequent connections.
This is not a background timer that runs every three hours.
A 401 when sending a message also triggers a credential refresh attempt, but the message is not automatically resent.
Refreshed access and refresh tokens are saved by replacing `pairing.json`.
If the refresh token is rejected, pair again and replace the credential files.
`init` creates `proxy.toml` with mode 0600; refreshed `pairing.json` files are also saved with mode 0600.
On Unix, use mode 0700 for the credential directory and 0600 for each transferred file, and grant the runtime user write access.
Treat credential files and configuration as secrets; do not commit them or distribute them to clients.