KeiSeiKit-1.0/docs/encyclopedia/multi-cli-agents.md
KeiSei84 4e5e6bd2c0
Some checks are pending
CI (Forgejo Actions — self-hosted runner on Mac, host mode) / preflight (push) Waiting to run
CI (Forgejo Actions — self-hosted runner on Mac, host mode) / vps-smoke (push) Waiting to run
CI (Forgejo Actions — self-hosted runner on Mac, host mode) / rust-primitives (map[crates:frustration-matrix,kei-frustration-loop,kei-skill-importer,kei-projects-index,kei-projects-watcher,kei-gdrive-import,kei-leak-matrix,kei-skills,kei-gateway,kei-cron-scheduler,kei-export-trajectories,kei-backend-daytona,kei-d… (push) Blocked by required conditions
CI (Forgejo Actions — self-hosted runner on Mac, host mode) / rust-primitives (map[crates:kei-compute-baremetal,kei-compute-vultr,kei-compute-linode,kei-compute-digitalocean,kei-svc-systemd,kei-llm-bridge-mlx name:hosted-sleep-compute]) (push) Blocked by required conditions
CI (Forgejo Actions — self-hosted runner on Mac, host mode) / rust-primitives (map[crates:kei-diff,kei-scheduler,kei-watch,kei-prune,kei-discover,kei-brain-view,kei-hibernate,kei-ledger-sign,kei-fork name:wave13-15]) (push) Blocked by required conditions
CI (Forgejo Actions — self-hosted runner on Mac, host mode) / rust-primitives (map[crates:kei-git-gitea,kei-git-forgejo,kei-git-gitlab,kei-git-bitbucket,kei-memory-sled,kei-memory-redis,kei-memory-postgres,kei-memory-sqlite,kei-auth-google,kei-auth-apple,kei-auth-magiclink,kei-auth-webauthn,kei-notify-slack,kei-n… (push) Blocked by required conditions
CI (Forgejo Actions — self-hosted runner on Mac, host mode) / rust-primitives (map[crates:kei-ledger,kei-migrate,kei-changelog,kei-memory,kei-store,kei-conflict-scan,kei-refactor-engine,kei-graph-check,kei-shared,kei-dna-index,kei-pet name:core]) (push) Blocked by required conditions
CI (Forgejo Actions — self-hosted runner on Mac, host mode) / rust-primitives (map[crates:kei-machine-probe,kei-llm-ollama,kei-llm-llamacpp,kei-llm-mlx,kei-llm-router,kei-model name:llm-stack]) (push) Blocked by required conditions
CI (Forgejo Actions — self-hosted runner on Mac, host mode) / rust-primitives (map[crates:kei-router,kei-sage,kei-task,kei-chat-store,kei-crossdomain,kei-search-core,kei-content-store,kei-social-store,kei-curator,kei-auth,kei-artifact name:mcp-lbm]) (push) Blocked by required conditions
CI (Forgejo Actions — self-hosted runner on Mac, host mode) / rust-primitives (map[crates:keisei,kei-forge,kei-runtime,kei-runtime-core,kei-atom-discovery,kei-agent-runtime,kei-capability,kei-provision,kei-entity-store,kei-pipe,kei-cache,kei-spawn,kei-replay name:atom-substrate]) (push) Blocked by required conditions
feat(phase-C): cross-CLI hook enforcement via kei_bash/kei_edit/kei_write MCP tools
Closes the "hooks only fire on Claude" gap. Phase C extends KeiSeiKit safety
enforcement (no-github-push, safety-guard, destructive-guard, citation-verify,
numeric-claims-guard) to any MCP-capable LLM CLI through a 3-tier honesty model.

## 3-tier model

TIER 1 (full native): claude (existing), grok (port hooks to grok settings.json)
TIER 2 (MCP-wrapped): copilot (--excluded-tools=shell + force kei_bash via MCP)
TIER 3 (advisory):    agy + kimi (cannot disable native shell; prompt-level only)

## Design (Constructor Pattern)

1. hooks/_lib/policy-chain.toml — SSoT: which hooks gate which tool (bash/edit/write)
2. _primitives/_rust/kei-mcp/src/handlers/safe_tools.rs — new module, 3 built-in
   MCP tools that synthesize Claude PreToolUse JSON, run hook chain, abort on
   exit-2, exec on all-pass. Same input contract → hooks reused as-is, no rewrite.
3. tools.rs short-circuit: kei_bash/kei_edit/kei_write dispatched before atom layer
4. 6 wire scripts: orchestrator + one per CLI (Constructor Pattern, no mixin)
5. bin/kei mcp-wire arm
6. docs/encyclopedia/cross-cli-policy.md — honest 3-tier matrix + verification

## Double-enforcement guard

If kei-mcp invoked from a process with $CLAUDECODE=1 or $GROKCODE=1, the chain
SKIPS — native hooks already fired. Wire scripts set these env vars in the
MCP server registration for claude/grok respectively. On copilot/agy/kimi the
env is unset → chain runs.

## Smoke (verified live)

Block: kei_bash{command: forbidden-push-pattern}
  → JSON-RPC error -32603 with full "BLOCK — RULE 0.1 NO GITHUB PUSH" stderr ✓
Pass:  kei_bash{command: "echo HELLO-FROM-KEI-BASH"}
  → result.content[0].text = "HELLO-FROM-KEI-BASH" ✓
tools/list: 4 built-ins present (spawn_agent + kei_bash + kei_edit + kei_write) ✓

## Tests

kei-mcp: 3/3 (tools_list assertions updated for atoms+4 built-ins).
Build clean with toml = "0.8" dep added.

## Out of scope (deferred)

- Codex CLI wiring (not installed locally)
- ACP middleware proxy (transport, not middleware — ruled out at research)
- Container/firejail sandboxing for agy/kimi (heavy; documented limit instead)
- Native Rust PatternGate migration (optimization, separate phase)
2026-05-26 18:03:33 +08:00

8.8 KiB

Multi-CLI agent invocation

Cross-LLM agent execution. Same agent definition, different backend. Same DNA, swap the brain. KeiSeiKit is no longer Claude-Code-only.

KeiSeiKit agents are markdown files. Any LLM CLI that takes a prompt can host them. Three call shapes:

kei agent <name> "<task>"                # DNA-resolved (manifest → primary → claude)
kei agent --on=<backend> <name> "<task>" # override DNA
kei run-via <backend> <name> "<task>"    # explicit backend (no DNA lookup)

Backends — smoke-tested 2026-05-26

Backend CLI Flag Smoke Notes
claude claude -p Claude Code, native --agent flag
grok grok --print xAI Grok Build TUI, native --agent flag
agy agy --print Google Antigravity (Gemini models). Alias: antigravity
copilot copilot --prompt GitHub Copilot CLI (@github/copilot)
kimi kimi TUI-only No print mode — launcher saves prompt to tmpfile + opens TUI for paste. kimi acp JSON-RPC integration is future work.
codex codex -p OpenAI Codex (register-only; not installed locally)

Run kei run-via list to see installed backends, current primary, and agent names.

DNA — agent prefers a provider

Add provider to the agent manifest:

# _manifests/my-agent.toml
name = "my-agent"
provider = "grok"     # preferred backend; optional
model = "grok-2"      # advisory; informs choice but not yet sent through

The assembler emits it into frontmatter:

---
name: my-agent
provider: grok
---

Resolution order (each falls through if previous returns nothing):

  1. --on=<backend> flag on the command line
  2. provider: field in agent manifest
  3. ~/.claude/config/primary.toml (set via kei primary <backend>)
  4. Default: claude

Primary — your default LLM

kei primary                # show current primary (and fallback)
kei primary grok           # set default to Grok
kei primary claude         # back to Claude Code

kei primary writes ~/.claude/config/primary.toml. Any agent without its own provider: field will resolve to this. This is the lever to "swap out Claude Code as the primary shell" — set primary to grok, and every kei agent <name> runs on Grok.

Usage examples

# DNA mode (manifest's provider, or primary, or claude):
kei agent critic "review src/auth.rs"

# Override DNA — try the same agent on a different model for a second opinion:
kei agent --on=grok critic "review src/auth.rs"
kei agent --on=agy  critic "review src/auth.rs"
kei agent --on=copilot critic "review src/auth.rs"

# Explicit backend, no DNA lookup (legacy):
kei run-via grok critic "review src/auth.rs"

# Point at an arbitrary agent file:
kei agent --on=grok --file=/tmp/my-agent.md "do the thing"

# Native --agent flag (grok/claude only):
KEI_NATIVE_AGENT=1 kei agent critic "review src/auth.rs"

How it works

  1. Resolves backend from DNA (see above).
  2. Reads ~/.claude/agents/<agent-name>.md (assembler-generated prompt).
  3. Strips YAML frontmatter.
  4. Composes with task: <agent prompt>\n\n---\n\nTASK FOR THIS RUN:\n<task>.
  5. Execs the backend's non-interactive CLI with the composed prompt.

No agent file is modified. No new tokens are issued — subscription authentication is whatever each CLI uses (its own login / config dir).

When to use each

This is a tool, not a recommendation. Each backend has different strengths; the substrate is agnostic about which you pick. Pick by:

  • Familiarity — the CLI you already use day-to-day.
  • Subscription cost — burn the one with cheaper marginal cost first.
  • Specific feature — e.g. grok --agent for native sub-agent switching mid-conversation; agy --sandbox for terminal restriction.
  • Independent second opinion — same agent, different model, see if conclusions diverge.

Orchestrator picker — kei no longer hardcodes claude

Without args, kei reads ~/.claude/config/primary.toml and execs that CLI. The picker lets you change it interactively:

kei pick               # interactive menu → set primary → launch it
kei                    # splash → exec the configured primary
kei --on=grok          # one-shot launch of grok (does NOT change primary)
kei primary grok       # set default to grok (no launch)
kei primary            # show current primary

The splash shows primary CLI: <backend> so you always know which orchestrator will start. If the chosen primary isn't installed, kei prints the install command and offers kei pick as recovery.

Cross-CLI sub-agent spawn via MCP — spawn_agent

kei-mcp exposes a built-in spawn_agent MCP tool. Any CLI that connects to it as an MCP client can invoke KeiSeiKit agents on any backend, no matter what the orchestrator is:

{
  "jsonrpc": "2.0",
  "method": "tools/call",
  "params": {
    "name": "spawn_agent",
    "arguments": {
      "name": "critic",
      "task": "review src/auth.rs for race conditions",
      "on": "grok"
    }
  }
}

Internally spawn_agent shells out to kei-agent-cli.sh with the same DNA resolution as kei agent. The on argument is optional — without it, the backend is picked from the agent's manifest, then primary.toml, then claude.

Why this matters: Claude Code has a native Agent tool for sub-agent spawning. Grok / Antigravity / Copilot / Kimi do NOT have that surface natively — but they all support MCP. With spawn_agent exposed via kei-mcp, every backend that speaks MCP gets KeiSeiKit's sub-agent capability. So when Grok is your orchestrator, it can still spawn critic on Claude (or code-implementer on Antigravity, or anything else) — the orchestrator choice no longer caps your sub-agent surface.

Wire kei-mcp into the orchestrator's MCP config (each CLI has its own):

CLI MCP config
claude ~/.claude/settings.json mcpServers block
grok ~/.grok/config.json (or check grok --help)
agy ~/.antigravity/mcp.json (check agy plugin list)
copilot ~/.copilot/mcp.json (check copilot --help)
kimi kimi mcp add subcommand

Point each at <kit>/_primitives/_rust/target/release/kei-mcp (built via cargo build -p kei-mcp --release).

Rule enforcement — see also: cross-CLI policy

Phase C delivered: KeiSeiKit's safety hooks now have a 3-tier enforcement model across CLIs. See cross-cli-policy.md for the full matrix and kei mcp-wire setup. Short version: TIER 1 (full native) on claude+grok, TIER 2 (MCP-wrapped) on copilot, TIER 3 (advisory) on agy+kimi.

Rule enforcement caveat (READ THIS — pre-Phase-C view)

KeiSeiKit hooks (numeric-claims-guard, citation-verify, no-github-push, safety-guard, push-to-main, etc.) are Claude Code-side: PreToolUse:Bash / :Edit / :Write events that fire inside Claude Code's process. They do not propagate to grok / agy / copilot / kimi.

That means:

  • Prompt-level rules (the agent's instructions inside the .md) DO carry through — the agent reads Constructor Pattern, Evidence Grading, No Hallucination, etc. as part of its system prompt on any backend.
  • Tool-level enforcement (hard-deny on git push github.com, citation guard, etc.) only applies on the claude backend. Other backends' tool surfaces are governed by THEIR own hooks/policies.

If you need true rule-enforcement on a non-claude backend, the path is the MCP server (_primitives/_rust/kei-mcp/): registers KeiSeiKit primitives as MCP tools that the other CLI invokes. Tool-side policies travel with the MCP wrapper, not with the CLI.

Adding a new backend

  1. Add a [backend.<name>] table to _primitives/cli-backends.toml.
  2. Add a case arm in scripts/kei-agent-cli.sh backend_bin() and backend_invoke() for the new CLI's print-flag.
  3. Add a row to the smoke-test table above (state PASS/FAIL/PARTIAL).

What it is NOT

  • Not a router — picks no backend for you; you (or DNA) ask, it dispatches.
  • Not a federation — each backend runs independently with its own context; there is no cross-backend state.
  • Not a rule-enforcement layer — hooks only fire on the claude backend (see caveat above). For non-claude rule enforcement use MCP server.
  • Not a wrapper around the backend's tool surface — what the CLI can do (Bash, file edits, MCP, etc.) is determined by that CLI, not KeiSeiKit. The substrate only ships the prompt.
  • _primitives/_rust/kei-llm-router/ — Beta-posterior router for programmatic model selection inside Rust code (a different layer).
  • _primitives/_rust/kei-mcp/ — MCP server that exposes KeiSeiKit primitives to ANY MCP-compatible client (Cursor / Continue / Zed / Aider / Cline / Windsurf / OpenClaw).