Skip to content

Repository files navigation

claude-code-python

An idiomatic Python port of Claude Code's agentic core — a translation of the leaked Claude Code TypeScript/React source (D:/openSource/claude-code, ~513k lines across 1,902 files).

A literal 1:1 port of half a million lines of TypeScript + 552 React/Ink terminal UI components isn't sensible, so this repo follows the original's own ARCHITECTURE_ANALYSIS.md 5-phase refactoring roadmap. All 5 phases are implemented and tested (~126 offline tests; validated end-to-end against DeepSeek). Each phase was built then put through two adversarial multi-agent review rounds with every confirmed bug fixed and regression-tested. The full original src/ tree is also mirrored as a documented structural skeleton (see PORTING_STATUS.md).

PhaseScopeStatus
1 — agentic corequery loop, Tool contract, orchestration, model layer, permissions, built-in tools, REPL✅ implemented
2 — robustnesshooks lifecycle (settings.json + PreToolUse/PostToolUse/Stop/UserPromptSubmit/SessionStart), token budget, model fallback retry✅ implemented
3 — long-running contextmicrocompact (tool_result cleanup), autocompact (fork-summary), token accounting✅ implemented
4 — multi-agent & memoryAgentTool subagent spawn (reuses the loop, isolated context), persistent memory (MEMORY.md + topic files, injected)✅ implemented
5 — ecosystemslash commands (.claude/commands/*.md), MCP stdio client (MCPTool), skills (.claude/skills + Skill tool)✅ implemented

Documented deferrals (feature-gated experiments or large background subsystems in the original): StreamingToolExecutor; snip/context-collapse/reactive-compact; background/remote/worktree tasks, coordinator/swarm, and Dream consolidation; SessionMemory auto-extraction; MCP .mcp.json/SSE/HTTP transports.

The agentic core (Phase 1)

The crown jewel of Claude Code — the part the architecture doc itself says is "most worth reusing" — ported to idiomatic Python (asyncio, dataclasses, type hints) and wired to the real anthropic SDK:

ConcernModulePorted from
Agentic loop state machineclaude_code/query/loop.pysrc/query.ts
Session / turn orchestratorclaude_code/query_engine.pysrc/QueryEngine.ts
Tool contract + DI contextclaude_code/tool.pysrc/Tool.ts
Tool orchestration (concurrency)claude_code/services/tools/orchestration.pysrc/services/tools/toolOrchestration.ts
Per-tool executionclaude_code/services/tools/execution.pysrc/services/tools/toolExecution.ts
Anthropic streaming model callclaude_code/model/anthropic_client.pysrc/services/api/claude.ts
Four-phase permission systemclaude_code/permissions/src/utils/permissions/
Built-in toolsclaude_code/tools/src/tools/*
Tool-pool assemblyclaude_code/tools_registry.pysrc/tools.ts
System-prompt assemblyclaude_code/context.pysrc/utils/queryContext.ts
Task abstractionclaude_code/task.pysrc/Task.ts
Transcript persistenceclaude_code/session_storage.pysrc/utils/sessionStorage.ts
Terminal REPLclaude_code/cli.pysrc/main.tsx (Ink → rich)

Built-in tools: Read, Write, Edit, Bash, Glob, Grep, TodoWrite.

Faithfully reproduced behaviors include: the while True loop rewritten as a single mutable-state machine, the tool_use/tool_result pairing invariant (synthetic results on abort/error), withhold-then-recover error handling (max-output-tokens escalation 8k→64k then recovery nudges; prompt-too-long surfacing), concurrency-safe batch partitioning (read-only tools run in parallel, the rest serially), and the fail-closed four-phase permission pipeline (deny rules → tool check → allow rules → mode default → interactive prompt).

Third-party API only

This is a third-party-API build: it authenticates only via a model API key / base URL. All official Claude/Anthropic account login, subscription, and claude.ai-bound features are intentionally removed — there is no login/logout, no OAuth, no plan/billing/rate-limit management, no claude.ai remote bridge or Anthropic CCR. You bring your own endpoint.

Install

pip install -e ".[dev]"

Then configure one backend via environment variables.

Anthropic-compatible endpoint (e.g. DeepSeek's /anthropic, or real Anthropic):

export ANTHROPIC_BASE_URL=https://api.deepseek.com/anthropic
export ANTHROPIC_AUTH_TOKEN=<your-key># or ANTHROPIC_API_KEYexport ANTHROPIC_MODEL=deepseek-v4-pro[1m]

OpenAI-compatible endpoint (DeepSeek /v1, OpenAI, local servers):

export LLM_API_BASE=https://api.deepseek.com/v1
export LLM_API_KEY=<your-key>export LLM_MODEL=deepseek-chat

The backend is auto-detected from whichever credentials are set (Anthropic wins if both are present; force with CLAUDE_CODE_BACKEND=anthropic|openai).

Run

claude-py # interactive REPL
claude-py "fix the failing test in app.py"# one-shot
claude-py --bypass "..."# auto-allow all tools
claude-py --plan # plan mode (no mutating tools)
claude-py --print "summarize README.md"# non-interactive (deny tools needing prompts)
claude-py --model deepseek-chat --max-turns 20

Both backends are validated end-to-end against real DeepSeek: the agent reads a buggy file, fixes it with Edit, and runs it with Bash to verify.

In the REPL: /exit, /clear, /model <id>, /help.

Test

python -m pytest # 38 tests, runs offline (fake model + mock SDK client)

The test suite drives the entire agentic loop end-to-end without the real API via an injectable QueryDeps fake, and separately validates the real model-serialization layer against a mock that mimics the anthropic SDK's messages.stream interface.

Architecture

See ARCHITECTURE.md for the port's design and the mapping to the original TypeScript, and PORTING_STATUS.md for the phase-by-phase status of every src/ subsystem.

Disclaimer

This is a study/reference reimplementation derived from a public source leak. It is not affiliated with or endorsed by Anthropic. Use the official Claude Code for real work.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages