# Agent Inspector

Agent Inspector is an agent observability and knowledge-capture platform for AI coding tools. It keeps the local proxy, log capture, MCP, and Chrome companion foundation, and evolves it toward agent interaction analysis, knowledge extraction, and memory-ready workflows for systems such as OpenClaw.

> **设计理念：** Agent Inspector 以 Rust/Tokio 高性能透明代理为核心、TypeScript/Node.js/Bun 为工程与生态底座、React 19 + Vite 7 + TanStack Router + Tailwind CSS 4 构建解耦实时界面，通过 Anthropic/OpenAI 双协议、SSE 并行转发、REST/MCP 人机共用接口、JSONL 权威存储与 SQLite 可重建索引，实现低延迟、可观测、跨平台、可扩展、安全隔离且全链路可降级的 AI Coding Agent 架构。

The npm package and CLI remain `agent-inspector`; the platform name is Agent Inspector.

## What It Does

- Runs a local transparent proxy for Anthropic and OpenAI-compatible APIs, including OpenAI Chat
  Completions and Responses paths.
- Captures model requests, responses, tool definitions, token usage, and errors.
- Provides a web UI for browsing sessions and logs in real time.
- Exposes sessions, logs, runs, and evidence packs through MCP Tools, Resources, and Prompts.
- Includes a Chrome companion extension for quick capture status and log navigation.
- Generates reviewable knowledge candidates from agent sessions.
- Bridges approved knowledge to OpenClaw while keeping OpenClaw hidden behind the Inspector surface.

## Quick Start

Install the published CLI:

```bash
npm install -g @tonyclaw/agent-inspector
agent-inspector
```

Optional MCP-first companion package:

```bash
npm install -g @tonyclaw/agent-inspector-mcp
agent-inspector-mcp doctor --url http://localhost:9527/inspector/api/mcp
```

Agent Inspector requires Node.js 22 or newer. Node.js 24 LTS is recommended for production use.
When using npm 12, use Node.js `24.15.0` or newer (`24.18.0` is verified) so npm's engine checks
do not warn during installs, releases, or smoke tests.

By default, Agent Inspector binds to `127.0.0.1` and local tools need no Inspector credential.
With `--host 0.0.0.0`, non-loopback coding tools must authenticate `/proxy` with a dedicated
`AGENT_INSPECTOR_PROXY_TOKEN`, supplied as `Proxy-Authorization: Bearer <token>` or
`X-Agent-Inspector-Proxy-Token: <token>`. Provider `Authorization` remains separate and is never
accepted as the Inspector proxy credential. The UI, REST API, and MCP control plane remain
local-only unless `AGENT_INSPECTOR_CONTROL_TOKEN` is configured for authenticated remote API/MCP
clients. `AGENT_INSPECTOR_ALLOW_UNAUTHENTICATED_REMOTE_PROXY=1` and
`AGENT_INSPECTOR_ALLOW_REMOTE_CONTROL=1` are temporary compatibility overrides intended only for a
trusted firewall or loopback-only port mapping.

The packaged CLI keeps the protected identity ingress enabled even on loopback because it also owns
Host validation, CSRF enforcement, credential scoping, and first-hop byte budgets. Disabling it with
`--no-identity-proxy` requires the explicit diagnostic-only
`AGENT_INSPECTOR_ALLOW_UNPROTECTED_INGRESS=1` override.

When exposing Inspector through a named reverse proxy, add its public hostname to the comma-separated
`AGENT_INSPECTOR_TRUSTED_HOSTS` allowlist. Browser mutations require same-origin CSRF proof; the
built-in UI supplies it automatically. The public ingress streams request bodies with backpressure
and defaults to a 64 MiB hard limit and a 120 second body deadline; override these with positive
integer byte/millisecond values in `AGENT_INSPECTOR_MAX_REQUEST_BYTES` and
`AGENT_INSPECTOR_REQUEST_TIMEOUT_MS` when a trusted workload requires different bounds.

`@tonyclaw/agent-inspector` runs the proxy, REST/SSE API, storage, and built-in `/api/mcp`
endpoint. Its default composed mode also serves the independently built UI; `--backend-only`
leaves every Coding Agent endpoint running without UI files. `@tonyclaw/agent-inspector-mcp` is the
enhancement package for stdio-first MCP clients and setup automation; it bridges to the local
Inspector endpoint without moving your captured evidence out of the machine.

On Windows, the npm install step creates a local `agent-inspector.exe` runtime
from the user's installed Node.js runtime. The long-running server process
therefore appears in Task Manager as **Agent Inspector <version>** with the
project icon. The executable also carries standard `FileVersion` and
`ProductVersion` metadata for the installed package version. If npm lifecycle
scripts are disabled, Agent Inspector falls back to `node.exe` and keeps
working normally. Set `AGENT_INSPECTOR_SKIP_WINDOWS_RUNTIME=1` to skip the
Windows runtime metadata step explicitly.

### Rust backend

Agent Inspector defaults to the Rust backend when the current platform has a verified native
backend package installed. If the platform package is missing or fails package, manifest, hash, or
runtime identity validation, startup automatically falls back to the TypeScript backend. Use
`--backend typescript` to force the TypeScript backend, or `--backend rust` to require Rust and fail
closed when the native package is not valid.

```bash
agent-inspector --backend-only --no-open
agent-inspector --backend typescript --backend-only --no-open
agent-inspector --backend rust --backend-only --no-open
```

On Windows x64, installable releases include the native optional package
`@tonyclaw/agent-inspector-backend-win32-x64-msvc`; Linux x64 and macOS arm64 native packages are
tracked as delayed targets. If the optional native package is unavailable, build the Rust server
from source:

