🇻🇳 Tiếng Việt: OFF

@anthropic-ai/claude-code

v2.1.89 — Architecture Deep DivePhân Tích Kiến Trúc Chi Tiết
Agentic coding tool by Anthropic — CLI, IDE, WebCông cụ lập trình AI của Anthropic — Terminal, IDE, Web
💡 Tip: Click any dotted-underline text to see Vietnamese translation. Or toggle the 🇻🇳 button (top-right) to show all translations at once.Nhấp vào bất kỳ chữ có gạch chấm để xem bản dịch tiếng Việt. Hoặc bật nút 🇻🇳 (góc phải trên) để hiện tất cả bản dịch.
16.5MB
Package Size (packed)Dung lượng (nén)
43MB
Unpacked SizeDung lượng (giải nén)
21
Core ToolsCông cụ tích hợp
16,824
Lines (minified)Dòng code (đã nén)
9
Tool CategoriesNhóm công cụ
0
Runtime DependenciesPhụ thuộc runtime
📦

Package StructureCấu Trúc Package

@anthropic-ai/claude-code/ ├── cli.js 13MBAll logic, bundled + minified into single fileToàn bộ logic, đóng gói + nén thành 1 file ├── sdk-tools.d.ts 117KBTypeScript type definitions (2,723 lines)Định nghĩa kiểu TypeScript (2,723 dòng) ├── package.json 1.2KB — Entry: bin.claude → cli.js ├── README.md 2KB ├── LICENSE.md 147B ├── bun.lock 596B └── vendor/ ├── ripgrep/ ~23MBFast search binary (rg) for 6 platformsCông cụ tìm kiếm nhanh (rg) cho 6 nền tảng │ ├── arm64-darwin/rg, arm64-linux/rg, arm64-win32/rg.exe │ └── x64-darwin/rg, x64-linux/rg, x64-win32/rg.exe └── audio-capture/ ~3MBNative module for voice inputModule gốc cho nhập liệu bằng giọng nói ├── arm64-darwin, arm64-linux, arm64-win32 └── x64-darwin, x64-linux, x64-win32

Key insight: Zero runtime dependencies — everything bundled into single cli.js. Optional: @img/sharp-* for image processing. Source code is closed — "Want to see the unminified source? We're hiring!"Không có phụ thuộc runtime — mọi thứ đóng gói vào 1 file cli.js. Tùy chọn: @img/sharp-* để xử lý ảnh. Mã nguồn không công khai — "Muốn xem mã nguồn gốc? Chúng tôi đang tuyển dụng!"

🏗️

Architecture OverviewTổng Quan Kiến Trúc

User InputĐầu vào từ người dùng
Terminal REPL / IDE Extension / Web App / GitHub @claude
Settings & EnvironmentCài đặt & Môi trường
~/.claude/settings.json, .claude/settings.json, env vars
Permission LayerLớp Phân Quyền
PreToolUse Hook → allow / deny / askHook trước khi dùng công cụ → cho phép / từ chối / hỏi người dùng
Tool DispatcherBộ Điều Phối Công Cụ
Built-in (21 tools) | MCP Servers | Custom PluginsTích hợp sẵn (21 công cụ) | MCP Servers | Plugin tùy chỉnh
Tool ExecutionThực Thi Công Cụ
PostToolUse / PostToolUseFailure hooks
Conversation ManagerQuản Lý Hội Thoại
Message history, token counting, context compaction, streamingLịch sử tin nhắn, đếm token, nén ngữ cảnh, phát trực tuyến
Anthropic Messages API
/v1/messages (create/stream) | countTokens | batches/v1/messages (tạo/stream) | đếm token | xử lý hàng loạt
Agent / Subagent DispatchĐiều Phối Agent / Agent Con
Fresh context, model selection (opus/sonnet/haiku), worktree isolationNgữ cảnh mới, chọn model (opus/sonnet/haiku), cách ly worktree
Claude ResponsePhản Hồi Claude
Text + tool calls → render to userVăn bản + gọi công cụ → hiển thị cho người dùng
🔧

21 Core Tools (9 Categories)21 Công Cụ Tích Hợp (9 Nhóm)

