Agent Adapters, Wire Proxy & Interception Specification¶
References: ref-docs/agent-internals/rea-binary-and-sqlite-forensics.md, ref-docs/agent-internals/cross-agent-hook-and-wire-matrix.md, docs/deployment-and-agent-integration-guide.md
Target Crates: crates/icx-adapters, crates/icx-proxy
Release: v1.2.0 candidate
1. Purpose¶
crates/icx-adapters and crates/icx-proxy connect the Infinity-Context (icx) Virtual Context MMU to agent CLIs. They implement five native hook adapters (Claude Code, OpenAI Codex CLI, Google Antigravity CLI (agy), Hermes Agent, Meta Muse Code), the single-tool MCP pager (McpPagerServer), and an HTTP/1.1 & SSE Cache-Epoch reverse proxy (WireProxyTransformer).
Hook contracts below were checked against upstream documentation on 2026-11-18 (Claude Code 2.1.328, codex-cli 0.170.0, agy 1.5.11, Hermes source dc394c6). crates/icx-adapters/tests/claude_contract.rs pins the Claude Code output shapes; the other adapters are covered by unit tests, not by fixtures captured from live agent runs.
The v1.2.0 Codex correction is also pinned by protocol_validation.rs and the local
Codex 0.171 diagnostic: tool-output replacement is unsupported. The tests exercise adapter
output and storage; they are not live paid-provider or complete host-integration acceptance.
Current compatibility and evidence limits supersede older design promises in
ADR 0006.
Common behaviour of icx hook --agent <agent> --event <EVENT>:
- The workspace is resolved as
--dir>ICX_DIR> the per-project default under$XDG_STATE_HOME/icx/workspaces/. A repository-local.icx/is never loaded implicitly. - If an
icx daemonserves the workspace, the hook is forwarded over its private Unix socket; otherwise it runs in-process under the workspace lock.ICX_NO_DAEMON=1disables the daemon path. - stdin is bounded. The process always exits 0. On malformed input or internal errors it prints
{}(or a non-replacing response), so the agent keeps its original behaviour. - Outputs of the
icxpager tool itself (InfinityContextMmu::is_icx_pager_tool) are never re-stubbed. - Content is redacted (
SecretRedactor::redact) before it reaches the store, index, or bus. Model-facing text is additionally Tier-0 delimiter-escaped. - The daemon commits with SQLite WAL
synchronous=FULLunder the workspace lock before sending success. Save failure yields a failed response and the daemon reloads from disk before the next request (exiting after 5 consecutive failures); the CLI may then fall back to in-process handling, which is the only ingestion because a failed request is never saved. One request per connection: bytes after the request line are rejected as a protocol error. There is no acknowledged write-behind window. - Tail producers select fitting whole frames, prioritizing the header and best recall, then
sibling and remaining recall/PPR frames. Oversized recoverable frames can use compact CAS
handles. Unsent sibling frames remain queued; their cursor is not advanced past them.
The default tail cap is 1,024 conservative accounting units, also limited by remaining managed
window space.
icx context-budgetcontrols the persisted model policy. It does not cap all external native-agent messages or an entire provider request; callers reserve that content.
2. Claude Code Adapter (ClaudeCodeAdapter)¶
Upstream reference: https://code.claude.com/docs/en/hooks.
2.1 Hook Event Handling (icx hook --agent claude-code --event <event>)¶
SessionStart:-
Returns the AHTL legend and the initial tail slot in
hookSpecificOutput.additionalContext: -
UserPromptSubmit: - Reads
prompt, builds the tail slot (HDC query + fractal suffix + PPR walk + unseen sibling bus frames), and returns it inhookSpecificOutput.additionalContext. PostToolUse(in-flight tool output virtualization):-
Reads
tool_name,tool_input, andtool_response. If the output is at or abovetool_virtualize_threshold(default 512 bytes):- Redacts secrets via
SecretRedactor. - Chunks and commits the bytes into
CasStore, obtaining#icx:<16-hex>. - Runs
StructuralSkeletonizer, the Titans-inspiredTitansSurpriseGateheuristic, andAhtlEncoderto produce a compact stub. - Publishes a summary frame on the bus.
-
Returns
updatedToolOutputin the tool's own output shape. Claude Code ignores a replacement whose shape does not match the tool's output. For Bash the object{stdout, stderr, interrupted, isImage}is returned with the stub instdout; for other object outputs all fields are kept and the largest string leaf is replaced. MCP tools (mcp__*) additionally getupdatedMCPToolOutput(string):
- Redacts secrets via
-
Below the threshold the response is
{}. PreToolUse: returns only{"hookSpecificOutput":{"hookEventName":"PreToolUse"}}. icx makes no permission decision and does not modify the tool input; registering this hook is unnecessary.SubagentStart/SubagentStop:SubagentStartopens an isolated subagent branch and returns a tail slot inadditionalContext.SubagentStopreadslast_assistant_message, folds the branch into anL2node, and returns{}. Any decision oradditionalContexthere would keep the subagent running.PreCompact&PostCompact:PreCompactseals the active window into anL3CacheEpochNodeand prints plain stdout (not JSON), which Claude Code uses as compaction instructions: keep every#icx:handle and icx packet verbatim, followed by the current context map. Output stays under Claude Code's 10,000-character limit. (systemMessageis discarded on this event.)PostCompactstorescompact_summaryin the workspace, seals the epoch, and returns{}.- icx never blocks compaction.
SessionEnd: folds open subagent branches, seals the epoch, returns{}.Stop: not handled; returns{}.
3. OpenAI Codex CLI Adapter (CodexAdapter)¶
Upstream reference: the Codex hooks documentation (developers.openai.com/codex/hooks). Hooks are configured in ~/.codex/hooks.json with PascalCase event names, a string command, and timeout in seconds; hooks are enabled by default (codex_hooks is a deprecated feature alias).
3.1 Hook & Wire Integration¶
SessionStart,UserPromptSubmit&SubagentStart:- Return
{"continue": true, "hookSpecificOutput": {"hookEventName": ..., "additionalContext": ...}, ...}with the legend and/or tail slot. PostToolUse:- Ingests the tool output (store, index, bus) in every case.
- Returns a non-replacing response (
continue:trueandhookSpecificOutput.hookEventNamefor ingested outputs), with neitherupdatedMCPToolOutputnoradditionalContext.CodexAdapter::SUPPORTS_TOOL_OUTPUT_REPLACEMENTisfalse. v1.1.0 emitted the unsupported MCP replacement field; v1.2.0 removes it rather than claiming replacement succeeded. - Net effect: through hooks alone, icx does not shrink tool output in Codex; the model still sees the full native output. Use the wire proxy (§6) to reduce what Codex resends.
PreToolUse: returnscontinue: truewith no decision and no input change.SubagentStop: readslast_assistant_messageand folds the subagent branch; the fold frame is returned insystemMessage.PreCompact,PostCompact&SessionEnd: seal the epoch and return{"continue": true, "systemMessage": "<deterministic prefix>"}.PreModelRequest/PostModelRequest: not used. Upstream defines them as diagnostic only; they cannot change the request.- Rollout tailer (
CodexRolloutTailer): a bounded JSONL reader for~/.codex/sessions/**/rollout-*.jsonl. Known limitations: it is not wired into theicxCLI in this candidate (only the library and tests use it), and it does not read zstd-compressed.jsonl.zstrollouts, which current Codex versions write.
4. Google Antigravity CLI (agy) Adapter (AntigravityAdapter)¶
Upstream reference: https://antigravity.google/docs/hooks. Hooks are configured in a workspace .agents/hooks.json or the global ~/.gemini/config/hooks.json as named groups of events; each handler has a single command string, optional type (default "command"), timeout in seconds (default 30), and enabled. The documented events are SessionStart, PreToolUse, PostToolUse, PreInvocation, PostInvocation, and Stop. (Gemini CLI event names such as BeforeModel, AfterTool, or PreCompress do not apply to agy.)
4.1 camelCase Protojson Hook Contract¶
SessionStart,PreInvocation&PostInvocation:- Read
conversationId,transcriptPath,lastUserInput(orprompt/query), and related fields. -
Build the tail slot (HDC/PPR/fractal recall + unseen bus frames) and return it as an injected system message with
"terminationBehavior": "": -
The
metadata.user_markdownkey is intended to keep the frame out of the chat UI; it is not documented upstream, so that effect is unverified. PostInvocationnever setsforce_continue(v1.0.x did when the input carriedforceContinue).PreToolUse:- agy requires a
decision. icx always returns{"decision": "allow"}, expressing no opinion, and never modifies the tool call. v1.0.x echoeddecision/overwritefrom its input; that was removed. Registering this hook is unnecessary. PostToolUse:- Ingests
toolCall.argsand the tool response. When the payload omits the response, reads the matching step from the last512 KiBoftranscriptPath. The transcript is opened non-blocking without following symlinks, and only regular files are read. Returns{}. Stop:-
Always returns
{"decision": "stop"}; icx never keeps the agent running. It folds open subagents and seals the active window into an epoch (forced onmax_steps_exceededorerror), so the next session resumes from that state: -
v1.0.x returned
"continue"onMAX_TOKEN_BUDGET_EXCEEDED/MAX_INVOCATIONS, overriding the user's budget; that was removed. SubagentStart,SubagentStop&SessionEnd: handled by the adapter (branch isolation and folding), but not part of agy's published event list.
5. Hermes Agent Adapter (HermesAdapter)¶
Target: the Hermes ContextEngine ABC (agent/context_engine.py) and MemoryProvider.on_pre_compress (agent/memory_provider.py).
HermesAdapterimplements the context-engine logic in Rust:select_context,prune_tool_results_only,compress,on_turn_complete,on_pre_compress(checkpoint API version 2), andSessionStart, all reachable throughicx hook --agent hermes --event <name>with a JSON payload on stdin. The JSON contract is listed in the deployment guide §2.5.- No Python plugin or shim ships in this repository. To use icx with Hermes, a user must write a
ContextEngineplugin that callsicx hook --agent hermes .... The plugin must implement the abstractnameproperty,update_from_response,should_compress, andcompress;select_context,on_turn_complete, andprune_tool_results_onlyare optional. Hermes loads context-engine plugins fromplugins/context_engine/<name>/or$HERMES_HOME/plugins/<name>/, selected bycontext.enginein~/.hermes/config.yaml. - Hermes has no
hooks.yaml. Its shell hooks (underhooks:inconfig.yaml, snake_case events such aspre_tool_callandon_session_start) and gateway hooks (~/.hermes/hooks/<name>/HOOK.yaml) are not handled by icx. select_contextreplaces middle-history messages with oneicx_cache_epochsystem message plus anicx_tail_slotmessage, without touching Hermes'sstate.dbmessagestable. Preserved verbatim: the protected head and tail,icxpager results, messages with structured non-text content, and completetool_callsgroups.
6. Meta Muse Code Adapter (MuseAdapter, v1.3.0)¶
icx hook --agent muse --event <event>. Contract observed on Muse Code 1.4.25 with probe hooks
(a real headless session; every event below fired and its payload was recorded):
- Configuration. Command hooks live in
~/.config/muse/settings.json(${XDG_CONFIG_HOME}honoured) in Claude Code's shape:"hooks": {"<Event>": [{"matcher": "", "hooks": [{"type": "command", "command": "...", "timeout": <seconds>}]}]}. The file must keep"schema_version": 1. Muse rejects an unknown event name (unsupported hook event), andInterruptandToolUseStartadmit onlyasync: truehooks. MCP servers are added withmuse mcp add <name> --user -- <command> [args]. - Invocation. Hooks run in the project directory with the caller's environment (plus
MUSE_SESSION_IDandMUSE_THREAD_ID), so icx resolves the project workspace from the working directory, as for Claude Code. - Payload. Claude-Code-shaped JSON on stdin:
hook_event_name,session_id,cwd,tool_name,tool_input,tool_response,tool_use_id, plusturn_id,model,model_providerandpermission_mode;transcript_pathis null. The Bash tool'stool_responseis a JSON-encoded string (output,exit_code,terminal_status,truncated); icx stores itsoutputtext and uses itsexit_code. Subagent events carrysubagent_idandchild_session_id;Stop/SubagentStopcarrylast_assistant_message. - Replies.
hookSpecificOutput.additionalContextfrom SessionStart, UserPromptSubmit and PostToolUse reaches the model;hookSpecificOutputmust name itshookEventName. A reply'ssystemMessageis shown to the user, not the model.
| Event | icx action | Reply |
|---|---|---|
SessionStart |
Tail slot with the AHTL legend | additionalContext |
UserPromptSubmit |
Prompt-scoped tail slot (recall) | additionalContext |
PostToolUse |
Ingest the tool output (Bash JSON unwrapped) | {"hookSpecificOutput":{"hookEventName":"PostToolUse"}} |
PostToolUseFailure |
Ingest the error text as an anomaly | {} |
SubagentStart / SubagentStop |
Open / fold the subagent branch | {} |
PreCompact / PostCompact |
Seal the epoch; PostCompact also stores a compact_summary when present |
{} |
SessionEnd |
Fold open subagents, seal the epoch | {} |
| any other event | none | {} |
No output replacement. Muse refuses it ("PostToolUse output cannot replace tool output"),
so MuseAdapter::SUPPORTS_TOOL_OUTPUT_REPLACEMENT is false. Under Muse icx stores every tool
output and feeds recent activity and recall back into the conversation, like Codex; it does not
shrink tool output in Muse's own context. No reply carries a JSON null, and malformed stdin
fails open with {}.
Workspace trust. Muse loads MCP servers, the icx pager included, only in a trusted
workspace; hooks run either way. See the deployment guide §2.6 (#30).
Compatibility. AgentKind::Muse (value 8) is new in v1.3.0. A v1.2.x binary cannot read a
workspace in which a Muse event was recorded, so upgrade every agent's icx before wiring Muse.
7. Wire-Level Reverse Proxy (crates/icx-proxy)¶
icx proxy is an HTTP/1.1 listener (upstream requests are sent over HTTPS through curl).
- Bind:
127.0.0.1:49380by default (orICX_PROXY_BIND). Non-loopback binds are refused unless--allow-remoteis passed. - Authentication: every request must carry the per-install token, as the path prefix
/t/<token>or the headerx-icx-token: <token>; otherwise the proxy answers401. The header is removed before forwarding. The token is derived frominstall.keyand printed at startup (set ANTHROPIC_BASE_URL / OPENAI_BASE_URL to http://127.0.0.1:49380/t/<token>).--insecure-no-authdisables the check and is not recommended. - Routing: after the token prefix is removed, the provider is selected by an optional route prefix (
/anthropic,/openai,/gemini, stripped before forwarding), by the API path (/v1/messages,/v1/responses,/v1/chat/completions,/v1beta/models/*), or by--provider. Typical base URLs: ANTHROPIC_BASE_URL=http://127.0.0.1:49380/t/<token>OPENAI_BASE_URL=http://127.0.0.1:49380/t/<token>/v1- Upstream:
--upstream/ICX_UPSTREAM_URL, else the provider default (https://api.anthropic.com,https://api.openai.com,https://generativelanguage.googleapis.com).
Proxy Transformations¶
- Outbound Request Pass:
- Tier-0-escapes forged icx markers (
⟦ ⟧ ⟪ ⟫) anywhere in any non-system message, including the latest one, unless the block is byte-identical to one icx emitted. System/developer messages andicxpager results are left as-is. - Replaces oversized middle-history content outside the last 2 messages with deterministic AHTL packets, exempting
icxpager outputs. Folded messages are normalized to content-block form, so folded history stays byte-stable across turns. - Anthropic: keeps every client
cache_controlbreakpoint; adds at most one icx breakpoint, on the last content block of the folded region, only while the request has fewer than 4 breakpoints; uses a 1-hour TTL when a later client breakpoint uses one. - Appends the Ephemeral Tail Slot (HDC/PPR/fractal recall and unseen bus frames) to the final message, replacing any earlier tail slot.
- Inbound Response Pass:
- Expands inline dereference directives (
⟪!icx:deref(#icx:<16-hex>)⟫or⟪!icx:deref(#icx:<16-hex>,start:end)⟫) in SSE and JSON responses. Expanded content is escaped before it is returned.