```powershell
$env:RUSTUP_TOOLCHAIN = "1.95.0-x86_64-pc-windows-msvc"
cargo build --manifest-path rust-backend\Cargo.toml --locked --release --package agent-inspector-server --target x86_64-pc-windows-msvc
```

For a backend-only health smoke on an isolated port:

```powershell
$dir = Join-Path $env:TEMP ("agent-inspector-rust-" + [Guid]::NewGuid().ToString("N"))
New-Item -ItemType Directory -Force $dir | Out-Null
$env:AGENT_INSPECTOR_DATA_DIR = $dir
$env:AGENT_INSPECTOR_PORT = "9537"
$env:PORT = "9537"
$env:AGENT_INSPECTOR_BASE_PATH = "/"
$env:AGENT_INSPECTOR_PUBLIC_ORIGIN = "http://127.0.0.1:9537"
.\rust-backend\target\x86_64-pc-windows-msvc\release\agent-inspector-server.exe
```

Then verify from another shell:

```powershell
Invoke-WebRequest -UseBasicParsing http://127.0.0.1:9537/api/health
Invoke-WebRequest -UseBasicParsing http://127.0.0.1:9537/api/runtime
```

For Linux containers, the Windows runtime setup is a no-op. To keep images lean,
install with optional dependencies omitted:

```bash
npm install -g --omit=optional @tonyclaw/agent-inspector
```

Optional guided setup:

```bash
agent-inspector onboard
```

The onboarding command installs guided setup skills for local agents:

The generated instructions and automatically merged MCP entries derive the backend Base URL from
`AGENT_INSPECTOR_PUBLIC_ORIGIN` (or the default local CLI origin) plus
`AGENT_INSPECTOR_BASE_PATH`. The default is `http://localhost:9527/inspector`. This control/agent
Base URL is separate from both the optional UI URL and each Provider's upstream Base URL.

- Claude Code: `~/.claude/skills/agent-inspector-onboard/SKILL.md` plus a slash command.
- Codex: `~/.codex/skills/agent-inspector-onboard/SKILL.md`, focused on connecting
  `<agent-base-url>/api/mcp` through Codex `mcp_servers.agent-inspector`.
- OpenCode: run `agent-inspector onboard --opencode-only` to merge
  `mcp.agent-inspector` into `~/.config/opencode/opencode.json` or `opencode.jsonc`, then verify
  with `opencode mcp list`.
- MiMo Code: run `agent-inspector onboard --mimo-only` to merge `mcp.agent-inspector` into
  `~/.config/mimocode/mimocode.jsonc` or `mimocode.json`, then route MiMo through the proxy with
  `OPENAI_BASE_URL=<agent-base-url>/proxy/v1`.

During npm global install, Agent Inspector also makes a best-effort onboarding skill install for
detected local agents. If `~/.claude` exists, it installs the Claude Code skill and slash command.
If `~/.codex` exists, it installs the Codex skill. Generated onboarding files are stamped with the
current npm package version; a later package install refreshes older generated files automatically,
while same-version, newer-version, or user-created files without Agent Inspector version metadata are
left in place.

Set `AGENT_INSPECTOR_SKIP_CLAUDE_SKILL=1` or `AGENT_INSPECTOR_SKIP_CODEX_SKILL=1` to skip either
postinstall step. Set `AGENT_INSPECTOR_INSTALL_CLAUDE_SKILL=1` or
`AGENT_INSPECTOR_INSTALL_CODEX_SKILL=1` to attempt installation even before the corresponding agent
home directory exists. To refresh generated onboarding files later, run
`agent-inspector onboard --force`.

To check what is installed, run `agent-inspector onboard --status`. It reports each generated file,
its stamped version, whether it is current/outdated/custom, and the suggested next command. For
scripts and CI checks, use `agent-inspector onboard --status --json`.

OpenCode and MiMo Code config is explicit rather than installed during npm postinstall, because it
edits a real tool config file instead of adding an Agent Inspector generated skill. Use
`agent-inspector onboard --status --opencode-only --json` or
`agent-inspector onboard --status --mimo-only --json` to inspect those MCP entries.

For coding agents that must address more than one Inspector, onboarding can target either a
registered Windows instance or an explicit wrapper URL:

```powershell
agent-inspector onboard --instance review --force
agent-inspector onboard --instance review --mcp-name agent-inspector-review --opencode-only --force
agent-inspector onboard --base-url https://tools.example.test/inspector --mcp-name team-inspector --force
agent-inspector onboard --control-base-url https://control.example.test/inspector `
  --agent-base-url https://agent.example.test/inspector `
  --ui-url https://ui.example.test/observe --mcp-name team-inspector --force
agent-inspector onboard --control-base-url https://control.example.test/inspector `
  --agent-base-url https://agent.example.test/inspector --no-ui --force
