# Provider: `claude-bridge` — the agent CLI as a provider (no Agent SDK)

An alternative provider that routes through your **local agent CLI** — the
coding CLI of the Agent SDK vendor — instead of the
`@anthropic-ai/claude-agent-sdk`. It uses your existing CLI sign-in and needs no
API key. All agent capability (tools, sub-agents, MCP, hooks) is preserved
because it lives in Alvin's own orchestration, not in the SDK — so the bot can
run fully SDK-independent (useful as a fallback, or where the SDK isn't
preferred).

> Advanced, opt-in option. As with any provider, make sure your usage complies
> with the relevant provider's terms of service.

## Why this works without losing features

Alvin's `OpenAICompatibleProvider` already runs its **own** tool loop
(`tool-executor.ts`, 8 tools) and its **own** sub-agent orchestration
(`subagents.ts`, which just calls `registry.queryWithFallback()`). So a provider
only has to: accept OpenAI `/chat/completions` **with a `tools` array** and
return real **`tool_calls`** for Alvin to execute. A local bridge that fronts
the CLI binary does exactly that.

```
Alvin (OpenAICompatibleProvider tool loop + sub-agents)
   → POST /v1/chat/completions  (tools[], stream:false)
      → bridge (localhost, bot-managed)
         → spawns the agent CLI (uses your CLI sign-in)
      ← OpenAI tool_calls  (parsed from the model's <tool_call> text)
   → executeTool() runs the tool (EXEC_SECURITY allowlist + path-safety guards)
   → next round → final answer
```

The model itself never touches the filesystem: the bridge spawns the CLI with
`--tools ''`, so it only *emits* `<tool_call>` blocks; **Alvin** executes them
under its own safety guards.

## What stays / what is dropped vs the Agent SDK

The parity work (capability flags + a few bridge-specific seams) brings the
bridge to near-feature-parity with the SDK. **Stays / now wired:** sub-agents
(parallel), **detached dispatch** (the agent CLI in print mode), the 8-tool
loop, **mid-task stop**, **`/effort`** (→ `--effort`), **live `/btw`
steering**, **per-workspace overrides** (model / temperature / toolset /
effort), external MCP client, hook event bus, fallback chain, budget/usage,
cron, memory, streaming.

