Skip to content

API Reference

Mo Abualruz edited this page Dec 15, 2025 · 4 revisions

API Reference

Status: ✅ Complete

Last Updated: December 5, 2025


Overview

This document provides comprehensive API reference documentation for RiceCoder. It covers all public APIs, data structures, and interfaces available for programmatic use.

Table of Contents


CLI API

Commands

rice init

Initialize a new RiceCoder project.

Usage:

rice init [OPTIONS] [PATH]

Arguments:

  • PATH - Project directory (default: current directory)

Options:

  • --template <TEMPLATE> - Project template to use
  • --language <LANGUAGE> - Primary language for the project
  • --force - Overwrite existing configuration

Example:

rice init --template rust --language rust

Returns: Project initialized with .agent/ directory and default configuration


rice chat

Start interactive chat session.

Usage:

rice chat [OPTIONS]

Options:

  • --session <SESSION> - Session name (default: new session)
  • --mode <MODE> - Chat mode (code, ask, vibe, think-more)
  • --provider <PROVIDER> - AI provider to use
  • --model <MODEL> - AI model to use
  • --offline - Use offline mode (local models only)

Example:

rice chat --mode code --provider openai --model gpt-4

Returns: Interactive chat interface


rice gen

Generate code from specification.

Usage:

rice gen [OPTIONS] --spec <SPEC>

Options:

  • --spec <SPEC> - Specification file or name (required)
  • --preview - Preview changes without applying
  • --auto-approve - Automatically approve changes
  • --output <OUTPUT> - Output directory
  • --force - Overwrite existing files

Example:

rice gen --spec my-feature --preview
rice gen --spec my-feature --auto-approve

Returns: Generated code with diff preview or applied changes


rice review

Review code with AI assistance.

Usage:

rice review [OPTIONS] <FILE>

Arguments:

  • FILE - File to review

Options:

  • --focus <FOCUS> - Review focus (quality, security, performance, style)
  • --detailed - Provide detailed review
  • --suggestions - Include improvement suggestions

Example:

rice review src/main.rs --focus security --detailed

Returns: Code review with findings and suggestions


rice config

Manage configuration.

Usage:

rice config <COMMAND> [OPTIONS]

Commands:

  • show - Display current configuration
  • set <KEY> <VALUE> - Set configuration value
  • get <KEY> - Get configuration value
  • reset - Reset to defaults
  • validate - Validate configuration
  • init - Initialize default configuration

Example:

rice config set provider openai
rice config set model gpt-4
rice config show

Returns: Configuration value or status


rice spec

Manage specifications.

Usage:

rice spec <COMMAND> [OPTIONS]

Commands:

  • create <NAME> - Create new specification
  • list - List all specifications
  • show <NAME> - Display specification
  • validate <NAME> - Validate specification
  • delete <NAME> - Delete specification

Example:

rice spec create my-feature
rice spec list
rice spec validate my-feature

Returns: Specification or list of specifications


rice session

Manage sessions.

Usage:

rice session <COMMAND> [OPTIONS]

Commands:

  • list - List all sessions
  • show <NAME> - Display session
  • save <NAME> - Save current session
  • load <NAME> - Load session
  • delete <NAME> - Delete session
  • cleanup - Clean up old sessions

Example:

rice session list
rice session save my-session
rice session load my-session

Returns: Session information or list of sessions


rice lsp

Manage LSP (Language Server Protocol).

Usage:

rice lsp <COMMAND> [OPTIONS]

Commands:

  • start - Start LSP server
  • stop - Stop LSP server
  • status - Show LSP status
  • logs - Show LSP logs
  • config - Show LSP configuration

Example:

rice lsp start
rice lsp status
rice lsp logs

Returns: LSP status or logs


rice completion

Manage code completion.

Usage:

rice completion <COMMAND> [OPTIONS]

Commands:

  • enable - Enable code completion
  • disable - Disable code completion
  • status - Show completion status
  • config - Show completion configuration

Example:

rice completion enable
rice completion status

Returns: Completion status or configuration


rice hooks

Manage hooks.

Usage:

rice hooks <COMMAND> [OPTIONS]

Commands:

  • list - List all hooks
  • show <NAME> - Display hook
  • enable <NAME> - Enable hook
  • disable <NAME> - Disable hook
  • test <NAME> - Test hook
  • logs - Show hook logs