```

`--instance` resolves the saved instance URL and defaults the MCP config key to
`agent-inspector-<instance>`. `--base-url` accepts a credential-free HTTP(S) backend control/agent
Base URL as a compatibility shortcut; it does not imply that a browser UI exists. Separated
deployments can set `--control-base-url`, `--agent-base-url`, and either `--ui-url` or `--no-ui`.
`--instance` is mutually exclusive with every explicit URL option. `--mcp-name` selects the exact MCP
config key, allowing the generated config to preserve other Inspector entries. Explicit per-client
MCP URL options still take precedence over the resolved target.

Before uninstalling the npm package, run `agent-inspector onboard --uninstall` to remove matching
generated onboarding files. The uninstall command only removes Agent Inspector generated files whose
metadata version matches the currently installed npm package. npm v7+ does not run package uninstall
lifecycle scripts, so `npm uninstall -g @tonyclaw/agent-inspector` alone cannot reliably clean these
files automatically.

For local development from source:

```bash
bun install
bun run dev
```

### Deployment modes and runtime Base URLs

Agent Inspector ships one compatible UI/backend release but can run it in three topologies:

| Mode | Start | UI | Coding Agent surfaces |
| --- | --- | --- | --- |
| Composed (default) | `agent-inspector` | Served by the protected public ingress | REST, SSE, proxy, health, and MCP use the same public backend Base URL. |
| Backend-only | `agent-inspector --backend-only --no-open` | Not served; document requests return a bounded headless response | REST, SSE, proxy, health, MCP, capture, and named-instance control remain available. |
| Standalone UI | Build/host `.output/ui` with SPA fallback | Served by a separate static host | The UI reads operator runtime configuration and calls an explicitly configured backend. |

Do not use "Inspector Base URL" to mean every surface implicitly. The browser-safe runtime
contract keeps three locations explicit:

- UI Base Path: router/asset mount for the static UI.
- Control Base URL: REST, uploads/downloads, mutations, and log SSE.
- Agent Base URL: model proxy, OpenAI-compatible `/proxy/v1`, and MCP guidance.

Composed and backend-only deployments currently publish the same backend Base URL for control and
agent traffic, but clients must still use the corresponding runtime field. A separately hosted UI
has its own origin and mount path. `GET <control-base-url>/api/runtime` returns a versioned,
token-free, `no-store` discovery document with deployment mode and capabilities.

External coding agents should read `availableBaseUrls` from that document instead of assuming
whether the deployment is mounted at `/inspector` or `/`. The configured Base Path is listed first,
followed by the compatible root entry, with duplicates removed. For example:

```json
{
  "availableBaseUrls": [
    "http://localhost:9527/inspector",
    "http://localhost:9527"
  ]
}
```

Clients can append `/proxy` for Anthropic, `/proxy/v1` for OpenAI-compatible protocols, or
`/api/runtime` to verify a candidate before adopting it.

The static UI loads `runtime-config.js` before the application bundle. For a separately hosted UI,
replace `.output/ui/runtime-config.js` with an operator-owned value such as:

```js
window.__AGENT_INSPECTOR_RUNTIME_CONFIG__ = {
  schemaVersion: 1,
  deploymentMode: "separated",
  ui: { basePath: "/" },
  control: { baseUrl: "http://127.0.0.1:19527/inspector" },
  agent: { baseUrl: "http://127.0.0.1:19527/inspector" },
  capabilities: { rest: true, sse: true, proxy: true, mcp: true },
};
```

Replace the example URLs with the exact backend URLs printed by the CLI or returned by
`agent-inspector instance connect <name> --json`. Base URLs must be credential-free HTTP(S) URLs
without query or fragment. Never put Provider keys, control tokens, or proxy tokens in
`runtime-config.js`, bootstrap HTML, query strings, or browser storage.

The standalone static host must send a CSP whose `connect-src` contains only `'self'` and the exact
configured control origin; never use `*`. Composed mode generates a same-origin CSP at the protected
ingress. If the control Base URL changes, update `runtime-config.js` and CSP together.

For a local UI that directly calls another local origin, set a comma-separated exact loopback
allowlist on the protected backend, for example:

```bash
AGENT_INSPECTOR_UI_ORIGINS=http://127.0.0.1:4173,http://localhost:4173 agent-inspector --backend-only
```

`AGENT_INSPECTOR_UI_ORIGINS` accepts only exact `http`/`https` loopback origins: no wildcard,
credentials, path, query, fragment, or non-loopback hostname. It enables the control API/SSE CORS
path only; browser CORS access to `/proxy` and `/api/mcp` stays forbidden. A non-loopback remote UI
must use an authenticated same-origin gateway that protects the public edge and forwards to the
loopback Inspector backend. Do not use the loopback CORS allowlist as remote authentication.

When a reverse proxy changes the browser-visible scheme/host/port, set the exact external origin
separately from the Base Path:

```bash
AGENT_INSPECTOR_PUBLIC_ORIGIN=https://tools.example.test \
AGENT_INSPECTOR_BASE_PATH=/inspector \
agent-inspector
```

`AGENT_INSPECTOR_PUBLIC_ORIGIN` is an origin only; it allows no credentials, path, query, or
fragment. It drives request-local runtime discovery, copied endpoint guidance, and MCP outward URLs;
the proxy must also be included in `AGENT_INSPECTOR_TRUSTED_HOSTS` when its hostname is not otherwise
trusted.

Independent source workflows:

```bash
bun run dev             # Windows-safe supervisor: backend dev server + UI dev server
bun run dev:backend     # backend route tree only (development listener)
bun run dev:ui          # static UI dev server; same-Base-Path proxy by default

bun run build:backend   # .output/server
bun run build:ui        # .output/ui
bun run build           # both artifacts plus CLI/workers/MCP and boundary checks

