docs/agent-api/external-model-providers.md
External model provider contract
External model providers implement the daemon's model-provider boundary in an owned subprocess. This is a separate JSONL protocol from the client and addon API. The Agent remains responsible for conversation history, tool admission and execution, triggers, and persistence. The provider translates finalized model requests to its backend. See configuration, the host package, and the Muse bridge.
Runtime protocol
The host starts the configured executable with --stdio. Standard output is
reserved for UTF-8 JSON objects, one per line. Frames have a type and id;
the maximum encoded frame is 32 MiB. The host sends hello with protocol 1,
session_id, options, and optional private auth. The provider replies with
the same ID, protocol 1, and nonempty name and version. Unknown optional
fields are ignored, but unknown frame types and invalid required values fail.
One complete is active at a time. It includes model, context, tools,
and optional thinking_level and positive max_tokens. Each tool has a unique
name and parameters object. Context has mode (replace or append),
base_revision, revision, and a messages array. A replacement has base zero;
revisions increase. Messages carry a role, content, and optional reasoning, tool
calls, tool call ID and error status. Tool call arguments are JSON object strings.
The provider acknowledges installed context with accepted and
context_revision before producing events. The host compares finalized input
with its last acknowledged input and appends only for an exact prefix;
otherwise it replaces. A pre-acceptance context_mismatch gets one replacement
retry. Acknowledgement is not inference success or durable storage. Provider
output is not added to the host's context shadow.
Provider event frames carry content_delta, reasoning_delta,
reasoning_reset, informational, usage_only, assistant_boundary, or
done. A done event ends the invocation with stop or tool_calls; the
latter includes calls to offered tools. Usage counts cannot be negative.
Any existing event may optionally carry context_tokens, a nonnegative integer
replacement snapshot of provider-reported context occupancy. Omission means no
measurement; zero is a measurement. It is independent of usage and billing.
The host stores the latest snapshot on the assistant turn and uses it for the
existing context statistic, without adding it to cumulative usage.
Events may also carry access_observation, an object with source,
observed_at_ms, and expires_at_ms. The known sources are unknown and
muse_subscription. Unknown uses zero timestamps and clears earlier evidence.
A Muse observation requires positive epoch-millisecond timestamps in order,
at most 31 days apart. The host accepts it only from the current execution's
provider and only while it is current. It retains no native usage fields and
uses the existing public access_source; the observation is not persisted.
assistant_boundary separates visible assistant items without ending the
invocation. error frames use invalid_request, unsupported_input,
context_mismatch, authentication, rate_limited, unavailable, or
internal, with a message and optional nonnegative retry_after_ms. The host
routes replies by ID and validates order and payloads. Cancellation retires the
owned connection; cancel and cancelled frames support the cancellation
exchange. See wire.go for field definitions
and validation.
The host sends only finalized projected context and offered tools. A tool result alone does not authorize a provider continuation: the next finalized completion does. The daemon runs tools and its normal lifecycle before that request. The Muse bridge holds its native tool response until this point, or starts a fresh native session if the context or settings no longer match.
Host watchdog selection
The client retains the validated hello name and version as immutable connection
identity. This is a behavior hint from the configured executable, whether launched
locally or by the remote provider host, not a security boundary. External providers normally have a ten-minute
first_output_timeout and five-minute stream_idle_timeout. Only the exact
hello name ezagent-muse-code-bridge defaults both semantic-output watchdog
phases to disabled. Each explicit positive timeout overrides its own phase,
without enabling the other phase. Local and remote clients apply the same policy
after hello. The remote catalog preserves unspecified external timeout phases
rather than filling them with generic defaults. Startup timeout policy is unchanged.
Quiet Muse execution waits for its native terminal result, real connection or protocol failure, or explicit caller cancellation. Model text, reasoning text, and tool-call yields count as semantic output. Acceptance, informational/status frames and usage updates do not extend an enabled deadline. Failure and cancellation still retire and reap the owned child, without replaying accepted requests or tools or cancelling independent background tasks. The service logs the selected watchdog durations and enabled flags without provider payloads.
Discovery
--list-models is a separate, explicit, bounded process. It reads one JSON
object containing protocol: 1, options, and optional private auth, and
writes one catalog object with protocol: 1 and models. Each model has a
unique nonblank name and may have display_name, max_context,
context_limit, max_tokens, and thinking_levels. Numeric limits are
positive when present. max_context is an operating budget and cannot exceed
a known hard context_limit. Unknown limits are not unlimited. Discovery is
advisory and does not itself rewrite configuration or invalidate saved models.
The host package guide describes input limits, environment, and lifecycle.
Ownership and isolation
The Agent owns the process across model steps of an execution. It retires the process on execution end or provider identity change. Processes run in private scratch with filtered environment and isolated XDG cache, state and runtime; this is not a filesystem sandbox. Provider-specific children remain the provider's responsibility. Failures and cancellation retire the owned runtime. Agent error diagnostics discard arbitrary provider-controlled text. Exact Muse stage, category, protocol-guard and MCP lifecycle labels from the shared fixed vocabulary are retained in terminal errors, including saved error turns. MCP lifecycle reasons distinguish request disconnect, response-delivery failure, parallel calls, duplicate request IDs and replay-capacity exhaustion. These are diagnostics, not permission to replay tools or proof of an unexecuted request. This uses the existing error message, not additional wire fields. Raw native diagnostics remain private. See the Muse bridge limits and replay rules for its bounded per-session request-ID protection.
Remote execution streams
An exported external provider carries this same protocol-1 JSONL over a
tunnel.llmprovider.<provider> byte stream. This is not a new daemon JSONL
frame or an alternate bridge API. The consumer uses the ordinary protocol
client and keeps its local Agent, tools, finalized context and session storage.
The bridge runs on the credential-owning host, once per execution stream, and
survives between model steps so append revisions and held Muse tool calls keep
their existing semantics.
The consumer sends no auth. The host ignores any caller auth/options and injects its own hello configuration. Command, arguments and allowed environment come only from host configuration, never tunneled rows. Muse native login continues to omit supplied auth. Each complete is checked against the exported model catalog, including request-model targets of aliases.
This is a trusted socket/SSH relay. The existing consumer client owns protocol state validation and context recovery. The host preserves normal frames and unknown optional fields, without scanning model content, tool arguments or JSON keys for auth or environment strings. Hello identity is unchanged. Error messages retain bounded useful details with literal supplied auth replaced only in the diagnostic. Credential ownership comes from host-only resolution and injection, not from attempting to sanitize successful output. The consuming adapter also preserves bounded launch, protocol-validation and transport failure reasons, with the known-credential diagnostic precaution. These errors retire the affected owner without implying that an ambiguous completion may be replayed. Muse's connection-ended explanation includes the underlying diagnostic. Remote access observations are tied to the validated external owner and full selected route. Idle projection uses non-secret destination/provider identity, not consumer credentials; expiry or a route edit discards the observation. The host enforces its configured startup timeout; the consumer does not impose a shorter process deadline. Stream cancellation, connection loss, destination retirement and export withdrawal terminate and reap the stream's exact host child. A disconnect while parked invalidates that client. A later step on a reconnected destination opens a new bridge and sends full replacement context; an ambiguously executed active request is not automatically replayed. There is no provider execution or tool execution on the host daemon beyond that bridge. See provider-owned host exports for admission and lifetime details.
Remote setup discovers only configured host catalogs through IFO/LIST. It does
not launch the bridge or run its list_models command. In the
configurator, consumers
explicitly select names such as bridge/org/model. Only names persist in normal
remote provider config; host options, process settings, credentials and runtime
catalog metadata do not. Removing an export or taking a host down leaves those
selections saved. Model browsers refresh availability, showing not found after
successful discovery of an absent model and unavailable on discovery failure.