Agent Binary Routing¶
amplihack supports four AI backends — claude, copilot, codex, and amplifier — each launched via the same amplihack <tool> pattern. This document explains how downstream components (recipe runner, hooks, sub-agents) know which backend is active, and why this matters.
Contents¶
- The problem
- The solution: a config-driven resolver
- Resolution algorithm
- How it propagates across processes
- Default: copilot
- Consumers
- Recipe runner
- Hooks
- Sub-agents
- Hook registration
- Security
- Related
The problem¶
The recipe runner, hooks, and various Python skill helpers must spawn new AI sessions on behalf of the user. They cannot hardcode the binary — if a user invokes amplihack copilot and triggers a recipe that spawns a follow-up session, that session must use copilot, not claude.
Earlier iterations of amplihack-rs solved this by writing AMPLIHACK_AGENT_BINARY into the subprocess environment. This worked for direct child processes but degraded badly through:
tmux new-session -d(which gives the command the tmux server's global environment, copied from whatever started the server, not the caller's; it can hold another CLI's session markers. A detached launch now hands the binary over with$(amplihack agent-binary --shell)inside the double-quoted command, which also removes them, see Active Agent Binary)- background processes started outside the caller's process tree, such as a
daemonized hook, a cron job or a service manager unit, which never had the
caller's environment (
setsidandnohupthemselves pass the environment on unchanged and lose nothing) - sub-recipes that re-exec a fresh
amplihackbinary - Python
subprocess.runcalls that inherit a partially stripped env
The result: a session started as copilot could end up running claude for late-arriving hooks or sub-recipes, and SessionEnd hooks would fail-silent looking for a claude-shaped file that did not exist.
The solution: a config-driven resolver¶
A single shared resolver (amplihack_utils::agent_binary::resolve) is now the only sanctioned way to determine the active binary. It consults four sources in order, falling through on missing or invalid input:
AMPLIHACK_AGENT_BINARYenvironment variable (explicit override), unless it is taggedAMPLIHACK_AGENT_BINARY_SOURCE=default:<same binary>as a parent's guess (issue #1481), orsession:<same binary>as a description of a session amplihack launched or observed- A live session marker: an environment variable the hosting CLI exports,
such as
CLAUDECODE,CLAUDE_CODE_ENTRYPOINTorCOPILOT_CLI(agent_binary::SESSION_MARKERS). Asession:<binary>-tagged value is one more marker of the CLI it names, ranked after that CLI's own markers <repo>/.claude/runtime/launcher_context.jsonlauncherfield, found by walking up from the working directory- Built-in default
"copilot"
There is no $AMPLIHACK_RUNTIME_ROOT layer. amplihack recipe run does set
AMPLIHACK_RUNTIME_ROOT for the runner, but the resolver never reads a
launcher context from it. Active Agent Binary
is the reference for this order; this page explains why it looks the way it does.
Resolution algorithm¶
flowchart TD
A[Caller invokes resolve(cwd)] --> B{AMPLIHACK_AGENT_BINARY set?}
B -- yes --> T{Tagged default: or session:<br/><same binary>?}
T -- yes --> M
T -- no --> V1[Validate against allowlist]
V1 -- ok --> R1[Return env value]
V1 -- reject --> M
B -- no --> M{Session marker set?<br/>a session:<cli> value counts,<br/>after that CLI's own markers}
M -- yes --> R2[Return the marker's binary]
M -- no --> L1[Start the walk-up at cwd]
L1 --> U{Directory world-writable<br/>or foreign-owned?}
U -- yes --> N[Name any launcher_context.json here<br/>as unusable, without reading it] --> D
U -- no --> F{.claude/runtime/launcher_context.json<br/>fresh, ≤64 KiB, allowlisted?}
F -- yes --> R3[Return file value]
F -- absent or unusable --> G{.git here, or 32 ancestors checked?}
G -- yes --> D[Return built-in default 'copilot']
G -- no --> L2[Move to the parent directory] --> U
Walk-up rules for the persisted launcher context:
- Return the first usable
.claude/runtime/launcher_context.json. A file that is stale (older than 24h), oversized, malformed, has no RFC 3339timestamp, is not allowlisted or escapes its directory through a symlink is skipped, and the walk continues upward. Every skipped file except a stale one is recorded with its path and reason (agent_binary::resolve_detailed), andrecipe run's stderr notice lists it when the answer was inferred (issue #1525). Before that, an empty or malformed file was dropped without a word, and a parent directory's file could answer in its place. - Stop at the first
.gitboundary; do not cross into a parent repo. - Stop at the first world-writable or foreign-owned directory (issue #1335),
without reading a
.claude/runtime/launcher_context.jsonin it. Such a file is still recorded, with the directory and why it is not trusted, so the notice names it rather than reporting only that no variable or marker was found. - Cap at 32 ancestors.
The anchor for symlink-escape checks is the walked directory in which the
file was found, the one that contains .claude/. The discovered file is
canonicalized; if the canonical path does not start with the canonical anchor,
the file is rejected.
If every layer above fails, the resolver returns the built-in default with no anchor check because there is nothing to escape from.
How it propagates across processes¶
The launcher (amplihack claude, amplihack copilot, ...) records its choice
in two places at start time:
<repo>/.claude/runtime/launcher_context.json, which later processes in the same checkout can read back (layer 3)AMPLIHACK_AGENT_BINARYin the subprocessCommandenv, taggedAMPLIHACK_AGENT_BINARY_SOURCE=session:<cli>, which children read as a session marker of that CLI (layer 2)
The launcher also removes every other CLI's session markers from the child.
The export used to be untagged, which made it layer 1, an instruction above
every marker. That was wrong for the one thing an environment variable cannot
control: where it ends up. tmux copies the environment of whatever starts its
server into the server's global environment, and every later session starts
from that copy. An agent of an amplihack copilot session that started a
server for a build gave AMPLIHACK_AGENT_BINARY=copilot to every later
session on it. A Claude Code session in one of its panes then ran every recipe
step under copilot, and so did the documented hand-off from that pane, because
the pane's own resolution was layer 1 (crusty review of #1490). The launcher's
export only says which session it started, the same kind of evidence as
COPILOT_CLI, so it now ranks with the markers. In that pane, Claude Code's
own marker answers.
The marker stripping is what keeps the ranking honest in the other direction.
A Copilot session launched from a Claude Code shell would otherwise inherit
CLAUDECODE, which outranks session:copilot.
A launcher started on an inherited default:<binary>-tagged value naming
itself does not write launcher_context.json: that launch was a guess, not a
session's choice, and persisting it would pin later runs in the checkout.
amplihack recipe run resolves once, at entry, while it can still see the
session markers of the CLI that invoked it, and exports the answer to
recipe-runner-rs as AMPLIHACK_AGENT_BINARY. Steps run under the runner's
curated environment, where those markers may be gone. When the answer came
from the launcher context or the default layer, recipe run prints a notice on
stderr naming the file it read, and any it skipped as unusable (#1525). Only an
answer from layer 1 is exported untagged. One from the default layer is tagged
default:<binary> (issue #1481), and one from a session marker or a launcher
context session:<binary>, so that a step which starts a tmux server does not
hand the run's answer to every later session on it as an instruction.
session:claude ranks ahead of every Copilot marker, so a Claude-hosted run's
steps, which lose CLAUDECODE on the way down, are not taken over by a
COPILOT_CLI that their tmux pane inherited.
An explicit AMPLIHACK_AGENT_BINARY still outranks a session marker that
names a different CLI. That is not an inference, but a stale profile export
produces the same silent wrong-CLI run, so recipe run names the session it
overrode on stderr as well. For the same reason, an AMPLIHACK_AGENT_BINARY
that fails validation is named whatever answered in its place, a session
marker included.
Inside amplihack-rs, code that picks the binary calls resolve(&cwd) rather
than reading the env var directly. One older helper,
amplihack_utils::llm_client::detect_launcher, still reads
AMPLIHACK_AGENT_BINARY itself. It honours neither tag, and it does not check
CLAUDECODE, the marker Claude Code exports. Nothing in amplihack calls it,
so it decides nothing, and it was left as it was rather than taught a ranking
that no caller exercises.
Nothing in amplihack reads the variable's presence as a sign of running as a
subprocess any more (issue #1525). Subprocess safety is decided as described in
COPILOT_SUBPROCESS_SAFE.md, and a set
AMPLIHACK_AGENT_BINARY plays no part in it.
sequenceDiagram
participant U as User
participant L as amplihack launcher
participant F as .claude/runtime/launcher_context.json
participant R as amplihack recipe run
participant S as recipe step (nested amplihack)
U->>L: amplihack copilot
L->>F: write {"launcher":"copilot",...}
L->>R: spawn with AMPLIHACK_AGENT_BINARY=copilot<br/>AMPLIHACK_AGENT_BINARY_SOURCE=session:copilot
R->>R: resolve(--working-dir) → "copilot" (layer 2)
R->>S: run step with AMPLIHACK_AGENT_BINARY=copilot<br/>AMPLIHACK_AGENT_BINARY_SOURCE=session:copilot
S->>S: resolve(step cwd) → "copilot" (layer 2)
Default: copilot¶
The implicit default changed from "claude" to "copilot". This affects only sessions where:
AMPLIHACK_AGENT_BINARYis unset (or is a tagged default guess), AND- No session marker is set, AND
- No fresh, trusted
launcher_context.jsonis found within the walk-up window
For typical use the default never matters: the launcher exports
AMPLIHACK_AGENT_BINARY tagged as its session, and a CLI session exports its
own marker. The default
only governs cold-start cases where none of those exist, and amplihack recipe
run says so on stderr when it happens.
To force claude for a single command, prefix with
AMPLIHACK_AGENT_BINARY=claude.
Consumers¶
Recipe runner¶
recipe-runner-rs does not resolve on its own; it reads the
AMPLIHACK_AGENT_BINARY (and AMPLIHACK_AGENT_BINARY_SOURCE) that
amplihack recipe run resolved and exported, and passes them to every step.
Hooks¶
Hooks are native amplihack-hooks <subcommand> commands registered in
settings. They do not resolve per-binary script files.
Sub-agents¶
amplihack-utils::llm_client::resolve_binary, claude_cli::get_claude_cli_path, knowledge_builder, and workflows::cascade all call into the shared resolver. There is exactly one read implementation in Rust.
amplihack multitask and the fleet reasoner follow the run's CLI too. With no valid AMPLIHACK_DELEGATE, a multitask workstream is delegated to amplihack <active binary> and started in that CLI's own prompt form (-p for claude and copilot, exec for codex, run for amplifier). With the default auto backend, the fleet reasoner uses its heuristic proposals when the active binary was set explicitly or observed from a live session and is not claude, and says so once; amplihack fleet dry-run --backend claude still asks for claude.
Hook registration¶
Installed settings register native hook commands such as:
amplihack-hooks dispatches the subcommand to the native Rust implementation
for each hook event. Missing or stale settings are detected by the install
verifier and hook verification code, not by resolving script files.
The user must take an explicit action — install the hook, switch binaries, or set the override. The system never silently runs claude/session_end.py in place of the missing copilot/session_end.py, and stub session_end.py files created solely to suppress the error are an architectural smell that the resolver is designed to reject. (See [PHILOSOPHY.md — Forbidden Patterns / Silent Fallbacks].)
Security¶
The resolver and hook paths are derived from values that may originate in user-controlled environment variables or files. To prevent injection and path-traversal:
| Concern | Mitigation |
|---|---|
| Path traversal | Allowlist binary names before substituting into a path; canonicalize then starts_with the root |
| Symlink escape | Reject canonicalized paths that escape the discovered repo or amplihack-home |
| Oversized config | Cap launcher_context.json reads at 64 KiB |
| JSON depth bombs | Parse with serde_json::from_str into a typed struct; reject depth > 8 (current schema is depth 2; the cap is defense-in-depth against future additions) |
| Env injection | Reject any /, \, ., ;, NUL or control char; trim; reject internal whitespace or > 32 bytes; lowercase; exact allowlist match |
| Shell-quoted values | The resolved value is never passed through sh -c; only used as Command::new(binary) or path key |
| Stale state | Files older than 24h are treated as unset |
| Diagnostic leakage | A rejected value is never logged: a rejected env value gets no log line of its own and the stderr notice names only the variable; a rejected launcher context is named by Path::display() and a fixed reason |
Related¶
- Active Agent Binary — Resolver API and full algorithm
- Environment Variables — Env var reference
- Agent Configuration — Where this fits into broader config precedence
- Hook Specifications — Per-binary hook layout and event list
- Bootstrap Parity — How the Rust CLI matches the Python launcher's environment contract