Example:

rice hooks list
rice hooks enable my-hook
rice hooks test my-hook

Returns: Hook information or list of hooks


Configuration API

Configuration Structure

# Global configuration (~/.ricecoder/config.yaml)
ricecoder:
  version: "0.1.4"
  
  # AI Provider configuration
  provider:
    name: "openai"  # openai, anthropic, ollama, etc.
    model: "gpt-4"
    api_key: "${OPENAI_API_KEY}"
    timeout_ms: 30000
    
  # Ollama configuration (for local models)
  ollama:
    url: "http://localhost:11434"
    model: "mistral"
    
  # Project configuration
  project:
    language: "rust"
    template: "rust-cli"
    
  # LSP configuration
  lsp:
    enabled: true
    servers:
      rust: "rust-analyzer"
      typescript: "typescript-language-server"
      python: "pylsp"
      
  # Completion configuration
  completion:
    enabled: true
    context_lines: 50
    max_suggestions: 10
    
  # Hooks configuration
  hooks:
    enabled: true
    directory: ".agent/hooks"
    
  # Storage configuration
  storage:
    cache_dir: "~/.ricecoder/cache"
    session_dir: "~/.ricecoder/sessions"
    log_dir: "~/.ricecoder/logs"

Configuration Methods

Get Configuration Value

rice config get provider.name
rice config get provider.model

Set Configuration Value

rice config set provider.name openai
rice config set provider.model gpt-4

Reset Configuration

rice config reset

Validate Configuration

rice config validate

Session API

Session Structure

{
  "id": "session-uuid",
  "name": "my-session",
  "created_at": "2025-12-05T10:30:00Z",
  "updated_at": "2025-12-05T10:35:00Z",
  "mode": "code",
  "provider": "openai",
  "model": "gpt-4",
  "messages": [
    {
      "id": "msg-uuid",
      "role": "user",
      "content": "Generate a Rust function",
      "timestamp": "2025-12-05T10:30:00Z"
    },
    {
      "id": "msg-uuid",
      "role": "assistant",
      "content": "Here's a Rust function...",
      "timestamp": "2025-12-05T10:30:05Z"
    }
  ],
  "metadata": {
    "project": "/path/to/project",
    "language": "rust"
  }
}

Session Methods

List Sessions

rice session list

Returns: Array of session objects

Get Session

rice session show my-session

Returns: Session object

Create Session

rice session save my-session

Returns: Session object with ID

Delete Session

rice session delete my-session

Returns: Success status

Load Session

rice session load my-session

Returns: Session loaded and ready for use


Spec API

Specification Structure

# Specification file (.agent/specs/my-feature/requirements.md)
---
title: "My Feature"
description: "Feature description"
version: "1.0.0"
---

## Requirements

### Requirement 1

**User Story**: As a user, I want...

#### Acceptance Criteria

1. WHEN ... THEN ...
2. WHILE ... THEN ...

Spec Methods

Create Specification

rice spec create my-feature

Returns: Specification created with template files

List Specifications

rice spec list

Returns: Array of specification names

Get Specification

rice spec show my-feature

Returns: Specification content

Validate Specification

rice spec validate my-feature

Returns: Validation results

Delete Specification

rice spec delete my-feature

Returns: Success status


Generation API

Generation Request

{
  "spec": "my-feature",
  "output_dir": "src/",
  "language": "rust",
  "auto_approve": false,
  "preview": true
}

Generation Response

{
  "id": "gen-uuid",
  "status": "completed",
  "files": [
    {
      "path": "src/lib.rs",
      "action": "create",
      "diff": "...",
      "approved": false
    }
  ],
  "summary": "Generated 3 files"
}

Generation Methods

Generate Code

rice gen --spec my-feature --preview

Returns: Generation result with diffs

Auto-Approve Generation

rice gen --spec my-feature --auto-approve

Returns: Generation result with applied changes


Refactoring API

Refactoring Request

{
  "id": "refactor-uuid",
  "refactoring_type": "Rename",
  "target": {
    "file": "src/main.rs",
    "symbol": "old_name",
    "range": null
  },
  "options": {
    "preview": true,
    "auto_approve": false
  }
}

Refactoring Response

