docs/cmd/ezagent-muse-code-bridge.md
Muse Code bridge
ezagent-muse-code-bridge --stdio adapts the dedicated external-model-provider
protocol to the official installed muse serve MSP host. Build it with
just build-muse-bridge, or install it from the Linux distribution, including
with --minimal. Linux is supported; other platforms
refuse native launch because owned process-group cleanup is Linux-specific.
Install Muse and complete its sign-in and native setup in the official app before configuring EzAgent. EzAgent reuses that login; it does not install Muse or manage credentials. Routine leaf/session use does not require reopening the official app. Reauthentication or other exceptional native maintenance may still require it.
In the configurator, choose Muse Code (subscription login) when adding a provider to prefill its name and the executable sibling of the physical configurator when available. Otherwise the command is a PATH basename. Use Advanced command settings to edit it, or choose Custom external command for another executable. Choosing a profile does not launch the bridge or save configuration. Discovery is explicit; an empty result does not establish why no models were listed, and native catalogs may be incomplete.
Example provider configuration:
| 1 | providers: |
| 2 | muse: |
| 3 | type: external |
| 4 | command: /absolute/path/to/ezagent-muse-code-bridge |
| 5 | options: |
| 6 | muse_command: /home/developer/.local/bin/muse |
| 7 | models: |
| 8 | - name: muse-spark-1.3 |
The shared launcher adds --stdio; do not repeat it in args.
The command option must be an absolute executable path or a basename resolved
through absolute PATH entries. The bridge rejects unknown options and supplied
authentication. It preserves the official launcher's HOME/config login resolution,
selects provider meta, checks the returned model ID, and excludes META_API_KEY.
It does not read or copy authentication files, use a direct inference endpoint,
or choose a fallback model.
For trusted-machine forwarding, set remote_eligible: true on this provider
and save its host/muse/muse-spark-1.3 ref on the consumer. See
minimal host/consumer setup.
just test-remote-muse-live exercises the real local bridge followed by a second,
credential-free daemon through AF_UNIX. It needs prebuilt artifacts and an existing
native login, never rebuilds implicitly, and is excluded from ordinary test runs.
See live acceptance prerequisites and diagnostics.
Model discovery
ezagent-muse-code-bridge --list-models reads one JSON object from stdin,
then writes one JSON catalog and exits. The input has protocol: 1, an
options object with the same optional muse_command, and no supplied auth.
Discovery uses the official subscription login and a private native workspace.
It calls native initialize and model/list, without starting a session or
generating a response. The native result's string source (for example
providerCatalog or bundledCatalog) is copied verbatim to the catalog's
optional source; a missing, non-string, blank or oversize native value is
omitted without failing discovery. Native warnings are informational; errors are generic
and never include native diagnostic text. Input and output are limited to 1 MiB.
The official host uses the native user's catalog data location during discovery:
an absolute XDG_DATA_HOME, or the HOME-based default when unset or relative.
Discovery keeps temporary files, cache, state and runtime in scratch. Native
inference sessions still use isolated data and do not share that catalog location.
The bridge reports native model IDs, display labels, hard context limits and
known reasoning variants. Missing values remain unknown. For the included Muse
setup, the model editor suggests the reported hard context limit as the operating
max_context, or 1,000,000 when the limit is unknown. Manual entries use a
cached limit for the entered name when available. This is a default, not a
backend recommendation. Save or activate the model to stage the default, then
use Save and Exit to write the YAML. Back/Escape leaves an untouched suggestion
unstaged; edits to an active model still stage in memory as usual. Existing
configured budgets take precedence. Native output ceilings are not imported as
max_tokens because the bridge cannot enforce them.
Cold, offline or partial native catalogs can be incomplete or empty and do not
establish account entitlement. Existing configured model IDs remain usable when
discovery fails or does not list them.
Native tools and workspace
Muse gets an owned private run directory under
$XDG_STATE_HOME/ez-agent/muse-sandbox/<session-id>/. Its CWD, workspace root,
mutable state, cache, runtime and native session logs stay there. EzAgent's
scheduler still executes offered tools in the actual project CWD. Native process
retirement removes the run directory and its logs.
The selected ez-agent application state directory may be a symlink to a
relocated private directory. The bridge opens that target and checks ownership
and permissions before entering muse-sandbox. The target must be owned by the
current user, with no group/other permissions or sticky/set-ID bits. Managed
sandbox, session and run directories must not be symlinks. New directories use
mode 0700; existing directories are never chmodded. Cleanup stays anchored to the
opened session directory and refuses to remove a replaced run.
Launch uses the supported empty preset, run.toolset=["mcp__ezagent__*"],
run.reminder_roster=[], and run.parallel_tool_calls=true, with the native
user-input tool separately disabled. The bridge does not pass the redundant
shell and write suppression flags; the toolset restricts model-selectable tools
to the mcp__ezagent__* namespace and excludes native tools. It does not exclude
inherited MCP servers from startup. Model discovery keeps run.toolset=[].
The native sandbox stays on
with restricted networking. Only the current finalized EzAgent tool snapshot is
exposed through a required stdio MCP server authenticated to its Unix owner. This selection
excludes model-selectable delegation, workflow and scheduling tools
without enumerating tool names. Unexpected native activity or concurrent MCP
calls retire the native session; these checks supplement configuration rather
than prove that no hidden execution could ever occur.
Native Muse launches the same absolute bridge executable with --mcp-relay ADDRESS.
That helper only forwards bounded MCP JSONL after a private Unix authentication
hello; it never starts Muse, executes tools or loads native credentials. No TCP
MCP listener is opened. The independent random check reaches the helper through
supported MCP child env forwarding, not argv, logs or model content.
--mcp-socket auto|abstract|filesystem selects the Unix policy. Linux auto uses
abstract sockets with no files; other platforms use private filesystem sockets.
An explicit unsupported abstract fails. In provider configuration, put
--mcp-socket=filesystem in args when needed; the launcher adds --stdio.
Filesystem sockets use a private directory below process scratch, restrictive
permissions and identity-checked cleanup. The daemon-owned outer scratch is the
crash-cleanup backstop. A clean idle native reconnect preserves process-wide
RPC-ID replay tombstones; uncertain tool work is never replayed after a disconnect. See the shared
relay protocol and lifecycle.
Before launch, the bridge writes its server to .mcp.json in the private run
directory, with file mode 0600 and tool_timeout_sec: 86400, a one-day budget
for each native MCP call. It uses project configuration because the
session-supplied MCP type does not apply that timeout. The server URL and
authorization header stay in the private file, not in model input. This budget
does not extend a host tool's own timeout or disable cancellation. A native
disconnect can still require the recovery described below.
Global MCP configuration is not isolated. On installed Muse 1.4.20-R8619.1,
the private project's ezagent entry wins over a same-name global entry, but
unrelated global entries are merged and started, including stdio processes,
even when absent from run.toolset. HOME and XDG_CONFIG_HOME remain inherited
for official login resolution. XDG_STATE_HOME, XDG_CACHE_HOME, XDG_DATA_HOME,
XDG_RUNTIME_DIR and TMPDIR are private for inference sessions. The bridge does
not read, copy or rewrite auth files. The observed project precedence selected
the bridge-owned endpoint; no wrong-endpoint selection was observed. It does
not exclude other user-configured MCP servers from startup. Treat those servers
as inherited native configuration, not as isolated by EzAgent. The bridge does
not refuse startup or relocate the official login because of this limitation.
Each offered tool gets a readable MCP registration name, ezagent_ followed
by up to 24 sanitized label characters and a 16-character SHA-256 suffix.
Names are at most 49 ASCII bytes, or 63 with the observed native record
namespace. The digest distinguishes labels that sanitize alike; an actual
digest/name collision rejects the snapshot. Names are stable across snapshot
ordering. Dispatch uses only the exact reverse mapping, for every offered tool,
including tools added outside the defaults.
The authenticated endpoint, exact-name mapping, replay protection and held-result
delivery are owned by the shared internal/bridgemcp
package. Muse's thin adapter retains its descriptions, diagnostics, single held
call, 4,096-request ceiling and prohibition on catalog updates while held.
Muse 1.4.20-R8619.1 exposes the complete multi-call boundary through the
experimental turn/toolBatchSubmitted notification, not the stable schema.
TurnToolBatchSubmittedParams.calls contains every call's callId, tool and
verbatim args in model order, before any call starts. It applies to batches of
two or more calls. SubmittedToolCall documents the join to subsequent
toolCall items by callId. The event is ephemeral, has no sourceRange, and
is never journaled or paged back. session/read cannot reconstruct it.
Delivery requires initialize.capabilities.experimentalApi: true, without
opting out of that notification, and a live view subscription before the turn
starts. session/start automatically subscribes the connection from its
returned view head; view/subscribe explicitly reattaches a detached view.
A gap cannot be repaired into a complete call list by reading public history.
The opt-in native transport API CollectToolCalls observes these events before
public filtering. Its NativeCallCollection retains one full batch, bounded to
64 calls and the existing 16 MiB frame budget, separately from one held MCP
handler. A live item/started supplies a singleton when no batch was submitted.
This requires the negotiated live batch-event stream, not a timeout or an
assumption about serialized handler arrival. The collection validates native
item identity and permits held-call matching only with an independently
obtained provider NativeID, exact registration and matching arguments. It
never executes tools or releases MCP responses.
The bridge's host-facing path accepts one whole-batch done/tool_calls event
and requires exactly one finalized result for each pending provider ID on the
next request. It rejects missing, duplicate and foreign results before delivery.
Its batch delivery code releases the original MCP handlers serially; it does not
wait for every serialized handler before yielding the batch. Cancellation retires
the pending batch and native owner. Partial or uncertain delivery cannot be
replayed through readable-history recovery.
The required native interface is verified against Muse 1.4.20-R8619.1.
Multi-call model support is not experimental; the MSP
turn/toolBatchSubmitted notification used to observe the complete response is
experimental. Production startup requests experimentalApi: true and installs
CollectToolCalls before turn/start. If initialize omits or declines that
acknowledgment, startup fails with Muse initialize: unavailable before
initialized, session/start or model input. There is no singleton fallback
or alternative launch mode.
The MCP adapter also requires the exact provider ID from
tools/call.params._meta.callId, supplied by this verified version. Missing or
malformed identity retires the endpoint before host admission and reports
Muse stream: mcp_fault (native_id_mismatch). The collector validates the ID
against the authoritative native list, tool registration and arguments. It
waits for the native opening if MCP arrives first, selecting on cancellation
and transport closure rather than using a timer. For either interface failure,
check the configured native executable and run the installed-native contract
fixture. The bridge does not replay an accepted turn or uncertain tool delivery.
Launch sets run.parallel_tool_calls=true for the owned MCP toolset so a model
can submit several calls in one response. The catalog explicitly declares
readOnlyHint:false; native tools, shell and orchestration remain disabled.
Shared MCP still rejects overlapping handlers. Muse 1.4.20-R8619.1 serializes
these handlers and consumes both results before its next inference request.
just test-muse-batch-native /absolute/path/to/muse-bin-VERSION checks that
installed behavior through the production backend using a loopback fake API,
equal-argument calls with distinct IDs, private login-free roots and no online
inference. This checks the required native adapter interface, not inherited
configuration exclusion or the live two-file daemon smoke.
After delivery, the collector retains bounded call-identity digests so delayed native item notifications cannot recreate a delivered call or replace another pending batch. Identity reuse within the same native turn is ambiguous and rejected; a different turn may reuse the ID. Closing the collector clears this bookkeeping.
The opt-in just test-native-two-file-live muse/muse-spark-1.3 smoke requires
one two-call model response, serial reads of two real files, both finalized
results on the immediate next provider request, and an answer using both files.
Two successive single-call responses fail. The recipe builds only its required
worktree artifacts, reuses the installed login and isolates all three XDG roots.
Offline coverage establishes the daemon's batching behavior with a fake Muse
process. Live model acceptance is separate. See
two-file acceptance for offline coverage,
exact model selection and cleanup.
An unavailable MCP tool name is recoverable when the bridge itself rejects it
before host dispatch. It returns ordinary MCP tool-result content with
isError: true, the same shape used for host tool errors, rather than a
JSON-RPC client-protocol error. Within a 2 KiB budget, the text says nothing was
dispatched and pairs host labels with MCP registration names. It directs the
model to its supplied function definitions for callable spellings and schemas.
The bridge does not claim that native record names are model-facing names.
This lets the model
correct its selection in the same turn without user Retry. The bridge never
fuzzy-matches or executes a replacement, starts a corrective turn, or replays
an action. The initial handoff also directs Muse to correct unavailable
selections using the offered names. Internally a new choice needs a new request
ID, but the feedback does not ask the model to manage client protocol IDs.
Offline fixtures verify MCP error delivery and subsequent exact-name admission;
they do not establish model behavior or the native client's name transformation.
The shim's no-dispatch decision is joined to the native call ID, name and
arguments, regardless of which transport opens first. Rejected entries retire
without host results, including a fully rejected batch. Bounded identity
records validate late native lifecycle events without reopening rejected calls.
A mixed batch yields only offered calls to EzAgent, in model order, while the
collector retains the complete native list. Serialized delivery waits for exact
no-dispatch rejection of every unavailable entry, even after the final offered
result. No additional host completion or intermediate inference is needed for
those rejected entries. A fully unavailable batch returns selection guidance
without yielding a host call and can proceed directly to a corrected selection.
Waiting for a native opening or trailing rejection also ends on cancellation or
transport closure, retaining the shim's failure diagnostic. MCP-first rejection
checks native replay only after joining the turn ID, so a later turn can reuse a
call ID without weakening same-turn protection.
Replay, concurrent calls while a host call is held, and uncertain response
delivery still fault the session; rejected calls do not displace a held call.
Native unavailable-tool recovery remains unsupported. The offline stable and
experimental MSP schemas exported by Muse 1.4.14-R7309.1 expose item status,
open-string failureKind, and free-text failureReason, but no typed
bad_args_kind: unknown_tool projection or documented failure class proving
that an unavailable function never executed. Failed or rejected status alone
is insufficient. held: true describes a call held before admission at that
observation, not permanent rejection, and notifications cannot intercept
execution. The guard still stops unrecognized tool-call records and native
orchestration, including before later session filtering. It conservatively
covers foreign-session activity on the owned connection too. These native
reports still stop the session; MCP correction does not apply to them.
Muse must support session/read with native session logs enabled. Memory-only
sessions do not support the public-history read needed by this bridge. Help/config acceptance
and fake activity tests are not proof of universal native-tool exclusion.
Native sandbox/registry/stderr warnings are informational. Only a failed
required operation or protocol violation fails the request.
Public history and tool checkpoints
Initial and replacement context is an explicitly labeled, role/tool-aware
public-history handoff, not an arbitrary native history import. Canonical inline
JPEG, PNG, GIF and WebP image data is sent as native image input, with labeled
references preserving its message, part and role in the transcript. Historical
images are replayed on fresh handoffs, but not on exact held-tool resumes or
settled-session continuations. A continuation sends only new inputs and images;
image labels preserve their roles and indices in the full host history.
Remote image URLs, malformed data and unsupported media or content parts are
rejected before model work; the bridge does not fetch URLs or read image paths.
Images are limited to 8 MiB decoded, with at most 4096 content parts and a
16 MiB bound on both the serialized context and projected history with image
payloads. The latter excludes bridge-added text such as the workspace preface
and tool names; the native transport separately enforces its 32 MiB frame limit.
Before that handoff, the bridge explains
that EzAgent MCP tools use the actual project CWD from conversation metadata,
not Muse's scratch workspace or its native sandbox restrictions. Bridge-exposed
descriptions clarify the CWD for buffer, write_file and run-cmd. The
Muse-specific run-cmd description also explains that a finite timeout stops
the command, not just waiting for it. timeout: "0s" disables the deadline;
background: true does not. Bash expiry sends SIGKILL to the owned process
group, but cannot undo earlier side effects. The reminder asks Muse to verify
their state before retrying. Other providers' tool descriptions are unchanged.
Host instructions, active modes and approvals still apply; this does not grant
write permission. Exact tool-result resumes do not repeat the handoff. Muse's own
system additions remain intact.
An MCP request holds the native result while the bridge reads the full ordered
public history with session/read. The native read is a point-in-time fold,
not a guarantee that a held MCP call has settled earlier public items. The
bridge requires every public assistant/reasoning item in that checkpoint to
have explicit status: completed before projecting missing text and returning
the tool call. Open items, missing status, failed items and unknown statuses
fail with Muse public_read: protocol (item_not_completed) and retire the held
native work. The bridge does not seal an unfinished prefix or guess whether
later deltas belong before the tool result. Distinct visible assistant items use
the nonterminal assistant_boundary event. The Agent finalizes the earlier
assistant through normal lifecycle admission and opens the next streaming
assistant before it schedules any tool. Delayed MSP notifications for completed
checkpointed item IDs are not emitted again under the next provider request.
Native turn identity gates terminal completion. Internal bookkeeping does not
create public turns.
When Muse marks a reasoning item truncated, the bridge retains coherent
observed summary prefixes in part order and adds a single annotation that the
item was marked truncated. The available summary may be incomplete; the flag
does not identify which part was cut. Conflicting prefixes and truncated
assistant text still fail the request. The bridge does not inspect private
native logs to reconstruct reasoning or invent provider reasoning data. Held MCP calls resume with their tool
result; the MSP turn/start contract has no reasoning replay or truncation
acknowledgement field.
The bridge tracks the owned session's latest observed session/contextUsage
notification and annotates output and terminal events with its usedTokens.
Installed Muse may publish no such notification during a turn, so the bridge
also samples native metadata before each tool yield and after a native turn
completes. A version-1 session/read snapshot's contextUsage supplies the
measurement; at a tool yield this is the snapshot already read for the public
checkpoint, and after completion the bridge reads session/read again.
When unavailable, the bridge reads one backward view/page, limited to 64 events
and 256 KiB, for the latest owned context fact or the current native turn's
counted-once model-completion total. The latter is native promptTokens plus
output, not the session's cumulative usage or a client-derived cache estimate.
The optional reads share a two-second deadline; missing or failed optional
reads leave the last observed measurement intact and do not fail the yield or
completion. If the request is cancelled or the shim or native transport fails
while a yield-time read is outstanding, the turn fails instead of yielding the
held calls.
A snapshot or notification reports Muse's usedTokens directly. The
session/tokenUsage fallback is a counted-once prompt-plus-output occupancy
floor at the latest native reported durable fact. Neither is billed usage.
Measurements can decrease after a context reset,
and queued notifications may lag a tool yield. Missing measurements remain
unknown. Native usage is not reported as billing because attribution across
held MCP calls is not established.
On failure, the bridge attaches the last observed snapshot to its existing safe
informational event before retiring the native session.
For multipart reasoning, the bridge streams summary field 0 as it arrives and holds later fields until the completed item supplies their final values. It checks streamed prefixes and emits the remaining text in field order. An unfinished reasoning item cannot be overtaken by another public item; the bridge fails the request rather than publish unprovable ordering. Later summary fields therefore have completion-time latency.
The checkpoint requires a complete inline or version-1 snapshot envelope to establish public ordering. Only assistant text/reasoning is retained and checked for completed status, identity, consistency, truncation and public-output limits. Harmless native bookkeeping is discarded before buffering; its IDs, unrelated fields and item count are not continuation requirements. Forbidden native activity is checked before that filtering. The bridge does not wait for native tool execution to finish before yielding its call.
The native transport and public inbox each retain at most 256 entries and
32 MiB of original method, ID and parameter bytes. Adjacent string deltas with
identical non-delta parameters share one entry, preserving their text order.
Different items, fields, sessions, extensions, requests and item/control events
are not merged across a boundary. Duplicate keys, case-fold aliases and
non-ASCII parameter names are passed unchanged rather than canonicalized.
Coalesced text is chunked conservatively so JSON escaping cannot turn individually
admissible deltas into an oversized public output frame.
Every original delta still counts toward the
byte bound, including after transfer between the inboxes. This lets a delayed
session/read receive fragmented public output without exhausting one slot per
fragment. Buffering does not publish that output or prove completion: the same
explicit completed-item and full-snapshot checks still apply before tool yield.
Non-coalescible entry floods and byte overflow still fail the owned session.
Native admission failures retain fixed limit (native_inbox_full) or
limit (native_inbox_bytes) diagnostics at the native RPC/stream stage. Public
inbox failures retain their mcp_fault (public_inbox_full) or
mcp_fault (public_inbox_bytes) reasons. Unknown native errors remain generic.
Only the next finalized completion can release the exact held MCP request, with the admitted processed text and error status. All projected assistant turns, model, reasoning level, tools and tool identities must still match. Rewritten context, additional input, replacement or changed settings instead retires the old native work and starts an explicit fresh-session handoff. There is no raw result or preplugin channel into the bridge.
After done with stop reason stop, a healthy native session remains resident.
The next finalized completion can start turn/start in that same session with
only its new user, developer or system inputs. Background-completion followups
use this ordinary suffix path. The bridge compares the entire previously
accepted context plus every emitted assistant message against the committed
history. Text, readable reasoning, assistant boundaries, tool identities and
results must match; nil and empty text content are equivalent. Provider output
is not assumed to have been inserted into the daemon's context shadow. A full
context replacement preserves this settled checkpoint only when the whole
semantic prefix matches. Changed earlier input or output, an assistant or tool
suffix, changed model, thinking level, tools or settings, or invalidated native
state requires a fresh full-history handoff. Actual system and mode instruction
changes are never discarded to force reuse. Held-tool checkpoints keep their
stricter replacement-epoch rule. Assistant model and provider provenance is not
part of the replayed transcript or either continuation check. A replacement
that changes only provenance in the accepted prefix does not invalidate a held
tool call.
Every text and reasoning item must have an observed item/completed before a
successful turn can settle. An open text item at turn/completed fails with
Muse stream: protocol (assistant_text); the bridge does not seal partial text and suppress a
possible final suffix. Nonempty deltas after an ordinary item completion and
before turn completion also fail rather than extending an already-final item.
An explicit non-completed item status is rejected before any final text or
reasoning suffix is emitted; already-streamed chunks remain part of the failed response.
Checkpoint-sealed items keep their separate delayed-duplicate suppression.
Completed item identities remain as bounded tombstones,
but their text and reasoning bodies are released. Public item identities and
completed-turn tombstones are bounded to 4,096 per session. Reaching the turn
tombstone capacity disables reuse on the next invocation rather than evicting
old identities. MCP request replay tombstones also survive continuation.
The session-owned idle drain retains no invocation callback. Known delayed
duplicates are discarded even during later turns. Unexpected idle public items
invalidate continuation, idle MCP calls fault without host dispatch, and newly
observed items on continued turns must identify the current native turn. Idle
native process or shim failure permits a full-history handoff before attempting
turn/start. Once that call is attempted, failures do not automatically replay
the invocation, even if no output has arrived. Per-turn output and context
measurements reset without resetting session-level replay protection.
Each shim retains SHA-256 tombstones for up to 4,096 admitted or unavailable-name
rejected tools/call request IDs. Reusing an ID faults the session before another host call is
emitted, including while the original call is held or its response is being
written. Tombstones are never evicted; the next new tool request after the
limit faults the session. They retain no raw IDs, arguments or results.
JSON string IDs are decoded before hashing, so equivalent escape spellings
have the same identity. All MCP request IDs have a 1,024-byte encoded limit.
Numeric IDs must be decimal integers of at most 128 bytes, including an optional
minus sign; -0 and 0 share identity. Fractional and exponent forms are
rejected, without floating-point conversion or exponent expansion. String and
numeric IDs are distinct. Invalid IDs are rejected before tool admission.
Distinct new IDs with identical arguments remain legitimate sequential calls; arguments are not deduplicated. Concurrent calls with distinct IDs still fault while a call is held. Replay protection belongs only to this shim's native session. It does not provide cross-restart exactly-once execution, undo tool side effects, or prove that a model or MCP client actually retried a request.
Failure diagnostics
Normal terminal-failure diagnostics do not require EZAGENT_MUSE_TRACE. The
bridge sends the specific check through its existing informational/error
messages. The daemon
writes one Muse provider request failed record with the safe diagnostic,
daemon-owned leaf_id, and turn_id when available. Saved error turns and
terminal notifications explain the check and its measurements independently of
the deployment's log sink.
Log location depends on how the service was launched. EZ_AGENT_LOG_FILE is used
when it opens successfully; otherwise logging goes to service stderr. Client
auto-launch captures service stdout/stderr in
config.StateDir()/ez-agent-service.log, commonly
$XDG_STATE_HOME/ez-agent/ez-agent-service.log. That capture is truncated on each
auto-launch, so save it before restarting. A direct or supervised service may
send stderr elsewhere or discard it. Use the initialization record's actual
destination, pid and usable log_file fields, plus the launcher's stderr
redirection. Configured-file open failure logs open_failed and falls back to
stderr. Configuration alone does not establish the sink. See the
service logging guide. Match the process/run and the
leaf_id/turn_id, not just a similarly named old log file.
Local checks preserve the observed expression, configured bound and unit, for
example Muse stream: limit (reasoning_bytes; observed=33554433; limit=33554432; unit=bytes). The human error reports both numbers too. Counters
are validated bounded canonical decimals; no raw native text, paths, tool
arguments/results or credentials enter diagnostics.
| Check | Retained evidence |
|---|---|
| Native/public notification queue | Entries versus original accounted bytes, including all coalesced input bytes; 256 entries and 32 MiB. Queue closure is not an overflow. |
| Full public checkpoint | Separate item count and accumulated per-item envelope bytes; 4,096 items and 32 MiB. Missing item ID is a protocol error, not a count limit. |
| Assistant/reasoning output | Per-item assistant bytes, summary parts and summary bytes; 32 MiB, 4,096 parts and 32 MiB respectively. |
| Outer bridge output | Aggregate text/reasoning bytes, assistant message boundaries, and encoded output frame bytes are separate checks; 32 MiB, 4,096 boundaries and 32 MiB. |
| Input/transport frames | Encoded outbound bytes include the JSONL newline. Host/native scanner failures retain capacity and an explicit lower bound on buffered bytes; the full rejected frame size is unknown. |
| Host context/images | Serialized and projected context bytes, content parts, base64 image bytes and decoded image bytes are separate checks. Context is limited to 16 MiB, decoded images to 8 MiB, and content to 4,096 parts. |
| MCP terminal faults | Offered snapshot bytes, encoded result bytes and replay-tombstone count; 32 MiB, 32 MiB minus 8,192 bytes and 4,096 requests respectively. The result reservation covers the maximum escaped RPC ID, JSON-RPC envelope and newline. |
| MCP inbound frame rejection | A frame exceeding 32 MiB closes that relay without dispatching it. An otherwise idle owner permits a clean reconnect; outstanding tool work retires the owner without replay. |
Muse's structured native inputTooLarge, pageEventTooLarge and
outputResultTooLarge refusals keep those exact fixed kinds on both JSON-RPC
errors and turn/completed error notifications. For inputTooLarge, the
bridge retains the documented integer ErrorData.limitBytes as a byte bound
without inventing an observed size. Negative, malformed or out-of-range bounds
are omitted without losing the error kind. When no usable measurement survives,
the human error says the diagnostic has no size or bound, not that Muse supplied
none. These diagnostics do not trigger automatic retries or image reduction.
An incomplete public history is not labeled a measured size overflow. The
checkpoint distinguishes anchoredSnapshot, unsupported modes, and none with
known reasons excluded, cursorSuffix, historyBudget,
projectionUnavailable, or projectionReadLimit. Missing or unknown reasons
use a fixed unknown label, never native prose. These histories cannot establish
the full item ordering required for a tool yield. A native history-budget or
projection-read-limit explanation has no sizes unless the native contract
supplies them.
The first known fault survives cancellation and exact-owner parked retirement. Invalid or oversized bridge output produces an error, not a user-cancelled terminal. Oversized host scanner input during an active request also produces a safe error instead of appearing as normal EOF. If the host will not read output or the transport is already broken, a diagnostic cannot be delivered over that same connection; the daemon can retain only its transport-failure explanation. Pre-handshake input without a usable request ID likewise cannot receive an invented terminal response.
EOF, cancellation, incompatible replacement, shim faults and process failure retire the
owned native process group, MCP handlers and scratch. Diagnostics expose only
bounded stage/category labels, including structured RPC categories and fixed
stream protocol guard labels. A failed turn/completed classifies its error kind
like an RPC rejection: overloaded and backpressured become rate_limited
(quota and request-denial flags still take precedence), without granting replay.
When the owned native process ends without a terminal frame, an already-reaped
nonzero exit status or allowlisted signal class is kept as a fixed
native_exit_<1-255> or native_signal_<name> reason, for example
Muse stream: unavailable (native_exit_42). Stderr is never forwarded. A
rejection the backend has already processed, or a known shim fault, remains
primary. Native process death does not outrank frames already decoded into the
backend's public notification queue, such as a terminal rejection: the stream
consumes them in order first, and only an empty queue reports the dead transport.
Frames still in the transport's raw inbox, not yet forwarded to that queue, are
outside this guarantee. The bounded stdout-EOF grace only orders the transport's
reader and waiter.
Unknown native errors remain generic; raw
diagnostic prose and native payloads are never forwarded. The daemon records
these exact fixed labels in service logs, for example
Muse stream: protocol (reasoning_index). Native tool guards retain fixed
native_tool_failed, native_tool_rejected, native_tool_completed,
native_tool_in_progress, native_tool_cancelled, native_tool_timed_out, or
native_tool_unconfirmed reasons on both the event stream and public checkpoint;
native orchestration retains native_activity. Human explanations describe a
reported record with unverified effects, not proven native execution.
Native-activity and view-gap diagnostics also carry bounded incident evidence
in the existing error message. Both the normal service log and the saved error
retain it, without requiring trace output or native files that retirement
deletes. It includes the original stream or checkpoint path, event method,
item kind/status, and an independent random run-generation token. A checkpoint
uses a synthetic item/completed envelope; its path remains checkpoint even
when the reporting stage later becomes resume.
Item IDs and tool names have 16-hex-character SHA-256 fingerprints, not raw
values. Fingerprints permit comparison but are not encryption or authorization.
The name label is run-cmd, buffer, write_file, offered for another tool
in the snapshot, or unknown. Recognition checks the whole offered catalog,
not the defaults. Name length and prefix class survive for unknown names.
A catalog fingerprint identifies the sorted registration names, not schemas.
These comparisons do not add dispatch aliases or change the activity guard.
The evidence also records the most recent processed MCP request's fingerprint,
name fingerprint and state, plus the admitted-or-rejected request count. States
distinguish rejection, admission, result release and response write. This is a
snapshot, not a request history or proof of execution. This diagnostic does not
encode the adapter's provider-call-ID join. Native item IDs alone do not identify
MCP requests, so its correlation field remains unknown. A successful
write does not prove recipient delivery. The first stream fault freezes its
evidence under the admission lock, before retirement can discard the shim.
Optional EZAGENT_MUSE_TRACE=1 traces retain their smaller fixed-label identity
set; non-default names may still appear as unattributed there. Native failure
prose, raw IDs, arguments, results and auth are never included in diagnostics.
Terminal notifications and saved error turns explain the failure in ordinary
language and append the exact validated, non-secret diagnostic, including
incident evidence for native guards. They
distinguish setup/login, provider limits, tool
connection failures and safety guards. Independent background work is preserved;
real failures are not hidden or treated as authorization to replay tools.
For stream and resume, the mcp_fault category can include a fixed reason:
request_disconnected, response_delivery_failed, parallel_call,
duplicate_request, replay_capacity, native_activity, view_gap,
public_event_invalid, public_inbox_bytes, public_inbox_full, listener_failed,
request_id_failed, or shim_closed. view_gap is separate from forbidden native
activity. Inbox reasons distinguish the byte bound from the
coalesced-entry bound. shim_closed identifies an unavailable or already-closed
relay without an underlying fault, rather than inventing a disconnect cause.
Unknown faults remain generic; raw errors are never substituted for a reason.
The first shim fault survives parked child retirement. On the next finalized
completion, if the bridge observes resume: mcp_fault (request_disconnected)
before releasing a held result or sending new native input, and before any new
model output, it automatically starts one fresh native session with the full
finalized EzAgent history. This includes the recorded tool calls, processed
results and error status, historical images, and any intervening steers in their
original order. Recovery applies both to an exact tool-result resume and to a
full finalized handoff selected by the context matcher. It does not
append a synthetic user recovery message or dispatch the completed host tool
again. The bridge reports this continuation as informational. The fresh model
may still independently request tools. Cancellation stops the continuation; a
failure in the fresh session is reported without another automatic attempt.
Other faults are reported on the next continuation. In particular, the bridge
does not retry uncertain response delivery: a response write succeeding is not
proof that its recipient received the result. These reasons contain no native
IDs or payloads. A disconnected held request retires native ownership, but
does not itself cancel a separately dispatched host tool or undo its effects.
Include the saved error and, when available, the matching service log when reporting a failure. Manual retry starts fresh
native work; these diagnostics do not authorize automatic replay of a failed
request. Neither an MCP fault nor a tool timeout establishes that Muse retried,
and timeout failures can affect foreground and background command use.
The bridge optionally reads the owned native host's subscription usage around
execution and coalesces usage/changed notifications before the public queue.
A recent, well-formed observation within its current window can identify the
route as muse_subscription. It does not assert a paid plan or active
entitlement; percentages above 100 are still observations. Missing, invalid,
future or expired evidence is unknown. The daemon keeps this non-secret route
live observation only for the unchanged admitted provider and model until expiry
or unload. Separately, it remembers the last reported access source in ordinary
leaf properties. Idle and unloaded lookups retain that label, including after
restart, until new information replaces it. No native tier, usage values, or
observation timestamps are published or persisted.
Timing diagnostics
Set EZAGENT_MUSE_TRACE=1 in the bridge process environment to write JSON timing
records to stderr. For daemon-managed providers, also add EZAGENT_MUSE_TRACE to
that provider's existing pass_env list; exporting it only in the daemon's
environment does not bypass the provider launch allowlist. The shared launcher
discards provider stderr, so forwarding the variable alone does not retain a trace.
To capture daemon-managed runs, point the provider command at an executable wrapper
that exports the switch and redirects stderr to an existing private cache directory:
| 1 | #!/bin/sh |
| 2 | umask 077 |
| 3 | export EZAGENT_MUSE_TRACE=1 |
| 4 | exec /absolute/path/to/ezagent-muse-code-bridge "$@" 2>>/absolute/path/to/private-cache/muse-trace.jsonl |
The launcher supplies --stdio through "$@"; the wrapper must not add it again.
No authentication file needs to be read or copied. Tracing is off by default.
A single process-wide worker writes records from a bounded 256-record queue.
Trace call sites never wait for sink I/O. When the queue is full, new records are
dropped, so traces can have gaps and unmatched start/end records. Event timestamps
are captured before enqueueing. Shutdown does not join the writer or flush the
queue; queued records can be lost on exit. A stalled stderr sink cannot block
invocation cancellation, held-result delivery or MCP teardown through tracing.
Records contain only bridge-owned phase,
method and route labels, process IDs, counts, sizes, success flags and durations.
They contain no native request IDs, conversation text, image bytes, tool arguments,
results, credentials or raw native errors. This does not enable native stderr or
private-log forwarding and does not change provider frames or retry behavior.
At native completion, native_token_usage records can include the owned public
sample's reported prompt, input, output, reasoning and cache counters. Each record
is a sample, not an amount to add to daemon usage. Cached-token and cache-read
fields can overlap; do not add them together. Missing counters remain absent,
foreign session/turn samples and invalid counters are ignored, and cumulative
native totals are never copied. Reported cache reads show reuse at the native
provider boundary, not how long backend queueing or processing took.
Tracing may make one bounded view/page read even when the context snapshot was
sufficient. It shares the existing two-second optional-metadata deadline and
cannot replace snapshot occupancy or affect billing. Without tracing, the existing
optional-read behavior is unchanged.
Continuation records distinguish exact held-result reuse, settled-session suffix continuation and a fresh handoff, and identify settings, history or result mismatches. A fresh handoff includes the full public history and historical images; an exact held-tool resume does not resend that history or its images. A settled continuation sends only its new context suffix and images. Native session reuse does not establish model-side cache hits.
During an admitted invocation, tracing also records native_wait every 30 seconds.
These records contain native I/O byte/frame counts, notification age, native/public
queue pressure, pending RPC count, transport/process state and MCP result-release
state. They never include stdout/stderr contents. Observation is passive: it sends
no native RPC, resets no deadline and cannot turn a diagnostic write timeout into
a native failure. It stops with the invocation and never releases tool results.
Native RPC start, sent and end records separate local submission from native
acknowledgement. MCP decoded method and handler-return records
cover initialization, initialized notifications and tool discovery, without
recording headers, credentials or unknown method names. mcp_call_received
precedes admission and the session/read
checkpoint. Its timestamp separates waiting for Muse's tool request from waiting
for our checkpoint. mcp_result_released and mcp_response_written distinguish
host continuation from writing the held MCP response; a successful write still
does not prove the recipient received it. First model output and run boundaries
provide timing for calls without tools. Closed-relay records retain only the safe
first-fault label. Pair records by bridge process and their ordered phases, not by
native IDs. Traces are diagnostic observations, not authorization to replay work.
Quiet requests and timeouts
The daemon recognizes this bridge by its existing validated protocol-1 hello
name, ezagent-muse-code-bridge. For this identity, unset first_output_timeout
and stream_idle_timeout have no semantic-output watchdog deadline. Quiet native
work can pause for any length of time. The daemon waits for the native terminal
result, a real connection or protocol failure, or explicit caller cancellation.
The hello identity is a behavior hint from the locally configured process, not a
security boundary. Startup timeout policy is unchanged. Other external providers
retain ten-minute first-output and five-minute idle defaults.
An explicit positive first_output_timeout or stream_idle_timeout still applies
to its own phase, independently of the other setting. Model text, reasoning text,
or a tool-call yield counts as model output and transitions to the idle phase.
A subsequent tool-result completion starts its own first-output phase. Acceptance,
informational/status frames, usage updates, native startup and MCP handshakes do
not extend an enabled watchdog. Bridge tracing does not forward status spam as a
heartbeat. Service logs show the selected durations and enabled flags without
payloads or native IDs.
Real protocol guards, authentication failures and MCP faults still terminate the request. Cancellation and failures retire and reap the exact owned process, without cancelling independent background tasks. No watchdog selection authorizes automatic request or tool replay. When an explicitly configured watchdog expires, its diagnostic reports missing model output rather than transport silence.
Limits and validation
Muse MSP does not expose a supported output-token cap. A requested max_tokens
is not enforced. The bridge emits one short notice per connection when requested.
Unknown usage attribution is omitted rather than charging native aggregate
usage again.
Focused deterministic tests use fake MSP/MCP children, including a configured
Agent journey that checks persisted history with deliberately delayed MSP
content. The journey can use the built executable via
EZAGENT_TEST_MUSE_BRIDGE=/absolute/path/to/ezagent-muse-code-bridge.
Live model validation is separate and must respect the shared attempt budget.
See the external-provider contract and the test guide.
Account quota usage
--list-models advertises usage: true. The separate --usage private query
initializes a scratch native process with the experimentalApi capability,
which Muse requires for usage/refresh, and calls usage/refresh without
starting a session or sending a user prompt. usage/read only reads that native
process's cached observation, which is empty at startup. Refresh performs one
native rate-bounded account query; unavailable data, an older native version or
a rate-limit refusal returns unavailable without retrying. It exports authoritative
observedAtMs, weekly/window usedPercent and resetsAtMs, and
windowDurationMins. The short window appears first with its reported duration,
followed by the weekly limit. Percentages above 100 are valid. The snapshot is
fresh for five minutes from the original provider observation, not the quota
reset or relay time.
Missing, expired or malformed native data returns unavailable without raw
native errors or account metadata.
Automatic usage querying defaults on for this adapter and can be disabled with
usage_auto_query: false on the owning provider to accept observer posts.
A usage timeout retires only its dedicated process, never a running completion.
See the external-provider usage protocol.