### Add Getting Started Guide to Help Page Source: https://github.com/claude-code-best/claude-code/blob/main/progress.md Integrates a 3-step 'Getting started' guide into the Help General page to assist new users. ```typescript import { HelpGeneral } from "../src/components/HelpV2/General"; import { render, screen } from '@testing-library/react'; describe("Help General Page with Getting Started Guide", () => { it("should display the new 3-step getting started guide", () => { render(); // Check for the presence of the Getting Started section title expect(screen.getByText(/Getting started/i)).toBeInTheDocument(); // Check for the 3 steps (example text) expect(screen.getByText(/Step 1: Explore commands/i)).toBeInTheDocument(); expect(screen.getByText(/Step 2: Use shortcuts/i)).toBeInTheDocument(); expect(screen.getByText(/Step 3: Customize settings/i)).toBeInTheDocument(); // Ensure the old single paragraph description is not the primary content expect(screen.queryByText(/This page provides a comprehensive list/i)).not.toBeInTheDocument(); }); }); // Mock HelpGeneral component if not available if (typeof HelpGeneral === 'undefined') { global.HelpGeneral = () => (

Getting started

  1. Step 1: Explore commands
  2. Step 2: Use shortcuts
  3. Step 3: Customize settings

All shortcuts: ...

); } ``` -------------------------------- ### Install acp-link from Source Source: https://github.com/claude-code-best/claude-code/blob/main/packages/acp-link/README.md Install the acp-link package from the monorepo root using bun. ```bash # From monorepo root bun install ``` -------------------------------- ### Install Bun on Windows (PowerShell) Source: https://github.com/claude-code-best/claude-code/blob/main/README_EN.md Installs the latest version of Bun on Windows systems using PowerShell. ```powershell powershell -c "irm bun.sh/install.ps1 | iex" ``` -------------------------------- ### External MCP Server Configuration Examples Source: https://github.com/claude-code-best/claude-code/blob/main/docs/extensibility/mcp-protocol.mdx Provides examples of how to configure external MCP servers in JSON format, including stdio, http, sse, and ws types. These configurations specify how to run or connect to the MCP servers. ```json // settings.json / .mcp.json 中的 MCP 配置 { "mcpServers": { // stdio 类型 — 启动子进程 "my-database": { "command": "npx", "args": ["@my-org/db-mcp-server"], "env": { "DB_URL": "postgres://..." } }, // HTTP 流类型 — 远程服务器 "remote-api": { "type": "http", "url": "https://api.example.com/mcp" }, // SSE 类型 — Server-Sent Events "realtime-feed": { "type": "sse", "url": "https://feed.example.com/sse" }, // WebSocket 类型 "ws-service": { "type": "ws", "url": "wss://ws.example.com/mcp" } } } ``` -------------------------------- ### Install Bun on Linux and macOS Source: https://github.com/claude-code-best/claude-code/blob/main/README_EN.md Installs the latest version of Bun on Linux and macOS systems using a curl command. ```bash curl -fsSL https://bun.sh/install | bash ``` -------------------------------- ### Start RCS with Docker Compose Source: https://github.com/claude-code-best/claude-code/blob/main/docs/features/remote-control-self-hosting.md Command to start the services defined in the Docker Compose file. ```bash docker compose up -d ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/claude-code-best/claude-code/blob/main/README_EN.md Installs all necessary project dependencies for Claude Code. This command must be run from the repository root. ```bash cd /path/to/claude-code bun install ``` -------------------------------- ### Verify Bun Installation Source: https://github.com/claude-code-best/claude-code/blob/main/README_EN.md Checks if Bun is installed and available in the current terminal by displaying its help information and version. ```bash bun --help bun --version ``` -------------------------------- ### Start Remote Control Server Daemon Source: https://github.com/claude-code-best/claude-code/blob/main/DEV-LOG.md CLI commands to start the remote control server daemon. Supports configuration for spawn mode and capacity. ```bash bun run dev daemon start bun run dev daemon start --spawn-mode=worktree --capacity=8 ``` -------------------------------- ### Auto Focus Example Source: https://github.com/claude-code-best/claude-code/blob/main/packages/@ant/ink/docs/10-events-and-focus.md Demonstrates how to use the autoFocus prop to give an element focus immediately when it mounts. ```tsx Receives focus immediately on mount ``` -------------------------------- ### Width and Height Examples Source: https://github.com/claude-code-best/claude-code/blob/main/packages/@ant/ink/docs/02-layout.md Demonstrates setting fixed or percentage-based dimensions for a Box component. ```tsx ... // Fixed 40 characters wide ``` ```tsx ... // Fixed 10 rows tall ``` ```tsx ... // 50% of parent's width ``` ```tsx ... // Full parent width ``` -------------------------------- ### Start Inspect Server for Debugging Source: https://github.com/claude-code-best/claude-code/blob/main/README_EN.md Start the inspect server in the terminal to enable VS Code debugging. This command outputs a WebSocket address for attaching the debugger. ```bash bun run dev:inspect ``` -------------------------------- ### Display Property Examples Source: https://github.com/claude-code-best/claude-code/blob/main/packages/@ant/ink/docs/02-layout.md Shows how to control the visibility and layout behavior of a Box component. ```tsx ... // Visible (default) ``` ```tsx ... // Hidden (removed from layout) ``` -------------------------------- ### Run acp-link via Global Install Source: https://github.com/claude-code-best/claude-code/blob/main/packages/acp-link/README.md Execute acp-link from a global installation, specifying the agent path. ```bash # Via global install acp-link /path/to/agent ``` -------------------------------- ### Capture and Bubble Phase Example Source: https://github.com/claude-code-best/claude-code/blob/main/packages/@ant/ink/docs/10-events-and-focus.md Demonstrates how to use onKeyDownCapture and onKeyDown to handle events during the capture and bubble phases, including stopping propagation. ```tsx { // Capture phase: fires top-down console.log('Parent captures key') }} onKeyDown={(e) => { // Bubble phase: fires bottom-up console.log('Parent receives bubbled key') }} > { // Target: fires first in bubble phase console.log('Child handles key') e.stopImmediatePropagation() // Stop here }} > Focus here ``` -------------------------------- ### Tab Navigation Example Source: https://github.com/claude-code-best/claude-code/blob/main/packages/@ant/ink/docs/10-events-and-focus.md Example of using tabIndex to control focusability and the onAction prop for handling button clicks during tab navigation. ```tsx ``` -------------------------------- ### Example Status Line Script: Cache Hit Rate and TTL Countdown Source: https://github.com/claude-code-best/claude-code/blob/main/docs/features/status-line.mdx A default example script for the status line that displays cache hit rate and a TTL countdown. It handles per-session state persistence, color-coded output, and fallbacks for null usage data. ```bash #!/bin/bash # Example script for status line # Outputs: | | ctx:N% | Cache X% SS:MM # --- Configuration --- STATE_FILE="~/.claude/statusline-state/$(echo -n "$SESSION_ID" | md5sum | head -c 16).state" DEFAULT_HIT_RATE="?%" DEFAULT_TTL="--:--" # --- State Management --- load_state() { if [[ -f "$STATE_FILE" ]]; then read -r signature timestamp hit_rate < "$STATE_FILE" # Basic numeric validation if [[ "$timestamp" =~ ^[0-9]+$ ]] && [[ "$hit_rate" =~ ^[0-9]+$ ]]; then echo "$signature" echo "$timestamp" echo "$hit_rate" return 0 fi fi echo "" echo "0" echo "0" return 1 } save_state() { local signature="$1" local timestamp="$2" local hit_rate="$3" mkdir -p "$(dirname "$STATE_FILE")" echo "$signature" echo "$timestamp" echo "$hit_rate" > "$STATE_FILE" } # --- Helper Functions --- get_color() { local value=$1 local type=$2 if [[ "$type" == "hit_rate" ]]; then if (( value >= 50 )); then echo "32"; # Green elif (( value >= 20 )); then echo "33"; # Yellow else echo "90"; # Gray fi elif [[ "$type" == "ttl" ]]; then local ttl_minutes=$(( value / 60 )) if (( ttl_minutes <= 5 )); then echo "1;31"; # Blinking Red elif (( ttl_minutes <= 20 )); then echo "31"; # Red elif (( ttl_minutes <= 40 )); then echo "33"; # Yellow else echo "32"; # Green fi fi } # --- Main Logic --- # Load current state read -r last_signature last_timestamp last_hit_rate < <(load_state) # Get current context usage (if available) current_usage_json="$(cat)" # Read from stdin # Parse current usage current_signature="$(echo "$current_usage_json" | jq -r '.context_window.current_signature // ""')" current_usage="$(echo "$current_usage_json" | jq -r '.context_window.current_usage // ""')" # Calculate hit rate if [[ -n "$current_usage" ]]; then cache_read=$(echo "$current_usage" | jq '.cache_read // 0') input=$(echo "$current_usage" | jq '.input // 0') cache_creation=$(echo "$current_usage" | jq '.cache_creation // 0') cache_total=$(( input + cache_creation + cache_read )) if (( cache_total > 0 )); then hit_rate=$(( cache_read * 100 / cache_total )) else hit_rate=0 fi # Reset TTL only if signature changes if [[ "$current_signature" != "$last_signature" ]]; then timestamp=$(date +%s) save_state "$current_signature" "$timestamp" "$hit_rate" else # Use last timestamp if signature is the same timestamp="$last_timestamp" save_state "$current_signature" "$timestamp" "$hit_rate" fi else # Fallback to last known state if current_usage is null hit_rate="$last_hit_rate" timestamp="$last_timestamp" current_signature="$last_signature" # If no state, use defaults if [[ "$last_hit_rate" == "0" && "$last_timestamp" == "0" ]]; then hit_rate="$DEFAULT_HIT_RATE" timestamp=$(date +%s) fi fi # Calculate TTL current_time=$(date +%s) # Assuming 60 minutes = 3600 seconds for TTL max_ttl=$(( 60 * 60 )) elapsed_time=$(( current_time - timestamp )) ttl=$(( max_ttl - elapsed_time )) # Handle expired TTL if (( ttl < 0 )); then ttl=0 hit_rate="exp" fi # Format TTL for display ttl_minutes=$(( ttl / 60 )) ttl_seconds=$(( ttl % 60 )) formatted_ttl="$(printf "%02d:%02d" "$ttl_minutes" "$ttl_seconds")" # Determine colors hit_color=$(get_color "$hit_rate" "hit_rate") ttl_color=$(get_color "$ttl" "ttl") # Output # Use default values if hit_rate is not a number (e.g., 'exp') if ! [[ "$hit_rate" =~ ^[0-9]+$ ]]; then display_hit_rate="$hit_rate" display_hit_color="90" # Gray for 'exp' else display_hit_rate="$hit_rate%" display_hit_color="$hit_color" fi # Use default values if ttl is 0 and expired if [[ "$ttl" == "0" && "$hit_rate" == "exp" ]]; then formatted_ttl="exp" display_ttl_color="90" # Gray for expired else display_ttl_color="$ttl_color" fi # Get current directory and model (simplified) current_dir="$(pwd)" current_model="$(echo "$current_usage_json" | jq -r '.model // "default"')" # Print the status line echo -e "\033[${display_hit_color}m${display_hit_rate}\033[0m | ${current_model} | ctx:${hit_rate}% | Cache ${formatted_ttl}" ``` -------------------------------- ### Initialize Keybinding Setup Source: https://github.com/claude-code-best/claude-code/blob/main/packages/@ant/ink/docs/08-keybindings.md Load and validate keybinding configuration at app startup using `KeybindingSetup`. It requires functions to load bindings, subscribe to changes, and handle validation warnings. ```tsx import { KeybindingSetup } from '@anthropic/ink' parseUserKeybindings(configFile)} subscribeToChanges={(cb) => watchConfigFile(cb)} onWarnings={(warnings, isReload) => { warnings.forEach(w => console.warn(w.message)) }} > ``` -------------------------------- ### acp-link Basic Usage Source: https://github.com/claude-code-best/claude-code/blob/main/packages/acp-link/README.md Start acp-link with the default settings, providing the path to the agent. ```bash # Basic usage acp-link /path/to/agent ``` -------------------------------- ### Min/Max Dimension Examples Source: https://github.com/claude-code-best/claude-code/blob/main/packages/@ant/ink/docs/02-layout.md Shows how to set minimum and maximum dimensions for a Box component, supporting percentage values. ```tsx ... ``` ```tsx ... ``` ```tsx ... ``` ```tsx ... ``` ```tsx Percentage values are supported: `minWidth="30%"`. ``` -------------------------------- ### Background Session Start Handler Source: https://github.com/claude-code-best/claude-code/blob/main/docs/task/task-013-bg-engine-abstraction.md Handles the initiation of a new background session by selecting the appropriate engine, generating a session name, defining the log path, and calling the engine's start method. It then logs the session details to the console. ```typescript export async function handleBgStart(args: string[]): Promise { const engine = await selectEngine() const sessionName = `claude-bg-${randomUUID().slice(0, 8)}` const logPath = join(getClaudeConfigHomeDir(), 'sessions', 'logs', `${sessionName}.log`) const result = await engine.start({ sessionName, args: filteredArgs, env: { ...process.env, CLAUDE_CODE_SESSION_KIND: 'bg', ... }, logPath, cwd: process.cwd(), }) console.log(`Background session started: ${result.sessionName}`) console.log(` Engine: ${result.engineUsed}`) console.log(` Log: ${result.logPath}`) console.log(` Use \`claude daemon attach ${result.sessionName}\` to reconnect.`) } ``` -------------------------------- ### Flex Wrap Examples Source: https://github.com/claude-code-best/claude-code/blob/main/packages/@ant/ink/docs/02-layout.md Demonstrates how to control whether flex items wrap onto multiple lines. ```tsx ... // Single line (default) ``` ```tsx ... // Multiple lines ``` ```tsx ... // Reverse cross-axis stacking ``` -------------------------------- ### Update First Fork Example with `fork: true` Source: https://github.com/claude-code-best/claude-code/blob/main/spec/feature_20260502_F001_fork-agent-redesign/spec-plan.md Adds the `fork: true` parameter to the first example within the `forkExamples` section in `prompt.ts` to explicitly demonstrate the new fork invocation method. ```typescript Agent({ description: "Fork the current conversation to continue a multi-file refactor.", fork: true, subagent_type: "code-reviewer", }) ``` -------------------------------- ### Flex Grow, Shrink, and Basis Examples Source: https://github.com/claude-code-best/claude-code/blob/main/packages/@ant/ink/docs/02-layout.md Shows how to control the flexibility of children within a flex container. ```tsx ... // Grow to fill available space ``` ```tsx ... // Don't shrink below intrinsic size ``` ```tsx ... // Initial size before flex distribution ``` ```tsx ... // Percentage basis ``` -------------------------------- ### Margin Examples Source: https://github.com/claude-code-best/claude-code/blob/main/packages/@ant/ink/docs/02-layout.md Shows how to add outer spacing around a Box component. Only integer values are supported. ```tsx ... // All sides ``` ```tsx ... // Left and right ``` ```tsx ... // Top and bottom ``` ```tsx ... // Left only ``` ```tsx ... // Right only ``` ```tsx ... // Top only ``` ```tsx ... // Bottom only ``` -------------------------------- ### Padding Examples Source: https://github.com/claude-code-best/claude-code/blob/main/packages/@ant/ink/docs/02-layout.md Illustrates how to add inner spacing within a Box component. Only integer values are supported. ```tsx ... // All sides ``` ```tsx ... // Left and right ``` ```tsx ... // Top and bottom ``` ```tsx ... // Left only ``` ```tsx ... // Right only ``` ```tsx ... // Top only ``` ```tsx ... // Bottom only ``` -------------------------------- ### Example Component Tree Structure Source: https://github.com/claude-code-best/claude-code/blob/main/packages/@ant/ink/docs/01-getting-started.md Illustrates a nested component structure using Ink's `Box` and `Text` components, demonstrating Flexbox layout for terminal output. ```tsx Header Left Right ``` -------------------------------- ### Dialog with Custom Input Guide Source: https://github.com/claude-code-best/claude-code/blob/main/packages/@ant/ink/docs/05-design-system.md Customize the keyboard hint footer of a Dialog component using the `inputGuide` prop. This allows for dynamic guidance based on the dialog's state. ```tsx ( exitState.pending ? Press {exitState.keyName} again to exit : Press Enter to save, Esc to cancel )} > ... ``` -------------------------------- ### Using the color() Utility Source: https://github.com/claude-code-best/claude-code/blob/main/packages/@ant/ink/docs/04-theme-system.md Demonstrates how to use the `color` utility to get a theme-aware coloring function. The `paint` function returned can then be used to color strings with ANSI escape codes. ```tsx import { color, useTheme } from '@anthropic/ink' function MyComponent() { const [themeName] = useTheme() const paint = color('success', themeName) // paint('text') returns ANSI-colored string } ``` -------------------------------- ### Cross-Machine Attach Flow Example Source: https://github.com/claude-code-best/claude-code/blob/main/docs/features/lan-pipes-implementation.md Details the sequence of events for attaching a CLI client (CLI-B) to another machine (CLI-A) over TCP within a LAN. ```text CLI-B (192.168.50.27) 心跳循环 → beacon.getPeers() 发现 CLI-A (192.168.50.22) → connectToPipe(pName, myName, 3000, { host: '192.168.50.22', port: 58853 }) → PipeClient.connectTcp() → net.createConnection({ host, port }) → client.send({ type: 'attach_request', meta: { machineId } }) → CLI-A 收到: isLanPeer = (msg.meta.machineId !== myMachineId) → true → 不检查 role,直接 reply({ type: 'attach_accept' }) → setPipeRelay(socket.write) → CLI-B 收到 attach_accept → addSlaveClient(pName, client) → store.setState: role='master', slaves[pName] = { status: 'idle' } ``` -------------------------------- ### Minimal KAIROS Activation Source: https://github.com/claude-code-best/claude-code/blob/main/docs/features/kairos.md Command to enable the minimal KAIROS setup, including persistent assistant mode and BriefTool functionality. This is useful for basic background operation. ```bash # 最小启用(常驻助手 + Brief) FEATURE_KAIROS=1 FEATURE_KAIROS_BRIEF=1 bun run dev ``` -------------------------------- ### Sandbox Startup Link Source: https://github.com/claude-code-best/claude-code/blob/main/docs/safety/sandbox.mdx Illustrates the sequence of calls during the sandbox initialization phase, from checking if sandboxing is enabled to initializing the sandbox manager. ```text REPL / CLI 启动 -> isSandboxingEnabled() -> convertToSandboxRuntimeConfig(settings) -> BaseSandboxManager.initialize(runtimeConfig, callback) -> 设置变化时 BaseSandboxManager.updateConfig(newConfig) ``` -------------------------------- ### Build Project Source: https://github.com/claude-code-best/claude-code/blob/main/README_EN.md Run the build command using Bun. This process uses code splitting and outputs to the dist/ directory. ```bash bun run build ``` -------------------------------- ### ToolSearchTool Prompt Update with 'discover:' Mode Source: https://github.com/claude-code-best/claude-code/blob/main/spec/feature_20260508_F001_tool-search/spec-plan-1.md The PROMPT_TAIL in ToolSearchTool now includes documentation for the 'discover:' query form, explaining its use for understanding available tools before invocation. ```typescript const PROMPT_TAIL = ` ... (保留现有内容) ... Query forms: - "select:Read,Edit,Grep" — fetch these exact tools by name - "discover:schedule cron job" — pure discovery, returns tool info (name, description, schema) without loading. Use when you want to understand available tools before deciding which to invoke. - "notebook jupyter" — keyword search, up to max_results best matches - "+slack send" — require "slack" in the name, rank by remaining terms` ``` -------------------------------- ### Open Application on Linux Source: https://github.com/claude-code-best/claude-code/blob/main/docs/features/computer-use.md Launching applications on Linux can be done using xdg-open or gtk-launch. ```bash xdg-open ``` ```bash gtk-launch ``` -------------------------------- ### acp-link Manager UI with Default Port Source: https://github.com/claude-code-best/claude-code/blob/main/packages/acp-link/README.md Start the acp-link Manager UI on the default port (9315). This launches a separate management service without starting an agent. ```bash # 启动 Manager(默认端口 9315) acp-link --manager ``` -------------------------------- ### ToolSearchTool 'discover:' Mode in prompt.ts Source: https://github.com/claude-code-best/claude-code/blob/main/spec/feature_20260508_F001_tool-search/spec-plan-1.md Confirms that the prompt.ts file contains the documentation explaining the 'discover:' mode for the ToolSearchTool, informing users about its functionality. ```bash grep -n "discover:" packages/builtin-tools/src/tools/ToolSearchTool/prompt.ts ``` -------------------------------- ### Get Current Theme and Setter with useTheme Source: https://github.com/claude-code-best/claude-code/blob/main/packages/@ant/ink/docs/04-theme-system.md Use the useTheme hook to get the resolved theme name (never 'auto') and a function to set the theme. This is useful for components that need to react to theme changes. ```tsx const [currentTheme, setTheme] = useTheme() // currentTheme: ThemeName (never 'auto') // setTheme: (setting: ThemeSetting) => void ``` -------------------------------- ### Implement 'discover:' Query Mode Source: https://github.com/claude-code-best/claude-code/blob/main/spec/feature_20260508_F001_tool-search/spec-plan-1.md Adds a 'discover:' prefix to the query to enable a pure discovery search. This mode returns tool information (name, description, schema) as text without triggering deferred tool loading, suitable for planning or information gathering. ```typescript // Check for discover: prefix — pure discovery search. // Returns tool info (name + description + schema) as text, // does NOT trigger deferred tool loading. const discoverMatch = query.match(/^discover:(.+)$/i) if (discoverMatch) { const discoverQuery = discoverMatch[1]!.trim() const index = await getToolIndex(deferredTools) const tfIdfResults = searchTools(discoverQuery, index, max_results) // discover 模式返回文本格式的工具信息 const textResults = tfIdfResults.map(r => { let line = `**${r.name}** (score: ${r.score.toFixed(2)}) ${r.description}` if (r.inputSchema) { line += ` Schema: ${JSON.stringify(r.inputSchema)}` } return line }) const text = textResults.length > 0 ? `Found ${textResults.length} tools: ${textResults.join(' ')}` : 'No matching deferred tools found' logSearchOutcome(tfIdfResults.map(r => r.name), 'keyword') return buildSearchResult(tfIdfResults.map(r => r.name), query, deferredTools.length) } ``` -------------------------------- ### Get Raw Theme Setting with useThemeSetting Source: https://github.com/claude-code-best/claude-code/blob/main/packages/@ant/ink/docs/04-theme-system.md Use the useThemeSetting hook to get the raw theme setting, which may include 'auto'. This is useful for components that need to display the user's explicit choice or the auto setting. ```tsx const setting = useThemeSetting() // 'auto' | 'dark' | ... ``` -------------------------------- ### Entering Auto Mode Logic Source: https://github.com/claude-code-best/claude-code/blob/main/docs/safety/auto-mode.mdx Outlines the steps involved in transitioning to auto mode, including enabling the gate, setting active status, stripping dangerous permissions, and injecting system prompts. ```text 1. 检查 auto mode gate 是否开启(isAutoModeGateEnabled) 2. 设置 autoModeActive = true 3. 调用 stripDangerousPermissionsForAutoMode() 剥离危险规则 4. 向对话注入 Auto Mode 系统提示 ``` -------------------------------- ### 启用 Buddy 功能 Source: https://github.com/claude-code-best/claude-code/blob/main/docs/features/buddy.mdx 在开发环境中启用 Buddy 功能需要设置环境变量 FEATURE_BUDDY=1。 ```bash FEATURE_BUDDY=1 bun run dev ``` -------------------------------- ### Configure API Login Source: https://github.com/claude-code-best/claude-code/blob/main/README_EN.md After the first run, use the /login command in the REPL to access the login configuration screen. Select 'Anthropic Compatible' to connect to third-party API-compatible services. ```bash /login ``` -------------------------------- ### useTerminalSize Source: https://github.com/claude-code-best/claude-code/blob/main/packages/@ant/ink/docs/09-hooks-reference.md Get the current terminal dimensions, including columns and rows. ```APIDOC ## useTerminalSize() ### Description Get current terminal dimensions. ### Signature ```ts function useTerminalSize(): { columns: number rows: number } ``` ### Note Throws if used outside ``. ``` -------------------------------- ### Align Items Examples Source: https://github.com/claude-code-best/claude-code/blob/main/packages/@ant/ink/docs/02-layout.md Shows how to align children along the cross-axis of a flex container. ```tsx ... // Cross-axis start ``` ```tsx ... // Cross-axis center ``` ```tsx ... // Cross-axis end ``` ```tsx ... // Stretch to fill (default) ``` -------------------------------- ### Install @anthropic/ink Source: https://github.com/claude-code-best/claude-code/blob/main/packages/@ant/ink/docs/01-getting-started.md Add @anthropic/ink as a workspace dependency. This package is for internal use and not published to npm. ```json { "dependencies": { "@anthropic/ink": "workspace:*" } } ``` -------------------------------- ### Linux Sandbox Implementation Source: https://github.com/claude-code-best/claude-code/blob/main/docs/safety/sandbox.mdx Describes the sandbox implementation on Linux, utilizing 'bubblewrap' and 'seccomp' for isolation of mounts, PIDs, and networks. Notes differences in glob path support and cleanup requirements compared to macOS. ```text - 底层使用 `bubblewrap + seccomp` - 会建立 mount / PID / network 等隔离 - Linux 上对 glob 路径的支持比 macOS 弱一些 - 某些运行后残留需要在 `cleanupAfterCommand()` 中清理 ``` -------------------------------- ### Update Bun to Latest Version Source: https://github.com/claude-code-best/claude-code/blob/main/README_EN.md Updates an existing Bun installation to the latest available version. ```bash bun upgrade ``` -------------------------------- ### Run Typecheck, Tests, Lint, and Build Source: https://github.com/claude-code-best/claude-code/blob/main/docs/agent/sur-loop-scheduled-oom.md Execute various development and quality assurance commands for the project. This includes type checking, running unit tests for specific modules or the entire suite, linting for code style, and building the project. ```bash bun run typecheck bun test src/utils/__tests__/autonomyRuns.test.ts bun test src/hooks/__tests__/useScheduledTasks.test.ts bun test src/utils/processUserInput/__tests__/processSlashCommand.test.ts bun test # full unit suite bun run lint bun run build ``` -------------------------------- ### Iterative Loop Example Source: https://github.com/claude-code-best/claude-code/blob/main/docs/conversation/the-loop.mdx Illustrates a multi-turn execution flow for a user request to find and remove unused imports. It shows the progression of API calls, tool executions, and state transitions across four iterations. ```text 迭代 1: 思考→行动 预处理管道: applyToolResultBudget → snipCompact(HISTORY_SNIP feature) → microcompact → applyCollapses(CONTEXT_COLLAPSE feature) → autocompact → 上下文很短,无需压缩 API 调用: 返回 tool_use(Glob, "**/*.ts") 工具执行: 返回 42 个文件路径 → needsFollowUp = true → transition: { reason: 'next_turn' }, continue 迭代 2: 思考→行动 预处理管道: 42 个文件结果仍在预算内 API 调用: 返回 tool_use(Grep, "import.*from") 工具执行: 在 15 个文件中找到 120 条 import → needsFollowUp = true → transition: { reason: 'next_turn' }, continue 迭代 3: 思考→行动(多轮) 预处理管道: 120 条 Grep 结果触发 microcompact → 摘要化 API 调用: 返回 3 个 tool_use(FileEdit, ...) 工具执行: 删除 5 条未使用导入 → needsFollowUp = true → transition: { reason: 'next_turn' }, continue 迭代 4: 总结 API 调用: 返回纯文本"已清理 3 个文件中的 5 条未使用导入" → needsFollowUp = false → Stop hooks 通过 → Token Budget 检查通过(如果启用) → return { reason: 'completed' } ``` -------------------------------- ### Gap Spacing Examples Source: https://github.com/claude-code-best/claude-code/blob/main/packages/@ant/ink/docs/02-layout.md Shows how to add spacing between flex items. Only integer values are supported. ```tsx ... // Both row and column gap ``` ```tsx ... // Gap between columns only ``` ```tsx ... // Gap between rows only ``` -------------------------------- ### Justify Content Examples Source: https://github.com/claude-code-best/claude-code/blob/main/packages/@ant/ink/docs/02-layout.md Demonstrates how to distribute children along the main axis of a flex container. ```tsx ... // Main-axis start (default) ``` ```tsx ... // Main-axis end ``` ```tsx ... // Center ``` ```tsx ... // Equal gaps, no edges ``` ```tsx ... // Equal gaps with edges ``` ```tsx ... // Evenly distributed ``` -------------------------------- ### Align Self Examples Source: https://github.com/claude-code-best/claude-code/blob/main/packages/@ant/ink/docs/02-layout.md Illustrates how to override the parent's alignment for individual flex items. ```tsx ... // Override parent's alignItems ``` ```tsx ... ``` ```tsx ... ``` ```tsx ... // Inherit from parent ``` -------------------------------- ### Task Creation and Updates Source: https://github.com/claude-code-best/claude-code/blob/main/docs/tools/task-management.mdx Illustrates the sequence of operations for creating and updating tasks, including status changes, dependency setting, and owner assignment. ```mermaid graph TD Leader["Leader 创建团队"] TaskCreate["Leader 用 TaskCreate 创建任务 (status=pending, owner=undefined)"] TaskUpdateDeps["Leader 用 TaskUpdate 设置依赖关系 (addBlocks/addBlockedBy)"] TeammateList["Teammate 调用 TaskList → 发现可认领的任务"] TeammateUpdateProgress["Teammate 调用 TaskUpdate(taskId, {status: \"in_progress\"}) → 自动设置 owner 为 teammate 名称 → Leader 通过 mailbox 收到 task_assignment 通知"] TeammateComplete["Teammate 完成工作 → TaskUpdate(taskId, {status: \"completed\"}) → tool_result 提示 \"Call TaskList to find your next available task\" → 依赖此任务的其他任务自动解锁"] TeammateExit["Teammate 异常退出 → unassignTeammateTasks() → 未完成任务被重置为 pending + owner=undefined → Leader 收到通知并重新分配"] Leader --> TaskCreate --> TaskUpdateDeps --> TeammateList --> TeammateUpdateProgress --> TeammateComplete --> TeammateExit ``` -------------------------------- ### Configure GrowthBook Custom Server Adapter Source: https://github.com/claude-code-best/claude-code/blob/main/DEV-LOG.md Connect to a custom GrowthBook server using environment variables. This bypasses the default Anthropic-specific configuration and enables feature flag management from an external source. ```bash CLAUDE_GB_ADAPTER_URL=https://gb.example.com/ CLAUDE_GB_ADAPTER_KEY=sdk-xxx bun run dev ``` -------------------------------- ### Use Terminal Size Hook Source: https://github.com/claude-code-best/claude-code/blob/main/packages/@ant/ink/docs/09-hooks-reference.md Get current terminal dimensions. Throws if used outside ``. ```ts function useTerminalSize(): { columns: number rows: number } ``` -------------------------------- ### 压缩命令优先级链 Source: https://github.com/claude-code-best/claude-code/blob/main/docs/context/compaction.mdx 当用户执行 /compact 或系统触发自动压缩时,压缩命令按此优先级链尝试执行。优先使用 Session Memory 压缩,其次是 Reactive 压缩,最后是传统的 API 摘要。 ```typescript if (!customInstructions) { const sessionMemoryResult = await trySessionMemoryCompaction(messages, ...) if (sessionMemoryResult) return sessionMemoryResult // 优先:SM 压缩 } if (reactiveCompact?.isReactiveOnlyMode()) { return await compactViaReactive(messages, ...) // 次选:Reactive 压缩 } // 兜底:传统 API 摘要 const microcompactResult = await microcompactMessages(messages, context) const messagesForCompact = microcompactResult.messages // → 调用 AI 模型生成摘要 ``` -------------------------------- ### Creating a Managed Root with createRoot() Source: https://github.com/claude-code-best/claude-code/blob/main/packages/@ant/ink/docs/01-getting-started.md Use `createRoot` to set up a managed Ink root without immediate rendering. You can later render into this root and re-render as needed. Call `unmount` to clean up. ```tsx import { createRoot } from '@anthropic/ink' const root = await createRoot({ exitOnCtrlC: false }) // Later, render into it root.render() // You can re-render into the same root root.render() // Clean up root.unmount() ``` -------------------------------- ### Flex Direction Examples Source: https://github.com/claude-code-best/claude-code/blob/main/packages/@ant/ink/docs/02-layout.md Illustrates different flex direction options for arranging children along the main axis. ```tsx ... // Left to right (default) ``` ```tsx ... // Top to bottom ``` ```tsx ... // Right to left ``` ```tsx ... // Bottom to top ``` -------------------------------- ### WSL Sandbox Support Source: https://github.com/claude-code-best/claude-code/blob/main/docs/safety/sandbox.mdx Clarifies that only WSL2 is supported for sandboxing; WSL1 is considered an unsupported platform for this feature. ```text - 只支持 WSL2 - WSL1 视为不支持平台 ``` -------------------------------- ### Get Active Window on Linux Source: https://github.com/claude-code-best/claude-code/blob/main/docs/features/computer-use.md Retrieving the currently active window ID on Linux is done using xdotool. ```bash xdotool getactivewindow ``` -------------------------------- ### Start Claude Code CLI from Build Artifacts Source: https://github.com/claude-code-best/claude-code/blob/main/docs/features/remote-control-self-hosting.md Executes the Claude Code CLI using its built JavaScript files. ```bash # 或使用构建产物 bun run dist/cli.js ``` -------------------------------- ### Positioning Examples Source: https://github.com/claude-code-best/claude-code/blob/main/packages/@ant/ink/docs/02-layout.md Illustrates absolute and relative positioning for Box components. Absolute positioning removes the element from the normal flow. ```tsx ... ``` ```tsx ... ``` ```tsx ... // Default ``` -------------------------------- ### Get Display Text for Binding Source: https://github.com/claude-code-best/claude-code/blob/main/packages/@ant/ink/docs/08-keybindings.md Use `getBindingDisplayText` to retrieve a human-readable string for a specific keybinding action within a context. ```ts getBindingDisplayText('app:save', 'Global', bindings) // 'Ctrl+S' ``` -------------------------------- ### Get Canonical Key Name Source: https://github.com/claude-code-best/claude-code/blob/main/packages/@ant/ink/docs/08-keybindings.md Use `getKeyName` to extract the standard name of a key from raw input, useful for normalization. ```ts getKeyName('\x1b[A', { upArrow: true }) // 'up' ``` -------------------------------- ### File System Write Permissions (Default) Source: https://github.com/claude-code-best/claude-code/blob/main/docs/safety/sandbox.mdx Specifies the default directories that are allowed for writing within the sandbox environment. This typically includes the current working directory and Claude's temporary directory. ```text 默认 `allowWrite` 只有两类: - 当前工作目录 `.` - Claude 的临时目录 这意味着: - 工作区内的构建、测试、生成临时文件通常能正常运行 - 根路径如 `/etc/...`、`/usr/...`、`/var/...` 默认不在写白名单里 ``` -------------------------------- ### Import Resolver Functions Source: https://github.com/claude-code-best/claude-code/blob/main/packages/@ant/ink/docs/08-keybindings.md Import functions for resolving key inputs to actions and getting display text for bindings from the '@anthropic/ink' library. ```tsx import { resolveKey, resolveKeyWithChordState, getBindingDisplayText } from '@anthropic/ink' ``` -------------------------------- ### Measure DOM Element Dimensions Source: https://github.com/claude-code-best/claude-code/blob/main/packages/@ant/ink/docs/03-text-and-styling.md Use `measureElement` to get the width and height of a rendered DOM element. This is useful for layout calculations. ```tsx import { measureElement } from '@anthropic/ink' const { width, height } = measureElement(domElement) ``` -------------------------------- ### List Running Applications on Linux Source: https://github.com/claude-code-best/claude-code/blob/main/docs/features/computer-use.md Listing running applications on Linux can be achieved using wmctrl or ps. ```bash wmctrl -l ``` ```bash ps ``` -------------------------------- ### Focus and Blur Event Handling Source: https://github.com/claude-code-best/claude-code/blob/main/packages/@ant/ink/docs/10-events-and-focus.md Shows how to use onFocus, onBlur, onFocusCapture, and onBlurCapture to react to focus changes on an element. ```tsx console.log('Got focus')} onBlur={(e) => console.log('Lost focus')} onFocusCapture={(e) => console.log('Capture: focus in')} onBlurCapture={(e) => console.log('Capture: focus out')} > Focusable element ``` -------------------------------- ### Get Alive Subscriptions Source: https://github.com/claude-code-best/claude-code/blob/main/docs/features/lan-pipes-implementation.md Retrieves a list of currently alive pipe subscriptions from the registry. It probes each subscription to check its liveness with a timeout. ```typescript export async function getAliveSubs(): Promise { const registry = await readRegistry() const results = await Promise.all( registry.subs.map(sub => isPipeAlive(sub.pipeName, 1000).then(alive => alive ? sub : null) ) ) return results.filter(Boolean) } ``` -------------------------------- ### System Permission Check on Linux Source: https://github.com/claude-code-best/claude-code/blob/main/docs/features/computer-use.md On Linux, system permission checks for features like screen recording involve verifying the installation of xdotool. ```bash xdotool ``` -------------------------------- ### Dynamic Registration of Computer Use MCP Source: https://github.com/claude-code-best/claude-code/blob/main/docs/extensibility/mcp-protocol.mdx Shows how the Computer Use MCP is dynamically registered during the main application startup, including feature flag checks and platform compatibility. ```typescript // main.tsx: Computer Use MCP 动态注册 if (feature("CHICAGO_MCP") && getPlatform() !== "unknown" && !getIsNonInteractiveSession()) { const { getChicagoEnabled } = await import("src/utils/computerUse/gates.js") if (getChicagoEnabled()) { const { setupComputerUseMCP } = await import("src/utils/computerUse/setup.js") const { mcpConfig, allowedTools } = setupComputerUseMCP() dynamicMcpConfig = { ...dynamicMcpConfig, ...mcpConfig } allowedTools.push(...cuTools) } } ```