pkg/externalprovider/README.md

External provider stdio component

This package implements the host side of the dedicated version 1 external model provider JSONL protocol over owned streams or an owned child process. It is a component used by the configured Agent external provider, not an end-to-end Muse provider. The integration contract is described in the external model provider contract. It is separate from the daemon addon JSONL API.

NewClient exchanges an exact-version hello with the supplied leaf session ID and optional leaf-owning service node ID. An empty node ID is omitted and means unknown identity. This lookup identity is not authentication evidence and is separate from the provider's reply identity. Client.Identity() returns a copy of the validated provider name and version, fixed for that connection. This is a configured process behavior hint for both local and remote clients, not an authentication boundary. Complete accepts the complete, finalized projected input and an offered tool snapshot, and delivers validated events serially to its callback. Only one completion may be active. The client compares each input with the last acknowledged input, sends an append for an exact prefix and a replacement otherwise, and retries one pre-acceptance context mismatch with a replacement. Generated output is not added to that shadow. A caller must not mutate request values while Complete is using them.

The connection bounds individual frames and its outgoing queue; the frame ceiling applies to each transmitted update, not the cumulative acknowledged input. Validated incoming frames use a growable FIFO with no fixed frame-count or aggregate-byte cap. A slow callback does not block the reader or fail a valid output burst. Delivery preserves frame order and releases consumed entries; the backing array is released when the FIFO drains. Cancellation retires the owned connection. Close, failed startup, and retired completion paths interrupt and join transport work; the supplied close function must promptly interrupt both reads and writes. The callback executes synchronously in Complete, not in the transport reader. A callback must return: arbitrary caller code cannot be forcibly stopped, so cancellation cannot promise a bounded return while that callback is blocked. For caller-supplied streams, call Close when finished. The Agent adapter maps its finalized requests and events; Muse-specific continuation is not provided. Client.Done() reports completion of transport work independently of local process ownership.

The Agent adapter normally uses ten-minute first-output and five-minute idle semantic-output watchdogs. For the hello name ezagent-muse-code-bridge, unset phases have no watchdog deadline. Each explicit positive timeout still applies independently. Quiet native execution waits for terminal output, a real failure, or caller cancellation; informational frames do not count as semantic output.

StartProcess(ctx, ProcessOptions) launches an absolute command or a basename found in an absolute PATH entry, appends --stdio, and performs the hello using the supplied SessionID, optional NodeID, options, and auth. Startup defaults to a 10 second timeout. Each process gets a private scratch working directory, temporary directory, and XDG cache, state, and runtime directories. It retains the user's HOME and XDG configuration directory for normal native login resolution. The child receives a filtered PATH and only the additional parent variables named in PassEnv; agent-control and isolation variables cannot be passed. Commands whose basename is ezagent-claude-code-bridge also inherit CLAUDE_CONFIG_DIR automatically so Claude can locate its native configuration and login during discovery and conversations. Wrappers and renamed bridges must request it through PassEnv. When forwarded, a nonempty relative CLAUDE_CONFIG_DIR resolves against the launcher's working directory before the child enters scratch. Empty values keep the native default. Other providers retain the explicit PassEnv policy. The launcher also supplies the reserved EZ_AGENT_PROVIDER_STATE_HOME metadata with the parent's effective absolute XDG state root, using the HOME default when needed. It ignores inherited claims and PassEnv cannot replace it. This lets a native adapter select its own application state without inheriting the entire parent XDG root; it changes no JSONL fields. Providers that do not need native state can ignore it. Stderr goes directly to the null device, without buffering or logging it. This is environment isolation, not a sandbox.

The returned Process.Client is ready for use. Call BeginClose to start shutdown without blocking, then Wait(ctx) to wait for child reaping, transport shutdown, and scratch removal. Shutdown interrupts only the owned child and kills it after ShutdownGrace, which defaults to 500 milliseconds. Wait does not initiate shutdown and may return the child's signal-related exit error. Descendants are not managed; providers must manage their own children. The Claude bridge identity raises the effective grace to eight seconds for native interrupt/drain/reaping, locally and through the host relay. On leader exit the owner allows up to 500 milliseconds to drain stdout before retiring the client, so an already-written completed record can be delivered. If EOF does not arrive, it closes the streams and removes scratch even when a descendant retains stdout. Explicit close still interrupts stalled I/O immediately.

StartRawProcess applies the same launch policy without creating a client or sending hello. Its returned Process implements io.Reader and io.Writer. The raw protocol owner must call BeginClose and Wait; Process.Client is nil. The launch context bounds admission, not the returned child's lifetime. StartProcess composes that launcher with the existing NewClient hello.

ServeBridge hosts one raw process behind a trusted remote protocol-1 stream. It replaces consumer options and auth with host settings and checks request models against supplied catalog targets. It preserves the consumer's leaf session_id and service node_id, without substituting the provider host's identity. The consumer's existing client owns protocol validation, revision recovery and event delivery; the host does not validate that state again. Optional future fields and normal output pass through, including content, tool arguments, property names and exact numbers. There is no auth/PassEnv echo scanner. Only bounded error diagnostics replace literal supplied auth values. Provider errors keep useful details rather than fixed labels. The provider's hello identity remains unchanged, so local and remote clients select the same watchdog and diagnostic policy. The host applies ProcessOptions.StartupTimeout to the hello exchange. Stream retirement joins relay work, exact-child reaping and scratch cleanup. See host exports.

Optional native transport

native.go defines the negotiated native_context_v1 / claude_code.thinking.v1 extension. The client sends source IDs, runtime capture confirmations and private native entries only after both ends agree; old providers remain valid without it. Accepted-input shadowing includes native data, so changing an earlier capture forces replacement. Output item IDs bind deltas and each closing native capture to one assistant message. The Agent maps these fields to per-message atomic native finalization without projecting them through the public API. ServeBridge passes them through unchanged. The contract defines negotiation, association and absence rules.

Command discovery

Discover(ctx, ProcessOptions) explicitly runs the configured command with --list-models appended, using the same command resolution, environment and private working directory as runtime. It sends one JSON object with protocol: 1, options (an object), and optional private auth, then closes stdin. It waits for exactly one catalog object and process exit. Input and output are each limited to 1 MiB. StartupTimeout bounds the complete operation (default ten seconds); cancellation interrupts the owned child, kills it after the shutdown grace if needed, and reaps it. Diagnostics never include child stdout or stderr. Discovery does not create a runtime session.

Catalog contains protocol 1 and a possibly empty Models array. Each Model has a unique nonblank name, optional display_name, positive optional max_context, context_limit, and max_tokens, and optional string array thinking_levels. Null numeric limits and absent limits are unknown (nil), not unlimited; other defined fields reject null. A nil ThinkingLevels means unknown; a non-nil empty slice means a known empty set of selectable levels and serializes as []. max_context is an operating budget, while context_limit is a separately known hard ceiling. If both are known, the budget cannot exceed the ceiling. Unknown fields are ignored. Discovery is advisory: an empty or partial list does not invalidate configured models, and callers should preserve existing lower budgets and saved metadata.