docs/cmd/ezagent-claude-code-bridge.md

Claude Code bridge

ezagent-claude-code-bridge is an external provider backed by the official, unmodified Claude Code executable. EzAgent owns conversation history, permission checks, tool execution and finalized results. Claude supplies model output using its existing native subscription login. There is no SDK or Node runtime added by this bridge, and it does not call an inference endpoint itself.

Setup

Install Claude Code, sign in, and complete its official setup first. Put claude on PATH. If Claude uses CLAUDE_CONFIG_DIR, set it in the daemon's environment. The launcher forwards it automatically to ezagent-claude-code-bridge for both model discovery and conversations, including with an absolute bridge path. A nonempty relative value resolves against the daemon's working directory before the launcher enters private scratch. Only wrappers or renamed bridge executables must request it through pass_env. In ez-agent-configurator, add Claude Code, save the profile, then choose Discover external models / Refresh under Edit Models, or enter a supported model ID manually. Discovery launches Claude's native stream-json interface and reads the models array from its initialize control response. It sends no user prompt, performs no inference and disables session persistence. The configurator selects the included bridge beside its physical executable, falling back to ezagent-claude-code-bridge on PATH.

To list models directly from the repository after just build-claude-bridge:

sh
1printf '%s\n' '{"protocol":1,"options":{}}' | ./build/ezagent-claude-code-bridge --list-models

The bounded discovery process reuses native launch isolation and reaps its exact child before returning. Only model metadata is retained, not the account or full initialization payload. Native values and order are preserved, including aliases such as default, opus, fable, sonnet and haiku; aliases are not replaced by their resolved model IDs. Aliases follow newer releases, so each native resolvedModel that is not already listed is added once after its first alias, such as claude-opus-5-5 after opus. Selecting that versioned ID pins the release and makes the session's model ID name the exact version. It takes the alias's thinking choices and the display name of a non-default alias that resolves to it. Listing is advisory, not proof of subscription access. The catalog carries no source: Claude Code 2.1.322's initialization reply has no catalog origin or provenance field, so the bridge reports none rather than inventing one. The configurator shows that provenance was not reported, which does not imply the list is complete or incomplete. Missing model metadata from older native versions produces an empty advisory catalog. Malformed catalogs fail without exposing native diagnostics.

Thinking choices include default when native thinking controls are advertised, none only when supportsThinkingOff is true, and native effort levels from the bridge's supported set only when both effort and adaptive thinking are supported. Unknown effort names are omitted. Initialization supplies no context or output ceilings, so discovery does not invent them.

There is no API-key prompt, app installer, credential copying or second login flow. Normal conversation, tools, idle continuation and branches stay in EzAgent. Returning to the official app is exceptional maintenance, such as reauthentication, not a per-leaf step. The Muse profile keeps its existing setup behavior and also requires installation and native sign-in first.

Example configuration:

yaml
1providers:
2 claude-code:
3 type: external
4 command: ezagent-claude-code-bridge
5 models:
6 - name: claude-haiku-5-5
7 max_context: 1000000
8default_model: claude-code/claude-haiku-5-5

An optional options.claude_command selects an absolute executable or a PATH basename. No other bridge option or supplied provider auth is accepted. Do not configure API-key environment variables as a substitute for native sign-in. Current bounded live checks use Claude Code 2.1.322 and claude-haiku-5-5. This is not an effort/model compatibility matrix. The implementation is Linux-first; other platforms fail native launch rather than running without safe process-group cleanup.

Model settings

max_context is EzAgent's operating budget, not a native output or thinking setting. The configurator preserves effective model/provider budgets and, when none is set, seeds a known catalog ceiling or the existing 1,000,000 operating default. An unknown native ceiling stays unknown. Activate or explicit Save persists this budget; Back without edits does not. Blank max_tokens leaves native output defaults unchanged. Use the discovered per-model thinking choices; in particular, none is not available unless that model supports thinking off.

SettingNative behavior
Empty or default thinkingLeave native thinking and effort defaults unchanged
noneDisable thinking
low, medium, high, xhigh, maxAdaptive thinking, summarized display and the same named effort
Other thinking valuesReject without substitution
Positive max_tokensSupply CLAUDE_CODE_MAX_OUTPUT_TOKENS
No token ceilingLeave the native ceiling unchanged