**Dropped (genuinely SDK-native):** the SDK's *internal* `Task` tool (Alvin's
own sub-agent orchestration replaces it), `.jsonl` session continuity (falls
back to Alvin's own `history[]`), the 1M-context beta, the SDK `PostToolUse`
fence hook. External MCP tools are NOT in the LLM loop on *either* provider
(SDK or bridge) — they're only callable via `/mcp` — so that's parity, not a gap.

## Command compatibility

Coupling was moved from hardcoded checks on the provider type to
Provider **capability flags** (`supportsDispatch`, `supportsLiveSteer`,
`supportsReasoning`), so the bridge opts into the same behaviours. All commands
work on the bridge:

| Command | Bridge | How |
|---|---|---|
| `/stop` `/cancel` `/stopall` | ✅ | abortSignal cuts the fetch + the tool loop bails at round/tool boundaries; the bridge kills its CLI process on disconnect. (Sync execSync tools finish their own 30s timeout.) |
| `/effort` | ✅ | provider forwards `reasoning_effort` → CLI `--effort` (gated on `supportsReasoning`). |
| `/btw` (live steering) | ✅ | `supportsLiveSteer`; the tool loop drains the SteerChannel between rounds and folds notes into the running turn. Plain mid-task messages steer too. |
| Detached sub-agents | ✅ | `supportsDispatch`; the `alvin_dispatch_agent` function tool spawns the same raw CLI print-mode process the SDK does. |
| Parallel sub-agents | ✅ | Alvin's own orchestration → `queryWithFallback`, provider-agnostic. |
| Workspace overrides | ✅ | model / temperature / effort forwarded; `toolset` (readonly/research) gates the exposed tools by name mapping — a readonly workspace can't write or run shell on the bridge. |
| `/model` | ✅ | bridge special-case lists/sets the vendor's three model tiers (`*-latest` ids, see below), persisted via `CLAUDE_BRIDGE_MODEL`. |
| `/status` | ✅ | reasoning badge + context meter capability-keyed; rendered like the other CLI-based provider. |
| `/new` `/dir` `/verbosity` `/continuation` `/export` `/provider` `/mcp` `/cron` … | ✅ | bot-level, provider-agnostic. |

Steering nuance: the bridge folds notes at tool-round / message boundaries (the
bridge resumes the same CLI session each round), not mid-token. This
matches the SDK's own behaviour, which integrates steer messages at message
boundaries too. Verified live: a mid-task /btw redirected a running turn's
output (topic + language) and dropped the original.

## Bot wiring

- `src/providers/types.ts` — `claude-bridge` preset (openai-compatible,
  `supportsTools:true`, loopback baseUrl, `options.managed:"claude-bridge"`).
- `src/providers/claude-bridge-provider.ts` — `ClaudeBridgeProvider` (subclass
  of `OpenAICompatibleProvider`) adds a `ProviderLifecycle` + capability flags.
- `src/services/claude-bridge-manager.ts` — on-demand **auto-spawn /
  health-check / stop**, exactly like `ollama-manager`. Spawns the bridge from
  `CLAUDE_BRIDGE_DIR` (default `~/.alvin-bot/claude-bridge`), pins `CLAUDE_BIN`,
  derives ports from `CLAUDE_BRIDGE_URL`. Degrades to an info-log (never a throw)
  when the bridge isn't installed or the CLI isn't signed in.
- `src/providers/registry.ts` — **always** registers the bridge (Ollama
  parity) so it's selectable at runtime; `createProvider` returns the
  lifecycle-aware `ClaudeBridgeProvider`. No API key.
- `src/providers/openai-compatible.ts` — the tool loop sends explicit
  `stream:false` **for the bridge**; honors per-query model/temperature; gates
  tools by `allowedTools`; drains the SteerChannel for `/btw`.
  Since v5.120.0 the loop streams (`stream:true` + `stream_options`) against
  every OTHER OpenAI-compatible endpoint. The bridge is deliberately excluded,
  and this is not an oversight to "fix": once its stream headers are out, a CLI
  failure can only be reported as a text chunk `\n\n[Error: …]` instead of an
  HTTP 500 (`claude-bridge/src/server.js`), and the empty-completion 502 is not
  sent at all — so the bot would book an error message as an answer and never
  fall over to the next provider. It gains nothing either: the bridge emits its
  whole answer in a single frame. Streaming here needs a real error frame (or a
  502 before `flushHeaders`) in the bridge server first.
- `bin/cli.js` — setup wizard lists it; `/provider use claude-bridge` switches at
  runtime. The bridge itself is bundled, so there's no separate install step.
- `claude-bridge/` — the vendored, patched bridge (CommonJS), shipped with the
  package. `express`/`uuid` are alvin-bot dependencies, so it resolves them from
  the parent install; state/log are written to `~/.alvin-bot/`.

Enable it — pick the **Code CLI bridge** entry in `alvin-bot setup`, or:

```
PRIMARY_PROVIDER=claude-bridge          # or: Telegram → /provider use claude-bridge
# optional overrides:
CLAUDE_BRIDGE_URL=http://127.0.0.1:3456/v1
CLAUDE_BRIDGE_MODEL=claude-sonnet-latest   # or claude-opus-latest / claude-haiku-latest
CLAUDE_BRIDGE_DIR=~/.alvin-bot/claude-bridge
```

The bot **auto-spawns and health-checks** the bridge on demand.

## The bundled bridge

The bridge ships **with** alvin-bot (vendored at `claude-bridge/`), so there's
nothing to install — the bot auto-spawns it on demand and it updates with
`/update`. It's a slim fork of
[`shinglokto/openclaw-claude-bridge`](https://github.com/shinglokto/openclaw-claude-bridge)
(MIT — see `claude-bridge/LICENSE`) with the React dashboard removed and a few
patches applied (documented in `claude-bridge.upstream.patch`). Without those
patches the model refuses the protocol, hallucinates, or drops tool arguments:

1. **`src/claude.js`** — spawn the CLI with `--setting-sources ''` and
   `--strict-mcp-config`, so the CLI does NOT auto-load the host's global
   `CLAUDE.md` + any configured MCP servers. Otherwise that context (a) bloated
   input from ~600 to ~72,000 tokens and (b) made the model think its tools were
   those MCP servers and **refuse** `read_file`/`run_shell`. Also: `mapEffort`
   passes `low|medium|high|max` straight to `--effort`.
2. **`src/tools.js`** — include each tool's full **parameter schema** (names,
   types, required, descriptions) in the protocol instructions, not just
   name+description; plus stronger "nest args under `arguments`; STOP after the
   call; don't fabricate results" wording. Took tool-call compliance from ~50%
   to 5/5 in trials.
3. **`src/server.js` `parseToolCalls`** — robust argument extraction. The model
   often **flattens** args to the top level
   (`{"name":"python_execute","code":"…"}` instead of nesting under
   `arguments`); recover every non-reserved key. Plus a lenient JSON repair for
   raw control chars inside string values. Without this, multi-line args
   (python/code) were silently dropped → the tool ran with `{}` and errored.
4. **Bundling** — `src/index.js` binds the status port to **loopback** (was
   `0.0.0.0`); `src/server.js` writes its state file to a **writable** path
   (`CLAUDE_BRIDGE_STATE_FILE`, default `~/.alvin-bot/`) and only serves the
   dashboard if present (the slim fork ships none).

Prereq: be **signed in to the agent CLI** (`claude auth status` →
`loggedIn:true`). No separate CLI install is needed — `findClaudeBinary()` uses
the CLI binary that ships with the Agent SDK dependency (and updates with
alvin-bot), preferring your own newer system install if present. So the bridge
inherits the same (newest) CLI the SDK path uses.

## Verified (live E2E, 2026-06-16, two machines)

- **Tool loop / all 8 function-callings:** run_shell, read_file, write_file,
  edit_file, list_directory, python_execute (un-fakeable SHA256), web_fetch,
  web_search — 8/8 routed bridge → `executeTool` (no SDK in chain).
- **read_image (v5.131.0, suite-verified, live E2E pending):** the ninth tool
  reads local PNG/JPEG/WebP/GIF through the same `executeTool` path; the
  tool_result image is forwarded as its own user message (see
  `test/read-image-tool.test.ts`). The 2026-06-16 live pass above predates it —
  the bridge-parity suite pins the 9-tool catalog, a live bridge E2E still has
  to confirm it once.
- **Sub-agent fan-out:** 3 `spawnSubAgent()` concurrently, 3/3 correct.
- **Detached dispatch:** the bridge LLM called `alvin_dispatch_agent` → a real
  detached CLI print-mode process spawned, output files on disk.
- **Mid-task stop:** abort after the 1st of 5 tools → halted at 1/5.
- **/effort:** `effort:"high"` → bridge spawned the CLI with `--effort high`
  (thinking on).
- **Live /btw steering:** a mid-task note redirected a running turn (ocean poem
  → German mountains poem; original dropped).
- **Workspace `readonly`:** a write was blocked (no write tool available, nothing
  on disk) while `read_file` still worked.
- **Lifecycle:** with the bridge stopped, `queryWithFallback` auto-spawned it.
- Full unit suite green incl. `bridge-parity`, `registry-claude-bridge`,
  `openai-compatible-stream-false`, `provider-models`, `steer-routing` tests.

> macOS note: the CLI login token lives in the login keychain, which is
> **locked in a non-interactive SSH session** (the auth status reports
> `loggedIn:false` over SSH even when logged in). Run the bot/bridge in a GUI or
> launchd session (or set `CLAUDE_CODE_OAUTH_TOKEN`) so it can read the token.

## Caveats

- **One login = shared rate limits** across parallel sub-agents.
- Per-round latency: a fresh CLI spawn per request (no `.jsonl` reuse).
- The bridge runs as a small bundled local service (loopback only, auto-managed,
  state/log in `~/.alvin-bot/`).
