agent-commander
Rust bindings and CLI tools for controlling AI coding agents through their native command-line interfaces.
This crate provides the same core behavior as the JavaScript package: command building, process control, isolation wrappers, JSON streaming helpers, model aliasing, and read-only planning mode.
Install
Install the CLI binaries:
CLI
Common options:
--tool <name>:claude,codex,opencode,qwen,gemini, oragent--working-directory <path>: directory where the agent command runs--prompt <text>and--system-prompt <text>: user and system prompts--prompt-file <path>: read prompt input from a file for stdin-based tools--model <name>: tool-specific model alias or full model name--read-onlyor--plan-only: enforce native planning/no-write mode when supported--approve-each(alias--permission-mode ask): approve each command, relaying native permission prompts as normalized NDJSON (supported foragentandclaude)--tool-executable <path>: override the native executable for any supported tool--tool-env <KEY=VALUE>: add an environment variable to the native tool process, repeatable--tool-arg <arg>: append a raw native tool argument, repeatable--skip-default-safety-flags: suppress default autonomous safety bypass flags, including Qwen/Gemini--yolo--reasoning-effort <level>: native reasoning effort (claude--effort, codexmodel_reasoning_effort, opencode--variant)--max-output-tokens <count>for Claude Code and OpenCode--temperature <number>for@link-assistant/agent--mcp-config <path|json>and--strict-mcp-config: MCP servers (claude, codex, qwen; strict for claude)--add-dir <dir>: extra directory the agent may access, repeatable (claude, codex, gemini, qwen)--attach <file>: attach a file to the prompt, repeatable (codex--image, opencode--file)--json-schema <json>: JSON Schema the final answer must match (claude and qwen--json-schema, codex--output-schema)--gateway-base-url <url>or--gateway-router <origin>with--gateway-token-env <name>: route Claude, Codex, Agent or OpenCode through an API gateway such as link-assistant/router; the token is read from the named variable--docker-image <image>,--docker-network <network>,--docker-memory <limit>,--docker-cpus <cpus>,--docker-arg <arg>(repeatable),--docker-keep-containerconfigure Docker isolation.--timeout-ms <ms>and--close-timeout-ms <ms>configure the attached run deadline.--isolation <mode>:none,screen, ordocker--dry-run: print the command without executing it
Claude-specific options include --append-system-prompt, --fallback-model, --session-id, --fork-session, --verbose, and --replay-user-messages.
Library
use ;
async
result.metadata is a normalized summary for all six supported tools. It includes success and error classification, session ID, usage-limit reset details, result summary, cost estimates, stream token usage, optional model usage, and sub-agent call summaries. result.usage exposes the aggregated stream token usage as JSON for parity with the JavaScript package.
For large generated prompts, set prompt_file or let the controller create a temporary prompt file automatically for claude, codex, opencode, agent, qwen, and gemini.
For parity with fast-moving native CLIs, set raw executable, environment, and argument overrides for any supported tool on AgentOptions:
let mut controller = agent?;
Environment values and private input never appear on the command line, which other local users can read with ps and /proc/<pid>/cmdline (issue #60):
extra_envis applied through the child environment, as isunset_env.inherit_env: InheritEnv::Only(vec!["PATH".into(), "HOME".into()])(orInheritEnv::None) limits what the tool inherits.env: Some(...)replaces the inherited environment.- Docker isolation forwards
extra_envnames with-e NAME. - Claude system prompts are passed with
--system-prompt-fileand--append-system-prompt-file(0600 temporary files). launch.json_schemais written to a file: Codex uses--output-schema <file>, Qwen uses--json-schema @<file>, and Claude uses--json-schema "$(cat <file>)". The Claude form is still one argument, limited to 128 KiB on Linux.
The Rust controller never installs a process-exiting signal handler. A host owns SIGINT and SIGTERM and stops runs with cancel().
Completion, usage and cancellation
For direct JSON runs, metadata.success requires native completion and a successful process exit. Empty or unfinished streams return incomplete_stream; Agent's default NDJSON mode uses the same check. Protocol parsing and usage use stdout, while plain_output retains stderr diagnostics. Parent session metadata excludes Claude subagent-scoped results.
AgentStartOptions { timeout, close_timeout, .. } sets an overall deadline and its termination grace. On expiry, stop() returns exit_code: None, error_type: Some("timeout"), captured output and partial usage. Other exit codes are returned as Some(code).
stop() waits for an attached process to finish. AgentStopOptions { close_timeout, background_wait, .. } ends a process that stays alive after its final result (the Claude print-mode hang, hive-mind#1280), allowing background_wait more while the result reports running background tasks. Such a run keeps success with terminated_after_result. controller.cancel().await? interrupts it and collects the final result. Unix cancellation signals the process group; Windows cancellation signals the immediate child. A native CLI that ignores SIGTERM needs a caller-managed termination policy. Process pipes drain concurrently from start, including when attached output is disabled. Set AGENT_COMMANDER_DEBUG=1 for cancellation diagnostics.
When a failed Codex or Claude run did not print its usage limit, stop() reads the last turn of the Codex rollout or the last entry of the Claude transcript and sets limit_source to codex-rollout or claude-transcript (hive-mind#3570). A CODEX_HOME or CLAUDE_CONFIG_DIR in extra_env is honoured. The checks are public: apply_codex_rollout_usage_limit, detect_codex_rollout_usage_limit, can_resume_codex_session (hive-mind#2888), apply_claude_transcript_usage_limit and read_claude_transcript_api_error, with CodexRolloutOptions and ClaudeTranscriptOptions. detect_usage_limit_sources and is_recoverable_tool_error are Hive Mind's classifiers.
Usage preserves native final totals without adding repeated assistant snapshots. Codex input_tokens now counts fresh input; add cache_read_tokens to recover inclusive input. Serializable usage structs expose cache and reasoning fields, and Qwen/Gemini results now include usage too.
Bundled aliases track a recorded Hive Mind catalogue (v2.39.5: sonnet is claude-sonnet-5-5, opus is claude-opus-5-5); exact model IDs pass through for caller-managed live discovery. Omitting model leaves selection to the native CLI. Claude's opus execution alias stays rolling. Common resume works for all six tools; Agent adds --no-fork, and OpenCode uses --session.
See the parity audit for the feature matrix and regression evidence.
Launch options, live input and run telemetry
use ;
# async
A tool without a native flag for a launch option is rejected before it starts; launch_capabilities(tool) reports what each tool supports. attachments works for Codex (--image) and OpenCode (--file). launch.json_schema (JSON text) asks Claude, Codex or Qwen for an answer that matches the schema and reports it as metadata.structured_output. launch.gateway (GatewayOptions { base_url | router, token_env, standalone_web_search }) routes Claude, Codex, Agent or OpenCode through an API gateway without putting the token on the command line; standalone_web_search (None = on with router) lets Codex Responses Lite models use the gateway's standalone web search. AgentOptions::fail_fast_on_auth_error (None = on with a gateway) stops Claude on its first 401/403 retry with error_type: "auth_refused"; metadata.api_error_status (for Codex too) and metadata.api_retry_status report the HTTP status. interrupt().await ends the running turn for Claude and Qwen; end_input() closes stdin. metadata.usage_windows comes from Claude rate_limit_event messages and Codex rate_limits; metadata.context_usage reports the last and peak context fill against the model's window. For Codex, stop() reads both from the thread's rollout file. See launch options and the upcomputer case study.
Set LaunchOptions::max_output_tokens for Claude Code or OpenCode and LaunchOptions::temperature for @link-assistant/agent. Check the corresponding booleans on launch_capabilities(tool) before starting a run.
Tool overrides
AgentOptions.tool_overrides (ToolOverrides) replaces a failing or missing part of a tool for one run: build_command, parse_output, extract_session_id, extract_usage or launch_capabilities. With a build_command it also drives a CLI that is not registered. build_base_command returns the built-in native command for the builder to extend.
use ;
use Arc;
#
cargo run --example tool_overrides prints the resulting dry-run command. See tool overrides.
Shared Behavior
JavaScript and Rust expose the same core concepts:
- Tool selection and model alias mapping
none,screen, anddockerisolation modes- Dry-run command preview
- JSON/NDJSON output parsing for tools that support it
- Read-only planning mode for tools with enforceable native restrictions
- Per-command approval (ask mode) with a normalized
permission_request/permission_responserelay for tools with a drivable native handshake - Launch options, live input, usage windows, context usage and the tool version probe
- Per-run tool overrides for the command builder, output parser, session ID and usage extractors, and launch capabilities
See shared concepts for behavior that should stay aligned across both packages, including the per-command approval parity table.
Release Flow
Rust releases use changelog fragments in rust/changelog.d/:
bump: patch
-
The GitHub Release workflow publishes language-specific releases with rust_ tags and [Rust] vX.Y.Z release names.
Test
Interactive Terminal Capture
Use tui::capture_agent_tui when a test needs the client's real terminal
interface rather than its headless JSON mode. The capture drives text, control
keys, and resizes through a PTY, then returns an unrolled transcript, normalized
message/tool-call events, settled frames, and asciicast-compatible replay data.
When artifact_directory is set it also writes a transcript, frame data, a
static snapshot, a cast, and an animated SVG suitable for CI artifacts.
frames_on_write: true records a frame after every PTY write instead of after
each settle, and recording: false keeps only the latest frame and the last
1 MB of output for long sessions (command-stream 1.9.0).
use ;
let capture = capture_agent_tui?;
println!;
# Ok::