Live effort changes use native control requests. Resetting an explicit effort to an unspecified default requires a new provider session and is rejected on a live connection. Changing the output ceiling also requires a new provider session; normal saved-config changes already retire the old configured owner. The bridge never silently changes a selected model or substitutes an API backend.

Text, readable thinking, tool calls, inline JPEG/PNG/GIF/WebP images and PDF attachments are supported. EzAgent's existing FiletypeGate applies before the bridge receives content. Text files and directories retain the normal labeled text projection. Disabled media retains the gate's warning; the bridge never fetches a URL or opens an attachment filename as a path. Unsupported multipart formats, malformed base64 and images above the documented encoded-byte check fail before acceptance.

Fresh prompts, warm follow-ups and held-tool user steers carry ordered native text/image/document blocks, with filename and MIME labels. Queued user steers use native priority-next input with an explicit human origin so Claude retains PDFs. This stamp applies only to user steers, never to tool output or recovery history. Finalized tool media stays associated with the original tool ID. Images use standard MCP image results. PDFs use inline MCP blob resources and the owned PostToolUse hook's supported updatedMCPToolOutput replacement with native document blocks. They are not sent as unrelated user prompts.

Claude Code 2.1.322 does not invoke PostToolUse or expose image/PDF content for MCP error results. The bridge forwards their exact typed MCP content and error flag, but reports this limitation through an informational event instead of pretending the model saw the media. It does not retain an unconsumable document replacement or retry the tool. Canonical attachment bytes stay saved in EzAgent and remain available in labeled readable-history recovery. Successful tool results retain normal native image/PDF support.

The bridge preserves Claude's base system prompt and appends static EzAgent system text. That text asks Claude to batch every tool call it can already choose, because EzAgent runs a batch in order (concurrently only for calls that set parallel) and continues after a failed call. It disables built-in tools, ambient settings/hooks, slash commands, project instruction discovery and native auto-compaction. Only the owned MCP tools and pre/post-tool correlation hooks remain. This is execution restriction and environment isolation, not an OS sandbox.

Native discovery and conversation launches set CLAUDE_CODE_ENTRYPOINT=ezterry/ezagent, replacing any inherited entrypoint, to identify this application rather than another client or a generic SDK. This is a public application label that Anthropic may receive and log, not a URL, credential or per-user identifier. The variable is not an officially documented Claude Code contract. Installed-native verification against a local fake API checks that the label, including its slash, reaches the request's User-Agent and cc_entrypoint billing-header text. This attribution does not establish any change in subscription accounting, entitlement or third-party usage approval.

Conversation and tool ownership

A healthy loaded leaf keeps its bridge and native conversation through idle. Only new user input goes to the warm session. Generated assistant output must match the next saved history before reuse. If an idle native process, its output stream or its MCP relay has already ended when new input arrives, with no held or waiting tool, the bridge checks this before sending. It replaces the owner from the retained canonical history, reports an informational event and sends the new input once. Failures after input was submitted, or while tools are held or waiting, are reported and not resubmitted to that owner. The one exception is described below: a held request that disconnected before release is continued from finalized history. Tool results are released only after EzAgent's next finalized request, including plugin processing and error status. Catalog additions, removals and schema changes use MCP rediscovery without restarting healthy history or invalidating the old held result. User steers accepted during tool execution are queued in source order through native priority-next input before the finalized results are released. They never replace a tool result or cause a tool to run again. Waiting for the first native MCP handler still observes native failure and EOF; it cannot wait silently for a dead process until the outer watchdog expires.

The owned MCP server sets Claude's supported maximum tool timeout, 2,147,483,647 milliseconds, about 24.9 days, instead of leaving its independent 60-second default in force. This is a finite native bound, not a disabled timer. EzAgent's tool timeout and cancellation still govern normal execution. Ambient native MCP tool and idle-timeout overrides are removed. A native failure or lost connection while a result is held prevents its later release; it never authorizes tool replay. Request failures name the bridge check that failed with a structural code. When the owned MCP relay retired with a fixed bridge fault, the code keeps it as mcp/<fault>, or mcp/held_connection_lost/<fault> while a result is held, for example mcp/request_disconnected. Relay failures without a recognized structural fault, including an unrecorded close, keep the generic mcp/delivery_unknown, and failed writes to Claude's native input are unchanged. Diagnosis never releases a result or replays a tool. When Claude reports the failure itself, such as a login, quota or API error, the code carries Claude's category and message, for example native/api_error/authentication_failed: Not logged in. The host bounds that text but does not generally redact native diagnostic messages. Local restoration and executable-start failures use restore/failed and native/start_failed; unclassified errors use the fixed native/failure reason rather than their free-text details. When the native stream or a pending control wait ends, a recorded reader failure such as native/stream_invalid is reported first. Absent one, a nonzero process exit is reported as native/exit_status/<n>, and a crash by SIGSEGV, SIGABRT or SIGBUS as native/signal/<name>. Clean exit, other signals and an exit not observed within a short bound remain native/connection_ended. Native stderr stays discarded, and cancellation is reported as cancellation, not as a native failure. The bridge does not attach captured thinking, signatures or generated output to failure reasons.