{
  "id": "refactor-uuid",
  "status": "completed",
  "success": true,
  "impact": {
    "affected_files": ["src/main.rs", "src/lib.rs"],
    "affected_symbols": ["old_name", "call_site_1", "call_site_2"],
    "risk_level": "low",
    "estimated_effort": "low"
  },
  "diff": {
    "format": "unified",
    "hunks": [
      {
        "file": "src/main.rs",
        "content": "--- a/src/main.rs\n+++ b/src/main.rs\n@@ -1,3 +1,3 @@\n-fn old_name() {}\n+fn new_name() {}\n"
      }
    ]
  },
  "backup_info": {
    "path": "~/.ricecoder/backups/refactor-uuid",
    "created_at": "2025-12-05T10:30:00Z"
  }
}

Refactoring Methods

Preview Refactoring

rice refactor preview --type Rename --file src/main.rs --symbol old_name --new-name new_name

Returns: Refactoring preview with impact analysis and diff

Execute Refactoring

rice refactor execute --type Rename --file src/main.rs --symbol old_name --new-name new_name

Returns: Refactoring result with applied changes

Analyze Impact

rice refactor analyze --type Rename --file src/main.rs --symbol old_name

Returns: Impact analysis with affected files and symbols

Rollback Refactoring

rice refactor rollback --backup-id refactor-uuid

Returns: Rollback status

Refactoring Configuration

refactoring:
  enabled: true
  
  # Language-specific configurations
  languages:
    rust:
      enabled: true
      rules:
        - name: "unused_variable"
          pattern: "let \\w+ = .*;"
          refactoring_type: "RemoveUnused"
          enabled: true
    
    typescript:
      enabled: true
      rules:
        - name: "unused_import"
          pattern: "import .* from .*;"
          refactoring_type: "RemoveUnused"
          enabled: true
    
    python:
      enabled: true
      rules:
        - name: "unused_variable"
          pattern: "\\w+ = .*"
          refactoring_type: "RemoveUnused"
          enabled: true
  
  # Backup configuration
  backup:
    enabled: true
    directory: "~/.ricecoder/backups"
    retention_days: 30
  
  # Validation configuration
  validation:
    enabled: true
    run_tests: true
    check_syntax: true

Refactoring Types

Type Description Example
Rename Rename a symbol Rename function from foo to bar
Extract Extract code into new function Extract code block into separate method
Inline Inline a function or variable Inline function call
Move Move symbol to different location Move function to different module
ChangeSignature Modify function signature Add/remove parameters
RemoveUnused Remove unused code Remove unused variables or imports
Simplify Simplify code structures Simplify conditional logic

Refactoring Patterns

List Patterns

rice refactor patterns list

Returns: Array of available patterns

Get Pattern

rice refactor patterns show rename_function

Returns: Pattern object with template and parameters

Apply Pattern

rice refactor patterns apply rename_function --old-name foo --new-name bar

Returns: Refactoring result

Export Pattern

rice refactor patterns export rename_function --output pattern.yaml

Returns: Pattern exported to file

Import Pattern

rice refactor patterns import --file pattern.yaml

Returns: Pattern imported and saved


LSP API

LSP Server Configuration

lsp:
  enabled: true
  servers:
    rust:
      command: "rust-analyzer"
      args: []
      languages: ["rust"]
    typescript:
      command: "typescript-language-server"
      args: ["--stdio"]
      languages: ["typescript", "javascript"]
    python:
      command: "pylsp"
      args: []
      languages: ["python"]

LSP Methods

Start LSP Server

rice lsp start

Returns: LSP server started

Stop LSP Server

rice lsp stop

Returns: LSP server stopped

Get LSP Status

rice lsp status

Returns: LSP server status

Get LSP Logs

rice lsp logs

Returns: LSP server logs


Completion API

Completion Request

{
  "file": "src/main.rs",
  "line": 10,
  "column": 5,
  "context": "fn hello() {\n    let x = ",
  "language": "rust"
}

Completion Response

{
  "completions": [
    {
      "label": "String::new()",
      "kind": "function",
      "detail": "Creates a new empty String",
      "score": 0.95
    },
    {
      "label": "String::from()",
      "kind": "function",
      "detail": "Creates a String from a string literal",
      "score": 0.85
    }
  ]
}

Completion Methods

Enable Completion

rice completion enable

Returns: Completion enabled

Disable Completion

rice completion disable

Returns: Completion disabled

Get Completion Status