Agent Agent Tool
Spawn subagent with fresh context. Supports model override (sonnet/opus/haiku), git worktree isolation, async/background execution.Tạo agent con với ngữ cảnh mới. Hỗ trợ chọn model (sonnet/opus/haiku), cách ly git worktree, chạy nền/đồng bộ.
prompt subagent_type model? isolation?
Agent TaskOutput
Poll results from background tasks. Blocking or non-blocking mode.Theo dõi kết quả từ tác vụ nền. Chế độ chờ hoặc không chờ.
task_idblocktimeout
Agent TaskStop
Stop a running background task.Dừng tác vụ nền đang chạy.
task_id
File Read
Read files with 6 output types: text, image (base64), notebook, PDF, PDF pages, unchanged.Đọc file với 6 kiểu đầu ra: văn bản, ảnh (base64), notebook, PDF, trang PDF, không đổi.
file_pathoffset?limit?pages?
File Write
Write files, returns structured diff + git metadata.Ghi file, trả về bản so sánh thay đổi + thông tin git.
file_pathcontent
File Edit
String replacement (old → new). Supports replace_all for renaming across file.Thay thế chuỗi (cũ → mới). Hỗ trợ thay thế tất cả để đổi tên xuyên file.
file_pathold_stringnew_stringreplace_all?
Search Glob
Pattern matching to find files. Max 100 results.Tìm file theo mẫu đường dẫn. Tối đa 100 kết quả.
patternpath?
Search Grep
Content search using bundled ripgrep. Regex, context lines, multiline mode.Tìm kiếm nội dung dùng ripgrep (đi kèm). Hỗ trợ regex, dòng ngữ cảnh, chế độ nhiều dòng.
patternoutput_mode?multiline?
System Bash
Execute shell commands. Sandboxed by default, timeout max 600s, background mode.Chạy lệnh shell. Mặc định trong sandbox, timeout tối đa 600 giây, chế độ nền.
commandtimeout?dangerouslyDisableSandbox?
System EnterWorktree
Create isolated git worktree for agent/task isolation.Tạo git worktree riêng để cách ly agent/tác vụ.
name?
System ExitWorktree
Leave worktree, keep or remove it.Rời worktree, giữ lại hoặc xóa.
actiondiscard_changes?
Code NotebookEdit
Edit Jupyter notebooks at cell level. Insert/replace/delete modes.Chỉnh sửa Jupyter notebook theo từng ô. Chế độ: thêm/thay thế/xóa.
notebook_pathnew_sourceedit_mode?
Planning ExitPlanMode
Submit plan for user approval. Supports prompt-based Bash permissions.Gửi kế hoạch để người dùng phê duyệt. Hỗ trợ cấp quyền Bash theo mô tả.
allowedPrompts?
Web WebSearch
Web search with domain filtering (allow/block lists).Tìm kiếm web. Lọc theo tên miền (cho phép/chặn).
queryallowed_domains?blocked_domains?
Web WebFetch
Fetch URL + AI content analysis. HTML → markdown conversion.Tải URL + phân tích nội dung bằng AI. Chuyển đổi HTML → markdown.
urlprompt
UI AskUserQuestion
Ask user 1-4 questions, 2-4 options each. Multi-select support.Hỏi người dùng 1-4 câu, mỗi câu 2-4 lựa chọn. Hỗ trợ chọn nhiều.
questions[]annotations?
UI TodoWrite
Manage todo list. States: pending, in_progress, completed.Quản lý danh sách việc cần làm. Trạng thái: chờ, đang làm, hoàn thành.
todos[]
UI Config
Get/set settings. Dot-notation paths.Đọc/ghi cài đặt. Đường dẫn dạng dấu chấm.
settingvalue?
MCP MCP Tool
Generic MCP tool call. Flexible key-value input.Gọi công cụ MCP tổng quát. Đầu vào linh hoạt dạng key-value.
any params
MCP ListMcpResources
Discover resources from MCP servers.Khám phá tài nguyên từ các MCP server.
server?
MCP ReadMcpResource
Read MCP resource by URI.Đọc tài nguyên MCP theo URI.
serveruri
🪝

Hook Lifecycle SystemHệ Thống Hook (Vòng Đời)