The relay records request_disconnected when Claude's tool request ends before any response is written: its stdio relay session closes with the call pending, or Claude cancels the call. The call may already be held, or, mid-batch after an earlier result was released, admitted by the relay but not yet taken by the bridge. Either way Claude never received the outstanding finalized results. When this fault fails a request that carries finalized results for outstanding tools, before any output from that request has reached the host, the bridge retires the owner and starts one fresh native session from the retained EzAgent history instead of failing. Results already released earlier in the same batch are part of that history. The restored transcript ends at the tool calls, and the new input is the finalized results in call order, with their error status, followed by any intervening steers. No tool is dispatched again and no synthetic recovery message is added; the fresh model may still request tools itself. The bridge reports this continuation as informational. Cancellation stops it, and a failure of the fresh session is reported without another attempt. Uncertain delivery, such as response_delivery_failed, other held faults and failures after model output still fail the request.

Changing enabled filetypes retires the loaded owner when it changes the effective projection of previously supplied images or PDFs. The next request recovers from the newly gated canonical history, including any finalized held-tool result, without executing historical tools again. Equivalent gate settings preserve warm reuse. Strict prefix equality remains in force.

Each completed API assistant message has its own usage and optional native capture, including private-only messages. Several native transcript records may share one API ID and stay together in that capture. Missing or unusable capture metadata does not invalidate a verified completed stream. The bridge omits the whole private capture with an informational reason, preserving ordered text, readable thinking and completed tools. If omission leaves no text, readable thinking or tools, no empty assistant boundary or generated history entry is created. Empty text and thinking fragments emit no delta event and open no output identity. Existing usage-only events preserve interim accounting, and omitted usage is carried into the next retained message without inflating its current context measurement. The bridge does not fabricate provider thinking or signatures. Tool dispatch still requires matching completed native tool records and the original MCP handler. Premature native results are checked against every still undelivered tool ID, including between serialized handlers. The existing native-thinking store keeps signed/redacted data out of public history and client events.

A brand-new conversation sends plain user input, with static system/developer text appended to Claude's base system prompt. It has no recovery label or historical-tool framing.

EzAgent is the durable conversation owner. After restart, rewind or fork, the bridge materializes only the retained canonical history as a temporary native transcript and loads it into a new native session. It does not need Claude's original session to survive. Matching saved assistant messages supply their original ordered signed and redacted thinking blocks unchanged. User messages and finalized tool results retain their native roles, media, original tool IDs and error status. Only the pending user input or finalized tool-result suffix starts the next model turn; historical tools are not executed again.

Tool history follows the direct Anthropic provider's projection: retain calls only when a matching finalized result exists before the next assistant, place those results immediately after their calls in call order, and then include intervening user steers. Unresolved calls and orphan or duplicate results are omitted without synthesizing results or changing canonical storage. Removing an abandoned tool_use block never strips its message's signed thinking blocks.

This follows the official SDK's external session restoration and cross-host resume format. Static system/developer instructions still use the appended system prompt. An assistant without a capture is restored from its public text and tool calls. Readable reasoning from other providers or unknown origins is wrapped in <previous_thoughts>. The bridge omits it for Anthropic-origin turns, including compacted copies, based on the original producer's identity. The anthropic adapter type or an external bridge name or executable basename containing claude or anthropic, regardless of case, identifies Anthropic origin. A model match counts only when the producer is uncertain. The host also withholds signed thinking that cannot replay on this route. If a supplied capture no longer matches the retained prefix or cannot supply a required finalized canonical call, the turn is restored from its public text and tool calls without thinking, and an informational event reports the omission. Native thinking without a signature or redacted data is omitted, not reconstructed from readable reasoning. A native restoration failure is an error, not a silent downgrade of otherwise usable signed history.