bun run start:backend   # protected production CLI in backend-only mode
bun run preview:ui      # preview the independently built static UI
```

For a true separate-origin development UI, inject its runtime surfaces instead of relying on the
same-Base-Path dev proxy:

```bash
AGENT_INSPECTOR_UI_BASE_PATH=/observe \
AGENT_INSPECTOR_UI_CONTROL_BASE_URL=http://127.0.0.1:19527/inspector \
AGENT_INSPECTOR_UI_AGENT_BASE_URL=http://127.0.0.1:19527/inspector \
AGENT_INSPECTOR_UI_PORT=4173 bun run dev:ui
```

The backend must allow that exact local UI origin with `AGENT_INSPECTOR_UI_ORIGINS`. The explicit
control/agent variables are used only by UI dev/preview; production static hosting continues to use
the operator-owned `runtime-config.js` so one `.output/ui` artifact remains relocatable.

The direct backend development listener is loopback-oriented and is not a replacement for the
protected production ingress. An arbitrary static host must provide SPA fallback for supported deep
links such as `/session/<id>`.

Run a local health check when you need to verify the proxy and installed
configuration:

```bash
agent-inspector doctor
```

The default doctor check covers proxy health, provider configuration, and
package metadata. Chrome companion source and zip artifacts are optional and
only checked when you ask for them explicitly:

```bash
agent-inspector doctor --chrome-extension
```

Then point an AI coding tool at the agent Base URL reported by the CLI or connection descriptor:

```bash
ANTHROPIC_BASE_URL=http://localhost:9527/inspector/proxy <tool>
```

In default composed mode, the web UI runs at `http://localhost:9527/inspector`. The public proxy
endpoint is `http://localhost:9527/inspector/proxy`; internally Agent Inspector may run the app on a
private helper port, but AI tools should use the public URL printed by the CLI.

When the dashboard has no captured requests, its copyable Claude, OpenCode, OpenAI, OpenAI `/v1`,
and MCP examples are derived from the resolved browser runtime contract. They therefore use the
configured agent surface even when the UI origin, backend origin, or Base Path differs from the
default.

### Base path

Agent Inspector defaults to the `/inspector` public base path:

```bash
agent-inspector
```

In composed mode this additionally generates these browser document/asset URLs:

- Web UI: `http://localhost:9527/inspector`
- Assets: `http://localhost:9527/inspector/assets/...`
- Sessions: `http://localhost:9527/inspector/session/...`

Both composed and backend-only modes keep these backend endpoints at the derived control/agent
Base URL:

- REST API: `http://localhost:9527/inspector/api/...`
- Runtime discovery: `http://localhost:9527/inspector/api/runtime`
- Health: `http://localhost:9527/inspector/api/health`
- MCP: `http://localhost:9527/inspector/api/mcp`
- Proxy: `http://localhost:9527/inspector/proxy`

AI tools should use the prefixed proxy URL:

```bash
ANTHROPIC_BASE_URL=http://localhost:9527/inspector/proxy <tool>
```

To run at the domain root instead, explicitly set the base path to `/`:

```bash
AGENT_INSPECTOR_BASE_PATH=/ agent-inspector
```

### Runtime Base Path aliases

An already-running Inspector can expose an additional path without starting a second runtime or
sharing its data directory with another process. For example, after starting the canonical UI at
the domain root, add `/inspector` on the same origin and port:

```bash
AGENT_INSPECTOR_BASE_PATH=/ agent-inspector --background --no-open
agent-inspector alias add /inspector
```

The canonical and alias URLs share the same Providers, logs, sessions, MCP server, workers, and live
SSE state. Manage the current runtime's aliases with:

```bash
agent-inspector alias list
agent-inspector alias remove /inspector
```

Use `--port <port>` and `--host <host>` when the running local Inspector does not use
`localhost:9527`. Runtime aliases are intentionally temporary and are cleared when the Inspector
supervisor restarts; configure `AGENT_INSPECTOR_BASE_PATH` when a path must remain canonical across
restarts.

### Windows named instances

Use a named instance when the second URL must have its own Providers, runtime configuration, logs,
sessions, workers, and data directory. Named instances run as hidden background supervisors on
Windows; the command waits for readiness before returning. The existing `agent-inspector` and
`agent-inspector start` commands remain the unmanaged default-instance startup path and do not
create an instance record.

```powershell
agent-inspector instance start <name> [--port <port>] [--base-path <path>] [--host <host>] [--mode simple|full] [--data-dir <absolute-path>] [--backend-only|--with-ui] [--open] [--json]
agent-inspector instance list [--json]
agent-inspector instance status <name> [--json]
agent-inspector instance connect <name> [--json]
agent-inspector instance stop <name> [--json]
agent-inspector instance restart <name> [--port <port>] [--base-path <path>] [--host <host>] [--mode simple|full] [--data-dir <absolute-path>] [--backend-only|--with-ui] [--open] [--json]
```

Names use lowercase letters, digits, dots, hyphens, and underscores; `default` is reserved for the
existing unmanaged runtime. A first start without `--port` allocates an available public/private
port pair. The pair and the other launch options are saved, so later `start` calls reuse the same
configuration. Use `restart` with overrides to change a saved value. `--backend-only` persists a
headless instance; `--with-ui` restores composed UI serving. `--open` is valid only when UI serving
is enabled. `--json` produces token-free output suitable for PowerShell:

```powershell
agent-inspector instance start review --base-path /inspector --json
$review = agent-inspector instance status review --json | ConvertFrom-Json
$connection = agent-inspector instance connect review --json | ConvertFrom-Json
$env:OPENAI_BASE_URL = $connection.environment.OPENAI_BASE_URL
$review
```

`connect` (also accepted as `connection`) returns a token-free connection descriptor with explicit
`surfaces.ui`, `surfaces.control`, and `surfaces.agent` locations. Use
`surfaces.control.baseUrl` for REST/SSE and `surfaces.agent.baseUrl` for proxy/MCP setup;
`surfaces.ui.baseUrl` is `null` when `surfaces.ui.enabled` is false. The descriptor also includes
protocol-ready environment variables, MCP settings, and a Codex Responses provider. The top-level
`uiEnabled`, `baseUrl`, and `endpoints` fields remain for compatibility, but new integrations should
use `surfaces`. In `--json` mode, success writes exactly one JSON document to stdout;
errors write exactly one `{ "schemaVersion": 1, "error": ... }` document to stderr with empty
stdout. Exit code `0` means success, `1` means an operational/lifecycle failure or a reported
conflict, and `2` means invalid command syntax or arguments. A `status`/`connect` conflict remains a
token-free state document on stdout while returning `1`. This makes the commands safe for coding
agents and PowerShell without scraping human text.

