### Shell Command Examples Source: https://github.com/commandcodeai/command-code/blob/main/_autodocs/system-prompt-and-tools.md Examples of using the 'shell' tool to execute various commands like listing files, installing packages, running scripts, checking git status, and making HTTP requests. ```json {"tool":"shell","args":{"cmd":"ls -la"}} ``` ```json {"tool":"shell","args":{"cmd":"npm install"}} ``` ```json {"tool":"shell","args":{"cmd":"python script.py"}} ``` ```json {"tool":"shell","args":{"cmd":"git status"}} ``` ```json {"tool":"shell","args":{"cmd":"curl https://api.example.com"}} ``` -------------------------------- ### Multi-Step Tasks Example Source: https://github.com/commandcodeai/command-code/blob/main/_autodocs/REFERENCE.md Example of using clai-old to perform multiple file creation operations for a Node.js project setup. ```bash clai-old "Create src/main.js, src/utils.js, and package.json for a Node.js project" ``` -------------------------------- ### Start Command Code in Project Source: https://github.com/commandcodeai/command-code/blob/main/readme.md Navigate to your project directory and start the Command Code CLI. ```bash cd your-project cmd ``` -------------------------------- ### Shell Command Execution Example Source: https://github.com/commandcodeai/command-code/blob/main/_autodocs/implementation-details.md Example of executing a shell command like 'npm install' via execSync. The command is run using /bin/sh -c, and its stdout is captured while stderr is discarded. ```bash # Shell command from agent: {"tool":"shell","args":{"cmd":"npm install"}} # Executed as: /bin/sh -c "npm install" # Returns: (stdout output from npm install) # Stderr is discarded (not visible to agent) ``` -------------------------------- ### Full Configuration Example Source: https://github.com/commandcodeai/command-code/blob/main/_autodocs/REFERENCE.md A complete bash script example demonstrating how to set multiple environment variables for CLAI and execute a command. ```bash #!/bin/bash export OPENAI_API_KEY="sk-..." export CLAI_MODEL="gpt-3.5-turbo-instruct" export CLAI_STEPS=20 export CLAI_MAX_TOKENS=1024 clai-old "Create src/index.js with a hello world function" ``` -------------------------------- ### Read File and Install Dependencies Source: https://github.com/commandcodeai/command-code/blob/main/_autodocs/system-prompt-and-tools.md Demonstrates reading a file using the 'read' tool, followed by executing a shell command for package installation. ```json {"tool":"read","args":{"path":"package.json"}} ``` ```json // LLM analyzes response, then: {"tool":"shell","args":{"cmd":"npm install"}} ``` -------------------------------- ### Shell Command Example Source: https://github.com/commandcodeai/command-code/blob/main/_autodocs/REFERENCE.md Demonstrates using clai-old to execute shell commands for tasks like installing dependencies and running tests. ```bash clai-old "Install dependencies and run tests" ``` -------------------------------- ### Minimal Environment Variable Setup Source: https://github.com/commandcodeai/command-code/blob/main/_autodocs/configuration.md Set the OPENAI_API_KEY to authenticate with OpenAI and then execute a command. ```bash export OPENAI_API_KEY="sk-..." cmd "your task here" ``` -------------------------------- ### CLI Usage Examples Source: https://github.com/commandcodeai/command-code/blob/main/_autodocs/configuration.md Demonstrates how to invoke the CLI tool, either with a task description as an argument or interactively. ```bash # Via command-line argument clai-old "task description" # Via interactive prompt (reads from stdin) clai-old task> task description ``` -------------------------------- ### Basic Usage Example Source: https://github.com/commandcodeai/command-code/blob/main/_autodocs/REFERENCE.md Demonstrates how to use clai-old for a simple file creation task from the command line. ```bash clai-old "Create a file named test.js with content console.log('hello')" ``` -------------------------------- ### All Command-Code Environment Variables Source: https://github.com/commandcodeai/command-code/blob/main/_autodocs/usage-guide.md A comprehensive example showing how to set all available environment variables for Command-Code, including API key, model, steps, and max tokens. ```bash #!/bin/bash export OPENAI_API_KEY="sk-your-key" export CLAI_MODEL="gpt-3.5-turbo-instruct" # Model ID export CLAI_STEPS=20 # Max iterations export CLAI_MAX_TOKENS=1024 # Tokens per request clai-old "your task" ``` -------------------------------- ### Minimal Bash Setup for Command Code AI Source: https://github.com/commandcodeai/command-code/blob/main/_autodocs/INDEX.md Sets the OpenAI API key and executes a task using the clai-old command. This is the most basic setup. ```bash export OPENAI_API_KEY="sk-..." clai-old "your task" ``` -------------------------------- ### Install CommandCodeAI Source: https://github.com/commandcodeai/command-code/blob/main/_autodocs/INDEX.md Install the CommandCodeAI CLI globally using npm and set your OpenAI API key as an environment variable. ```bash npm install -g clai-old export OPENAI_API_KEY="sk-your-key" ``` -------------------------------- ### Minimal Command Code AI Setup Source: https://github.com/commandcodeai/command-code/blob/main/_autodocs/usage-guide.md Sets the OpenAI API key and runs a basic command. Use this for simple, quick tasks. ```bash export OPENAI_API_KEY="sk-..." clai-old "write a hello world script" ``` -------------------------------- ### Install and Run clai-old Source: https://github.com/commandcodeai/command-code/blob/main/_autodocs/README.md Install the clai-old package globally using npm. Set your OpenAI API key as an environment variable. Then, run the clai-old executable with your task. ```bash npm install -g clai-old export OPENAI_API_KEY="sk-your-api-key" clai-old "your task here" ``` -------------------------------- ### Install Command-Code via npm Source: https://github.com/commandcodeai/command-code/blob/main/_autodocs/usage-guide.md Install the Command-Code CLI globally using npm. Ensure Node.js version 18 or higher is installed. ```bash npm install -g clai-old ``` -------------------------------- ### Install Command Code CLI Source: https://github.com/commandcodeai/command-code/blob/main/readme.md Install the Command Code command-line interface globally using npm. ```bash npm i -g command-code ``` -------------------------------- ### Custom Settings Example Source: https://github.com/commandcodeai/command-code/blob/main/_autodocs/REFERENCE.md Illustrates setting environment variables CLAI_STEPS and CLAI_MAX_TOKENS to customize clai-old's behavior. ```bash export CLAI_STEPS=50 export CLAI_MAX_TOKENS=2048 clai-old "Build a Node.js server" ``` -------------------------------- ### Run CLAI in GitHub Actions Source: https://github.com/commandcodeai/command-code/blob/main/_autodocs/usage-guide.md Automate CLAI task execution within a GitHub Actions workflow. This example checks out code, sets up Node.js, installs CLAI, and runs a task using secrets for the API key. ```yaml name: Run Agent on: workflow_dispatch jobs: agent: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - uses: actions/setup-node@v3 with: node-version: 18 - run: npm install -g clai-old - run: clai-old "create README.md with project description" env: OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} ``` -------------------------------- ### Development/Testing Environment Variable Setup Source: https://github.com/commandcodeai/command-code/blob/main/_autodocs/configuration.md Configure environment variables for development or testing purposes, using a test API key and reduced step/token limits. ```bash export OPENAI_API_KEY="sk-test-..." export CLAI_MODEL="gpt-3.5-turbo-instruct" export CLAI_STEPS=5 export CLAI_MAX_TOKENS=512 cmd "test task" ``` -------------------------------- ### Example Usage of `trim` Function Source: https://github.com/commandcodeai/command-code/blob/main/_autodocs/api-reference.md Demonstrates how to use the `trim` function with both long and short strings to observe its truncation behavior. The first example shows truncation with an indicator, while the second shows the string remaining unchanged. ```javascript const longString = "a".repeat(5000); const truncated = trim(longString, 100); // Returns: "aaaa...aaaa\n[...truncated 4900 chars]" const shortString = "hello"; const unchanged = trim(shortString, 100); // Returns: "hello" ``` -------------------------------- ### Tool Call Sequence Example Source: https://github.com/commandcodeai/command-code/blob/main/_autodocs/system-prompt-and-tools.md Demonstrates a sequence of tool calls over multiple iterations. The LLM issues commands, the agent executes them and provides observations, culminating in the 'done' tool call to signal completion. ```text Iteration 1: LLM: {"tool":"create","args":{"path":"file1.txt","content":"content1"}} Agent: OBSERVATION: wrote file1.txt (8 bytes) Iteration 2: LLM: {"tool":"create","args":{"path":"file2.txt","content":"content2"}} Agent: OBSERVATION: wrote file2.txt (8 bytes) Iteration 3: LLM: {"tool":"done","args":{"answer":"Created 2 files"}} Agent: [done] Created 2 files ``` -------------------------------- ### LLM Tool Call Sequence Example Source: https://github.com/commandcodeai/command-code/blob/main/_autodocs/architecture.md Illustrates the expected JSON output from the LLM for tool calls, how it's parsed, executed, and its role in the next iteration's prompt. ```javascript // LLM output (example) {"tool":"create","args":{"path":"src/index.js","content":"console.log('test');"}} // Parsed by extractJson() { tool: "create", args: { path: "src/index.js", content: "console.log('test');" } } // Executed by runTool() // Returns: "wrote src/index.js (24 bytes)" // Appended to prompt for next iteration ``` -------------------------------- ### Advanced Environment Variable Setup Source: https://github.com/commandcodeai/command-code/blob/main/_autodocs/configuration.md Configure advanced settings like CLAI_MODEL, CLAI_STEPS, and CLAI_MAX_TOKENS for more control over agent behavior. ```bash export OPENAI_API_KEY="sk-..." export CLAI_MODEL="gpt-4" export CLAI_STEPS=50 export CLAI_MAX_TOKENS=2048 cmd "complex multi-step task" ``` -------------------------------- ### Prompt Accumulation Example Source: https://github.com/commandcodeai/command-code/blob/main/_autodocs/types.md Demonstrates how the internal prompt accumulates LLM output and observations after each step in the agent loop. ```plaintext ...\n{"tool":"create","args":{"path":"file.txt","content":"test"}}\nOBSERVATION: wrote file.txt (4 bytes) ``` -------------------------------- ### Interactive Mode Example Source: https://github.com/commandcodeai/command-code/blob/main/_autodocs/REFERENCE.md Shows how to initiate clai-old in interactive mode, allowing for multi-turn task execution. ```bash clai-old task> Create a file named test.js with content console.log('hello') ``` -------------------------------- ### Command-Code CLI Usage Examples Source: https://github.com/commandcodeai/command-code/blob/main/_autodocs/usage-guide.md Demonstrates different ways to invoke the Command-Code CLI, including passing tasks as arguments and using interactive mode. ```bash # With task as argument clai-old "task description here" ``` ```bash # Multiple arguments are joined clai-old Create a new file named test.txt with content hello ``` ```bash # Interactive mode (reads task from stdin) clai-old task> Create a new file named test.txt with content hello ``` -------------------------------- ### Optimize CLAI Cost and Performance Source: https://github.com/commandcodeai/command-code/blob/main/_autodocs/usage-guide.md Compares configurations for CLAI to reduce costs and improve performance. The high-cost example uses larger token limits, more steps, and a premium model, while the lower-cost example uses reduced settings and a cheaper model. ```bash # High cost (100 tokens, 100 iterations, ~$30-50) export CLAI_MAX_TOKENS=2048 export CLAI_STEPS=100 export CLAI_MODEL="gpt-4" # Lower cost (20 tokens, 30 iterations, ~$0.50) export CLAI_MAX_TOKENS=512 export CLAI_STEPS=30 export CLAI_MODEL="gpt-3.5-turbo-instruct" ``` -------------------------------- ### Example of String Truncation Source: https://github.com/commandcodeai/command-code/blob/main/_autodocs/implementation-details.md Demonstrates the `trim` function by creating a large string and then truncating it, showing the resulting trimmed string with a truncation indicator. ```javascript const output = "line1\nline2\nline3...".repeat(1000); // 30000 chars const trimmed = trim(output, 4000); // Result: first 4000 chars + "\n[...truncated 26000 chars]" ``` -------------------------------- ### Prompt Engineering Example Source: https://github.com/commandcodeai/command-code/blob/main/_autodocs/usage-guide.md Illustrates how to improve Command Code AI's output by providing specific requirements in the prompt. Vague prompts lead to generic results, while detailed prompts yield precise outcomes. ```bash # Vague clai-old "Create a script" # Better clai-old "Create a Node.js script named process.js that reads a CSV file and prints the first 5 rows" ``` -------------------------------- ### Example ToolCall Object Source: https://github.com/commandcodeai/command-code/blob/main/_autodocs/types.md An example of a ToolCall object used to create a file. This object is parsed from JSON strings by `extractJson()`. ```javascript const toolCall = { tool: "create", args: { path: "hello.txt", content: "Hello, world!" } }; ``` -------------------------------- ### Development Command Code AI Setup Source: https://github.com/commandcodeai/command-code/blob/main/_autodocs/usage-guide.md Sets up Command Code AI for development and testing purposes with a test API key, limited steps, and token count. Useful for debugging and iterative development. ```bash export OPENAI_API_KEY="sk-test-..." export CLAI_STEPS=5 export CLAI_MAX_TOKENS=256 clai-old "test task" ``` -------------------------------- ### File Operation Argument Examples Source: https://github.com/commandcodeai/command-code/blob/main/_autodocs/types.md Examples of FileOperationArgs for different file operations. Note that `content` is omitted for read and delete operations. ```javascript // Create file { path: "src/index.js", content: "console.log('hello');" } ``` ```javascript // Update file { path: "config.json", content: '{"debug":true}' } ``` ```javascript // Read file { path: "README.md" } ``` ```javascript // Delete file { path: "temp.txt" } ``` -------------------------------- ### Aggressive Command Code AI Setup (More Capable) Source: https://github.com/commandcodeai/command-code/blob/main/_autodocs/usage-guide.md Configures Command Code AI for higher capability by using a more advanced model, more steps, and a larger token limit. Recommended for complex, multi-step projects. ```bash export OPENAI_API_KEY="sk-..." export CLAI_MODEL="gpt-4" export CLAI_STEPS=100 export CLAI_MAX_TOKENS=2048 clai-old "complex multi-step project" ``` -------------------------------- ### Single Tool Call Example Source: https://github.com/commandcodeai/command-code/blob/main/_autodocs/system-prompt-and-tools.md Illustrates a single tool call where the LLM outputs a tool command, the agent processes it, and responds with an observation. The LLM then continues with another tool call. ```text LLM Output: {"tool":"create","args":{"path":"test.txt","content":"hello"}} Agent Processing: 1. Extract JSON 2. Validate tool name 3. Execute with args 4. Capture result Agent Response to LLM: OBSERVATION: wrote test.txt (5 bytes) LLM Continues: {"tool":"read","args":{"path":"test.txt"}} Agent Response: OBSERVATION: hello ``` -------------------------------- ### Example File Operation Errors Source: https://github.com/commandcodeai/command-code/blob/main/_autodocs/errors.md Illustrates common file operation error messages that can occur due to issues like non-existent files, permission problems, or attempting to operate on directories. ```text error: ENOENT: no such file or directory, open 'nonexistent.txt' ``` ```text error: EACCES: permission denied, open '/root/protected.txt' ``` ```text error: EISDIR: illegal operation on a directory, open 'mydir' ``` -------------------------------- ### Task Decomposition Example Source: https://github.com/commandcodeai/command-code/blob/main/_autodocs/usage-guide.md Breaks down a large task into smaller, manageable steps for Command Code AI. This approach can improve clarity and success rate for complex objectives. ```bash # Instead of: clai-old "Build entire REST API with auth" # Try: clai-old "Create basic Express server with one GET route" clai-old "Add authentication middleware" clai-old "Add error handling" ``` -------------------------------- ### Tool Execution Result Examples Source: https://github.com/commandcodeai/command-code/blob/main/_autodocs/types.md Illustrates the string format of ToolExecutionResult based on the type of tool operation performed. ```javascript // After create: "wrote src/index.js (45 bytes)" ``` ```javascript // After read: "console.log('hello');\n" ``` ```javascript // After delete: "deleted src/index.js" ``` ```javascript // After shell ls: "total 32 drwxr-xr-x 5 user group 160 Jun 23 10:00 src ..." ``` -------------------------------- ### CLI Usage Examples Source: https://github.com/commandcodeai/command-code/blob/main/_autodocs/api-reference.md Illustrates how to invoke the Command Code AI CLI. Tasks can be provided directly as a command-line argument or entered interactively after running the command without arguments. ```bash # Via command-line argument cmd "Create a file named test.txt with content 'hello'" # Via interactive prompt cmd # task> Create a file named test.txt with content 'hello' ``` -------------------------------- ### Production Bash Setup for Command Code AI Source: https://github.com/commandcodeai/command-code/blob/main/_autodocs/INDEX.md Configures the OpenAI API key and several clai-old environment variables for production use, including model, steps, and max tokens. Adjust these for optimal performance and cost. ```bash export OPENAI_API_KEY="sk-..." export CLAI_MODEL="gpt-3.5-turbo-instruct" export CLAI_STEPS=30 export CLAI_MAX_TOKENS=1024 clai-old "your task" ``` -------------------------------- ### Conservative Command Code AI Setup (Lower Cost) Source: https://github.com/commandcodeai/command-code/blob/main/_autodocs/usage-guide.md Configures Command Code AI for lower cost by specifying a less capable model, fewer steps, and smaller token limit. Suitable for simple tasks where cost is a primary concern. ```bash export OPENAI_API_KEY="sk-..." export CLAI_MODEL="gpt-3.5-turbo-instruct" export CLAI_STEPS=10 export CLAI_MAX_TOKENS=512 clai-old "simple task" ``` -------------------------------- ### complete(prompt: string): Promise Source: https://github.com/commandcodeai/command-code/blob/main/_autodocs/REFERENCE.md Sends a prompt to the OpenAI API to get a text completion. It is designed for deterministic output by setting the temperature to 0 and stopping at specific observation or task markers. ```APIDOC ## complete(prompt: string): Promise ### Description Send prompt to OpenAI API and get completion. This function is intended for interacting with the language model to generate text based on the provided prompt, including conversation history. ### Method POST (implicitly, via fetch) ### Endpoint [OpenAI completions endpoint, defined by ENDPOINT constant] ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None (parameters are set in fetch options) ### Request Example ```json { "prompt": "User: Write a short story about a robot. Assistant: Once upon a time...\nOBSERVATION:", "temperature": 0, "max_tokens": 1000, "stop": ["\nOBSERVATION:", "\nTASK:"] } ``` ### Response #### Success Response (200) - **completion** (string) - The text completion generated by the LLM. #### Response Example ```json { "choices": [ { "text": " A robot named Unit 734 felt a strange longing..." } ] } ``` ### Throws - Error if OPENAI_API_KEY not set. - Error if API returns an error or missing choices. ``` -------------------------------- ### Execute Commands with Command Code AI Source: https://github.com/commandcodeai/command-code/blob/main/_autodocs/usage-guide.md Delegate command execution to the agent, useful for sequences of operations like installations and starting services. ```bash clai-old "Run npm install and then npm start" ``` -------------------------------- ### Create Project Files Source: https://github.com/commandcodeai/command-code/blob/main/_autodocs/system-prompt-and-tools.md Use the 'create' tool to generate new files with specified content. This is useful for initializing project structures. ```json {"tool":"create","args":{"path":"src/index.js","content":"console.log('hello');"}} ``` ```json {"tool":"create","args":{"path":"src/utils.js","content":"module.exports = {};"}} ``` ```json {"tool":"create","args":{"path":"package.json","content":"{\"name\":\"project\"}"}} ``` -------------------------------- ### main() Source: https://github.com/commandcodeai/command-code/blob/main/_autodocs/api-reference.md Main entry point for the CLI. Accepts a task as command-line argument or interactive input, then orchestrates the agent loop to complete the task using tool execution. ```APIDOC ## Function: `main()` ### Description Main entry point for the CLI. Accepts a task as command-line argument or interactive input, then orchestrates the agent loop to complete the task using tool execution. ### Signature: ```javascript async function main(): Promise ``` ### Parameters: None. Reads from `process.argv` or stdin based on availability. ### Environment Variables: - **OPENAI_API_KEY** (string) - Required - API key for OpenAI authentication - **CLAI_MODEL** (string) - Optional - LLM model to use for completions (Default: "gpt-3.5-turbo-instruct") - **CLAI_STEPS** (number) - Optional - Maximum number of agent loop iterations (Default: 20) - **CLAI_MAX_TOKENS** (number) - Optional - Maximum tokens per API completion request (Default: 1024) ### Behavior: 1. Reads task from command-line arguments or prompts interactively if none provided 2. Initializes prompt with system message and task description 3. Executes up to MAX_STEPS iterations: - Calls `complete()` to get LLM response - Extracts JSON tool call from response using `extractJson()` - Executes tool using `runTool()` if valid JSON extracted - Appends observation to prompt for next iteration - Stops early if LLM calls "done" tool 4. Prints step-by-step output to stdout ### Throws: - **Error** - If main task encounters unhandled exception ### Exit Codes: - 0: Task completed successfully - 1: Error occurred during execution ### Example Usage (CLI): ```bash # Via command-line argument cmd "Create a file named test.txt with content 'hello'" # Via interactive prompt cmd # task> Create a file named test.txt with content 'hello' ``` ``` -------------------------------- ### Loop-and-Tool Execution Model Source: https://github.com/commandcodeai/command-code/blob/main/_autodocs/architecture.md Illustrates the step-by-step process of the clai-old agent's execution flow, from initialization to task completion or error handling. ```text ┌─────────────────────────────────────────────────────────────┐ │ 1. Initialize: Parse task from CLI or stdin │ └──────────────────────────┬──────────────────────────────────┘ │ ▼ ┌─────────────────────────────────────────────────────────────┐ │ 2. Build prompt: SYSTEM + task + history │ └──────────────────────────┬──────────────────────────────────┘ │ ▼ ┌─────────────────────────────────────────────────────────────┐ │ 3. API call: Send prompt to OpenAI completions endpoint │ └──────────────────────────┬──────────────────────────────────┘ │ ▼ ┌─────────────────────────────────────────────────────────────┐ │ 4. Parse: Extract JSON tool call from LLM output │ └──────────────────────────┬──────────────────────────────────┘ │ ┌──────────┴──────────┐ │ │ ▼ ▼ ┌───────────────┐ ┌────────────────┐ │ Valid JSON? │ │ Stop/Error? │ └───────────────┘ └────────────────┘ │ │ │ No │ Yes ▼ ▼ [Print error] [Print result & exit] │ │ Yes ▼ ┌─────────────────────┐ │ Tool = "done"? │ └─────────────────────┘ │ │ │ No │ Yes ▼ ▼ [Execute] [Print answer & exit] [Tool] │ ▼ ┌──────────────────┐ │ Append to prompt:│ │ • Output │ │ • Observation │ └──────────────────┘ │ ▼ ┌──────────────┐ │ Loop count < │ │ MAX_STEPS? │ └──────────────┘ │ │ │ Yes │ No ▼ ▼ [Next iter] [Max steps] ``` -------------------------------- ### Run Tool: Create File Source: https://github.com/commandcodeai/command-code/blob/main/_autodocs/api-reference.md Executes the 'create' tool to write content to a file. Supports optional content, defaulting to an empty string. ```javascript // Create a file const result1 = runTool("create", { path: "hello.txt", content: "Hello, world!" }); // Returns: "wrote hello.txt (13 bytes)" ``` -------------------------------- ### main(): Promise Source: https://github.com/commandcodeai/command-code/blob/main/_autodocs/REFERENCE.md Serves as the main entry point for the CLI agent. It orchestrates the agent's loop, processing tasks, interacting with the LLM via `complete`, executing tools via `runTool`, and managing the prompt history. ```APIDOC ## main(): Promise ### Description This is the main entry point for the Command Code AI CLI. It initializes the agent, processes tasks, and runs the core agent loop until the task is completed or the maximum number of steps is reached. ### Method N/A (CLI entry point) ### Endpoint N/A ### Parameters None ### Algorithm 1. Obtain the initial task from command-line arguments or standard input. 2. Initialize the prompt by combining the system prompt (`SYSTEM` constant) with the task. 3. Enter a loop that continues up to `MAX_STEPS`: a. Call the `complete()` function with the current prompt to get an LLM response. b. Use `extractJson()` to parse any JSON object from the LLM's response. c. If no JSON is found, exit the loop with an error. d. If the extracted tool is `"done"`, exit the loop with the final answer. e. Execute the identified tool using `runTool()` with its arguments. f. Append the result of the tool execution to the prompt for the next iteration. 4. Exit the program either when the task is successfully completed or when `MAX_STEPS` is reached without completion. ``` -------------------------------- ### Documentation File Structure Source: https://github.com/commandcodeai/command-code/blob/main/_autodocs/README.md Lists the directory structure for all documentation files within the project. ```bash /workspace/home/output/ ├── INDEX.md (navigation guide) ├── REFERENCE.md (quick reference) ├── api-reference.md (function API) ├── configuration.md (setup guide) ├── types.md (data structures) ├── errors.md (error reference) ├── architecture.md (system design) ├── system-prompt-and-tools.md (tool specs) ├── usage-guide.md (how to use) ├── implementation-details.md (internals) └── README.md (this file) ``` -------------------------------- ### Set Up OpenAI API Key Source: https://github.com/commandcodeai/command-code/blob/main/_autodocs/usage-guide.md Configure your OpenAI API key as an environment variable. This is required for the tool to function. ```bash export OPENAI_API_KEY="sk-your-api-key-here" ``` -------------------------------- ### Run a Simple Task with clai-old Source: https://github.com/commandcodeai/command-code/blob/main/_autodocs/REFERENCE.md Execute a basic command using the clai-old tool to test its functionality. ```bash clai-old "List the current directory" ``` -------------------------------- ### main() Source: https://github.com/commandcodeai/command-code/blob/main/_autodocs/MANIFEST.txt The main entry point function for the CLAI-OLD agent. ```APIDOC ## main() ### Description The main entry point function for the CLAI-OLD agent. ### Parameters (Signature and parameter details would be listed here if available in the source) ### Returns (Return value details would be listed here if available in the source) ### Example (Example usage would be listed here if available in the source) ``` -------------------------------- ### Create File Tool Specification Source: https://github.com/commandcodeai/command-code/blob/main/_autodocs/REFERENCE.md Use the 'create' tool to write content to a new or existing file. Specify the file path and the content to be written. ```json { "tool": "create", "args": { "path": "file.txt", "content": "contents" } } ``` -------------------------------- ### Create File Tool Specification Source: https://github.com/commandcodeai/command-code/blob/main/_autodocs/system-prompt-and-tools.md Use this tool to create a new file with specified content. Parent directories must exist. Existing files will be overwritten. ```json { "tool": "create", "args": { "path": "", "content": "" } } ``` -------------------------------- ### Tool: create Source: https://github.com/commandcodeai/command-code/blob/main/_autodocs/system-prompt-and-tools.md Creates a new file with the specified content. If the file exists, it will be overwritten. Parent directories must exist. ```APIDOC ## Tool: create ### Description Creates a new file with the specified content. Overwrites existing files without warning. Parent directories must exist. ### Usage ```json { "tool": "create", "args": { "path": "", "content": "" } } ``` ### Parameters #### Path Parameters - **path** (string) - Required - Absolute or relative file path. Parent directories must exist. - **content** (string) - Optional - File contents. If omitted, creates an empty file. ### Returns ``` wrote {path} ({bytes} bytes) ``` ### Error Conditions - Path is directory: `EISDIR` - Parent directory doesn't exist: `ENOENT` - Permission denied: `EACCES` - Disk full: `ENOSPC` ``` -------------------------------- ### Initialize Prompt with System and Task Source: https://github.com/commandcodeai/command-code/blob/main/_autodocs/implementation-details.md Initializes the prompt string by concatenating a SYSTEM constant (containing instructions and tool specifications) with the user's task and a newline character. ```javascript let prompt = SYSTEM + task + "\n"; ``` -------------------------------- ### Create File Equivalent Shell Command Source: https://github.com/commandcodeai/command-code/blob/main/_autodocs/system-prompt-and-tools.md This is the shell command equivalent to the 'create' tool for creating a file. ```bash cat > {path} << 'EOF' {content} EOF ``` -------------------------------- ### Initial Prompt Structure Source: https://github.com/commandcodeai/command-code/blob/main/_autodocs/types.md Shows the initial structure of the internal prompt, consisting of a SYSTEM constant followed by the task. ```plaintext You are clai-old, a coding agent... TASK: your task here ``` -------------------------------- ### Agent Execution Flow Overview Source: https://github.com/commandcodeai/command-code/blob/main/_autodocs/REFERENCE.md This diagram illustrates the agent's main loop, from task acquisition to tool execution and prompt updates. It shows the sequence of operations including LLM calls, JSON parsing, and tool running. ```text main() ├─ Get task (argv or stdin) ├─ Initialize prompt (SYSTEM + task) │ └─ Agent Loop (up to MAX_STEPS): ├─ complete(prompt) → LLM output │ └─ Fetch to OpenAI API │ └─ Parse response.choices[0].text │ ├─ extractJson(output) → ToolCall or null │ └─ Find balanced JSON in output │ ├─ Check tool: │ ├─ If null: print error, exit │ ├─ If "done": print answer, exit │ └─ Otherwise: execute │ ├─ runTool(name, args) → result │ ├─ case "create"/"update": writeFileSync() │ ├─ case "read": readFileSync() │ ├─ case "delete": unlinkSync() │ ├─ case "shell": execSync() │ └─ catch: return error message │ ├─ Append to prompt: │ ├─ LLM output │ ├─ OBSERVATION: {result} │ └─ Increment step counter │ └─ Loop if step < MAX_STEPS End: natural exit └─ [stop: hit MAX_STEPS=N] ``` -------------------------------- ### Update File Content with Shell Assistance Source: https://github.com/commandcodeai/command-code/blob/main/_autodocs/system-prompt-and-tools.md Shows how to use shell commands for analysis (e.g., 'grep') and then update file content. This workflow involves reading the file, analyzing it, and then applying modifications. ```json {"tool":"shell","args":{"cmd":"grep -n TODO src/index.js"}} ``` ```json // LLM sees results, then: {"tool":"read","args":{"path":"src/index.js"}} ``` ```json // LLM modifies specific lines, then: {"tool":"update","args":{"path":"src/index.js","content":"..."}} ``` -------------------------------- ### Check Environment Variables Source: https://github.com/commandcodeai/command-code/blob/main/_autodocs/REFERENCE.md Verify that essential environment variables like API keys and model configurations are set correctly. ```bash echo $OPENAI_API_KEY echo $CLAI_MODEL echo $CLAI_STEPS echo $CLAI_MAX_TOKENS ``` -------------------------------- ### Run CommandCodeAI Source: https://github.com/commandcodeai/command-code/blob/main/_autodocs/INDEX.md Execute CommandCodeAI with a natural language prompt to perform a task, such as creating a file. ```bash clai-old "Create a file named hello.js with console.log('hello')" ``` -------------------------------- ### Create File with Command Code AI Source: https://github.com/commandcodeai/command-code/blob/main/_autodocs/usage-guide.md Use this command to create a new file with specified content. Ensure the content is correctly quoted. ```bash clai-old "Create a file at src/main.js with function sayHello() { console.log('hello'); }" ``` -------------------------------- ### Run a Task with Command-Code Source: https://github.com/commandcodeai/command-code/blob/main/_autodocs/usage-guide.md Execute a task by providing a natural language description as an argument to the clai-old command. ```bash clai-old "Create a new file named hello.js with console.log('hello')" ``` -------------------------------- ### Node.js Process Arguments Structure Source: https://github.com/commandcodeai/command-code/blob/main/_autodocs/types.md Illustrates the structure of `process.argv`, showing the Node.js executable path, script path, and task arguments. ```bash # Command: clai-old Create a new file # Results in: process.argv = ["/usr/bin/node", "/path/to/agent.js", "Create", "a", "new", "file"] # Joined task: "Create a new file" ``` -------------------------------- ### Build Complex Projects with Command Code AI Source: https://github.com/commandcodeai/command-code/blob/main/_autodocs/usage-guide.md Describe complex project requirements, like setting up a Node.js server with specific endpoints and logging, for the agent to implement. ```bash clai-old "Build a Node.js server that listens on port 3000, has a GET /hello endpoint, and logs incoming requests" ``` -------------------------------- ### Run Tool: Execute Shell Command Source: https://github.com/commandcodeai/command-code/blob/main/_autodocs/api-reference.md Executes the 'shell' tool to run a command in the system's shell. Returns the command's standard output. ```javascript // Execute a command const result3 = runTool("shell", { cmd: "ls -la" }); // Returns: command output ``` -------------------------------- ### Run Tool: Read File Source: https://github.com/commandcodeai/command-code/blob/main/_autodocs/api-reference.md Executes the 'read' tool to retrieve the content of a specified file. ```javascript // Read a file const result2 = runTool("read", { path: "hello.txt" }); // Returns: "Hello, world!" ``` -------------------------------- ### Tool Specification Source: https://github.com/commandcodeai/command-code/blob/main/_autodocs/system-prompt-and-tools.md Defines the available tools and their argument schemas for the agent. This includes create, read, update, delete, shell, and done. ```json Available tools: {"tool":"create","args":{"path":"","content":""}} {"tool":"read","args":{"path":""}} {"tool":"update","args":{"path":"","content":""}} {"tool":"delete","args":{"path":""}} {"tool":"shell","args":{"cmd":""}} {"tool":"done","args":{"answer":""}} ``` -------------------------------- ### complete(prompt) Source: https://github.com/commandcodeai/command-code/blob/main/_autodocs/api-reference.md Sends a prompt to the OpenAI API and retrieves completion from the configured LLM model. It handles authentication and error checking for API requests. ```APIDOC ## Function: `complete(prompt)` ### Description Sends a prompt to the OpenAI API and retrieves completion from the configured LLM model. ### Signature ```javascript async function complete(prompt: string): Promise ``` ### Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | prompt | string | Yes | The prompt text to send to the OpenAI API endpoint | ### Returns Promise - The text response from the first choice returned by the OpenAI API completion endpoint. ### Throws | Error Type | Condition | |-----------|-----------| | Error | If `OPENAI_API_KEY` environment variable is not set | | Error | If API response is not OK or does not contain `choices` field | ### Example Usage: ```javascript const response = await complete("What is 2 + 2?"); console.log(response); ``` ``` -------------------------------- ### Iterative Refinement with Tests Source: https://github.com/commandcodeai/command-code/blob/main/_autodocs/system-prompt-and-tools.md Illustrates an iterative development process where tests are run, failures are analyzed, code is fixed, and updates are applied until tests pass. This involves shell commands for testing and tools for reading and updating files. ```json {"tool":"shell","args":{"cmd":"npm test"}} ``` ```json // Test fails, LLM sees output, then: {"tool":"read","args":{"path":"src/index.js"}} ``` ```json // LLM fixes bug, then: {"tool":"update","args":{"path":"src/index.js","content":"..."}} ``` ```json // Iterates until tests pass ``` -------------------------------- ### Project Structure Source: https://github.com/commandcodeai/command-code/blob/main/_autodocs/architecture.md The project consists of a single executable module with no external dependencies beyond Node.js built-ins. ```tree clai-old/ ├── agent.js # Main entry point and all logic ├── package.json # Package metadata └── README.md # Documentation ``` -------------------------------- ### Command Code AI Execution Model Source: https://github.com/commandcodeai/command-code/blob/main/_autodocs/README.md Illustrates the iterative process of how Command Code AI handles tasks, from prompt generation to tool execution and feedback. ```text Task → Prompt → API → JSON → Tool → Result → Feedback → [Repeat] ``` -------------------------------- ### Package.json CLI Entry Point Source: https://github.com/commandcodeai/command-code/blob/main/_autodocs/configuration.md Defines the command-line interface entry point for the package, mapping the 'clai-old' command to the agent's main script. ```json { "bin": { "clai-old": "./agent.js" } } ``` -------------------------------- ### Common Optional Configuration Source: https://github.com/commandcodeai/command-code/blob/main/_autodocs/REFERENCE.md Optional environment variables to customize CLAI's behavior, such as the model, iteration limit, and response token limit. ```bash export CLAI_MODEL="gpt-4" # Use GPT-4 instead ``` ```bash export CLAI_STEPS=50 # Increase iterations ``` ```bash export CLAI_MAX_TOKENS=2048 # Larger responses ``` -------------------------------- ### Running Command Code AI from Target Directory Source: https://github.com/commandcodeai/command-code/blob/main/_autodocs/usage-guide.md Ensures relative paths work correctly by running Command Code AI from the project's root directory. Use the `cd` command to navigate before executing. ```bash cd /path/to/project clai-old "Add TypeScript configuration" ``` -------------------------------- ### Tool: shell Source: https://github.com/commandcodeai/command-code/blob/main/_autodocs/system-prompt-and-tools.md Executes a shell command and returns its standard output. ```APIDOC ## Tool: shell ### Description Executes a shell command and returns stdout. ### Usage ```json { "tool": "shell", "args": { "cmd": "" } } ``` ### Parameters #### Path Parameters - **cmd** (string) - Required - Shell command to execute (any bash/sh command) ### Returns ``` ``` Command output (stdout only, stderr is discarded). ### Capabilities - Execute any command (git, npm, python, etc.) - Pipe commands: `ls -la | grep node` - Change directories: `cd src && npm install` (affects only that subprocess) - Use environment variables: `echo $HOME` ### Examples ```json {"tool":"shell","args":{"cmd":"ls -la"}} {"tool":"shell","args":{"cmd":"npm install"}} {"tool":"shell","args":{"cmd":"python script.py"}} {"tool":"shell","args":{"cmd":"git status"}} {"tool":"shell","args":{"cmd":"curl https://api.example.com"}} ``` ### Limitations - Cannot use interactive input - Cannot use pipes to stdin - Working directory is the original cwd - Each invocation is independent (no state between calls) - Output larger than 10 MB is truncated - Exit codes not returned (only stdout) ``` -------------------------------- ### Available Tools Definition Source: https://github.com/commandcodeai/command-code/blob/main/_autodocs/configuration.md Defines the set of available tools that the agent can use for task execution, including create, update, read, delete, shell, and done. ```javascript Available tools: - create: Write new file with content - update: Write to existing file (overwrites) - read: Read file contents - delete: Delete file from disk - shell: Execute shell command - done: Signal task completion ``` -------------------------------- ### Enter Interactive Mode Source: https://github.com/commandcodeai/command-code/blob/main/_autodocs/usage-guide.md Run the agent without any initial task to enter interactive mode, allowing for conversational task definition and execution. ```bash $ clai-old task> What do you want me to do? ``` -------------------------------- ### runTool() Source: https://github.com/commandcodeai/command-code/blob/main/_autodocs/MANIFEST.txt This function executes a specified tool with given arguments. ```APIDOC ## runTool() ### Description Executes a specified tool with given arguments. ### Parameters (Signature and parameter details would be listed here if available in the source) ### Returns (Return value details would be listed here if available in the source) ### Example (Example usage would be listed here if available in the source) ``` -------------------------------- ### runTool(name, args) Source: https://github.com/commandcodeai/command-code/blob/main/_autodocs/api-reference.md Executes a specified tool with given arguments. Supports file operations (create, read, update, delete) and shell command execution. ```APIDOC ## Function: `runTool(name, args)` ### Description Executes a tool command with the provided arguments. Supports file operations and shell execution. ### Signature ```javascript function runTool(name: string, args?: object): string ``` ### Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | name | string | Yes | The tool name to execute: `create`, `update`, `read`, `delete`, or `shell` | | args | object | No | Tool-specific arguments object | ### Returns string - The result of the tool execution. For file operations, returns status message. For `read`, returns file contents. For `shell`, returns command output. ### Tool Specifications: - **create** | **update**: Writes file to disk - args.path (string): File path to write - args.content (string, optional): File content (defaults to empty string) - Returns: Message indicating bytes written - **read**: Reads file from disk - args.path (string): File path to read - Returns: File contents as string - **delete**: Deletes file from disk - args.path (string): File path to delete - Returns: Deletion confirmation message - **shell**: Executes shell command - args.cmd (string): Shell command to execute - Returns: Command stdout output (up to 10MB) ### Throws: | Error Type | Condition | |-----------|-----------| | Error | If file operation fails (file not found, permission denied, etc.) | | Error | If unknown tool name is provided | ### Example Usage: ```javascript // Create a file const result1 = runTool("create", { path: "hello.txt", content: "Hello, world!" }); // Returns: "wrote hello.txt (13 bytes)" // Read a file const result2 = runTool("read", { path: "hello.txt" }); // Returns: "Hello, world!" // Execute a command const result3 = runTool("shell", { cmd: "ls -la" }); // Returns: command output // Delete a file const result4 = runTool("delete", { path: "hello.txt" }); // Returns: "deleted hello.txt" ``` ``` -------------------------------- ### Create and Use Readline Interface Source: https://github.com/commandcodeai/command-code/blob/main/_autodocs/implementation-details.md Creates a readline interface to prompt the user for a task, trims whitespace from the input, and closes the interface. This is a promise-based approach for async/await operations. ```javascript const rl = createInterface({ input: stdin, output: stdout }); task = (await rl.question("task> ")).trim(); rl.close(); ``` -------------------------------- ### clai-old Agent System Prompt Source: https://github.com/commandcodeai/command-code/blob/main/_autodocs/system-prompt-and-tools.md Defines the agent's role, output format, available tools, interaction flow, and termination condition. Ensure all output is JSON and use the 'done' tool to stop. ```text You are clai-old, a coding agent. You only speak by emitting one JSON object per turn, nothing else. Available tools: {"tool":"create","args":{"path":"","content":""}} {"tool":"read","args":{"path":""}} {"tool":"update","args":{"path":"","content":""}} {"tool":"delete","args":{"path":""}} {"tool":"shell","args":{"cmd":""}} {"tool":"done","args":{"answer":""}} After you emit a JSON object you will receive a line beginning with OBSERVATION: containing the tool result. Then emit the next JSON. Never emit prose outside JSON. Stop by calling tool "done". TASK: ``` -------------------------------- ### Task Prefix Source: https://github.com/commandcodeai/command-code/blob/main/_autodocs/system-prompt-and-tools.md Indicates where the user's specific task will be appended within the system prompt. ```text TASK: ``` -------------------------------- ### Command Code AI Key Configuration Variables Source: https://github.com/commandcodeai/command-code/blob/main/_autodocs/INDEX.md Details essential configuration variables for Command Code AI, including the required OPENAI_API_KEY for authentication, CLAI_MODEL for LLM selection, CLAI_STEPS for iteration limits, and CLAI_MAX_TOKENS for API request size. ```markdown | Variable | Default | Effect | |----------|---------|--------| | OPENAI_API_KEY | — | Required. API authentication. | | CLAI_MODEL | "gpt-3.5-turbo-instruct" | Which LLM to use. | | CLAI_STEPS | 20 | Max iterations before timeout. | | CLAI_MAX_TOKENS | 1024 | Max tokens per API request. | ``` -------------------------------- ### API Key Configuration Source: https://github.com/commandcodeai/command-code/blob/main/_autodocs/api-reference.md Loads the OpenAI API key from the OPENAI_API_KEY environment variable. The application will error if this is not set. ```javascript const API_KEY = process.env.OPENAI_API_KEY; ``` -------------------------------- ### Perform Multi-Step Tasks with Command Code AI Source: https://github.com/commandcodeai/command-code/blob/main/_autodocs/usage-guide.md Chain multiple operations, such as creating related files, by providing a sequence of instructions. ```bash clai-old "Create src/index.js with a function greet(), then create src/test.js that calls it" ``` -------------------------------- ### Command Code AI Project Document Map Source: https://github.com/commandcodeai/command-code/blob/main/_autodocs/INDEX.md Illustrates the file structure and organization of the Command Code AI project documentation. Each file provides specific details on different aspects of the project. ```markdown INDEX.md (this file) ├── REFERENCE.md [Quick reference] ├── api-reference.md [Function API] ├── configuration.md [Environment setup] ├── types.md [Data structures] ├── errors.md [Error catalog] ├── architecture.md [System design] ├── system-prompt-and-tools.md [Tool specs] ├── usage-guide.md [How to use] └── implementation-details.md [Internals] ``` -------------------------------- ### Run CLAI with Makefile Source: https://github.com/commandcodeai/command-code/blob/main/_autodocs/usage-guide.md Integrate CLAI into a Makefile for task execution. Set environment variables OPENAI_API_KEY and CLAI_STEPS. The TASK variable defines the operation. ```makefile .PHONY: agent agent: OPENAI_API_KEY="${OPENAI_API_KEY}" \ CLAI_STEPS=30 \ clai-old "$(TASK)" # Usage: make agent TASK="create src/index.js" ```