Tool Call Request │ ▼ ┌─────────────────────┐ │ PreToolUse Hook │ ← allow, deny, ask (prompt user) │ │ Can modify input, block execution │ │ Can register file watchers └─────────┬───────────┘ │ ┌────┴────┐ │ allowed? │ └────┬────┘ yes │ no → BLOCKED (show message) ▼ ┌─────────────────────┐ │ Tool Execution │ └─────────┬───────────┘ │ ┌────┴────┐ │ success? │ └────┬────┘ yes │ no │ │ │ ▼ │ ▼ ┌──────────┐ ┌───────────────────┐ │PostToolUse│ │PostToolUseFailure │ └──────────┘ └───────────────────┘ │ ▼ Tool Result → injected into message context

Hook Response FormatĐịnh dạng phản hồi Hook

{ "behavior": "allow" | "deny" | "ask", "message": "User prompt (if ask)", "updatedInput": { ...modified tool input... }, "decisionReason": { "type": "rule|policy|other", "reason": "..." }, "watchPaths": ["/path/to/watch"] }
🔒

Security Model (4 Layers)Mô Hình Bảo Mật (4 Lớp)

Layer 1: Policy Settings (Organization)Lớp 1: Chính sách tổ chức
Org-level policy overrides all user settings. Can disable hooks, restrict tools, enforce rules.Chính sách cấp tổ chức ghi đè mọi cài đặt. Có thể tắt hooks, giới hạn công cụ, áp đặt quy tắc.
policySettings > flagSettings > localSettings > projectSettings > userSettings
Layer 2: Hook-Based FilteringLớp 2: Lọc dựa trên Hook
PreToolUse hooks run before each tool call. Can block, modify, or ask user confirmation.Hook PreToolUse chạy trước mỗi lần gọi công cụ. Có thể chặn, sửa đổi, hoặc yêu cầu xác nhận.
Flags: disableAllHooks, allowManagedHooksOnly
Layer 3: Permission RulesLớp 3: Quy tắc phân quyền
Per-tool permission in settings.json. Prompt-based permissions for Plan mode.Quyền theo từng công cụ trong settings.json. Quyền theo mô tả cho Plan mode.
"toolName": "allow|deny|ask"
Layer 4: Command Parsing & SandboxLớp 4: Phân tích lệnh & Sandbox
Bash commands run in sandbox by default. Detects file redirections, unsafe patterns, arbitrary path writes.Lệnh Bash chạy trong sandbox mặc định. Phát hiện chuyển hướng file, mẫu không an toàn, ghi đường dẫn tùy ý.
Override: dangerouslyDisableSandbox: true

AuthenticationXác Thực

MethodPhương thứcDetailChi tiết
API KeyDirect Anthropic API keyKhóa API Anthropic trực tiếp
OAuth TokenCLAUDE_CODE_OAUTH_TOKEN env var
Token FileCLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR
Interactiveclaude auth login (browser OAuth flow)Đăng nhập qua trình duyệt
Setupclaude setup-token
🔌

MCP (Model Context Protocol) IntegrationTích Hợp MCP (Giao Thức Ngữ Cảnh Mô Hình)

settings.json │ mcpServers: { "serverName": { command, args } } ▼ MCP Client (stdio-based JSON-RPC) │ Spawn external processes │ Auto-monitor + restart on crash ▼ Tool Registry │ Format: mcp__<uuid>__<tool_name> │ Example: mcp__mcp-registry__search_mcp_registry ▼ Available Operations: ├── listTools() → Discover tools from server ├── callTool() → Execute tool (JSON-RPC call) ├── listResources() → Discover resources └── readResource() → Read resource by URI
🤖

Agent / Subagent SystemHệ Thống Agent / Agent Con

FeatureTính năngDetailChi tiết
ContextFresh context (no history inherited from parent)Ngữ cảnh mới (không kế thừa lịch sử từ agent cha)
Model Selectionsonnet | opus | haiku per-agentChọn model cho mỗi agent
IsolationGit worktree (isolation: "worktree")Cách ly bằng Git worktree
ExecutionSync (foreground) or Async (background)Đồng bộ (foreground) hoặc Bất đồng bộ (background)
CommunicationSendMessage between agents (by name)Gửi tin nhắn giữa các agent (theo tên)
PermissionacceptEdits | bypassPermissions | plan | dontAsk
Teamteam_name for multi-team orchestrationĐiều phối nhiều nhóm agent
TrackingToken usage, duration, tool count per agentSố token, thời gian, số lần gọi công cụ mỗi agent