On Windows, instance records default below `%LOCALAPPDATA%\agent-inspector\instances`, and isolated
runtime data defaults to `%LOCALAPPDATA%\agent-inspector\instances\<name>\data`. A per-user fallback
is used when `LOCALAPPDATA` is unavailable. Set `AGENT_INSPECTOR_INSTANCES_DIR` before every lifecycle
command, or set it persistently for the user, to move the registry root. `--data-dir` moves one
instance's runtime data. Agent Inspector rejects a data directory already registered to another
name rather than allowing Provider or capture state to be shared accidentally.

```powershell
[Environment]::SetEnvironmentVariable(
  "AGENT_INSPECTOR_INSTANCES_DIR",
  "$env:LOCALAPPDATA\agent-inspector-work",
  "User"
)
```

Runtime aliases and named instances solve different problems:

| Feature | Process and storage | Paths | Persistence |
| --- | --- | --- | --- |
| `agent-inspector alias add /path` | Same runtime, Providers, and logs | Adds a path on the same port | Cleared on supervisor restart |
| `agent-inspector instance start <name>` | Separate supervisor, Providers, and logs | Own saved port and Base Path | Saved until explicitly changed |

#### External wrapper: root plus `/inspector`

An external Windows reverse proxy can give two isolated backends one public origin. Start each
backend on a distinct public ingress port; the lifecycle manager also reserves a different private
runtime port for each supervisor:

```powershell
agent-inspector instance start root-site --port 19527 --base-path /
agent-inspector instance start review-site --port 19537 --base-path /inspector
```

Configure the wrapper to send `/inspector` and `/inspector/*` to `127.0.0.1:19537` **without
stripping the `/inspector` prefix**, and send the remaining root traffic to `127.0.0.1:19527`. Point
the wrapper only at each instance's public ingress port, never its private helper port. Add the
wrapper hostname to `AGENT_INSPECTOR_TRUSTED_HOSTS` when it differs from the local host.

The wrapper is a routing layer only: the two instance data directories and Provider configurations
remain independent. It also becomes the immediate TCP client seen by Inspector, so original coding
tool PID attribution can be replaced by the wrapper process's PID. Connect a coding tool directly
to the appropriate instance ingress when exact client-process attribution is required.

A wrapper that forwards to loopback must authenticate and authorize its own remote callers:
Inspector sees the wrapper as a local peer. Direct non-loopback calls to `/api/instances` always
require `Authorization: Bearer <AGENT_INSPECTOR_CONTROL_TOKEN>`, even when general remote UI control
is allowed. Keep that control token separate from `AGENT_INSPECTOR_PROXY_TOKEN`, which protects
remote model-proxy traffic.

Reverse proxies should preserve the configured prefix when forwarding public requests to Agent
Inspector (`/inspector` by default).

Treat the exact public backend URL printed by the CLI or connection descriptor as
`<agent-base-url>` for Coding Agent endpoints. In composed mode it is also the UI URL; in
backend-only or standalone-UI mode it is not. Client endpoints are derived from the agent surface:

- Proxy: `<agent-base-url>/proxy`
- OpenAI-compatible `/v1` proxy: `<agent-base-url>/proxy/v1`
- MCP: `<agent-base-url>/api/mcp`
- Health: `<control-base-url>/api/health`

For example, keep startup and onboarding aligned when using a custom prefix:

```bash
AGENT_INSPECTOR_BASE_PATH=/team/inspector agent-inspector
AGENT_INSPECTOR_BASE_PATH=/team/inspector agent-inspector onboard --force
AGENT_INSPECTOR_BASE_PATH=/team/inspector agent-inspector onboard --opencode-only --force
AGENT_INSPECTOR_BASE_PATH=/team/inspector agent-inspector onboard --mimo-only --force
```

For Codex-style OpenAI Responses clients, configure the proxy as an OpenAI-compatible `/v1` base:

```toml
model_provider = "agent-inspector"

[model_providers."agent-inspector"]
base_url = "http://127.0.0.1:9527/inspector/proxy/v1"
wire_api = "responses"
```

Use `/proxy` as the base for Anthropic clients (which append `/v1/messages`) and generic
`LLM_BASE_URL` clients. Use `/proxy/v1` as the OpenAI-compatible base for clients that append
`/chat/completions` or `/responses`; Codex Responses belongs in this second category. The resulting
full paths are `/proxy/v1/messages`, `/proxy/v1/chat/completions`, and `/proxy/v1/responses`.

## Documentation Map

- [Installation](docs/Installation.md): install and runtime notes.
- [Usage](docs/Usage.md): daily capture, browsing, replay, and export workflows.
- [MCP Server](docs/MCP-Server.md): MCP setup plus tools, resources, prompts, and evidence usage for coding agents.
- [Instance Control OpenAPI](docs/instance-control.openapi.yaml): versioned named-instance REST
  contract for coding agents and external controllers.
- [Troubleshooting](docs/TROUBLESHOOTING.md): port, provider, MCP, Replay, Jenkins, and GitCode fixes.
- [Jenkins + GitCode WebHook](docs/JENKINS_GITCODE_WEBHOOK_TUNNEL.md): team CI and tunnel setup.
- [Local Release Helper](docs/LOCAL_RELEASE.md): local maintainer release helper.
- [Foundation Smoke Guardrails](docs/FOUNDATION_SMOKE_GUARDRAILS.md): fast baseline regression
  coverage for Provider, runtime, CSRF, proxy, MCP, and UI-facing contracts.