rice completion status

Returns: Completion status


Hooks API

Hook Configuration

hooks:
  - name: "on-file-save"
    event: "file_saved"
    action: "run_command"
    command: "cargo test"
    enabled: true
    
  - name: "on-test-pass"
    event: "test_passed"
    action: "notify"
    message: "Tests passed!"
    enabled: true

Hook Methods

List Hooks

rice hooks list

Returns: Array of hook objects

Get Hook

rice hooks show on-file-save

Returns: Hook object

Enable Hook

rice hooks enable on-file-save

Returns: Hook enabled

Disable Hook

rice hooks disable on-file-save

Returns: Hook disabled

Test Hook

rice hooks test on-file-save

Returns: Hook test result


DI Container API

Container Creation

create_application_container()

Create a DI container with core services registered.

Signature:

pub fn create_application_container() -> DIResult<DIContainer>

Returns: Configured DI container with core services (sessions, providers, agents)

Example:

let container = create_application_container().unwrap();

create_full_application_container() (requires full feature)

Create a DI container with all available services registered.

Signature:

#[cfg(feature = "full")]
pub fn create_full_application_container() -> DIResult<DIContainer>

Returns: Fully configured DI container with all optional services

Service Registration

DIContainer::register()

Register a singleton service.

Signature:

pub fn register<F, T>(&self, factory: F) -> DIResult<()>
where
    F: Fn(&DIContainer) -> DIResult<Arc<T>> + Send + Sync + 'static,
    T: Send + Sync + 'static,

Parameters:

  • factory - Factory function that creates the service instance

Example:

container.register(|_| Ok(Arc::new(MyService::new()))).unwrap();

DIContainer::register_transient()

Register a transient service.

Signature:

pub fn register_transient<F, T>(&self, factory: F) -> DIResult<()>
where
    F: Fn(&DIContainer) -> DIResult<Arc<T>> + Send + Sync + 'static,
    T: Send + Sync + 'static,

Parameters:

  • factory - Factory function that creates new instances

DIContainer::register_scoped()

Register a scoped service.

Signature:

pub fn register_scoped<F, T>(&self, factory: F) -> DIResult<()>
where
    F: Fn(&DIContainer) -> DIResult<Arc<T>> + Send + Sync + 'static,
    T: Send + Sync + 'static,

Parameters:

  • factory - Factory function that creates scoped instances

DIContainer::register_with_health_check()

Register a service with health check capability.

Signature:

pub fn register_with_health_check<F, H, T>(&self, factory: F, health_check: H) -> DIResult<()>
where
    F: Fn(&DIContainer) -> DIResult<Arc<T>> + Send + Sync + 'static,
    H: Fn(&Arc<dyn Any + Send + Sync>) -> DIResult<HealthStatus> + Send + Sync + 'static,
    T: Send + Sync + 'static,

Service Resolution

DIContainer::resolve()

Resolve a service instance.

Signature:

pub fn resolve<T>(&self) -> DIResult<Arc<T>>
where
    T: Send + Sync + 'static,

Type Parameters:

  • T - The service type to resolve

Returns: Arc-wrapped service instance

Example:

let session_mgr = container.resolve::<SessionManager>().unwrap();

DIContainer::resolve_with_scope()

Resolve a service instance with optional scope.

Signature:

pub fn resolve_with_scope<T>(&self, scope: Option<&ServiceScope>) -> DIResult<Arc<T>>
where
    T: Send + Sync + 'static,

Parameters:

  • scope - Optional service scope for scoped services

Service Management

DIContainer::is_registered()

Check if a service type is registered.

Signature:

pub fn is_registered<T>(&self) -> bool
where
    T: Send + Sync + 'static,

Returns: true if the service type is registered

DIContainer::service_count()

Get the number of registered services.

Signature:

pub fn service_count(&self) -> usize

Returns: Number of registered services

DIContainer::health_check_all()

Perform health checks on all registered services.

Signature:

pub fn health_check_all(&self) -> DIResult<Vec<(String, HealthStatus)>>

Returns: Vector of (service_name, health_status) tuples

Builder Pattern

DIContainerBuilder::new()

Create a new container builder.

Signature:

pub fn new() -> Self

DIContainerBuilder::register_infrastructure_services()

Register all infrastructure services.

Signature:

pub fn register_infrastructure_services(self) -> DIResult<Self>