The bridge accepts the host's optional native_rejection_v1 extension. When Claude itself reports an invalid thinking signature or modified thinking block for a request that carried native captures, before any model output, the bridge answers with native_state_rejected instead of internal. Native stream starts and assistant records count as output even before the bridge forwards a host event, including tool-only responses waiting for an MCP handler. Synthetic API-error assistant records do not count as model output. The host then retries once on a fresh bridge without those captures and records an Anthropic reset; see the external provider contract. Without the extension, the same failure stays an ordinary internal error. Saved native data remains available to other branches; no second durable checkpoint store or transcript mirror is created.

A healthy loaded leaf still reuses its live native process. If finalized history no longer matches that process, the bridge retires it and restores the new host snapshot instead of continuing with discarded native context.

No accepted or uncertain request or tool is automatically retried. Cancellation interrupts, drains to a native result or deadline, then retires and reaps the exact native process group. The bridge does not cancel unrelated background work. Retained saved captures remain eligible independently of an interrupted successor.

Limits, files and remote use

Our transport bounds are 32 MiB per received external frame and per actual native write, an 8 MiB private capture per assistant message, and a native queue of 256 frames / 32 MiB. An oversized optional capture is omitted whole and its accumulation is dropped; the private-capture policy does not limit visible text or readable thinking. The omission reason distinguishes actual overflow from absent or unusable metadata. Base64 and JSON overhead count toward encoded byte bounds. Installed history is not a new wire frame: a small warm update is not rejected because earlier media is already installed. Restoration writes retained history to the temporary transcript; only its pending-input suffix is a new native wire frame. An orphaned-history handoff must still fit the native write bound. Nothing is silently truncated to fit.

The documented first-party image size maximum is 10 MB of base64-encoded data per image. Claude projection checks 10,000,000 base64 data bytes, excluding the data-URL prefix, not 5 MiB of decoded data. The direct Anthropic provider retains its original acceptance behavior. No Claude Code image-count or per-PDF byte ceiling is documented by the native image workflow, so the bridge does not invent one or import claude.ai/Muse limits. File-format, PDF-page and other native capacities remain the official client's responsibility. Payload syntax checks validate MIME metadata and canonical nonempty base64; they do not parse or resize images/PDFs. API/web capacities are not claimed as a Claude Code subscription capacity matrix. The shared MCP proxy retains replay protection without Claude's having a fixed call-count ceiling. Native MCP runs over stdio through the same bridge binary's relay-only mode, authenticated to its owner over AF_UNIX before MCP initialization. There is no TCP MCP listener. --mcp-socket auto|abstract|filesystem selects the socket policy: Linux auto uses abstract Unix; other platforms use a private filesystem socket. Explicit abstract fails where unsupported. For provider configuration, put --mcp-socket=filesystem in args when needed; the launcher still adds --stdio. The relay command and endpoint use absolute addressing.

The random check is forwarded through native MCP child env, not argv or model content. Claude explicitly opts into a new RPC-ID namespace on a clean idle reconnect because its client restarts IDs; the shared proxy preserves replay tombstones by default. A disconnect with uncertain tool work retires the bridge without replay. Native call IDs and host tool controls remain authoritative. See authenticated stdio relay. MCP frames over 32 MiB including the newline close the relay without dispatch, not a request-local HTTP 413. Idle owners permit reconnect; outstanding tool work retires the owner. Encoded tool-result JSON is limited to 32 MiB minus 8,192 bytes to reserve the escaped RPC ID, JSON-RPC envelope and newline. The opt-in just test-claude-mcp-native starts the installed CLI with private roots, no login and no prompt, and checks stdio initialization and mcp_reconnect. Transport limits fail explicitly; optional private-capture overflow is reported without discarding the answer. The bridge never truncates signatures or silently drops history to fit.

Generic external watchdogs apply: ten minutes until semantic output and five minutes of semantic-output inactivity. Explicit positive overrides work normally. Private signatures, redacted data and status frames are not visible progress. Claude does not inherit Muse's quiet-execution exemption.

