# claude-code-replica **Repository Path**: jackXUYY/claude-code-replica ## Basic Information - **Project Name**: claude-code-replica - **Description**: 复刻claude-code-replica - **Primary Language**: Unknown - **License**: Apache-2.0 - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2026-08-03 - **Last Updated**: 2026-08-03 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # Claude Code (open replica) An open-source, from-scratch implementation of the Claude Code experience: an agentic coding assistant that lives in your terminal. It streams responses, calls tools to read/write/search your codebase and run shell commands, asks for permission before changing anything, supports plan mode, hooks system, command injection detection, sub-agents, session resume and context compaction — against **Anthropic** or any **OpenAI-compatible** API (OpenAI, DeepSeek, Kimi, Doubao, GLM, …). ``` ✻ Claude Code (open replica) model: claude-sonnet-4-5 (anthropic) cwd: ~/src/my-project session: 9c75ea35-… /help for commands, Esc to interrupt, Ctrl+C to quit > Refactor the tokenizer to support unicode escapes ⏺ Grep(tokenize) ⎿ 4 files matched ⏺ Edit(src/tokenizer.ts) ⎿ added 18 lines, removed 3 lines … ``` ## Install & run ```bash pnpm install pnpm build # compiles to dist/ node dist/cli.js # interactive REPL node dist/cli.js -p "…" # one-shot print mode # or link the `claude-code` bin pnpm link --global claude-code ``` Requires Node.js ≥ 22 (developed on Node 24). ## Configuration Pick a provider and give it credentials: | Provider | Env vars | Default model | |------------|-----------------------------------------------------------------|----------------------| | `anthropic`| `ANTHROPIC_API_KEY` (+ optional `ANTHROPIC_BASE_URL`, `ANTHROPIC_MODEL`) | `claude-sonnet-4-5` | | `openai` | `OPENAI_API_KEY`, `OPENAI_BASE_URL`, `OPENAI_MODEL` | `gpt-4o` | `CCODE_PROVIDER=anthropic|openai` and `CCODE_MODEL=…` override detection. Examples: ```bash # Anthropic export ANTHROPIC_API_KEY=sk-ant-… # DeepSeek export CCODE_PROVIDER=openai export OPENAI_BASE_URL=https://api.deepseek.com export OPENAI_API_KEY=sk-… export OPENAI_MODEL=deepseek-chat # Kimi (Moonshot) export OPENAI_BASE_URL=https://api.moonshot.ai/v1 export OPENAI_MODEL=kimi-k2 # Zhipu (GLM) export CCODE_PROVIDER=openai export OPENAI_BASE_URL=https://open.bigmodel.cn/api/paas/v4 export OPENAI_API_KEY=your-key export OPENAI_MODEL=glm-4-flash ``` ### settings.json Settings files (both optional, project overrides user): - `~/.ccode/settings.json` - `/.ccode/settings.json` ```json { "permissions": { "defaultMode": "default", "allow": ["Bash(pnpm test:*)", "Bash(git status)", "Read(*)"], "deny": ["Bash(git push:*)", "Edit(src/secrets/**)"] }, "maxTokensBeforeCompact": 120000 } ``` Rule syntax: `Tool(pattern)` — `*` matches within a path segment, `**` crosses directories, and a trailing `:*` means "command starts with this prefix" (Bash). Bare `Tool` matches every use of that tool. ### Hooks Configure hooks in `.ccode/settings.json` to run shell commands before/after tool calls, on user prompts, or when the agent finishes: ```json { "hooks": { "PreToolUse": [ { "matcher": "Bash", "hooks": [ { "type": "command", "command": "echo '[HOOK] Bash command requested'" } ] } ], "PostToolUse": [ { "matcher": "Write", "hooks": [ { "type": "command", "command": "echo '[HOOK] File written'" } ] } ], "Stop": [ { "hooks": [ { "type": "command", "command": "echo '[HOOK] Agent finished'" } ] } ] } } ``` Hook events: `PreToolUse`, `PostToolUse`, `UserPromptSubmit`, `Stop`, `Notification`. - `matcher` filters by tool name (supports `*` wildcard). - Hook `command` runs in the project cwd; stdout is shown to the user as a notification. - PreToolUse hooks can block a tool call by outputting `{"decision": "block", "reason": "…"}` (JSON on stdout). ## CLI flags ``` claude-code [options] [prompt] -p, --print non-interactive: run once, print, exit -m, --model model override --provider anthropic | openai --permission-mode default | acceptEdits | plan | bypassPermissions --dangerously-skip-permissions --max-turns agent loop turn cap (default 50) --output-format text | json | stream-json -c, --continue resume most recent session in this directory -r, --resume resume a specific session (id or prefix) --append-system-prompt -v, --version ``` Piping stdin (`cat diff | claude-code -p "explain this"`) appends it to the prompt. ## Interactive commands | Command | What it does | |----------------------|--------------| | `/help` | list commands | | `/exit` | save session & quit (also Ctrl+C / Ctrl+D at an empty prompt) | | `/clear` | wipe conversation history | | `/compact` | summarize older history to free context (also automatic near the limit) | | `/model` | show / switch model | | `/cost` | token usage & estimated cost | | `/status` | show session info, model, permission mode, hooks config | | `/hooks` | list configured hooks | | `/permissions` | show current permission mode and rules | | `/doctor` | environment diagnostics (node, provider, api key, cwd) | | `/bug` | generate a bug report template | | `/vim` | toggle vim editing mode | | `/terminal-setup` | print shell integration instructions | | `/init` | have the agent write a CLAUDE.md for the repo | | `/plan` | toggle plan mode (research → approve plan → execute) | | `/mode` | set permission mode directly | | `/todos` | show the agent's task list | | `/resume` | list & switch sessions for this directory | While the agent works: **Esc** (or Ctrl+C) interrupts; typed lines are queued FIFO and run next; a `CLAUDE.md` found in the directory tree is loaded into the system prompt automatically. ## Tools available to the agent `Bash` (persistent cwd, timeouts, output truncation, command injection detection) · `Read` (offsets, line numbers) · `Write` · `Edit` / `MultiEdit` (exact-match, atomic) · `Glob` (mtime-sorted) · `Grep` (content/files/count modes, gitignore-ish skips) · `LS` · `TodoWrite` (visible via `/todos`) · `WebFetch` (fetch + model-read) · `WebSearch` (search the web) · `Task` (spawn a sub-agent with its own loop) · `NotebookEdit` (Jupyter notebooks) · `ExitPlanMode` (plan approval gate) ## Permission modes - **default** — read-only tools run free; writes and shell commands ask (with "don't ask again this session"). - **acceptEdits** — file edits auto-approved, shell still asks. - **plan** — read-only only; the agent must present a plan via `ExitPlanMode` and you approve it before any change happens. - **bypassPermissions** — everything runs (for sandboxes/CI). Non-interactive (`-p`) runs deny anything that would ask, unless you pass a permissive mode or allow-rules — same contract as Claude Code. ## Security The `Bash` tool runs all commands through a command injection detector that flags 8 categories of dangerous patterns: - `rm -rf` with broad targets - Piped downloads (`curl … | sh`, `wget … | bash`) - `sudo` execution - `chmod 777` - Redirecting to system files (`> /etc/`, `> /usr/`) - Fork bombs - Background `&` execution without supervision - `eval` / `source` of remote content Each command is assigned a security level (safe / caution / dangerous / blocked) and the agent is warned accordingly. ## Sessions Transcripts live in `~/.ccode/projects//.jsonl` with a meta sidecar (title, model, token usage). `-c` / `-r` / `/resume` restore them. ## Architecture ``` src/ cli.ts entry, arg parsing (commander) types.ts provider-agnostic messages / stream events provider/ anthropic (Messages API) + openai (chat completions) adapters agent/ loop (model⇄tools + hooks), runner, system prompt, context, compaction tools/ 14 tools + shared Tool/ToolContext types hooks.ts HookManager: 5 events, shell exec, settings.json loading settings.ts settings.json parser (hooks/permissions/env) security.ts command injection detection + sandbox levels permissions.ts modes + rule matching + ask flow repl/ interactive UI: input pump, markdown stream renderer, 18 slash cmds print.ts non-interactive mode & output formats session.ts JSONL persistence test/ node:test suites (loop, edit, permissions, grep/glob) ``` Provider-neutral core: the agent loop, tools and permissions never see vendor SDK types — both providers normalize to the same streaming event contract (`text_delta` / `tool_use` / `usage` / `done` / `error`). ## vs. the real Claude Code Implemented: agentic loop, 14 tools (including WebSearch & NotebookEdit), permission modes + rules, plan mode, hooks system (PreToolUse/PostToolUse/ UserPromptSubmit/Stop/Notification), command injection detection + sandbox levels, sub-agents, todos, sessions/resume, compaction, CLAUDE.md, settings.json, 18 slash commands, print/json/stream-json output, interruption. Not (yet) implemented: MCP servers, skills system, plugins & marketplaces, IDE extensions (VS Code/JetBrains), GitHub Actions, image/attachment input, background tasks, checkpoint-rewind, login/subscription auth (API keys only). ## Development ```bash pnpm dev # run from source via tsx pnpm test # unit tests (22 cases) pnpm typecheck # tsc --noEmit pnpm build # emit dist/ ```