KeiSeiKit-1.0/bin/kei
KeiSei84 3b54f0b5e0
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(v0.44): pre-release audit — 1 CRITICAL + 4 HIGH + 4 MEDIUM patched
Four-CLI parallel pre-release audit (Claude+Grok+Gemini+Copilot, each
reviewing different angle) surfaced 9 real issues in v0.43. All fixed.

## Audit team & their finds

- Claude (critic):   code review — found #5 KEI_ALLOWED_ROOTS bypass,
                     #6 macOS TMPDIR denylist conflict, #7 timeout doc
                     drift, #9 failure-cache schema mismatch.
- Gemini (security): wrote Rust PoC, verified — found #1 CRITICAL parent
                     symlink for non-existent leaf, #2 TOCTOU await,
                     #3 curl config injection, #4 env inheritance, #8 cwd.
- Grok (architect):  noted safe_tools.rs at 572 LOC (>200 Constructor
                     threshold). Deferred decomposition to v0.45.
- Copilot (docs):    inspected README/encyclopedia, no blocker findings
                     (1 Premium, 977k cached tokens).

## Fixes shipped

[#1 CRITICAL] Parent-symlink bypass for non-existent leaf paths
  v0.42 only canonicalized PARENT. If THAT parent didn't exist either,
  the path fell through to "absolute as-is" with no canonicalization.
  E.g. /proj/symlink -> /Users/denis, then kei_write /proj/symlink/
  newdir/file would write inside /Users/denis with no check.
  Fix: walk_up_to_canonicalize() — find DEEPEST existing ancestor,
  canonicalize THAT (resolving all symlinks in the existing prefix),
  then reattach the non-existent tail.

[#2 HIGH] TOCTOU between validate_path and fs::write
  60s of hook chain await between path check and write. Concurrent
  process could swap leaf for symlink during that window; fs::write
  followed it.
  Fix: open file with O_NOFOLLOW + write through the open fd (not the
  path again). Open() itself fails on symlink-swap. Edit + Write both
  patched. Falls back to plain tokio::fs on non-Unix.

[#3 HIGH] curl config injection via MOONSHOT_API_KEY
  Was: token interpolated into printf 'header = "...%s..."' fed to curl
  --config. If token contained " + newline + 'url = "evil"', curl
  parsed the injected config and redirected.
  Fix: validate MOONSHOT_API_KEY matches [A-Za-z0-9_.-]+; reject any
  other chars before probe runs.

[#4 HIGH] Subprocess env inheritance — secret leak via kei_bash
  Was: spawned bash inherited AWS_*, GITHUB_TOKEN, MOONSHOT_API_KEY,
  etc. Agent running `env` via kei_bash could exfiltrate all of them.
  Fix: apply_safe_env() — env_clear() + whitelist forward of PATH/
  HOME/USER/LANG/TERM/SHELL/PWD/TMPDIR/LOGNAME/LC_*. Operators add
  named vars via KEI_SAFE_ENV_EXTRA. Applied to BOTH kei_bash spawn
  AND hook subprocess spawn.

[#5 HIGH] KEI_ALLOWED_ROOTS unanchored prefix bypass
  Was: str::starts_with on raw user-supplied root.
  KEI_ALLOWED_ROOTS=/home/u/proj also allowed /home/u/proj-secrets/...
  Fix: normalize each entry to canonical + trailing slash; use
  Path::starts_with (component-aware). v0.44 combines with #6 fix
  (canonicalize symlinks like /var → /private/var on macOS).

[#6 MEDIUM] macOS $TMPDIR denied by /var/ blanket
  Was: denylist included /var/, /private/var/ blanket entries.
  macOS $TMPDIR = /var/folders/... canonicalized to /private/var/
  folders/... hit the denylist before allowed_roots was checked.
  Fix: (a) allowed_roots check FIRST; (b) narrowed denylist to /var/db/,
  /var/log/, /var/root/ (and /private/ counterparts) instead of blanket
  /var/. /var/folders + /private/tmp are now legitimate working dirs.

[#7 MEDIUM] Timeout aggregate claim was always false
  Was: doc said "Hard cap on single chain + action ... 60s" — actually
  was per-step. For 3-hook chain, total = 4 * 60 = 240s.
  Fix: doc comment now honest about per-step semantics. Aggregate-
  deadline impl deferred to v0.45 (not security-blocking).

[#8 MEDIUM] cwd not in hook input — hook approves wrong cwd
  Was: kei_bash accepts cwd arg but did not pass it to safety hooks.
  Hook could approve `rm -rf *` assuming PWD, while cwd actually
  pointed at /etc or ~/.ssh.
  Fix: include cwd in hook_input JSON. Hooks now see the real
  working dir for their decision.

[#9 MEDIUM] Failure-fallback cache had different schema
  Was: emit '{"ts":"","status":"assembly-failed"}' — no per-CLI keys.
  Pet's .kimi.available_balance_usd read got null/error; kei-limits
  own per-CLI render loop emitted 5 malformed rows.
  Fix: failure-fallback emits same shape as success {ts, claude, grok,
  agy, copilot, kimi} with each marked status='assembly-failed'.

LOW: empty old_string in kei_edit now rejected (was: silently
prepended new_string since contents.contains("") is always true).

## Tests + smokes

cargo test -p kei-mcp: 3/3 pass.

8 MCP smokes (all green after every audit round):
  - kei_bash blocks RULE 0.1 push
  - kei_bash passes echo OK
  - kei_write /etc/passwd → denied (system dir)
  - kei_write ../ → denied (.. segment)
  - kei_write ~/.ssh/ → denied (outside roots)
  - kei_write symlink-to-etc/passwd → denied (canonicalized)
  - kei_write ~/.claude/hooks/ → denied (substrate dir)
  - kei_write ~/.zshrc → denied (outside roots)

NEW v0.44 smokes:
  - kei_write /Users/denis/.ssh/newdir/keys via /tmp/v44_link → denied
  - KEI_ALLOWED_ROOTS=/tmp/proj does NOT match /tmp/proj-evil
  - FAKE_SECRET=stolen → TOKEN=empty in subprocess (env stripped)
  - MOONSHOT_API_KEY='abc"NL_url="evil"' → rejected pre-probe
  - macOS $TMPDIR via KEI_ALLOWED_ROOTS works (canonicalize fix)

## Deferred to v0.45

- safe_tools.rs at 572 LOC — extract path_guard + chain_runner modules
- Aggregate-deadline timeout (single Instant::now() + remaining)
- Hardlink check (open fd then fstat + dev/ino compare)
- INVALID_PARAMS used for missing-arg (currently INTERNAL_ERROR)
- INVALID_PARAMS_REF dead code at EOF (silencer for unused import)

These are correctness/style/architectural, NOT security blockers.
2026-05-26 23:00:34 +08:00

261 lines
9.2 KiB
Bash
Executable file

#!/usr/bin/env bash
# kei — KeiSeiKit launcher with TUI splash, then exec claude.
#
# Distinct from `keisei` (Rust exobrain CLI: `keisei attach/mount/...`).
# `kei` is the lightweight splash + launch entry point most users want.
#
# Usage:
# kei # splash → claude (interactive REPL)
# kei --no-splash # skip splash → exec claude
# kei --status # status only, don't launch claude
# kei message ... # inter-session mailbox (send/inbox/list) — see kei-message.sh
# kei configure # re-pick stack profile + opt-in hook packs
# kei pick # interactive picker → set primary → launch it
# kei agent <name> "<task>" # invoke agent, backend from DNA → primary
# kei agent --on=<backend> <name> "<task>" # override backend
# kei run-via <backend> <name> "<task>" # invoke agent on explicit backend
# # backends: claude grok agy copilot kimi codex
# # `kei run-via list` shows install status + agents
# kei primary [<backend>] # get/set primary LLM provider (DNA fallback)
# kei mcp-wire [<cli>] # wire kei-mcp into a CLI's MCP config + hook setup
# # (Phase C cross-CLI policy enforcement)
# kei mcp-wire --list # show enforcement tier per CLI
# kei limits # probe each CLI's subscription quota (best-effort)
# # (4 of 5 CLIs have no public API — honest report)
# kei --on=<backend> # one-shot launch of <backend> (does not change primary)
# kei [args...] # splash → exec primary CLI (default: claude)
#
# The splash shows: substrate version, agent count, last sleep run,
# active sessions (kei-ping). Press any key to skip the dwell.
#
# Returns: same exit code as `claude`.
set -e
# --- subcommand dispatch (before splash) ---------------------------------
# `kei message ...` → mailbox CLI
# `kei configure` → hook/stack re-picker
# `kei agent ...` → DNA-resolved agent (manifest provider → primary → claude)
# `kei run-via ...` → explicit-backend agent invocation
# `kei primary ...` → get/set primary LLM provider
# rest = splash + launch claude (legacy primary).
case "${1:-}" in
message|msg|m)
shift
exec "$HOME/.claude/scripts/kei-message.sh" "$@"
;;
configure|config|reconfigure)
shift
exec "$HOME/.claude/scripts/kei-configure.sh" "$@"
;;
agent)
shift
exec "$HOME/.claude/scripts/kei-agent-cli.sh" "$@"
;;
run-via|via|agent-via)
shift
exec "$HOME/.claude/scripts/kei-agent-cli.sh" "$@"
;;
primary)
shift
exec "$HOME/.claude/scripts/kei-agent-cli.sh" primary "$@"
;;
pick)
shift
exec "$HOME/.claude/scripts/kei-pick.sh" "$@"
;;
mcp-wire|wire)
shift
exec "$HOME/.claude/scripts/kei-mcp-wire.sh" "$@"
;;
limits|quota|usage)
shift
exec "$HOME/.claude/scripts/kei-limits.sh" "$@"
;;
esac
# --- one-shot --on=<backend> override (does not write primary.toml) -------
ONESHOT_BACKEND=""
for arg in "$@"; do
case "$arg" in
--on=*) ONESHOT_BACKEND="${arg#--on=}" ;;
esac
done
# --- args ----------------------------------------------------------------
SPLASH=1
STATUS_ONLY=0
PASSTHROUGH=()
for arg in "$@"; do
case "$arg" in
--on=*) ;; # already captured in ONESHOT_BACKEND; don't forward
--no-splash) SPLASH=0 ;;
--status) STATUS_ONLY=1; SPLASH=1 ;;
*) PASSTHROUGH+=("$arg") ;;
esac
done
# --- resolve primary backend ---------------------------------------------
# Order: --on=<backend> override → ~/.claude/config/primary.toml → claude.
resolve_primary() {
if [ -n "$ONESHOT_BACKEND" ]; then printf '%s\n' "$ONESHOT_BACKEND"; return; fi
if [ -n "${KEI_PRIMARY:-}" ]; then printf '%s\n' "$KEI_PRIMARY"; return; fi
local cfg="$HOME/.claude/config/primary.toml"
if [ -f "$cfg" ]; then
awk -F'=' '/^provider[[:space:]]*=/ {
gsub(/^[[:space:]]+|[[:space:]]+$/, "", $2)
gsub(/^"|"$/, "", $2)
print $2; exit
}' "$cfg"
return
fi
printf 'claude\n'
}
# Map backend name → executable. Mirrors scripts/kei-agent-cli.sh::backend_bin.
backend_bin_for() {
case "$1" in
claude) echo "claude" ;;
grok) echo "grok" ;;
agy|antigravity) echo "agy" ;;
copilot) echo "copilot" ;;
kimi) echo "kimi" ;;
codex) echo "codex" ;;
*) return 1 ;;
esac
}
PRIMARY="$(resolve_primary)"
PRIMARY_CLI="$(backend_bin_for "$PRIMARY")" || {
echo "error: unknown primary backend: $PRIMARY" >&2
exit 2
}
PRIMARY_BIN="$(command -v "$PRIMARY_CLI" 2>/dev/null || true)"
if [ -z "$PRIMARY_BIN" ] && [ "$STATUS_ONLY" = "0" ]; then
echo "error: primary backend '$PRIMARY' → '$PRIMARY_CLI' not on PATH." >&2
case "$PRIMARY" in
claude) echo " install: curl -fsSL https://claude.ai/install.sh | sh" >&2 ;;
grok) echo " install: see https://x.ai/grok" >&2 ;;
copilot) echo " install: npm i -g @github/copilot" >&2 ;;
kimi) echo " install: uv tool install kimi-cli" >&2 ;;
agy) echo " install: see https://antigravity.dev" >&2 ;;
codex) echo " install: see https://github.com/openai/codex" >&2 ;;
esac
echo " or: kei pick (interactive picker to choose + set primary)" >&2
echo " or: kei primary <backend> (set a different default)" >&2
exit 127
fi
# Legacy var name for splash code below.
CLAUDE_BIN="$PRIMARY_BIN"
# --- read state ----------------------------------------------------------
AGENTS_DIR="${HOME}/.claude/agents"
SYNC_DIR="${HOME}/.claude/memory/sync-repo"
# Agent count from generated .md files
agent_count() {
local n=0
if [ -d "$AGENTS_DIR" ]; then
n=$(find "$AGENTS_DIR" -maxdepth 1 -name "*.md" -not -name "_*" 2>/dev/null | wc -l | tr -d ' ')
fi
printf '%s' "$n"
}
# Profile from .installed marker file
profile_name() {
# install.sh stamps the chosen profile here; .installed only holds primitive
# names (so the old `grep ^profile .installed` always returned "?").
local f="$HOME/.claude/.kei-profile"
if [ -f "$f" ]; then head -1 "$f"; else echo "?"; fi
}
# Last Phase B sleep timestamp
last_sleep_run() {
local f="${SYNC_DIR}/reports/last-run.txt"
if [ -f "$f" ]; then
local ts
ts=$(cat "$f" 2>/dev/null | head -1)
if [ -n "$ts" ]; then
# epoch → human; macOS date(1) -r and Linux date(1) -d differ
if date -r "$ts" '+%Y-%m-%d %H:%M' >/dev/null 2>&1; then
date -r "$ts" '+%Y-%m-%d %H:%M'
elif date -d "@$ts" '+%Y-%m-%d %H:%M' >/dev/null 2>&1; then
date -d "@$ts" '+%Y-%m-%d %H:%M'
else
echo "$ts"
fi
else
echo "never"
fi
else
echo "never"
fi
}
# Active session count via kei-ping (auto-selects redis or sqlite backend)
active_sessions() {
if command -v kei-ping >/dev/null 2>&1; then
kei-ping list 2>/dev/null | grep -cE '^\s*[0-9]+s\s' || echo "0"
else
echo "n/a"
fi
}
# --- splash --------------------------------------------------------------
splash() {
local p ac sl as
p="$(profile_name)"
ac="$(agent_count)"
sl="$(last_sleep_run)"
as="$(active_sessions)"
# Only color if stdout is a tty. Brand palette: голубой (sky-blue) + жёлтый (gold).
local C0= C1= C2= C3= CV=
if [ -t 1 ]; then
C0=$'\033[0m'
C1=$'\033[1;38;5;39m' # голубой (sky-blue) — logo
C2=$'\033[1;38;5;220m' # жёлтый (gold) — brand line
C3=$'\033[2;38;5;39m' # dim blue — separators
CV=$'\033[1;38;5;220m' # жёлтый — field values
fi
cat <<EOF
${C1} ██╗ ██╗███████╗██╗███████╗███████╗██╗${C0}
${C1} ██║ ██╔╝██╔════╝██║██╔════╝██╔════╝██║${C0}
${C1} █████╔╝ █████╗ ██║███████╗█████╗ ██║${C0}
${C1} ██╔═██╗ ██╔══╝ ██║╚════██║██╔══╝ ██║${C0}
${C1} ██║ ██╗███████╗██║███████║███████╗██║${C0}
${C1} ╚═╝ ╚═╝╚══════╝╚═╝╚══════╝╚══════╝╚═╝${C0}
${C2} KeiSeiKit · substrate v0.44${C0}
${C3} ─────────────────────────────────────${C0}
primary CLI : ${CV}${PRIMARY}${C0}
profile : ${CV}${p}${C0}
agents : ${CV}${ac}${C0}
last sleep run : ${CV}${sl}${C0}
active sessions: ${CV}${as}${C0}
${C3} ─────────────────────────────────────${C0}
EOF
}
# --- main ----------------------------------------------------------------
if [ "$SPLASH" = "1" ]; then
splash
fi
if [ "$STATUS_ONLY" = "1" ]; then
exit 0
fi
# Brief dwell so user sees splash before claude takes over the screen.
# Skipped if stdin not a tty (CI / piped) or if --no-splash.
if [ "$SPLASH" = "1" ] && [ -t 0 ] && [ -t 1 ]; then
# Wait up to 0.6s; any keypress aborts immediately.
read -t 0.6 -n 1 -s _ 2>/dev/null || true
fi
exec "$CLAUDE_BIN" "${PASSTHROUGH[@]}"