## Capture Modes

Agent Inspector starts in `simple` capture mode by default:

```bash
agent-inspector
agent-inspector --mode simple
```

Simple mode keeps the proxy lightweight for everyday use. It records the data
needed for the session timeline, request/response views, token usage, provider
routing, errors, and knowledge workflows, but it does not retain raw request
headers, upstream headers, or detailed streaming chunk artifacts.

Use `full` mode when you need API-format-level diagnostics:

```bash
agent-inspector --mode full
```

Full mode captures the additional raw details used by the `Raw Headers`,
`Headers`, and `Raw Response` views. It is useful for provider debugging,
header transformation checks, and SSE stream inspection, but it uses more CPU,
memory, and disk.

The mode is decided at process start. To change modes, restart the server. You
can also set `AGENT_INSPECTOR_MODE=full` or
`AGENT_INSPECTOR_CAPTURE_MODE=full`; the CLI flag takes precedence over the
environment.

## Provider URLs And Responses

Provider URL fields are base URLs. The UI shows the immutable API suffix next to each input and a
`Final URL` preview beneath it, using the same upstream URL builder that the proxy uses at runtime.
This makes path mistakes visible before saving the Provider.

| Provider field | Enter this kind of base URL | Runtime suffix |
| --- | --- | --- |
| Anthropic Base URL | `https://api.anthropic.com` | `/v1/messages` |
| OpenAI Chat Base URL | `https://api.openai.com` | `/v1/chat/completions` |
| OpenAI Responses Base URL | `https://api.openai.com` | `/v1/responses` |

Existing configurations that already store a full endpoint stay compatible. For example,
`https://api.minimaxi.com/v1/responses` remains exactly that for Responses requests; Agent Inspector
does not append `/v1/responses` a second time. Bases that already end in `/v1` also avoid `/v1/v1`
duplication.

MiniMax supports both OpenAI-compatible endpoints:

```text
https://api.minimaxi.com/v1/chat/completions
https://api.minimaxi.com/v1/responses
```

In the Provider UI, enter `https://api.minimaxi.com` as the OpenAI Chat and OpenAI Responses base;
the preview will show the final endpoint with the suffix appended. DeepSeek's official API supports
OpenAI Chat Completions but does not currently expose OpenAI Responses, so leave the Responses URL
empty for DeepSeek unless you are routing through a compatible gateway.

The proxy chooses protocol by request path, not by Provider name:

| Client-facing path | Parsed as |
| --- | --- |
| `/proxy/v1/messages` | Anthropic |
| `/proxy/v1/chat/completions` | OpenAI Chat Completions |
| `/proxy/v1/responses` | OpenAI Responses |

Provider Test runs configured endpoints independently: Anthropic, OpenAI Chat Completions, and
OpenAI Responses each get separate non-streaming and streaming probes. Test evidence is written into
a provider-specific Session so the UI can show which exact path, payload shape, status code, and
upstream URL failed.

## Named Instance Control For Coding Agents

Every backend control Base URL exposes a versioned, token-free Windows named-instance control
contract.
The six endpoints are:

| Method | Endpoint | Purpose |
| --- | --- | --- |
| `GET` | `/api/instances` | List registered instances and their live state. |
| `GET` | `/api/instances/{name}` | Read one instance. |
| `GET` | `/api/instances/{name}/connection` | Read coding-agent URLs, environment, MCP, and Codex settings. |
| `POST` | `/api/instances/{name}/start` | Create, start, or idempotently reuse an instance. |
| `POST` | `/api/instances/{name}/stop` | Gracefully stop a sibling instance. |
| `POST` | `/api/instances/{name}/restart` | Restart with saved or validated replacement settings. |

`start` and `restart` accept a strict optional JSON object containing `port`, `basePath`, `host`,
`captureMode`, `uiEnabled`, and `dataDir`; `stop` accepts only `{}`. Responses use `schemaVersion: 1`,
never include lifecycle or Provider credentials, and send `Cache-Control: no-store`. Errors use the
stable shape `{ "schemaVersion": 1, "error": { "code", "message", "retryable" } }` with `400`,
`404`, `409`, `423`, or `503` according to the failure class. See the checked-in
[OpenAPI 3.1 contract](docs/instance-control.openapi.yaml) for the complete schemas.

Connection responses separate the optional browser surface from backend traffic:
`surfaces.ui` has `{ enabled, baseUrl }`, while `surfaces.control.baseUrl` and
`surfaces.agent.baseUrl` remain available for backend-only instances. Legacy top-level `baseUrl` and
`endpoints` are retained for existing clients.

Browser mutations require same-origin proof plus `x-agent-inspector-csrf: 1`. Direct non-loopback
control calls require `Authorization: Bearer <AGENT_INSPECTOR_CONTROL_TOKEN>`. A managed instance
cannot stop or restart itself through the REST/MCP transport it is currently serving; use the
external CLI or a different controller/anchor instance. A failed restart reports whether the old
launch was restored (`restart_failed_rolled_back`) or the instance remained degraded
(`restart_failed_degraded`).

## MCP Evidence Workflows

Agent Inspector exposes MCP from the backend agent Base URL at `<agent-base-url>/api/mcp`, whether
or not a Web UI is served. With the default public backend Base URL, that is:

```text
http://localhost:9527/inspector/api/mcp
```

Coding agents can connect to this MCP surface directly over Streamable HTTP, or through the
companion stdio bridge:

```bash
agent-inspector-mcp stdio --url http://localhost:9527/inspector/api/mcp
agent-inspector-mcp config codex --url http://localhost:9527/inspector/api/mcp
```