DIContainerBuilder::register_use_cases()

Register all application use cases.

Signature:

pub fn register_use_cases(self) -> DIResult<Self>

DIContainerBuilder::build()

Build the DI container.

Signature:

pub fn build(self) -> DIContainer

Feature-Gated Service Registration

The following methods are available when specific features are enabled:

Method Feature Description
register_storage_services() storage Register storage services
register_research_services() research Register research services
register_workflow_services() workflows Register workflow services
register_execution_services() execution Register execution services
register_mcp_services() mcp Register MCP services
register_tool_services() tools Register tool services
register_config_services() config Register config services
register_activity_log_services() activity-log Register activity log services
register_orchestration_services() orchestration Register orchestration services
register_specs_services() specs Register specs services
register_undo_redo_services() undo-redo Register undo-redo services
register_vcs_services() vcs Register VCS services
register_permissions_services() permissions Register permissions services
register_security_services() security Register security services
register_cache_services() cache Register cache services
register_domain_services() domain Register domain services
register_learning_services() learning Register learning services
register_industry_services() industry Register industry services
register_safety_services() safety Register safety services
register_files_services() files Register files services
register_themes_services() themes Register themes services
register_images_services() images Register images services
register_completion_services() completion Register completion services
register_lsp_services() lsp Register LSP services
register_modes_services() modes Register modes services
register_commands_services() commands Register commands services
register_hooks_services() hooks Register hooks services
register_keybinds_services() keybinds Register keybinds services
register_teams_services() teams Register teams services
register_refactoring_services() refactoring Register refactoring services

Macros

register_service!

Convenience macro for service registration.

Usage:

register_service!(container, MyService, |_| Ok(Arc::new(MyService::new())));

resolve_service!

Convenience macro for service resolution.

Usage:

let service = resolve_service!(container, MyService).unwrap();

Data Types

ServiceLifetime

Service lifetime management.

pub enum ServiceLifetime {
    Singleton,  // One instance for entire application
    Transient,  // New instance each request
    Scoped,     // One instance per scope
}

HealthStatus

Service health status.

pub enum HealthStatus {
    Healthy,                    // Service is operational
    Degraded(String),          // Service is degraded but functional
    Unhealthy(String),         // Service is not functional
}

ServiceScope

Service scope for managing scoped instances.

pub struct ServiceScope {
    // Manages scoped service instances
}

Error Types

DIError

DI container error types.

pub enum DIError {
    ServiceNotRegistered { service_type: String },
    ServiceAlreadyRegistered { service_type: String },
    InvalidServiceType { message: String },
    DependencyResolutionFailed { message: String },
    HealthCheckFailed { service_type: String, reason: String },
    CircularDependency { service_chain: String },
}

Data Types

Message

{
  "id": "msg-uuid",
  "role": "user|assistant|system",
  "content": "Message content",
  "timestamp": "2025-12-05T10:30:00Z",
  "metadata": {
    "model": "gpt-4",
    "tokens": 150
  }
}

File

{
  "path": "src/main.rs",
  "language": "rust",
  "content": "fn main() { ... }",
  "size": 1024,
  "modified": "2025-12-05T10:30:00Z"
}

Error

{
  "code": "ERROR_CODE",
  "message": "Error message",
  "details": "Additional details",
  "timestamp": "2025-12-05T10:30:00Z"
}

Error Handling

Error Codes

Code Meaning Solution
ERR_API_KEY_INVALID API key is invalid or expired Regenerate API key
ERR_CONNECTION_TIMEOUT Request timed out Check network connection
ERR_RATE_LIMIT_EXCEEDED Too many requests Wait before retrying
ERR_FILE_NOT_FOUND File not found Verify file path
ERR_PERMISSION_DENIED Permission denied Check file permissions
ERR_INVALID_CONFIG Configuration is invalid Validate configuration
ERR_SESSION_NOT_FOUND Session not found Check session name
ERR_SPEC_NOT_FOUND Specification not found Check spec name

Error Response

{
  "error": {
    "code": "ERR_API_KEY_INVALID",
    "message": "API key is invalid or expired",
    "details": "Please regenerate your API key from the provider's dashboard",
    "timestamp": "2025-12-05T10:30:00Z"
  }
}

See Also


Last updated: December 5, 2025

Clone this wiki locally