Agent Output (on completion)Đầu ra Agent (khi hoàn thành)

{ "status": "completed", "agentId": "uuid-xxx", "content": [{ "type": "text", "text": "..." }], "totalToolUseCount": 15, "totalDurationMs": 45000, "totalTokens": 25000, "usage": { "input_tokens": 18000, "output_tokens": 7000, "cache_creation_input_tokens": 5000, "cache_read_input_tokens": 12000, "service_tier": "standard" } }
💬

Conversation & StreamingHội Thoại & Phát Trực Tuyến

Message Loop: User message (role: "user") │ ▼ Anthropic API (/v1/messages, streaming) │ ├── content_block_start → New text/tool block ├── content_block_delta → Partial content (streaming) ├── content_block_stop → Block complete ├── message_delta → Message-level updates └── message_stop → Turn complete │ ▼ Assistant response (role: "assistant") │ ├── type: "text" → Render text to user └── type: "tool_use" → Execute tool │ ▼ Tool Result (type: "tool_result") │ ▼ Next API call (loop continues) Context Management: ├── Token counting (countTokens API) ├── Prompt caching (ephemeral 5m + 1h) ├── Context compaction (auto-summarize near limit) └── Message alternation enforcement (user ↔ assistant)
⚙️

Configuration HierarchyPhân Cấp Cài Đặt

PriorityƯu tiênLevelCấp độLocationVị tríScopePhạm vi
1 (highest)Policy (Managed)Organization policyOverrides everythingGhi đè mọi thứ
2CLI FlagsCommand-line argumentsSession
3Local.claude/settings.local.jsonProject (gitignored)
4Project.claude/settings.jsonProject (shared)
5 (lowest)User~/.claude/settings.jsonGlobal
⌨️

CLI Command ModesCác Chế Độ Lệnh CLI

CommandDescriptionMô tả
claudeInteractive REPL modeChế độ tương tác REPL
claude --bareSimple mode (CLAUDE_CODE_SIMPLE=1)Chế độ đơn giản
claude remote-controlRemote control / bridge modeChế độ điều khiển từ xa
claude computer-useMCP computer vision integrationTích hợp computer vision qua MCP
claude --tmuxTerminal multiplexer modeChế độ chia terminal
claude --worktreeGit worktree workspace modeChế độ workspace worktree
claude --updateSelf-update mechanismTự cập nhật
claude auth loginBrowser OAuth flowĐăng nhập qua trình duyệt
claude setup-tokenAPI key setupThiết lập khóa API
💡

Key Insights & ObservationsĐiểm Nổi Bật & Nhận Xét

Zero Dependencies
Everything bundled into a single 13MB cli.js. No runtime dependencies. Minimizes supply chain risk.Mọi thứ đóng gói vào 1 file cli.js 13MB. Không phụ thuộc runtime. Giảm thiểu rủi ro chuỗi cung ứng.
Bundled Ripgrep
Ships binary ripgrep for 6 platforms (~23MB). Grep tool calls this binary directly instead of Node.js regex.Đi kèm binary ripgrep cho 6 nền tảng (~23MB). Công cụ Grep gọi trực tiếp binary thay vì dùng regex Node.js.
Voice Input
Native audio-capture module for 6 platforms. Enables voice-to-text input in terminal.Module gốc thu âm cho 6 nền tảng. Cho phép nhập liệu bằng giọng nói trong terminal.
Closed Source
Source code minified + obfuscated. Anthropic: "Want to see the unminified source? We're hiring!"Mã nguồn nén + che giấu. Anthropic: "Muốn xem mã nguồn gốc? Chúng tôi đang tuyển dụng!"
dangerouslyAllowBrowser
Anthropic SDK initialized with this flag = true. Unusual for CLI, likely supports web-based mode (claude.ai/code).Anthropic SDK khởi tạo với cờ này = true. Bất thường cho CLI, có thể để hỗ trợ chế độ web (claude.ai/code).
Prompt Caching
2 tiers: ephemeral 5-minute and 1-hour. Reduces API cost for long conversations by caching system prompt + context.2 tầng: tạm thời 5 phút và 1 giờ. Giảm chi phí API cho hội thoại dài bằng cách cache system prompt + ngữ cảnh.