The companion package is useful for MCP clients that expect a local command. Direct HTTP remains the
shortest path for clients that support Streamable HTTP.

The MCP HTTP surface is also documented as OpenAPI YAML in
[`docs/mcp-openapi.yaml`](docs/mcp-openapi.yaml).

Use only one transport for the same Inspector instance. If the MCP client supports Streamable HTTP,
configure `<agent-base-url>/api/mcp` directly. If it only supports stdio, configure
`agent-inspector-mcp stdio`; that command is only a bridge to `/api/mcp`, not a second Inspector
server.

Coding agents can use the MCP surface in three ways:

- Tools: perform actions such as listing logs, reading bounded log details, testing providers,
  creating evaluation runs/groups, attaching sessions, and exporting evidence packs.
- Resources: read stable evidence URIs, MCP self-description, session timelines, and evidence file
  paths without invoking a tool call.
- Prompts: start common analysis/reporting tasks from reusable templates.

The current catalog contains 51 tools, 25 resources, and 5 prompts. Named-instance control adds six
tools—`inspector_list_instances`, `inspector_get_instance`,
`inspector_get_instance_connection`, `inspector_start_instance`, `inspector_stop_instance`, and
`inspector_restart_instance`—plus these resources:

| Resource URI | Purpose |
| --- | --- |
| `inspector://instances` | Token-free list of named instances. |
| `inspector://instances/{name}` | One named instance and its live state. |
| `inspector://instances/{name}/connection` | Protocol-correct connection descriptor for a coding agent. |

The three discovery tools and resources remain available in read-only mode. Instance start/stop/
restart require both `AGENT_INSPECTOR_MCP_WRITES=1` and
`AGENT_INSPECTOR_MCP_INSTANCE_WRITES=1`; their tool descriptions require explicit user approval.
They cannot stop or restart the instance serving the active MCP connection.

For an authenticated remote MCP endpoint, keep the token outside config and pass only its variable
name to the companion:

```bash
agent-inspector-mcp doctor --url https://tools.example.test/inspector/api/mcp --token-env INSPECTOR_CONTROL_TOKEN --json
agent-inspector-mcp stdio --url https://tools.example.test/inspector/api/mcp --token-env INSPECTOR_CONTROL_TOKEN
```

The companion reads the raw value from `INSPECTOR_CONTROL_TOKEN`, sends it as a Bearer credential,
and never prints it. `doctor` verifies health, MCP initialization, and `tools/list` before returning.

The evaluation-oriented run flow is:

1. Call `inspector_create_run` before a task starts to declare a stable `runId`, optional
   `sessionId`, and optional `groupId`.
2. Optionally call `inspector_set_current_context` so the active run/session/model/provider is
   discoverable through `inspector://context/current`.
3. Call `inspector_update_run` as the task moves through `running`, `failed`, `completed`, or
   `cancelled`; metadata keys are merged so CI can add build numbers, branch names, or case ids.
4. Let the coding agent run through the proxy as usual.
5. If something fails, call `inspector_get_recent_failures` or read
   `inspector://failures/recent`, then use `inspector_search_logs` to locate suspicious log ids.
6. Use `inspector_get_session_timeline` for a quick chronological view before opening large logs.
7. Call `inspector_get_run` to inspect the declared run.
8. Call `inspector_export_evidence` to write JSON, Markdown, and HTML artifacts under:

```text
<dataDir>/evidence/<runId>/evidence.json
<dataDir>/evidence/<runId>/evidence.md
<dataDir>/evidence/<runId>/evidence.html
```

Use `inspector_get_evidence_files` to return those paths and `inspector_export_evidence_bundle` to
create `evidence.zip`.

For benchmark or CI systems that spawn multiple coding-agent processes, use a group as the
outer evaluation artifact:

1. Call `inspector_create_group` once for the evaluation batch.
2. Call `inspector_set_current_context` with the group/project/task.
3. For each OpenCode/Codex/MiMo worker, call `inspector_create_run` with the group's `groupId`.
4. Start each OpenCode/Codex/MiMo process through the proxy with its own model/provider.
5. As each process discovers or reports its session id, call `inspector_update_run` with the real
   `sessionId`; runs that have a `groupId` are auto-attached to the group.
6. Optionally call `inspector_add_group_session` to override or enrich the group member with
   `groupId`, `sessionId`, and optional `runId`, `provider`, `model`, `agent`, `label`, and
   metadata.
7. Call `inspector_update_group` to mark the whole batch `running`, `failed`, `completed`, or
   `cancelled`.
8. Call `inspector_export_group_evidence` to write an aggregate provider/model matrix under:

```text
<dataDir>/evidence/groups/<groupId>/evidence.json
<dataDir>/evidence/groups/<groupId>/evidence.md
<dataDir>/evidence/groups/<groupId>/evidence.html
```

Use `inspector_get_group_evidence_files` to return those paths and
`inspector_export_group_evidence_bundle` to create `group-evidence.zip`.

Useful MCP resource URIs:

| Resource | Purpose |
| --- | --- |
| `inspector://mcp/health` | Read MCP version, transport, mode, and catalog counts. |
| `inspector://mcp/capabilities` | Read tools split into read vs write/action, resources, prompts, and write mode. |
| `inspector://mcp/config` | Read Streamable HTTP, stdio bridge, OpenCode, MiMo Code, and network config snippets. |
| `inspector://context/current` | Read the active eval/coding context. |
| `inspector://sessions` | List known session ids. |
| `inspector://sessions/{sessionId}` | Read a compact session summary with Inspector links, counts, models, providers, token totals, and recent logs. |
| `inspector://sessions/{sessionId}/timeline` | Read a chronological request timeline for a session. |
| `inspector://logs/{id}` | Read bounded log details for one captured request. Large bodies are capped for agent safety. |
| `inspector://runs` | List declared evaluation runs. |
| `inspector://failures/recent` | Read recent failed/cancelled runs and non-success evidence classifications. |
| `inspector://runs/{runId}` | Read one declared run and its evidence paths. |

