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, optional node_id, 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.

session_id is the leaf ID; node_id is the durable identity of the service that owns it, not the provider host or connection. Providers may ignore it, and its absence (older callers) means unknown. The pair may be used for lookup, but neither ID proves authentication. Ordinary clients receive the same service identity in the core hello_ack. Protocol 1 is unchanged.

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 live observation and its timestamps are not persisted. The last reported source is saved as ordinary leaf metadata for informational lookup after idle, unload, and restart. A reported unknown replaces that value; omission or expiry alone does not erase it. 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.

Optional native context extension

Hello remains a service-initiated shared protocol-1 exchange. The host advertises optional extensions and native_formats string arrays. The provider replies with only the intersection it supports. Missing or empty lists mean no native extension. The current host offers native_context_v1 with claude_code.thinking.v1. The Claude bridge requires both; it returns unsupported_input during hello otherwise. An unoffered negotiated extension or format fails startup.

These fields belong to the dedicated external-provider protocol, not the public client/tool/addon API. All old providers, including Muse, remain valid by omitting the hello lists and optional output. The host then omits source IDs, confirmations and private native input entirely. Muse continues to ignore unknown optional hello fields and uses its existing readable-history and tool-result contract. Direct HTTP providers do not speak this protocol; their existing native formats, replay and public output remain unchanged.

With the extension negotiated, each input message may carry source_turn_id, the daemon-owned source turn, and assistant messages may carry capture_ref, a runtime confirmation of a successfully finalized output_item_id. Source IDs are unique within installed history. Confirmation maps exist only in memory, are updated after successful finalization and are never hidden turn metadata. Content and tool identity must match too; a source ID alone is not proof of a matching generated answer.

The service-initiated complete may additionally carry native_context:

json
1[
2 {
3 "source_turn_id": "t_0123456789ab",
4 "format": "claude_code.thinking.v1",
5 "payload": [{"version": 1, "records": [], "prefix_digest": "format-specific value"}]
6 }
7]

This illustrates the transport envelope, not a valid empty Claude capture. Each entry names exactly one supplied source turn, with no duplicates. payload is a nonempty JSON array of objects, at most 8 MiB per capture; the selected provider's codec checks its format envelope. The daemon loads messages and native rows together using BuildProviderContext, selects format and permitted route, and keeps database row IDs private. A full replacement includes available native entries for all supplied messages. An append includes only new messages and their entries. A native-data change to an already installed source forces replacement, even if the readable message prefix is unchanged. A replacement received by a healthy bridge is not authorization to replay that history to its model.

Responses remain replies to that service-initiated completion. Associated text, reasoning and closing events may carry output_item_id, unique for the bridge connection and across bridge restarts. One item stays active until assistant_boundary or done; interleaving IDs, duplicate closes and associated chunks without an ID fail. Older/unassociated provider output remains valid. Only closing events may carry native_capture, an object with format and payload. It requires a negotiated format and output ID. A missing capture means no native row, never an invented placeholder. Native payloads cannot appear on ordinary deltas or public client events.

Each boundary carries its own capture and attributable usage through the internal loop admission callback and FinalizeAssistantTurnWithNative. A real private-only assistant message may close with empty readable content. It uses the existing public message/turn lifecycle, without a new public field or frame. An empty message without native data still fails the existing empty-response rule. An unfinished successor never reuses an earlier message's mutable capture. The next finalized input confirms saved output rather than resubmitting it. Cancellation and failed finalization do not advance that mapping.

The local launcher and socket/SSH relay preserve optional fields. The relay still replaces only options/auth with host configuration and preserves exact native JSON numbers. There is no native-data fetch RPC, commit-ack frame or separate checkpoint store. Provider-native interpretation belongs to the adapter, not the relay.

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. The catalog may also carry an optional top-level source: a nonblank string of at most 4096 bytes naming where the provider obtained the list. Its vocabulary is open and consumers keep unrecognized values. It is catalog-level provenance only: it is not a model identity, account entitlement or subscription status, and an absent source means provenance is unknown. A present source that is null, not a string, blank or oversize is invalid. The protocol version stays 1. 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 loaded Agent owns the process across model steps and successful executions, including idle and background periods. A compatible subsequent execution reuses it; provider identity changes, rewind, failure, cancellation, or Agent shutdown retire it. A changed FiletypeGate decision for media already in that owner's history also retires it before the next completion. The new owner receives the newly gated canonical history, including finalized results, without re-executing historical tools. Equivalent gate settings preserve reuse. Active completion and observation callbacks remain bound to their execution, so late cleanup cannot affect a later user of the same process. 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.

The relay preserves the consumer's node_id/session_id while replacing options/auth; it never substitutes the host's identity, and adds no outer tunnel fields.

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.