When Claude Code emits a rate_limit_event with an integer epoch-second resetsAt and a known status, the bridge attaches an access_observation with the provider-defined source claude_subscription to every event it emits afterwards, streaming deltas as well as completion, so the host indicator updates while a request runs. A window already reported by an earlier request stays attached until its reset. The observation runs from receipt until that reset, which must be within 31 days. No event, an invalid one, or an expired window reports nothing. Only the window end is kept: no tier, utilization or entitlement claim is made, and the observation is not inferred from the login or environment. Without a usable event the host indicator stays unknown, and none is available before the first event that follows the native frame unless an earlier request's window is still open.

The daemon and bridge must be the same release. A daemon that predates provider-defined subscription indicators rejects a claude_subscription observation as an invalid event, so a newly installed bridge can fail under an older running daemon. After installing matching binaries, restart the daemon so it and its provider processes use them.

The child uses a temporary workspace and private XDG directories, preserving HOME for the native login. Its private state/claude is an intentional symlink to the parent's effective $XDG_STATE_HOME/claude, or $HOME/.local/state/claude when that XDG root is unset or not absolute. Root and application-directory symlinks are supported. The external launcher preserves that original root in its reserved EZ_AGENT_PROVIDER_STATE_HOME environment metadata before isolating XDG; direct bridge launches use their effective XDG root. Only the Claude application state is linked, not the whole parent state directory. This native state is shared with the official app and is not a private transcript sandbox. Other native session storage may also live under HOME.

Every bridge-owned native conversation uses --no-session-persistence: loaded leaves keep their warm conversation in memory, not an accumulating set of Claude threads. Restoration creates a private ezagent-restore-* directory beneath the selected CLAUDE_CONFIG_DIR/projects, or ~/.claude/projects by default, containing only the temporary seed transcript. The seed contains plaintext retained user prompts, assistant messages and tool results. It uses a fresh session identity and remains on disk for the lifetime of the warm native process. Graceful retirement, failure handling or cancellation removes the seed directory and scratch workspace. SIGKILL, OOM termination or a host crash can leave them behind indefinitely. There is no automatic stale-seed sweep because concurrent bridges share the Claude configuration root. Remove leftover ezagent-restore-* directories only after confirming their owning bridges have stopped. The bridge never reads or copies login files, scans unrelated history, or deletes existing Claude sessions. Existing native cleanup defaults for unrelated sessions are unchanged.

The existing local, trusted socket and SSH external-provider paths carry the same negotiated private fields. The provider host chooses executable/options/login; the consumer owns history and tools. Existing route filtering keeps remote native captures on their permitted route. A shared login assumes mutually trusted operators, not untrusted tenants. No AgentHub protocol changes are involved.

just test-remote-claude-live is the opt-in two-service acceptance. Only the host configures/exports Claude; the consumer has a remote-only provider and an empty HOME. The case checks consumer-side tool/plugin execution, real user/tool PDFs, streamed thinking, private route-tagged persistence and a second prompt on the same native owner. It uses existing artifacts and the trusted AF_UNIX relay, without a local-host completion first or an SSH audit. See tests.

Build with just build-claude-bridge. just test-claude-restore-native checks installed-native transcript loading and cleanup under private login-free roots, without sending a user prompt or performing inference. The opt-in Haiku bridge live check also verifies a cold signed-history continuation after retiring the original native process. See tests, the external contract and shared implementation for validation and ownership.

Account quota usage

--list-models advertises usage: true. A separate --usage process uses native login and private scratch state, initializes the structured control transport, then sends a correlated control request with request: {subtype: "get_usage", skip_behaviors: true}. No user input or inference is sent. Only rate_limits_available and account rate_limits are projected: five_hour, seven_day, and seven_day_sonnet retain known utilization and optional ISO8601 reset timestamps. They appear in that order as Short window with a five-hour duration, Weekly limit, and Weekly limit · Sonnet. The Sonnet row is a separate reported quota, not a share of the overall weekly limit. Null measurements are unknown, not zero. Optional model_scoped arrays and unknown additions are ignored rather than invalidating valid account windows. extra_usage is not projected: its credits and utilization do not establish an authoritative cash unit/period or an account quota reset. Session costs, native account identifiers and model display names are never exported.

The bridge records observation when the native reply arrives and sets a five-minute freshness deadline, separate from quota reset times. get_usage is experimental in the native SDK; older versions, rejected controls and replies without usable account quota windows return cleanly unavailable. Native errors remain private. Cancellation can kill only this dedicated query runtime, not a running completion.

Automatic querying defaults on for this adapter. usage_auto_query: false on the owning provider disables queries and permits attributed observer posts. See the external-provider usage protocol.