`inspector://mcp/config` is a versioned machine-readable contract. It also returns the preferred
runtime discovery URL, ordered `availableBaseUrls`, and derived `availableMcpEndpoints`. The
`agent-inspector-mcp` companion tries an explicitly configured endpoint first and uses these
same-origin candidates only after a safe connection/catalog request fails; it never automatically
replays a mutating `tools/call` request.
| `inspector://evidence/{runId}` | Read the exported Markdown evidence pack for a run. |
| `inspector://evidence/{runId}/files` | Read local paths and byte status for run evidence files. |
| `inspector://groups` | List declared evaluation groups. |
| `inspector://groups/{groupId}` | Read one group, including attached session/run members and evidence paths. |
| `inspector://groups/{groupId}/sessions` | Read only the attached group member list. |
| `inspector://groups/{groupId}/evidence` | Read the exported Markdown evidence pack for a group. |
| `inspector://groups/{groupId}/evidence/files` | Read local paths and byte status for group evidence files. |

Built-in prompt templates help turn captured evidence into user-facing output:

- `inspector_analyze_session_failure`: explain why a session failed and cite log evidence.
- `inspector_triage_recent_failures`: prioritize recent failed runs and suggest next actions.
- `inspector_generate_jenkins_report`: produce a Jenkins-ready Markdown report for a run.
- `inspector_generate_group_report`: produce a provider/model evaluation report for a group.
- `inspector_extract_repro_steps`: extract concise reproduction steps from a session.

## TonyClaw Lab Ecosystem

TonyClaw Lab turns Inspector into a local control panel for the TonyClaw npm ecosystem. The UI shows
installed and latest package status for `@tonyclaw/agent-inspector`,
`@tonyclaw/agent-inspector-mcp`, and `@tonyclaw/eval-harness`; it can launch install, upgrade,
help, preset discovery, and safe smoke-test recipes without leaving Inspector.

The Lab also exposes copy-ready recipes that connect Inspector evidence, MCP checks, and evaluation
runners:

```bash
npx @tonyclaw/eval-harness check-inspector-mcp
npx @tonyclaw/eval-harness inspector-smoke --title "TonyClaw Lab smoke" --latest-log-limit 5
npx @tonyclaw/eval-harness runner-presets --format json
npx @tonyclaw/eval-harness run-once --smoke --project-source <project> --work-source <work> --count 1 --parallel 1
```

Use these recipes as stable starting points for CI smoke tests, local provider checks, and
multi-run evaluation batches. Inspector remains the evidence surface; eval-harness drives repeatable
workloads; the MCP package bridges coding agents that prefer stdio.

Recipes without placeholders can be run directly from TonyClaw Lab. Template recipes remain
copy-ready so users can fill project and work directories explicitly before running them.

## Jenkins And GitCode

Team CI, GitCode WebHook setup, Cloudflare Tunnel notes, local push fallback, and the verified PR workflow live in [Jenkins + GitCode WebHook](docs/JENKINS_GITCODE_WEBHOOK_TUNNEL.md). Keep real Jenkins notify tokens, GitCode access tokens, and tunnel URLs out of the repository.

Jenkins is verification-only for Rust-enabled releases because one host cannot prove all native
executables. The GitHub Actions matrix builds, installs, verifies default startup and production
health, performs graceful native shutdown, attests, and aggregates Windows x64, Linux x64, and macOS
arm64 backend packages. The root package release helper refuses to publish
until that exact-version, exact-source contract is present. See [Local Release
Helper](docs/LOCAL_RELEASE.md) and [Jenkins Verification Pipeline](docs/JENKINS_RELEASE.md).

## Project Direction

Agent Inspector should stay close to the proven inspector codebase while growing into an agent knowledge layer. The memory flow has four layers:

1. Raw Trace: capture requests, responses, streaming chunks, tools, errors, and token usage.
2. Episode: summarize a session into goal, steps, outcome, failures, and artifacts.
3. Memory Candidate: create reviewable, redacted knowledge candidates with evidence ids.
4. OpenClaw Memory: write approved candidates into OpenClaw's durable recall system.

Agent Inspector owns the first three layers. OpenClaw owns indexing, retrieval, consolidation, and long-term recall.

## OpenClaw Memory Bridge

Agent Inspector treats OpenClaw as a hidden memory backend. The preferred integration uses OpenClaw's file-backed memory layout:

```bash
OPENCLAW_WORKSPACE_DIR=C:\Users\<you>\.openclaw\workspace
OPENCLAW_GATEWAY_URL=http://127.0.0.1:18789
OPENCLAW_GATEWAY_TOKEN=<gateway-token>
OPENCLAW_SESSION_KEY=main
```

When a candidate is promoted, Agent Inspector writes sanitized Markdown under:

```text
memory/agent-inspector/YYYY-MM-DD/<candidate>.md
```

OpenClaw remains responsible for indexing and recall. Run `openclaw memory index --force` when you
need immediate reindexing, or rely on the running OpenClaw memory runtime to sync according to its
own policy.

Search stays behind the Inspector facade. Agents call Inspector MCP/API tools, and Inspector invokes OpenClaw Gateway `memory_search` when `OPENCLAW_GATEWAY_URL` is configured.

For older deployments, `OPENCLAW_MEMORY_URL` / `OPENCLAW_API_URL` remain supported as a legacy HTTP backend.
