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. 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 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. The bridge does not attach captured thinking, signatures or generated output to failure reasons.

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 usable capture is restored from its public projection, with readable reasoning in <previous_thoughts>, never a fabricated signature. If a supplied capture no longer matches the retained prefix or cannot supply a required finalized canonical call, an informational event reports its omission. A native restoration failure is an error, not a silent downgrade of otherwise usable signed history. 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. 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 or invent a public subscription-access source.

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.