### Install Git on Ubuntu/Debian Source: https://github.com/winfunc/opcode/blob/main/README.md Installs Git on Ubuntu or Debian-based Linux systems using apt. ```bash sudo apt install git ``` -------------------------------- ### Install Frontend Dependencies with Bun Source: https://github.com/winfunc/opcode/blob/main/README.md Installs frontend project dependencies using Bun. This command should be run after cloning the repository. ```bash bun install ``` -------------------------------- ### Install Rust via rustup Source: https://github.com/winfunc/opcode/blob/main/README.md Installs Rust using the official rustup script. Ensure you have curl installed. ```bash curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh ``` -------------------------------- ### Install Linux System Dependencies Source: https://github.com/winfunc/opcode/blob/main/README.md Installs necessary system dependencies for building on Ubuntu/Debian. Includes webkit2gtk, GTK, and build tools. ```bash sudo apt update sudo apt install -y \ libwebkit2gtk-4.1-dev \ libgtk-3-dev \ libayatana-appindicator3-dev \ librsvg2-dev \ patchelf \ build-essential \ curl \ wget \ file \ libssl-dev \ libxdo-dev \ libsoup-3.0-dev \ libjavascriptcoregtk-4.1-dev ``` -------------------------------- ### Install Bun Source: https://github.com/winfunc/opcode/blob/main/README.md Installs the latest version of Bun, a JavaScript runtime and toolkit. Requires curl. ```bash curl -fsSL https://bun.sh/install | bash ``` -------------------------------- ### Development Commands Source: https://github.com/winfunc/opcode/blob/main/README.md Common commands for developing the Opcode application, including starting the dev server, type checking, and running tests. ```bash # Start development server bun run tauri dev # Run frontend only bun run dev # Type checking bunx tsc --noEmit # Run Rust tests cd src-tauri && cargo test # Format code cd src-tauri && cargo fmt ``` -------------------------------- ### Build Development Server Source: https://github.com/winfunc/opcode/blob/main/web_server.design.md Command to build the frontend and start the Rust web server for development. Assumes Nix shell environment and 'just' build tool. ```bash nix-shell --run 'just web' ``` -------------------------------- ### Install Xcode Command Line Tools on macOS Source: https://github.com/winfunc/opcode/blob/main/README.md Installs the Xcode Command Line Tools on macOS, required for development. ```bash xcode-select --install ``` -------------------------------- ### Install pkg-config via Homebrew on macOS Source: https://github.com/winfunc/opcode/blob/main/README.md Installs pkg-config using Homebrew on macOS, a helper tool for managing compile flags. ```bash brew install pkg-config ``` -------------------------------- ### Backend Debug Tracing Source: https://github.com/winfunc/opcode/blob/main/web_server.design.md Example log messages from the Rust backend, illustrating trace-level output for WebSocket events, request parsing, process spawning, and message forwarding. ```text [TRACE] WebSocket handler started - session_id: uuid [TRACE] Successfully parsed request: {...} [TRACE] Claude process spawned successfully [TRACE] Forwarding message to WebSocket: {...} [TRACE] DOM event received: claude-output {...} [TRACE] handleStreamMessage - message type: assistant ``` -------------------------------- ### Agent File Format Example Source: https://github.com/winfunc/opcode/blob/main/cc_agents/README.md This JSON structure defines the format for exporting and importing Opcode agents. Ensure your agent configuration adheres to this schema, including versioning and model selection. ```json { "version": 1, "exported_at": "2025-01-23T14:29:58.156063+00:00", "agent": { "name": "Your Agent Name", "icon": "bot", "model": "opus|sonnet|haiku", "system_prompt": "Your agent's instructions...", "default_task": "Default task description" } } ``` -------------------------------- ### Get Usage Statistics by Date Range Source: https://context7.com/winfunc/opcode/llms.txt Fetches usage statistics filtered by a specific date range. Requires start and end dates in ISO format. ```typescript import { api } from './lib/api'; const stats = await api.getUsageByDateRange( "2024-01-01T00:00:00Z", // Start date (ISO format) "2024-01-31T23:59:59Z" // End date (ISO format) ); console.log(`January 2024 total: $${stats.total_cost.toFixed(2)}`); ``` -------------------------------- ### Get All Usage Statistics Source: https://context7.com/winfunc/opcode/llms.txt Retrieves comprehensive usage statistics across all projects. Includes total costs, tokens, and breakdowns by model and date. ```typescript import { api, UsageStats } from './lib/api'; const stats: UsageStats = await api.getUsageStats(); console.log(`Total cost: $${stats.total_cost.toFixed(2)}`); console.log(`Total tokens: ${stats.total_tokens.toLocaleString()}`); console.log(` Input: ${stats.total_input_tokens.toLocaleString()}`); console.log(` Output: ${stats.total_output_tokens.toLocaleString()}`); console.log(` Cache read: ${stats.total_cache_read_tokens.toLocaleString()}`); console.log(`Sessions: ${stats.total_sessions}`); // Usage by model stats.by_model.forEach(model => { console.log(` ${model.model}:`); console.log(` Cost: $${model.total_cost.toFixed(2)}`); console.log(` Sessions: ${model.session_count}`); }); // Usage by date stats.by_date.forEach(day => { console.log(`${day.date}: $${day.total_cost.toFixed(2)} (${day.models_used.join(', ')})`); }); ``` -------------------------------- ### Manage CLAUDE.md System Prompts Source: https://context7.com/winfunc/opcode/llms.txt Handles CLAUDE.md system prompt files across projects. Supports getting, saving, finding, reading, and updating global and specific prompt files. ```typescript import { api, ClaudeMdFile } from './lib/api'; // Get global system prompt const globalPrompt = await api.getSystemPrompt(); console.log('Global CLAUDE.md:', globalPrompt); // Save global system prompt await api.saveSystemPrompt("Updated system prompt content"); // Find all CLAUDE.md files in a project const claudeFiles: ClaudeMdFile[] = await api.findClaudeMdFiles("/Users/dev/project"); claudeFiles.forEach(file => { console.log(`${file.relative_path} (${file.size} bytes)`); }); // Read specific CLAUDE.md const content = await api.readClaudeMdFile(claudeFiles[0].absolute_path); // Save specific CLAUDE.md await api.saveClaudeMdFile(claudeFiles[0].absolute_path, "Updated content"); ``` -------------------------------- ### CC Agents API - Get Agent Run with Metrics Source: https://context7.com/winfunc/opcode/llms.txt Retrieves details of an agent run, including real-time metrics calculated from its output. ```APIDOC ## CC Agents API - Get Agent Run with Metrics ### Description Gets an agent run with real-time metrics calculated from JSONL output. ### Method GET ### Endpoint /agents/runs/{runId} ### Parameters #### Path Parameters - **runId** (string) - Required - The ID of the agent run. ### Response #### Success Response (200) - **run** (object) - The agent run object with metrics. - **id** (string) - The run ID. - **status** (string) - The status of the run (pending, running, completed, failed, cancelled). - **model** (string) - The model used. - **task** (string) - The task performed. - **metrics** (object) - Calculated metrics. - **duration_ms** (number) - Duration in milliseconds. - **total_tokens** (number) - Total tokens processed. - **cost_usd** (number) - Estimated cost in USD. - **message_count** (number) - Number of messages. ### Request Example ```typescript const run: AgentRunWithMetrics = await api.getAgentRunWithRealTimeMetrics(runId); ``` ``` -------------------------------- ### Execute New Claude Code Session with Streaming Output Source: https://context7.com/winfunc/opcode/llms.txt Starts a new Claude Code session, listening for real-time streaming JSON output and completion events. Requires event listeners for 'claude-output' and 'claude-complete'. ```typescript import { api } from './lib/api'; import { listen } from '@tauri-apps/api/event'; // Listen for streaming output const unlisten = await listen('claude-output', (event) => { const message = JSON.parse(event.payload); console.log('Claude:', message); }); // Listen for completion const unlistenComplete = await listen('claude-complete', (event) => { console.log('Session completed:', event.payload); unlisten(); unlistenComplete(); }); // Start a new session await api.executeClaudeCode( "/Users/dev/my-project", // Project path "Create a new React component for user authentication", // Prompt "sonnet" // Model: sonnet, opus, or haiku ); ``` -------------------------------- ### Get Checkpoint Differences Source: https://context7.com/winfunc/opcode/llms.txt Compares two checkpoints to identify file changes between them. Returns token delta, added files, deleted files, and modified files with their respective additions and deletions. ```typescript import { api, CheckpointDiff } from './lib/api'; const diff: CheckpointDiff = await api.getCheckpointDiff( "checkpoint-1-id", // From "checkpoint-2-id", // To "session-id", "project-id" ); console.log(`Token delta: ${diff.tokenDelta}`); console.log('Added files:', diff.addedFiles); console.log('Deleted files:', diff.deletedFiles); diff.modifiedFiles.forEach(file => { console.log(`${file.path}: +${file.additions} -${file.deletions}`); }); ``` -------------------------------- ### Fork a session from a Checkpoint Source: https://context7.com/winfunc/opcode/llms.txt Creates a new session branch starting from a specified checkpoint. Requires the checkpoint ID, original session details, project details, a new session ID, and a description for the new branch. ```typescript import { api } from './lib/api'; import { v4 as uuidv4 } from 'uuid'; const newSessionId = uuidv4(); const result = await api.forkFromCheckpoint( "checkpoint-uuid", "original-session-id", "-Users-dev-project", "/Users/dev/project", newSessionId, "Experimental branch for new feature" ); console.log(`Forked to new session: ${newSessionId}`); ``` -------------------------------- ### Build Universal Binary for macOS Source: https://github.com/winfunc/opcode/blob/main/README.md Builds a universal binary for macOS that supports both Intel and Apple Silicon architectures. ```bash bun run tauri build --target universal-apple-darwin ``` -------------------------------- ### Run Built Executable Source: https://github.com/winfunc/opcode/blob/main/README.md Execute the compiled application directly from the release directory. Ensure you are in the correct directory before running. ```bash # Run the built executable directly # Linux/macOS ./src-tauri/target/release/opcode # Windows ./src-tauri/target/release/opcode.exe ``` -------------------------------- ### Build Opcode for Production Source: https://github.com/winfunc/opcode/blob/main/README.md Builds the Opcode application for production. The executable will be located in `src-tauri/target/release/`. ```bash # Build the application bun run tauri build # The built executable will be in: # - Linux: src-tauri/target/release/ # - macOS: src-tauri/target/release/ # - Windows: src-tauri/target/release/ ``` -------------------------------- ### Get Session Usage Statistics Source: https://context7.com/winfunc/opcode/llms.txt Retrieves usage statistics grouped by session, with optional date filtering and ordering. Dates should be in YYYYMMDD format. ```typescript import { api, ProjectUsage } from './lib/api'; const sessions: ProjectUsage[] = await api.getSessionStats( "20240101", // Since (YYYYMMDD) "20240131", // Until (YYYYMMDD) "desc" // Order: 'asc' or 'desc' ); sessions.forEach(session => { console.log(`${session.project_name}: $${session.total_cost.toFixed(2)}`); console.log(` Last used: ${session.last_used}`); }); ``` -------------------------------- ### List Projects with Session Metadata Source: https://context7.com/winfunc/opcode/llms.txt Lists all projects in the ~/.claude/projects directory. Includes session IDs, creation timestamps, and the most recent session timestamp if available. ```typescript import { api } from './lib/api'; // List all projects const projects = await api.listProjects(); // Response structure interface Project { id: string; // Directory name (encoded path) path: string; // Original project path sessions: string[]; // Session IDs (UUID) created_at: number; // Unix timestamp most_recent_session?: number; // Most recent session timestamp } // Example output console.log(projects); // [ // { // id: "-Users-dev-my-project", // path: "/Users/dev/my-project", // sessions: ["abc123-def456-ப்படாத", "xyz789-ப்படாத"] // created_at: 1704067200, // most_recent_session: 1704153600 // } // ] ``` -------------------------------- ### Build Opcode for Development Source: https://github.com/winfunc/opcode/blob/main/README.md Builds the Opcode application for development purposes, enabling hot reloading for faster iteration. ```bash bun run tauri dev ``` -------------------------------- ### Create a Checkpoint Source: https://context7.com/winfunc/opcode/llms.txt Creates a checkpoint for a given session and project, capturing the current state. Optional parameters include message index and a description. ```typescript import { api, CheckpointResult } from './lib/api'; const result: CheckpointResult = await api.createCheckpoint( "abc123-session-id", // Session ID "-Users-dev-project", // Project ID "/Users/dev/project", // Project path 10, // Message index (optional) "Before major refactoring" // Description (optional) ); console.log(`Created checkpoint: ${result.checkpoint.id}`); console.log(`Files processed: ${result.filesProcessed}`); console.log(`Snapshot size: ${result.checkpoint.metadata.snapshotSize} bytes`); ``` -------------------------------- ### Configure Claude Code Hooks Source: https://context7.com/winfunc/opcode/llms.txt Manages Claude Code hooks for custom automation. Supports getting, updating, validating, and merging hooks configurations for user, project, and local scopes. ```typescript import { api, HooksConfiguration } from './lib/api'; // Get hooks for a scope const userHooks = await api.getHooksConfig('user'); const projectHooks = await api.getHooksConfig('project', '/Users/dev/project'); const localHooks = await api.getHooksConfig('local', '/Users/dev/project'); // Update hooks const hooks: HooksConfiguration = { PreToolUse: [{ matcher: { tool_name: "Bash" }, hooks: [{ type: "command", command: "echo 'Running bash command'" }] }], PostToolUse: [{ matcher: { tool_name: "Write" }, hooks: [{ type: "command", command: "git add $FILE_PATH" }] }] }; await api.updateHooksConfig('project', hooks, '/Users/dev/project'); // Validate hook command syntax const validation = await api.validateHookCommand("echo 'test'"); console.log(`Valid: ${validation.valid}, Message: ${validation.message}`); // Get merged hooks (respecting priority: local > project > user) const mergedHooks = await api.getMergedHooksConfig('/Users/dev/project'); ``` -------------------------------- ### Import MCP servers from Claude Desktop configuration Source: https://context7.com/winfunc/opcode/llms.txt Imports MCP servers from an existing Claude Desktop configuration. Specify the scope for the import. ```typescript import { api } from './lib/api'; const importResult = await api.mcpAddFromClaudeDesktop("local"); console.log(`Imported: ${importResult.imported_count}`); console.log(`Failed: ${importResult.failed_count}`); importResult.servers.forEach(server => { if (server.success) { console.log(`✓ ${server.name}`); } else { console.log(`✗ ${server.name}: ${server.error}`); } }); ``` -------------------------------- ### Build with Limited Parallel Jobs Source: https://github.com/winfunc/opcode/blob/main/README.md Builds the project using only two parallel jobs to mitigate 'out of memory' errors during compilation. ```bash cargo build -j 2 ``` -------------------------------- ### List, Create, and Delete Slash Commands Source: https://context7.com/winfunc/opcode/llms.txt Manage slash commands for your project. Ensure the API is imported and the project path is correctly specified. ```typescript import { api, SlashCommand } from './lib/api'; // List all slash commands const commands: SlashCommand[] = await api.slashCommandsList('/Users/dev/project'); commands.forEach(cmd => { console.log(`${cmd.full_command} - ${cmd.description}`); console.log(` Scope: ${cmd.scope}`); console.log(` Has bash: ${cmd.has_bash_commands}`); console.log(` Has file refs: ${cmd.has_file_references}`); }); // Create/update a slash command const newCommand = await api.slashCommandSave( 'project', 'optimize', 'frontend', `# Optimize Component Analyze and optimize the React component at $ARGUMENTS for: - Performance - Bundle size - Re-render reduction`, 'Optimize a React component', ['Read', 'Write', 'Grep'], '/Users/dev/project' ); console.log(`Created: ${newCommand.full_command}`); // Delete a slash command await api.slashCommandDelete(newCommand.id, '/Users/dev/project'); ``` -------------------------------- ### Get CC Agent Run with Metrics Source: https://context7.com/winfunc/opcode/llms.txt Retrieves details of a CC Agent run, including its status, model, task, and calculated metrics such as duration, token count, cost, and message count. Metrics are derived from the agent's JSONL output. ```typescript import { api, AgentRunWithMetrics } from './lib/api'; const run: AgentRunWithMetrics = await api.getAgentRunWithRealTimeMetrics(runId); console.log(`Run ID: ${run.id}`); console.log(`Status: ${run.status}`); // pending, running, completed, failed, cancelled console.log(`Model: ${run.model}`); console.log(`Task: ${run.task}`); if (run.metrics) { console.log(`Duration: ${run.metrics.duration_ms}ms`); console.log(`Tokens: ${run.metrics.total_tokens}`); console.log(`Cost: $${run.metrics.cost_usd?.toFixed(4)}`); console.log(`Messages: ${run.metrics.message_count}`); } ``` -------------------------------- ### Clone Opcode Repository Source: https://github.com/winfunc/opcode/blob/main/README.md Clones the Opcode project repository from GitHub and navigates into the project directory. ```bash git clone https://github.com/getAsterisk/opcode.git cd opcode ``` -------------------------------- ### Retrieve Project Sessions with First Message Preview Source: https://context7.com/winfunc/opcode/llms.txt Retrieves all sessions for a specific project, including the first message content. Useful for quickly previewing conversation history. ```typescript import { api, Session } from './lib/api'; // Get sessions for a project const sessions: Session[] = await api.getProjectSessions("-Users-dev-my-project"); // Response structure interface Session { id: string; // UUID session ID project_id: string; // Parent project ID project_path: string; // Decoded project path todo_data?: any; // Associated todo data created_at: number; // Unix timestamp first_message?: string; // First user message content message_timestamp?: string; // Timestamp of first message } // Example: Display session list sessions.forEach(session => { console.log(`Session: ${session.id}`); console.log(`Started: ${new Date(session.created_at * 1000).toISOString()}`); console.log(`First message: ${session.first_message?.substring(0, 100)}...`); }); ``` -------------------------------- ### Settings & Configuration API Source: https://context7.com/winfunc/opcode/llms.txt APIs for managing Claude settings and CLAUDE.md files. ```APIDOC ## Claude Settings API ### Description APIs for reading and writing Claude Code settings. ### Method GET, PUT ### Endpoints - GET /winfunc/opcode/settings/claude - PUT /winfunc/opcode/settings/claude ### Request Example (GET) ```typescript import { api, ClaudeSettings } from './lib/api'; // Get current settings const settings: ClaudeSettings = await api.getClaudeSettings(); console.log(settings); ``` ### Request Example (PUT) ```typescript import { api, ClaudeSettings } from './lib/api'; // Update settings const settings: ClaudeSettings = await api.getClaudeSettings(); settings['preferredModel'] = 'opus'; await api.saveClaudeSettings(settings); ``` ``` ```APIDOC ## CLAUDE.md Management API ### Description Manage CLAUDE.md system prompt files across projects. ### Method GET, POST, PUT ### Endpoints - GET /winfunc/opcode/claude-md/system-prompt - POST /winfunc/opcode/claude-md/system-prompt - GET /winfunc/opcode/claude-md/files - GET /winfunc/opcode/claude-md/read - PUT /winfunc/opcode/claude-md/save ### Request Example (Get Global System Prompt) ```typescript import { api } from './lib/api'; // Get global system prompt const globalPrompt = await api.getSystemPrompt(); console.log('Global CLAUDE.md:', globalPrompt); ``` ### Request Example (Save Global System Prompt) ```typescript import { api } from './lib/api'; // Save global system prompt await api.saveSystemPrompt("Updated system prompt content"); ``` ### Request Example (Find CLAUDE.md Files) ```typescript import { api, ClaudeMdFile } from './lib/api'; // Find all CLAUDE.md files in a project const claudeFiles: ClaudeMdFile[] = await api.findClaudeMdFiles("/Users/dev/project"); claudeFiles.forEach(file => { console.log(`${file.relative_path} (${file.size} bytes)`); }); ``` ### Request Example (Read Specific CLAUDE.md) ```typescript import { api } from './lib/api'; // Assuming claudeFiles is populated from findClaudeMdFiles // const content = await api.readClaudeMdFile(claudeFiles[0].absolute_path); ``` ### Request Example (Save Specific CLAUDE.md) ```typescript import { api } from './lib/api'; // Assuming claudeFiles is populated from findClaudeMdFiles // await api.saveClaudeMdFile(claudeFiles[0].absolute_path, "Updated content"); ``` ``` ```APIDOC ## Hooks Configuration API ### Description Manage Claude Code hooks for custom automation. ### Method GET, PUT, POST ### Endpoints - GET /winfunc/opcode/hooks/{scope} - PUT /winfunc/opcode/hooks/{scope} - POST /winfunc/opcode/hooks/validate-command - GET /winfunc/opcode/hooks/merged/{projectPath} ### Query Parameters - **scope** (string) - Required - The scope of the hooks (e.g., 'user', 'project', 'local'). - **projectPath** (string) - Optional - The path to the project for project or local scope. ### Request Body (PUT /winfunc/opcode/hooks/{scope}) - **hooks** (HooksConfiguration) - Required - The hooks configuration object. - **PreToolUse** (Array) - Hooks to run before tool use. - **matcher** (Object) - Criteria for matching a tool. - **tool_name** (string) - The name of the tool. - **hooks** (Array) - The list of hooks to execute. - **type** (string) - The type of hook (e.g., 'command'). - **command** (string) - The command to execute. - **PostToolUse** (Array) - Hooks to run after tool use. - **matcher** (Object) - Criteria for matching a tool. - **tool_name** (string) - The name of the tool. - **hooks** (Array) - The list of hooks to execute. - **type** (string) - The type of hook (e.g., 'command'). - **command** (string) - The command to execute. ### Response (POST /winfunc/opcode/hooks/validate-command) #### Success Response (200) - **valid** (boolean) - Indicates if the command syntax is valid. - **message** (string) - A message providing details about the validation. ### Request Example (GET Hooks) ```typescript import { api, HooksConfiguration } from './lib/api'; // Get hooks for a scope const userHooks = await api.getHooksConfig('user'); const projectHooks = await api.getHooksConfig('project', '/Users/dev/project'); const localHooks = await api.getHooksConfig('local', '/Users/dev/project'); ``` ### Request Example (UPDATE Hooks) ```typescript import { api, HooksConfiguration } from './lib/api'; const hooks: HooksConfiguration = { PreToolUse: [{ matcher: { tool_name: "Bash" }, hooks: [{ type: "command", command: "echo 'Running bash command'" }] }], PostToolUse: [{ matcher: { tool_name: "Write" }, hooks: [{ type: "command", command: "git add $FILE_PATH" }] }] }; await api.updateHooksConfig('project', hooks, '/Users/dev/project'); ``` ### Request Example (Validate Hook Command) ```typescript import { api } from './lib/api'; // Validate hook command syntax const validation = await api.validateHookCommand("echo 'test'"); console.log(`Valid: ${validation.valid}, Message: ${validation.message}`); ``` ### Request Example (Get Merged Hooks) ```typescript import { api } from './lib/api'; // Get merged hooks (respecting priority: local > project > user) const mergedHooks = await api.getMergedHooksConfig('/Users/dev/project'); ``` ``` -------------------------------- ### Create CC Agent Source: https://context7.com/winfunc/opcode/llms.txt Creates a new CC Agent with a specified name, icon, system prompt, default task, model, and optional hooks configuration. The system prompt defines the agent's behavior and constraints. ```typescript import { api, Agent } from './lib/api'; // Create a new agent const agent: Agent = await api.createAgent( "Code Reviewer", // Name "search", // Icon (lucide icon name) `You are a senior code reviewer. Analyze code for: - Security vulnerabilities - Performance issues - Code style and best practices - Potential bugs`, // System prompt "Review the codebase for issues", // Default task (optional) "sonnet", // Model JSON.stringify({ PreToolUse: [{ matcher: { tool_name: "Write" }, hooks: [{ type: "command", command: "echo 'File being written: $TOOL_INPUT'" }] }] }) ); console.log(`Created agent: ${agent.name} (ID: ${agent.id})`); ``` -------------------------------- ### Monitor Server Logs Source: https://github.com/winfunc/opcode/blob/main/web_server.design.md Monitors server logs in real-time. Use this command to observe backend activity and potential errors. ```bash # Monitor server logs tail -f server.log # if logging to file ``` -------------------------------- ### List Configured CC Agents Source: https://context7.com/winfunc/opcode/llms.txt Lists all configured CC Agents, displaying their icon, name, model, and creation timestamp. This is useful for retrieving agent details before execution. ```typescript import { api, Agent } from './lib/api'; const agents: Agent[] = await api.listAgents(); agents.forEach(agent => { console.log(`${agent.icon} ${agent.name}`); console.log(` Model: ${agent.model}`); console.log(` Created: ${agent.created_at}`); }); ``` -------------------------------- ### Create New Project Entry Source: https://context7.com/winfunc/opcode/llms.txt Creates a new project entry in the system for a given directory path. The ID is derived from the encoded path. ```typescript import { api } from './lib/api'; // Create a new project const newProject = await api.createProject("/Users/dev/new-project"); console.log(`Created project: ${newProject.id}`); // Output: Created project: -Users-dev-new-project ``` -------------------------------- ### Build Opcode with Debug Flags Source: https://github.com/winfunc/opcode/blob/main/README.md Builds the Opcode application with debug flags enabled, resulting in faster compilation times but a larger binary size. ```bash bun run tauri build --debug ``` -------------------------------- ### Set Rust Cargo Bin Path Source: https://github.com/winfunc/opcode/blob/main/README.md Ensures the Rust Cargo bin directory is added to the system's PATH environment variable. Run this if 'cargo not found' errors occur. ```bash source ~/.cargo/env ``` -------------------------------- ### List all configured MCP servers Source: https://context7.com/winfunc/opcode/llms.txt Retrieves a list of all configured MCP servers. The output includes server name, transport type, command, scope, and active status. ```typescript import { api, MCPServer } from './lib/api'; const servers: MCPServer[] = await api.mcpList(); servers.forEach(server => { console.log(`${server.name} (${server.transport})`); console.log(` Command: ${server.command}`); console.log(` Scope: ${server.scope}`); console.log(` Active: ${server.is_active}`); }); ``` -------------------------------- ### Check Claude Binary Path Source: https://github.com/winfunc/opcode/blob/main/web_server.design.md Verifies if the 'claude' executable is available in the system's PATH. ```bash # Check Claude binary which claude ``` -------------------------------- ### Opcode Project Structure Source: https://github.com/winfunc/opcode/blob/main/README.md Overview of the Opcode project's directory layout, separating frontend (React) and backend (Rust/Tauri) code. ```tree opcode/ ├── src/ # React frontend │ ├── components/ # UI components │ ├── lib/ # API client & utilities │ └── assets/ # Static assets ├── src-tauri/ # Rust backend │ ├── src/ │ │ ├── commands/ # Tauri command handlers │ │ ├── checkpoint/ # Timeline management │ │ └── process/ # Process management │ └── tests/ # Rust test suite └── public/ # Public assets ``` -------------------------------- ### Fetch Sessions using Zustand Store Source: https://github.com/winfunc/opcode/blob/main/src/stores/README.md Demonstrates how to use the `useSessionStore` hook to fetch and display session data within a React component. Ensure the `fetchSessions` function is correctly implemented in your store to match the API. ```typescript import { useSessionStore } from '@/stores/sessionStore'; function MyComponent() { const { sessions, fetchSessions } = useSessionStore(); useEffect(() => { fetchSessions(); }, []); return
{sessions.length} sessions
; } ``` -------------------------------- ### Add MCP Server from JSON configuration Source: https://context7.com/winfunc/opcode/llms.txt Adds an MCP server using a JSON configuration string. The configuration includes transport type, command, arguments, and environment variables. ```typescript import { api } from './lib/api'; const jsonConfig = JSON.stringify({ type: "stdio", command: "node", args: ["./mcp-server/index.js"], env: { "NODE_ENV": "production" } }); const result = await api.mcpAddJson("custom-server", jsonConfig, "project"); ``` -------------------------------- ### List Checkpoints for a session Source: https://context7.com/winfunc/opcode/llms.txt Retrieves a list of all checkpoints associated with a specific session and project. Output includes checkpoint ID, description, message index, token count, and file changes. ```typescript import { api, Checkpoint } from './lib/api'; const checkpoints: Checkpoint[] = await api.listCheckpoints( "abc123-session-id", "-Users-dev-project", "/Users/dev/project" ); checkpoints.forEach(cp => { console.log(`${cp.id} - ${cp.description || 'No description'}`); console.log(` Message index: ${cp.messageIndex}`); console.log(` Tokens: ${cp.metadata.totalTokens}`); console.log(` File changes: ${cp.metadata.fileChanges}`); }); ``` -------------------------------- ### Execute CC Agent with Streaming Output Source: https://context7.com/winfunc/opcode/llms.txt Executes a specified CC Agent on a given project path with a defined task, streaming real-time output and completion events. It requires listening to specific event channels for output and completion. ```typescript import { api } from './lib/api'; import { listen } from '@tauri-apps/api/event'; const agentId = 1; const projectPath = "/Users/dev/my-project"; const task = "Review all TypeScript files for security issues"; // Listen for agent output (run_id specific) const runId = await api.executeAgent(agentId, projectPath, task, "sonnet"); const unlisten = await listen(`agent-output:${runId}`, (event) => { try { const msg = JSON.parse(event.payload); if (msg.type === 'assistant' && msg.message?.content) { console.log('Agent:', msg.message.content); } } catch (e) { console.log('Raw:', event.payload); } }); // Listen for completion await listen(`agent-complete:${runId}`, (event) => { console.log('Agent completed:', event.payload); unlisten(); }); console.log(`Started agent run: ${runId}`); ``` -------------------------------- ### CC Agents API - Create Agent Source: https://context7.com/winfunc/opcode/llms.txt Creates a new CC Agent with custom configuration including name, icon, system prompt, model, and optional hooks. ```APIDOC ## CC Agents API - Create Agent ### Description Creates a new CC Agent with custom configuration. ### Method POST ### Endpoint /agents ### Parameters #### Request Body - **name** (string) - Required - The name of the agent. - **icon** (string) - Required - The lucide icon name for the agent. - **system_prompt** (string) - Required - The system prompt defining the agent's behavior. - **default_task** (string) - Optional - The default task for the agent. - **model** (string) - Required - The model to be used by the agent (e.g., 'sonnet'). - **hooks** (string) - Optional - A JSON string representing the hooks configuration. ### Request Example ```typescript const agent: Agent = await api.createAgent( "Code Reviewer", // Name "search", // Icon (lucide icon name) `You are a senior code reviewer. Analyze code for: - Security vulnerabilities - Performance issues - Code style and best practices - Potential bugs`, "Review the codebase for issues", // Default task (optional) "sonnet", // Model JSON.stringify({ PreToolUse: [{ matcher: { tool_name: "Write" }, hooks: [{ type: "command", command: "echo 'File being written: $TOOL_INPUT'" }] }] }) ); ``` ### Response #### Success Response (200) - **agent** (object) - The created agent object. - **id** (string) - The unique identifier for the agent. - **name** (string) - The name of the agent. - **icon** (string) - The icon of the agent. - **model** (string) - The model used by the agent. - **created_at** (string) - The timestamp when the agent was created. ``` -------------------------------- ### CC Agents API - Execute Agent Source: https://context7.com/winfunc/opcode/llms.txt Executes a specified agent on a given project path with a task, streaming output in real-time. ```APIDOC ## CC Agents API - Execute Agent ### Description Executes an agent on a project with real-time output streaming. ### Method POST ### Endpoint /agents/{agentId}/execute ### Parameters #### Path Parameters - **agentId** (string) - Required - The ID of the agent to execute. #### Request Body - **projectPath** (string) - Required - The path to the project. - **task** (string) - Required - The task for the agent to perform. - **model** (string) - Required - The model to use for the execution. ### Request Example ```typescript const agentId = 1; const projectPath = "/Users/dev/my-project"; const task = "Review all TypeScript files for security issues"; const runId = await api.executeAgent(agentId, projectPath, task, "sonnet"); // Listen for agent output const unlistenOutput = await listen(`agent-output:${runId}`, (event) => { try { const msg = JSON.parse(event.payload); if (msg.type === 'assistant' && msg.message?.content) { console.log('Agent:', msg.message.content); } } catch (e) { console.log('Raw:', event.payload); } }); // Listen for completion await listen(`agent-complete:${runId}`, (event) => { console.log('Agent completed:', event.payload); unlistenOutput(); }); ``` ### Response #### Success Response (200) - **runId** (string) - The ID of the agent run. - **status** (string) - The initial status of the run (e.g., 'pending'). ``` -------------------------------- ### AppState Structure for Process Management Source: https://github.com/winfunc/opcode/blob/main/web_server.design.md Defines the AppState struct to manage active sessions and their associated processes. Ensures proper tracking of Tokio child processes. ```rust pub struct AppState { pub active_sessions: Arc>>>, pub active_processes: Arc>>, } ``` -------------------------------- ### Checkpoint & Timeline API Source: https://context7.com/winfunc/opcode/llms.txt APIs for managing session checkpoints, allowing versioning, restoration, and forking of session states. ```APIDOC ## POST /api/checkpoints/create ### Description Creates a checkpoint capturing the current session state and project files. ### Method POST ### Endpoint /api/checkpoints/create ### Parameters #### Request Body - **sessionId** (string) - Required - The ID of the session. - **projectId** (string) - Required - The ID of the project. - **projectPath** (string) - Required - The absolute path to the project directory. - **messageIndex** (integer) - Optional - An index for the message associated with the checkpoint. - **description** (string) - Optional - A description for the checkpoint. ### Response #### Success Response (200) - **checkpoint** (object) - The created checkpoint object. - **id** (string) - The unique ID of the checkpoint. - **metadata** (object) - Metadata about the checkpoint. - **snapshotSize** (integer) - The size of the snapshot in bytes. - **filesProcessed** (integer) - The number of files processed during checkpoint creation. #### Response Example ```json { "checkpoint": { "id": "chk-abc123xyz", "metadata": { "snapshotSize": 102400 } }, "filesProcessed": 50 } ``` ``` ```APIDOC ## GET /api/checkpoints/list ### Description Lists all checkpoints for a given session and project. ### Method GET ### Endpoint /api/checkpoints/list ### Parameters #### Query Parameters - **sessionId** (string) - Required - The ID of the session. - **projectId** (string) - Required - The ID of the project. - **projectPath** (string) - Required - The absolute path to the project directory. ### Response #### Success Response (200) - **checkpoints** (array) - An array of checkpoint objects. - **id** (string) - The unique ID of the checkpoint. - **messageIndex** (integer) - The message index associated with the checkpoint. - **description** (string) - The description of the checkpoint. - **metadata** (object) - Metadata about the checkpoint. - **totalTokens** (integer) - Total tokens consumed up to this checkpoint. - **fileChanges** (integer) - Number of file changes recorded. #### Response Example ```json [ { "id": "chk-abc123xyz", "messageIndex": 10, "description": "Before major refactoring", "metadata": { "totalTokens": 5000, "fileChanges": 25 } } ] ``` ``` ```APIDOC ## POST /api/checkpoints/restore ### Description Restores a session to a previous checkpoint state. ### Method POST ### Endpoint /api/checkpoints/restore ### Parameters #### Request Body - **checkpointId** (string) - Required - The ID of the checkpoint to restore. - **sessionId** (string) - Required - The ID of the session. - **projectId** (string) - Required - The ID of the project. - **projectPath** (string) - Required - The absolute path to the project directory. ### Response #### Success Response (200) - **checkpoint** (object) - The restored checkpoint object. - **id** (string) - The unique ID of the checkpoint. - **filesProcessed** (integer) - The number of files restored. - **warnings** (array) - An array of warnings encountered during restoration. #### Response Example ```json { "checkpoint": { "id": "chk-abc123xyz" }, "filesProcessed": 45, "warnings": [] } ``` ``` ```APIDOC ## POST /api/checkpoints/fork ### Description Creates a new session branch from an existing checkpoint. ### Method POST ### Endpoint /api/checkpoints/fork ### Parameters #### Request Body - **checkpointId** (string) - Required - The ID of the checkpoint to fork from. - **originalSessionId** (string) - Required - The ID of the original session. - **projectId** (string) - Required - The ID of the project. - **projectPath** (string) - Required - The absolute path to the project directory. - **newSessionId** (string) - Required - The ID for the new forked session. - **description** (string) - Optional - A description for the new forked session. ### Response #### Success Response (200) - **message** (string) - Confirmation message indicating the fork was successful. #### Response Example ```json { "message": "Successfully forked session experimental-branch from checkpoint chk-abc123xyz" } ``` ``` ```APIDOC ## GET /api/checkpoints/diff ### Description Compares two checkpoints to determine file changes between them. ### Method GET ### Endpoint /api/checkpoints/diff ### Parameters #### Query Parameters - **fromCheckpointId** (string) - Required - The ID of the starting checkpoint. - **toCheckpointId** (string) - Required - The ID of the ending checkpoint. - **sessionId** (string) - Required - The ID of the session. - **projectId** (string) - Required - The ID of the project. ### Response #### Success Response (200) - **tokenDelta** (integer) - The difference in token count between the two checkpoints. - **addedFiles** (array) - A list of files added between the checkpoints. - **deletedFiles** (array) - A list of files deleted between the checkpoints. - **modifiedFiles** (array) - A list of modified files. - **path** (string) - The path of the modified file. - **additions** (integer) - Number of lines added. - **deletions** (integer) - Number of lines deleted. #### Response Example ```json { "tokenDelta": 1500, "addedFiles": ["new_feature.py"], "deletedFiles": ["old_code.js"], "modifiedFiles": [ { "path": "main.py", "additions": 10, "deletions": 5 } ] } ``` ``` -------------------------------- ### Add MCP Server with stdio transport Source: https://context7.com/winfunc/opcode/llms.txt Adds a new MCP server using the stdio transport. Requires server name, transport type, command, arguments, environment variables, and scope. ```typescript import { api } from './lib/api'; // Add a stdio-based MCP server const result = await api.mcpAdd( "my-mcp-server", // Server name "stdio", // Transport: "stdio" or "sse" "npx", // Command ["-y", "@modelcontextprotocol/server-filesystem", "/Users/dev"], // Args { "DEBUG": "true" }, // Environment variables undefined, // URL (for SSE transport) "local" // Scope: "local", "project", or "user" ); if (result.success) { console.log(`Added server: ${result.server_name}`); } else { console.error(`Failed: ${result.message}`); } ``` -------------------------------- ### Interact with Storage API Source: https://context7.com/winfunc/opcode/llms.txt Access and manage data within the application's storage. Use `storageExecuteSql` for read-only operations to ensure data integrity. ```typescript import { api } from './lib/api'; // List all database tables const tables = await api.storageListTables(); console.log('Tables:', tables.map(t => t.name)); // Read table data with pagination const agents = await api.storageReadTable('agents', 1, 50, 'reviewer'); console.log(`Found ${agents.total} agents matching 'reviewer'`); // Execute raw SQL (read-only recommended) const result = await api.storageExecuteSql( "SELECT name, model, created_at FROM agents ORDER BY created_at DESC LIMIT 5" ); console.log(result); // App settings helpers const theme = await api.getSetting('theme'); await api.saveSetting('theme', 'dark'); ``` -------------------------------- ### CC Agents API - List Agents Source: https://context7.com/winfunc/opcode/llms.txt Lists all configured CC Agents. ```APIDOC ## CC Agents API - List Agents ### Description Lists all configured agents. ### Method GET ### Endpoint /agents ### Response #### Success Response (200) - **agents** (array) - An array of agent objects. - **id** (string) - The unique identifier for the agent. - **name** (string) - The name of the agent. - **icon** (string) - The icon of the agent. - **model** (string) - The model used by the agent. - **created_at** (string) - The timestamp when the agent was created. ### Request Example ```typescript const agents: Agent[] = await api.listAgents(); ``` ```