### Install and Run Demos Source: https://github.com/agentforce314/clawcodex/blob/main/README.md Navigate to a demo directory, install dependencies, and start the development server. ```bash cd demos/crm-app # or linkedin-app / minecraft-app npm install npm run dev # vite dev server ``` -------------------------------- ### Configure Provider and Start REPL Source: https://github.com/agentforce314/clawcodex/blob/main/README.md After installation, use these commands to log in and set up your provider or start the REPL. The login command configures the ~/.clawcodex/config.json file. ```bash clawcodex login # interactive provider + API key setup → ~/.clawcodex/config.json ``` ```bash clawcodex --dangerously-skip-permissions # start the REPL in any project ``` -------------------------------- ### Quick Development Setup Source: https://github.com/agentforce314/clawcodex/blob/main/README.md Installs the project in editable mode with development dependencies and runs pytest for testing. Ensure you have Python and pip installed. ```bash # Quick dev setup pip install -e .[dev] python -m pytest tests/ -v ``` -------------------------------- ### Install TUI Dependencies and Start Server + TUI Source: https://github.com/agentforce314/clawcodex/blob/main/docs/agent-server.md One-time setup for TUI dependencies followed by a command to launch the backend server and TUI together. The TUI acts as the parent process, managing the Python agent-server as a child. ```bash cd ui-tui && bun install && cd .. # one-time: install the TUI deps clawcodex tui # starts the backend + TUI together ``` -------------------------------- ### Setup Test Fixtures Source: https://github.com/agentforce314/clawcodex/blob/main/docs/guide/TESTING.md Example of setting up test fixtures in Python, creating temporary directories and configuration paths for tests. ```python # In test file def setUp(self): """Set up test fixtures.""" self.temp_dir = tempfile.mkdtemp() self.config_dir = Path(self.temp_dir) / ".clawcodex" self.config_dir.mkdir(parents=True, exist_ok=True) ``` -------------------------------- ### Permission Suggestion System Example Source: https://github.com/agentforce314/clawcodex/blob/main/claude-code-wiki/raw/claude-code-sourcemap-learning-notebook/en/03_permission_security.md Provides an example of the permission suggestion system, outlining how to define rules for allowing specific tool actions, such as 'npm install' or 'npm:*', and where to save these rules. ```typescript // Example BashTool suggestions suggestions: [ { type: 'addRules', rules: [ { toolName: 'Bash', ruleContent: 'npm install' }, // Exact match { toolName: 'Bash', ruleContent: 'npm:*' }, // Prefix match ], behavior: 'allow', destination: 'localSettings', // Save to local settings }, ] ``` -------------------------------- ### Quick Install Clawcodex Source: https://github.com/agentforce314/clawcodex/blob/main/README.md Installs uv, Python 3.10+, and adds clawcodex to your PATH with a single command. This is the recommended method for a quick setup. ```bash curl -fsSL https://clawcodex.app/install.sh | bash ``` -------------------------------- ### Install Clawcodex Manually from Source Source: https://github.com/agentforce314/clawcodex/blob/main/README.md Provides steps for cloning the repository, setting up a Python virtual environment, installing dependencies, and running the login and REPL commands manually. ```bash git clone https://github.com/agentforce314/clawcodex.git ``` ```bash cd clawcodex ``` ```bash python3 -m venv .venv && source .venv/bin/activate # Python 3.10+ ``` ```bash pip install -r requirements.txt ``` ```bash python -m src.cli login # writes config to ~/.clawcodex/config.json ``` ```bash python -m src.cli --dangerously-skip-permissions # start the REPL ``` -------------------------------- ### Install Clawcodex Source: https://github.com/agentforce314/clawcodex/blob/main/README.md Clone the repository, set up a Python virtual environment using uv, and install the package in editable mode with development dependencies. ```bash git clone https://github.com/agentforce314/clawcodex.git cd clawcodex # Create venv (uv recommended) uv venv --python 3.11 source .venv/bin/activate # Install package + entry point (recommended) uv pip install -e ".[dev]" # Alternative: requirements only, then editable install # uv pip install -r requirements.txt && uv pip install -e . ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/agentforce314/clawcodex/blob/main/CONTRIBUTING.md Install the main project dependencies from requirements.txt and the development dependencies, including the project in editable mode. ```bash uv pip install -r requirements.txt uv pip install -e ".[dev]" ``` -------------------------------- ### Clone and Install Clawcodex Source: https://github.com/agentforce314/clawcodex/blob/main/docs/guide/SETUP_GUIDE.md Clone the repository, set up a virtual environment using uv, and install the package with development dependencies. Ensure Python 3.10+ is used. ```bash git clone https://github.com/agentforce314/clawcodex.git cd clawcodex # Create and activate a virtual environment (uv recommended) uv venv --python 3.11 source .venv/bin/activate # Windows: .venv\Scripts\activate # Install the package with its entry point uv pip install -e ".[dev]" ``` -------------------------------- ### Example Skill Invocation Source: https://github.com/agentforce314/clawcodex/blob/main/README.md A concrete example of invoking the 'explain-code' skill with a Python file as an argument. ```text > /explain-code qsort.py ``` -------------------------------- ### Clawcodex Configuration File Example Source: https://github.com/agentforce314/clawcodex/blob/main/README.md A minimal example of the Clawcodex configuration file, showing how to set up a default provider (Deepseek) and API keys. The TAVILY_API_KEY is required for the WebSearch tool. ```json { "default_provider": "deepseek", "providers": { "deepseek": { "api_key": "xxx-xxx", "base_url": "https://api.deepseek.com", "default_model": "deepseek-v4-pro" } }, "env": { "TAVILY_API_KEY": "tvly-YOUR-TAVILY-API-KEY" } } ``` -------------------------------- ### Install UI Dependencies Source: https://github.com/agentforce314/clawcodex/blob/main/ui-tui/README.md Install Node.js dependencies for the UI component. Navigate to the ui-tui directory first. ```bash cd ui-tui npm install ``` -------------------------------- ### Install Development Tools Source: https://github.com/agentforce314/clawcodex/blob/main/CONTRIBUTING.md Install essential development tools such as black for code formatting, isort for import sorting, mypy for type checking, and pytest for testing. ```bash uv pip install black isort mypy pytest ``` -------------------------------- ### Example Skill Markdown File Source: https://github.com/agentforce314/clawcodex/blob/main/README.md An example of a SKILL.md file, demonstrating metadata like description, when_to_use, allowed-tools, and arguments, along with the skill's core instruction. ```markdown --- description: Explains code with diagrams and analogies when_to_use: Use when explaining how code works allowed-tools: - Read - Grep - Glob arguments: [path] --- Explain the code in $path. Start with an analogy, then draw a diagram. ``` -------------------------------- ### Run Setup Verification Tests Source: https://github.com/agentforce314/clawcodex/blob/main/CONTRIBUTING.md Execute the project's tests using pytest to ensure the development environment and setup are correctly configured. ```bash python -m pytest tests/ -q ``` -------------------------------- ### Set up SWE-bench Virtual Environment Source: https://github.com/agentforce314/clawcodex/blob/main/eval/README.md Create and activate a Python virtual environment for SWE-bench, then install necessary dependencies including the SWE-bench package itself and libraries for FastAPI, Uvicorn, Tiktoken, and Transformers. ```bash cd SWE-bench-dev python3 -m venv .venv && source .venv/bin/activate pip install -U pip pip install -e . pip install fastapi uvicorn tiktoken transformers ``` -------------------------------- ### Install SWE-bench into Separate venv (Windows Git Bash) Source: https://github.com/agentforce314/clawcodex/blob/main/eval/README.md Set up a separate Python virtual environment for SWE-bench on Windows using Git Bash. Activate the environment and install SWE-bench and related packages. ```bash cd SWE-bench-dev python -m venv .venv # Windows Git Bash: source .venv/Scripts/activate pip install -U pip pip install -e . pip install fastapi uvicorn tiktoken transformers export SWEBENCH_PYTHON="$PWD/.venv/Scripts/python.exe" ``` -------------------------------- ### Coordinator System Prompt - Anti-pattern Example Source: https://github.com/agentforce314/clawcodex/blob/main/claude-code-wiki/raw/claude-code-sourcemap-learning-notebook/en/05_multi_agent_system.md Illustrates a bad practice in the Coordinator's system prompt, where a task is delegated lazily. The good example shows how to provide specific implementation details for workers. ```plaintext // Anti-pattern example in the system prompt: // Bad: "Based on your findings, fix the auth bug" ← Lazy delegation // Good: "Fix the null pointer in src/auth/validate.ts:42. // The user field on Session is undefined when sessions expire // but the token remains cached. Add a null check before user.id // access — if null, return 401 with 'Session expired.'" ``` -------------------------------- ### Run Clawcodex CLI or REPL Source: https://github.com/agentforce314/clawcodex/blob/main/README.md Start the interactive REPL session or view all available command-line flags for the Clawcodex tool. ```bash clawcodex # Start inline REPL (same as python -m src.cli) clawcodex --help # All flags: -p, --provider, --model, … ``` -------------------------------- ### Specific Examples for Git Commands Source: https://github.com/agentforce314/clawcodex/blob/main/claude-code-wiki/raw/claude-code-sourcemap-learning-notebook/en/07_prompt_engineering.md Provide concrete examples of forbidden actions rather than abstract rules when dealing with sensitive commands. This helps the AI understand the exact operations to avoid. ```text "Be careful with git commands" "NEVER run destructive git commands (push --force, reset --hard, checkout ., restore ., clean -f, branch -D) unless the user explicitly requests these actions" ``` -------------------------------- ### ClawCodex CLI Usage Examples Source: https://github.com/agentforce314/clawcodex/blob/main/README.md Demonstrates various ways to use the ClawCodex CLI, including interactive mode, non-interactive scripting with different output formats, and overriding provider/model settings. ```bash clawcodex # Interactive Ink TUI (default) clawcodex tui # Interactive Ink TUI (explicit) clawcodex login # Configure API keys (interactive) clawcodex config # Show ~/.clawcodex/config.json-backed settings clawcodex --version # Version string # Non-interactive / scripting (pipes, CI, agents) clawcodex -p "Summarize src/cli.py" clawcodex -p "Hello" --output-format json clawcodex -p --output-format stream-json --input-format stream-json < events.ndjson # Overrides for a single run clawcodex --provider anthropic --model claude-sonnet-4-6 -p "Hi" clawcodex --max-turns 10 --allowed-tools Read,Grep -p "Find TODOs" # Permission control (REPL, TUI, and -p all honor these) clawcodex --permission-mode plan # plan / acceptEdits / dontAsk clawcodex --dangerously-skip-permissions -p "ls" # bypass all permission checks clawcodex --allow-dangerously-skip-permissions # allow /permission-mode bypass later ``` -------------------------------- ### Start TUI Gateway Source: https://github.com/agentforce314/clawcodex/blob/main/ui-tui/README.md Initiate the Python backend for the TUI. This command is executed by the client entrypoint. ```bash python -m tui_gateway.entry ``` -------------------------------- ### Run Agent Server with Default Settings Source: https://github.com/agentforce314/clawcodex/blob/main/docs/agent-server.md Starts the agent server on an ephemeral port using the default provider and model. The server prints connection URLs upon startup. ```bash clawcodex agent-server # ephemeral port, default provider/model ``` -------------------------------- ### Conventional Commits Examples Source: https://github.com/agentforce314/clawcodex/blob/main/CONTRIBUTING.md Examples of valid commit messages following the Conventional Commits specification. ```bash feat(repl): add tab completion support fix(provider): handle API rate limiting correctly docs(readme): update installation instructions test(config): add tests for API key encoding ``` -------------------------------- ### Run Agent Server with Custom Configuration Source: https://github.com/agentforce314/clawcodex/blob/main/docs/agent-server.md Starts the agent server with specified port, provider, model, permission mode, and a custom token. This command also prints connection URLs. ```bash clawcodex agent-server --port 8791 \ --provider anthropic --model claude-opus-4-8 \ --permission-mode default --token "$(openssl rand -hex 16)" ``` -------------------------------- ### Get Cautious Operation Guidelines Source: https://github.com/agentforce314/clawcodex/blob/main/claude-code-wiki/raw/claude-code-sourcemap-learning-notebook/en/07_prompt_engineering.md Provides text for a section on executing actions with care. It details how to assess the risk of operations based on reversibility and blast radius, and lists examples of risky actions that require user confirmation. ```typescript function getActionsSection(): string { return `# Executing actions with care Carefully consider the reversibility and blast radius of actions. Generally you can freely take local, reversible actions like editing files or running tests. But for actions that are hard to reverse, affect shared systems beyond your local environment, or could otherwise be risky or destructive, check with the user before proceeding. The cost of pausing to confirm is low, while the cost of an unwanted action (lost work, unintended messages sent, deleted branches) can be very high. Examples of the kind of risky actions that warrant user confirmation: - Destructive operations: deleting files/branches, dropping database tables, killing processes, rm -rf, overwriting uncommitted changes - Hard-to-reverse operations: force-pushing, git reset --hard, amending published commits, removing packages/dependencies - Actions visible to others: pushing code, creating/closing/commenting on PRs or issues, sending messages (Slack, email, GitHub) - Uploading content to third-party web tools publishes it - consider whether it could be sensitive before sending When you encounter an obstacle, do not use destructive actions as a shortcut to simply make it go away. For instance, try to identify root causes and fix underlying issues rather than bypassing safety checks (e.g. --no-verify). Follow both the spirit and letter of these instructions - measure twice, cut once.` } ``` -------------------------------- ### Local UI Development Commands Source: https://github.com/agentforce314/clawcodex/blob/main/ui-tui/README.md Common npm scripts for developing the UI, including starting the dev server, building, linting, and formatting. ```bash npm run dev ``` ```bash npm start ``` ```bash npm run build ``` ```bash npm run lint ``` ```bash npm run fmt ``` ```bash npm run fix ``` -------------------------------- ### Install Coverage Tool Source: https://github.com/agentforce314/clawcodex/blob/main/docs/guide/TESTING.md Installs the pytest-cov plugin, which is used for generating code coverage reports. ```bash # Install coverage tool uv pip install pytest-cov ``` -------------------------------- ### Guide LLM to Choose the Right Tool with GlobTool Prompt Source: https://github.com/agentforce314/clawcodex/blob/main/claude-code-wiki/raw/claude-code-sourcemap-learning-notebook/en/02_tool_system.md This prompt guides the LLM to use the Agent tool for complex, multi-round searches involving globbing and grepping, rather than a simpler tool. ```typescript // GlobTool prompt.ts 'When you are doing an open ended search that may require multiple\n' + 'rounds of globbing and grepping, use the Agent tool instead' ``` -------------------------------- ### Example Message Flow Source: https://github.com/agentforce314/clawcodex/blob/main/claude-code-wiki/raw/claude-code-sourcemap-learning-notebook/en/01_architecture_overview.md Illustrates a typical interaction flow between a User and an Assistant, involving a tool use and its result. ```text User: "Read package.json for me" ↓ Assistant: [tool_use: { name: 'Read', input: { file_path: 'package.json' } }] ↓ User: [tool_result: { content: '{"name": "claude-code", ...}' }] ↓ Assistant: [text: "Here are the contents of package.json: ..."] ``` -------------------------------- ### Google-Style Docstring Example Source: https://github.com/agentforce314/clawcodex/blob/main/CONTRIBUTING.md Demonstrates the Google-style docstring format for Python functions. This includes sections for arguments, return values, and potential exceptions. ```Python def calculate_cost(tokens: int, model: str) -> float: """Calculate the cost for a given number of tokens. Args: tokens: Number of tokens used. model: Model name to determine pricing. Returns: Total cost in USD. Raises: ValueError: If model is not recognized. """ pass ``` -------------------------------- ### Install SWE-bench into Clawcodex venv Source: https://github.com/agentforce314/clawcodex/blob/main/eval/README.md Install SWE-bench and its dependencies directly into the clawcodex virtual environment. This option allows for a single Python interpreter to manage both clawcodex and SWE-bench. ```bash cd clawcodex # Prefer the venv binary so you are not using the Windows Store `python3` shim. uv pip install -e ./SWE-bench-dev fastapi uvicorn tiktoken transformers ``` -------------------------------- ### Project-Level MCP Server Configuration Source: https://github.com/agentforce314/clawcodex/blob/main/claude-code-wiki/raw/claude-code-sourcemap-learning-notebook/en/06_mcp_extensions.md Example of configuring an MCP server at the project level using `.claude/settings.json`. This allows defining custom commands and arguments for project-specific tools. ```json // .claude/settings.json (project-level) { "mcpServers": { "project-tools": { "command": "python", "args": ["tools/mcp_server.py"] } } } ``` -------------------------------- ### Run Clawcodex CLI Source: https://github.com/agentforce314/clawcodex/blob/main/docs/guide/SETUP_GUIDE.md Launch the Clawcodex interactive TUI or use command-line flags to specify providers and models. The interactive mode is started by default. ```bash clawcodex # start the interactive Ink TUI (same as: python -m src.cli) ``` ```bash clawcodex --help # all flags: -p, --provider, --model, … ``` ```bash clawcodex --provider zai # start this session with a specific provider ``` -------------------------------- ### Interactive TUI Command Examples Source: https://github.com/agentforce314/clawcodex/blob/main/README.md Examples of commands used within the interactive TypeScript Ink TUI. Supports file mentions, skill execution, and theme switching. ```text > Hello! Assistant: Hi! I'm ClawCodex, a Python reimplementation... > /help # Show commands > /theme dark # Switch color theme > @src/cli.py # @-mention a file (fuzzy file index) > /explain-code qsort.py # Run a SKILL.md skill (or /skill …) # Needs Node 18+ and a built ui-tui/dist (the installer builds it); `clawcodex -p` is the no-Node headless path. ``` -------------------------------- ### Skip OpenClaude Build During Prepare Source: https://github.com/agentforce314/clawcodex/blob/main/eval/README.md Execute the 'prepare' command while skipping the OpenClaude build process. This is useful if Bun is not yet installed or if you only need to build the SWE-bench dataset. ```bash python eval/run_compare.py prepare --skip-openclaude-build ``` -------------------------------- ### Clawcodex Configuration File Structure Source: https://github.com/agentforce314/clawcodex/blob/main/README.md Example JSON structure for the Clawcodex configuration file, detailing settings for default provider, specific provider configurations, session persistence, advisor features, and environment variables. ```json { "default_provider": "deepseek", "providers": { "anthropic": { "api_key": "your-api-key", "base_url": "https://api.anthropic.com", "default_model": "claude-sonnet-4-6" }, "openai": { "api_key": "your-api-key", "base_url": "https://api.openai.com/v1", "default_model": "gpt-5.4" }, "zai": { "api_key": "your-api-key", "base_url": "https://api.z.ai/api/coding/paas/v4", "default_model": "glm-5.2" }, "minimax": { "api_key": "your-api-key", "base_url": "https://api.minimaxi.com/anthropic", "default_model": "MiniMax-M2.7" }, "openrouter": { "api_key": "your-api-key", "base_url": "https://openrouter.ai/api/v1", "default_model": "deepseek/deepseek-v4-pro" }, "deepseek": { "api_key": "your-api-key", "base_url": "https://api.deepseek.com", "default_model": "deepseek-v4-pro" } }, "session": { "auto_save": true, "max_history": 100 }, "settings": { "advisor_enabled": false, "advisor_model": "claude-sonnet-4-6", "advisor_client_mode": false, "advisor_provider": "openai" }, "env": { "TAVILY_API_KEY": "tvly-YOUR-TAVILY-API-KEY" } } ``` -------------------------------- ### Disk-based Skill Frontmatter Example Source: https://github.com/agentforce314/clawcodex/blob/main/claude-code-wiki/raw/claude-code-sourcemap-learning-notebook/en/06_mcp_extensions.md Defines the metadata for a disk-based skill, including its name, description, allowed tools, and invocation conditions. This format is used for skills stored as Markdown files. ```markdown --- name: review-pr description: Review a pull request allowed-tools: - Bash(gh:*) - Read - Grep when_to_use: > Use when the user wants to review a PR. Examples: 'review this PR', 'check the changes' argument-hint: "[PR number or URL]" arguments: - pr_ref context: fork --- # PR Review Skill Review PR `$pr_ref`: 1. Run `gh pr diff $pr_ref` to see changes 2. Check for code quality issues and security vulnerabilities 3. Provide a summary with actionable feedback **Success criteria**: A structured review with actionable feedback. ``` -------------------------------- ### Type Hinting Example Source: https://github.com/agentforce314/clawcodex/blob/main/CONTRIBUTING.md Illustrates the correct usage of type hints for function signatures in Python. All public functions should include type hints for clarity and maintainability. ```Python def get_provider_config(provider: str) -> dict[str, Any]: """Get configuration for a specific provider.""" pass ``` ```Python def get_provider_config(provider): pass ``` -------------------------------- ### AgentTool Prompt Structure Source: https://github.com/agentforce314/clawcodex/blob/main/claude-code-wiki/raw/claude-code-sourcemap-learning-notebook/en/07_prompt_engineering.md Illustrates the hierarchical structure of AgentTool prompts, differentiating between Fork Mode (forkEnabled = true) and Traditional Mode (forkEnabled = false). Fork Mode includes sections on 'When to fork', fork-specific examples, and rules like 'Don't peek' and 'Don't race'. Traditional Mode lists agent types, provides examples, and a 'When NOT to use' section. ```markdown AgentTool Prompt ├── Fork Mode (forkEnabled = true) │ ├── "When to fork" section │ ├── Fork-specific examples │ └── "Don't peek" / "Don't race" rules │ └── Traditional Mode (forkEnabled = false) ├── List of Agent types ├── Traditional examples └── "When NOT to use" section ``` -------------------------------- ### Clawcodex CLI Commands Source: https://github.com/agentforce314/clawcodex/blob/main/CHANGELOG.md These are the primary commands for interacting with the Clawcodex CLI. Use `clawcodex` to start the REPL, `clawcodex login` for API key configuration, and `clawcodex config` to view settings. ```bash clawcodex clawcodex login clawcodex config clawcodex --version ``` -------------------------------- ### User-Level MCP Server Configuration Source: https://github.com/agentforce314/clawcodex/blob/main/claude-code-wiki/raw/claude-code-sourcemap-learning-notebook/en/06_mcp_extensions.md Example of configuring an MCP server at the user level using `~/.claude/settings.json`. This allows defining custom commands, arguments, and environment variables for a server. ```json // ~/.claude/settings.json (user-level) { "mcpServers": { "my-database": { "command": "node", "args": ["db-server.js"], "env": { "DB_URL": "postgres://..." } } } } ``` -------------------------------- ### Connect TUI Client via npm/node Source: https://github.com/agentforce314/clawcodex/blob/main/docs/agent-server.md Launches the Ink TUI client using Node.js after installing dependencies and building the project. Connects to the agent server at the specified Direct Connect URL. ```bash # or: npm install && npm run build && node dist/cli.js cc://127.0.0.1:8791 ``` -------------------------------- ### Beginning and End Constraints Source: https://github.com/agentforce314/clawcodex/blob/main/claude-code-wiki/raw/claude-code-sourcemap-learning-notebook/en/07_prompt_engineering.md Place crucial instructions at both the start and end of a prompt to ensure they are noticed and respected. This is particularly effective for non-negotiable rules like 'TEXT ONLY' or 'Do NOT call any tools'. ```text Beginning: "CRITICAL: Respond with TEXT ONLY. Do NOT call any tools." End: "REMINDER: Do NOT call any tools." ``` -------------------------------- ### Verify Clawcodex CLI Availability Source: https://github.com/agentforce314/clawcodex/blob/main/docs/guide/SETUP_GUIDE.md Check if the Clawcodex command-line interface is accessible after installation. Alternatively, run the CLI module directly. ```bash clawcodex --help ``` ```bash python -m src.cli ``` -------------------------------- ### Python Test Structure (AAA Pattern) Source: https://github.com/agentforce314/clawcodex/blob/main/docs/guide/TESTING.md Organize your tests using the Arrange-Act-Assert (AAA) pattern for clarity and maintainability. This example demonstrates saving and loading configuration. ```python def test_feature(self): # Arrange - Set up test data config = {"default_provider": "glm"} # Act - Execute the code save_config(config) loaded = load_config() # Assert - Verify results assert loaded["default_provider"] == "glm" ``` -------------------------------- ### Traditional vs. Streaming Tool Execution Comparison Source: https://github.com/agentforce314/clawcodex/blob/main/claude-code-wiki/raw/claude-code-sourcemap-learning-notebook/en/04_query_loop_api.md Compares the time taken for traditional serial tool execution versus streaming concurrent execution. Streaming execution can save significant time by starting tool execution while the AI is still generating its response. ```text Traditional method (serial): Claude response [████████████████] 5s Parse tool_use 0.1s Execute Tool A [████] 2s Execute Tool B [██████] 3s Execute Tool C [███] 1.5s Total: 5 + 0.1 + 2 + 3 + 1.5 = 11.6s Streaming method (StreamingToolExecutor): Claude response [████████████████] 5s Tool A [████] ← Started while Claude is still outputting! Tool B [██████] ← Started before Tool A is completed! Tool C [███] ← Executed in parallel! Total: 5 + max(2,3,1.5) = 8s 31% saved ``` -------------------------------- ### Initiate Asynchronous Memory Prefetch Source: https://github.com/agentforce314/clawcodex/blob/main/claude-code-wiki/raw/claude-code-sourcemap-learning-notebook/en/04b_context_management.md Starts the asynchronous prefetching of relevant memories at the beginning of each user turn. This process runs in parallel with the main model streaming. ```typescript using pendingMemoryPrefetch = startRelevantMemoryPrefetch( state.messages, state.toolUseContext, ); ``` -------------------------------- ### Metadata in Tool Specifications Example Source: https://github.com/agentforce314/clawcodex/blob/main/claude-code-wiki/raw/claude-code-sourcemap-learning-notebook/en/05_multi_agent_system.md Illustrates how tool specifications can include metadata for fine-grained control, such as restricting agent types or specifying file paths for edit tools. Shows the output of `permissionRuleValueFromString`. ```plaintext Tool specifications are not just tool names, they can also carry metadata: "Agent" → Allows Agent tools, all sub Agent types "Agent(worker, researcher)" → Allows Agent tools, but only worker and researcher can be created "Bash(npm test)" → Allows Bash tools, but only runs npm test "Edit(src/**)" → Allows Edit tools, but only edits files under src/ This is parsed by permissionRuleValueFromString(): "Agent(worker, researcher)" → { toolName: "Agent", ruleContent: "worker, researcher" } ``` -------------------------------- ### Get BashTool Simple Prompt Source: https://github.com/agentforce314/clawcodex/blob/main/claude-code-wiki/raw/claude-code-sourcemap-learning-notebook/en/07_prompt_engineering.md Generates the basic prompt for BashTool, including tool descriptions, usage guidelines, and sandbox/Git instructions. Ensure all necessary helper functions and constants are defined. ```typescript export function getSimplePrompt(): string { return [ // 1. Basic description 'Executes a given bash command and returns its output.', // 2. Tool priority (the most important constraint) `IMPORTANT: Avoid using this tool to run cat, head, tail, sed, awk, or echo commands, unless explicitly instructed. Instead, use the appropriate dedicated tool:`, ...prependBullets(toolPreferenceItems), // 3. Usage guidelines '# Instructions', ...prependBullets(instructionItems), // 4. Sandbox configuration (if enabled) getSimpleSandboxSection(), // 5. Git operation guidelines getCommitAndPRInstructions(), ].join('\n'); } ``` -------------------------------- ### Get Tool Usage Guidelines Source: https://github.com/agentforce314/clawcodex/blob/main/claude-code-wiki/raw/claude-code-sourcemap-learning-notebook/en/07_prompt_engineering.md Generates text for a section on tool usage guidelines. It emphasizes using dedicated tools over Bash for specific operations and outlines the priority mapping for tools like Read, Edit, Write, Glob, and Grep. ```typescript function getUsingYourToolsSection(enabledTools: Set): string { const providedToolSubitems = [ // ⬇ Tool priority mapping `To read files use Read instead of cat, head, tail, or sed`, `To edit files use Edit instead of sed or awk`, `To create files use Write instead of cat with heredoc or echo`, `To search for files use Glob instead of find or ls`, `To search the content of files, use Grep instead of grep or rg`, // ⬇ Bash is the last resort `Reserve using the Bash exclusively for system commands and terminal operations that require shell execution. If you are unsure and there is a relevant dedicated tool, default to using the dedicated tool.`, ]; const items = [ // ⬇ Core principle: Dedicated tools > Bash `Do NOT use the Bash to run commands when a relevant dedicated tool is provided. Using dedicated tools allows the user to better understand and review your work. This is CRITICAL.`, providedToolSubitems, // ⬇ Task management `Break down and manage your work with the TaskCreate tool.`, // ⬇ Parallel invocation `You can call multiple tools in a single response. If you intend to call multiple tools and there are no dependencies between them, make all independent tool calls in parallel.`, ]; return [`# Using your tools`, ...prependBullets(items)].join(' '); } ``` -------------------------------- ### AgentTool Prompt Writing Guide Source: https://github.com/agentforce314/clawcodex/blob/main/claude-code-wiki/raw/claude-code-sourcemap-learning-notebook/en/07_prompt_engineering.md Provides guidance on writing effective prompts for sub-agents within the AgentTool. It emphasizes briefing the agent as a knowledgeable colleague, providing sufficient context, and clearly defining task requirements. Crucially, it advises against delegating understanding, urging the user to synthesize information and provide specific instructions. ```typescript const writingThePromptSection = ` ## Writing the prompt Brief the agent like a smart colleague who just walked into the room — it hasn't seen this conversation, doesn't know what you've tried, doesn't understand why this task matters. - Explain what you're trying to accomplish and why. - Describe what you've already learned or ruled out. - Give enough context about the surrounding problem that the agent can make judgment calls rather than just following a narrow instruction. - If you need a short response, say so ("report in under 200 words"). - Lookups: hand over the exact command. Investigations: hand over the question — prescribed steps become dead weight when the premise is wrong. Terse command-style prompts produce shallow, generic work. **Never delegate understanding.** Don't write "based on your findings, fix the bug" or "based on the research, implement it." Those phrases push synthesis onto the agent instead of doing it yourself. Write prompts that prove you understood: include file paths, line numbers, what specifically to change. ` ``` -------------------------------- ### Prepare Data and Build Source: https://github.com/agentforce314/clawcodex/blob/main/eval/README.md Build the openclaude and the SWE-bench text dataset. This command is typically only needed once. ```bash python eval/run_compare.py prepare ``` -------------------------------- ### Define Programmable Skill with Markdown Source: https://github.com/agentforce314/clawcodex/blob/main/README.md Skills are defined using Markdown files with frontmatter specifying allowed tools and arguments. This example defines a skill to explain code using analogies and diagrams. ```markdown --- description: Explain code with diagrams and analogies allowed-tools: - Read - Grep - Glob arguments: [path] --- Explain the code in $path. Start with an analogy, then draw a diagram. ``` -------------------------------- ### Record First, Connect Later Audio Buffering Source: https://github.com/agentforce314/clawcodex/blob/main/claude-code-wiki/raw/claude-code-sourcemap-learning-notebook/en/08_voice_buddy.md Implements a strategy where audio recording starts immediately upon user input, buffering audio chunks until the WebSocket connection is established. This ensures no speech is lost at the beginning of a session, unlike traditional approaches that wait for connection. ```typescript // useVoice.ts — startRecordingSession // Key design: recording starts immediately, doesn't wait for WebSocket connection // Audio is buffered first, flushed when WebSocket is ready const audioBuffer: Buffer[] = [] // Start recording immediately const started = await voiceModule.startRecording( (chunk: Buffer) => { const owned = Buffer.from(chunk) // Copy! Native module may reuse buffer if (connectionRef.current) { connectionRef.current.send(owned) // WebSocket connected → send directly } else { audioBuffer.push(owned) // Not connected → buffer } }, ) // Flush buffer when WebSocket is ready onReady: conn => { // Merge into ~1s slices to reduce WS frame count const SLICE_TARGET_BYTES = 32_000 // 32KB ≈ 1s of 16kHz 16-bit mono const slices: Buffer[][] = [[]] for (const chunk of audioBuffer) { if (sliceBytes + chunk.length > SLICE_TARGET_BYTES) { slices.push([]) sliceBytes = 0 } slices[slices.length - 1]!.push(chunk) sliceBytes += chunk.length } for (const slice of slices) { conn.send(Buffer.concat(slice)) } audioBuffer.length = 0 } ``` -------------------------------- ### Python Workflow Example: User Prompt Research Source: https://github.com/agentforce314/clawcodex/blob/main/docs/workflow-engine.md This Python script defines a workflow for researching user prompts related to a keyword. It handles argument normalization, defines a helper function for slugification, and orchestrates parallel agent calls for search and question generation. The workflow returns structured data including generated questions and a CSV path. ```python meta = { "name": "user-prompt-research", "description": "Discover what customers ask about a keyword; score questions by search volume.", "when_to_use": "Run with a company, product, or keyword to mine real user questions for AEO.", "phases": [ {"title": "Search", "detail": "Reddit + Google search in parallel"}, {"title": "Questions", "detail": "Rewrite intent signals into natural user questions"}, ], } # args may be a bare keyword string or a dict; normalize both. data = args if isinstance(args, dict) else {} keyword = (args if isinstance(args, str) else data.get("keyword", "")).strip() if not keyword: raise ValueError('Pass a keyword via args — e.g. args="AI coding assistant"') count = int(data.get("count", 50)) def slugify(s, maxlen=80): # plain helper, defined before use (Python does not hoist) return re.sub(r"-+$ ", "", re.sub(r"[^a-z0-9]+", "-", s.lower()).strip("-")[:maxlen]) or "item" GOOGLE_SCHEMA = { "type": "object", "properties": { "organic_results": {"type": "array", "items": { "type": "object", "properties": {"title": {"type": "string"}, "link": {"type": "string"}}, "required": ["title", "link"], }}, "related_questions": {"type": "array", "items": {"type": "string"}}, }, "required": ["organic_results", "related_questions"], } log(f'Keyword: "{keyword}" · target questions: {count}') phase("Search") reddit, google = await parallel([ agent(f'Summarize real Reddit discussion about "{keyword}" for SEO research ...', label="reddit"), agent(f'Gather the Google SERP for "{keyword}" ...', label="google", schema=GOOGLE_SCHEMA), ]) google = google or {"organic_results": [], "related_questions": []} log(f'Google: {len(google["organic_results"]) } organic results') phase("Questions") raw = await agent( f"Using this research, write {count} natural user questions, one per line:\n" f"{reddit}\n{json.dumps(google)}", label="questions", ) questions = [q.strip() for q in (raw or "").splitlines() if "?" in q] if not questions: raise RuntimeError("No questions produced.") return { # the returned value is the workflow's result "keyword": keyword, "questions": questions, "csv_path": f"./out/{slugify(keyword)}-questions.csv", } ``` -------------------------------- ### Create and Activate Virtual Environment Source: https://github.com/agentforce314/clawcodex/blob/main/CONTRIBUTING.md Create a Python virtual environment using uv, recommending Python 3.11 for local development. Activate the environment for subsequent commands. ```bash uv venv --python 3.11 source .venv/bin/activate # On Windows: .venv\Scripts\activate ``` -------------------------------- ### Configure Clawcodex Provider Interactively Source: https://github.com/agentforce314/clawcodex/blob/main/docs/guide/SETUP_GUIDE.md Use the `clawcodex login` command to interactively set up API keys and default models for supported providers. This is the recommended method for initial configuration. ```bash clawcodex login ``` -------------------------------- ### Example contextModifier Usage Source: https://github.com/agentforce314/clawcodex/blob/main/claude-code-wiki/raw/claude-code-sourcemap-learning-notebook/en/02_tool_system.md Demonstrates how a FileEditTool might use contextModifier to update the file cache after an edit. ```typescript return { data: editResult, contextModifier: (ctx) => ({ ...ctx, readFileState: ctx.readFileState.set(filePath, newContent), }), }; ``` -------------------------------- ### Run All Tests with Unittest Source: https://github.com/agentforce314/clawcodex/blob/main/docs/guide/TESTING.md Activates the project environment and runs all tests using the unittest framework. ```bash # Activate the project environment first source .venv/bin/activate # Using unittest python -m unittest discover -s tests -v ``` -------------------------------- ### Buddy System Architecture Overview Source: https://github.com/agentforce314/clawcodex/blob/main/claude-code-wiki/raw/claude-code-sourcemap-learning-notebook/en/08_voice_buddy.md Provides a high-level overview of the Buddy System's architecture, outlining the key components and their responsibilities. ```text ┌─────────────────────────────────────────────────────────┐ │ Buddy System Architecture │ ├─────────────────────────────────────────────────────────┤ │ │ │ companion.ts → Deterministic generation (hash→PRNG→bones) │ │ types.ts → Type definitions (species, rarity, stats) │ │ sprites.ts → ASCII animation frames (18 species × 3) │ │ prompt.ts → Prompt injection (tell Claude about buddy) │ │ CompanionSprite → React component (render + animation loop) │ │ useBuddyNotification → Rainbow /buddy prompt │ │ │ └─────────────────────────────────────────────────────────┘ ``` -------------------------------- ### Generate Companion Introduction Text Source: https://github.com/agentforce314/clawcodex/blob/main/claude-code-wiki/raw/claude-code-sourcemap-learning-notebook/en/08_voice_buddy.md Creates introductory text for a companion AI, defining its name and species. Sets up the prompt for interaction and role separation. ```typescript // prompt.ts export function companionIntroText(name: string, species: string): string { return `# Companion A small ${species} named ${name} sits beside the user's input box and occasionaly comments in a speech bubble. You're not ${name} — it's a separate watcher. When the user addresses ${name} directly (by name), its bubble will answer. Your job in that moment is to stay out of the way: respond in ONE line or less, or just answer any part of the message meant for you. Don't explain that you're not ${name} — they know. Don't narrate what ${name} might say — the bubble handles that.` } ``` -------------------------------- ### Correcting Worker Failures with SendMessage Source: https://github.com/agentforce314/clawcodex/blob/main/tests/coordinator/__snapshots__/coordinator_prompt.simple.snap.txt If a worker reports test failures from its own changes, use `SendMessage` with a brief message to guide it on correcting the assertions. ```javascript // Correction — worker just reported test failures from its own change, keep it brief SendMessage({ to: "xyz-456", message: "Two tests still failing at lines 58 and 72 — update the assertions to match the new error message." }) ``` -------------------------------- ### Get Grep Tool Description Source: https://github.com/agentforce314/clawcodex/blob/main/claude-code-wiki/raw/claude-code-sourcemap-learning-notebook/en/07_prompt_engineering.md Provides the description for the GrepTool, detailing its usage for powerful regex-based search, output modes, and pattern syntax. ```typescript // src/tools/GrepTool/prompt.ts export function getDescription(): string { return `A powerful search tool built on ripgrep Usage: - ALWAYS use Grep for search tasks. NEVER invoke grep or rg as a Bash command. - Supports full regex syntax (e.g., "log.*Error", "function\\s+\\w+") - Filter files with glob parameter (e.g., "*.js", "**/*.tsx") or type parameter (e.g., "js", "py", "rust") - Output modes: "content" shows matching lines, "files_with_matches" shows only file paths (default), "count" shows match counts - Use Agent tool for open-ended searches requiring multiple rounds - Pattern syntax: Uses ripgrep (not grep) — literal braces need escaping - Multiline matching: For cross-line patterns, use multiline: true` } ``` -------------------------------- ### Configure Clawcodex Interactively Source: https://github.com/agentforce314/clawcodex/blob/main/README.md Run the login command to interactively set up API keys, base URLs, and default models for various AI providers. The configuration is saved to ~/.clawcodex/config.json. ```bash clawcodex login # or: python -m src.cli login ``` -------------------------------- ### Get All Base Tools Source: https://github.com/agentforce314/clawcodex/blob/main/claude-code-wiki/raw/claude-code-sourcemap-learning-notebook/en/02_tool_system.md Retrieves all core and conditional tools available. Conditional tools are included based on environment variables or feature flags. ```typescript export function getAllBaseTools(): Tools { return [ // Core tools (always available) AgentTool, TaskOutputTool, BashTool, FileReadTool, FileEditTool, FileWriteTool, NotebookEditTool, WebFetchTool, TodoWriteTool, WebSearchTool, TaskStopTool, AskUserQuestionTool, SkillTool, EnterPlanModeTool, ExitPlanModeV2Tool, BriefTool, // Conditional tools (based on environment/feature flags) ...(hasEmbeddedSearchTools() ? [] : [GlobTool, GrepTool]), ...(isAgentSwarmsEnabled() ? [TeamCreateTool, TeamDeleteTool] : []), ...(isWorktreeModeEnabled() ? [EnterWorktreeTool, ExitWorktreeTool] : []), ...(isToolSearchEnabledOptimistic() ? [ToolSearchTool] : []), // Experimental tools (feature flag controlled) ...(WebBrowserTool ? [WebBrowserTool] : []), ...(SleepTool ? [SleepTool] : []), ...cronTools, // MCP resource tools ListMcpResourcesTool, ReadMcpResourceTool, ]; } ``` -------------------------------- ### Enable Streaming Agent Output Source: https://github.com/agentforce314/clawcodex/blob/main/README.md Use the `/stream on` command to enable live streaming of agent output. Use `/render-last` to re-render the last streamed output as clean Markdown. ```text >>> /stream on >>> Explain tests/test_agent_loop.py [streaming answer...] • Read (tests/test_agent_loop.py) running... ↳ lines 1-180 >>> /render-last ``` -------------------------------- ### CLI Entry Point with Commander.js Source: https://github.com/agentforce314/clawcodex/blob/main/claude-code-wiki/raw/claude-code-sourcemap-learning-notebook/en/01_architecture_overview.md The main.tsx file serves as the CLI entry point, handling argument parsing with Commander.js and initializing various subsystems before launching the REPL or print mode. ```typescript // 1. Performance optimization: start parallel preloading before all imports profileCheckpoint('main_tsx_entry'); // Mark startup time startMdmRawRead(); // Parallel read MDM config startKeychainPrefetch(); // Parallel read keychain credentials // 2. Define all CLI arguments using Commander.js const program = new CommanderCommand() .option('-p, --print', 'Non-interactive mode') .option('--model ', 'Specify model') .option('--permission-mode ', 'Permission mode') // ... dozens of arguments // 3. Initialize subsystems await init(); // Auth, config, telemetry await initializeGrowthBook(); // Feature flags await initBundledSkills(); // Built-in skills await initBuiltinPlugins(); // Built-in plugins // 4. Launch REPL or print mode launchRepl(options); // Interactive mode // or ask({ prompt, tools, ... }); // Non-interactive mode ``` -------------------------------- ### Initial Request with Lazy Loading Source: https://github.com/agentforce314/clawcodex/blob/main/claude-code-wiki/raw/claude-code-sourcemap-learning-notebook/en/06_mcp_extensions.md Demonstrates how to structure an initial API request when using ToolSearch for lazy loading. Core tools are sent with full schemas, while other tools are represented by name and a 'defer_loading' marker. ```json Initial request: tools: [ Bash (full schema), Read (full schema), ToolSearch (full schema), ← search tool mcp__db__query (defer_loading), ← name only mcp__api__fetch (defer_loading), ← name only ] ``` -------------------------------- ### Hierarchical AbortController Structure Source: https://github.com/agentforce314/clawcodex/blob/main/claude-code-wiki/raw/claude-code-sourcemap-learning-notebook/en/04_query_loop_api.md Illustrates a three-tier AbortController setup for managing cancellation propagation. This structure allows for granular control over which cancellations bubble up to parent controllers. ```plaintext Root AbortController (highest level cancellation) └── Group AbortController (group-level cancellation) ├── Task A AbortController ├── Task B AbortController └── Task C AbortController ``` -------------------------------- ### Get Default Edit Tool Description Source: https://github.com/agentforce314/clawcodex/blob/main/claude-code-wiki/raw/claude-code-sourcemap-learning-notebook/en/07_prompt_engineering.md Provides the default description for the FileEditTool, outlining usage rules such as requiring prior file reading and preserving indentation. ```typescript // src/tools/FileEditTool/prompt.ts function getDefaultEditDescription(): string { return `Performs exact string replacements in files. Usage: - You must use your Read tool at least once in the conversation before editing. This tool will error if you attempt an edit without reading the file. - When editing text from Read tool output, ensure you preserve the exact indentation (tabs/spaces) as it appears AFTER the line number prefix. - ALWAYS prefer editing existing files. NEVER write new files unless explicitly required. - The edit will FAIL if old_string is not unique in the file. Either provide a larger string with more surrounding context or use replace_all. - Use replace_all for replacing and renaming strings across the file.` } ``` -------------------------------- ### Get User Context - TypeScript Source: https://github.com/agentforce314/clawcodex/blob/main/claude-code-wiki/raw/claude-code-sourcemap-learning-notebook/en/01_architecture_overview.md Retrieves user-specific context, including CLAUDE.md files and the current date. Uses memoization to compute context only once per session. ```typescript export const getUserContext = memoize(async () => { // 1. Read CLAUDE.md files (project-level + user-level) const claudeMd = getClaudeMds(await getMemoryFiles()); // 2. Current date const currentDate = `Today's date is ${getLocalISODate()}.`; return { claudeMd, currentDate }; }); ``` -------------------------------- ### Test Configuration Save and Load Source: https://github.com/agentforce314/clawcodex/blob/main/docs/guide/TESTING.md Tests the persistence of configuration settings by saving a configuration object and then loading it back. ```python def test_save_and_load_config(self): """Test save and load roundtrip.""" config = { "default_provider": "glm", "providers": { "glm": { "api_key": "test_key", "base_url": "https://example.com", "default_model": "glm-4" } } } save_config(config) loaded = load_config() assert loaded["default_provider"] == "glm" ``` -------------------------------- ### Embed Guidance in Search Results for Truncation Source: https://github.com/agentforce314/clawcodex/blob/main/claude-code-wiki/raw/claude-code-sourcemap-learning-notebook/en/02_tool_system.md This technique embeds a hint within the tool's output to guide the LLM to narrow its search scope when results are truncated. ```typescript '(Results are truncated. Consider using a more specific path or pattern.)' ``` -------------------------------- ### Get Ultracode Reminder Text Source: https://github.com/agentforce314/clawcodex/blob/main/docs/workflow-commands-and-ultracode-plan.md Returns a reminder message for the model regarding workflow authoring. It prioritizes the 'ultracode' keyword, then the session mode, and is disabled if workflows are not enabled. ```python ultracode_reminder_for(text) -> str | None ``` -------------------------------- ### Use a Skill in REPL Source: https://github.com/agentforce314/clawcodex/blob/main/README.md Demonstrates how to invoke a custom skill from the Clawcodex REPL. The command format is '/ '. ```text > / > / ```