Skip to content

vilanobeachflorida/phpclaw

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

22 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

PHPClaw

Terminal-first, multi-model AI agent shell built in PHP. Run it on your machine, connect any LLM provider, and work from your terminal.

  ╔══════════════════════════════════════════════╗
  ║           PHPClaw Agent Shell                ║
  ║                 v0.1.0                       ║
  ╚══════════════════════════════════════════════╝

  reasoning:ollama ❯ fetch the top 5 hacker news stories and summarize them
  ◆ Working...
    ✓ browser_fetch
    ✓ browser_fetch
    ✓ browser_fetch

  Here are today's top Hacker News stories...

  ─ 4.2k in · 890 out · 3 tools · 5.1s ─

PHPClaw is like Claude Code, but open-source, self-hosted, and works with any LLM. Connect Ollama, LM Studio, OpenAI, Claude, or any OpenAI-compatible endpoint. It has tools for file operations, shell commands, web browsing, and more. The agent loops autonomously -- calling tools, reading results, and continuing until the task is done.

Quick Start

git clone https://github.com/sergiozlobin/phpclaw.git
cd phpclaw/agent

# Install dependencies
composer install

# Run the setup wizard
php spark agent:setup

# Start chatting
php spark agent:chat

The setup wizard walks you through everything: environment check, directory setup, provider configuration (with interactive menus), and validation.

Requirements

  • PHP 8.2+
  • curl, json, mbstring extensions
  • Composer
  • At least one LLM provider (see below)

Optional but recommended:

  • readline extension (better chat input with history)
  • pcntl extension (graceful shutdown / signal handling)

Supported Providers

Provider Type Auth
Ollama Local None (runs on your machine)
LM Studio Local None
OpenAI / ChatGPT Cloud API key
Claude API Cloud API key (pay per token)
Claude OAuth Cloud Setup token (uses your subscription)
Claude Code CLI Local Claude Code must be installed
OpenLLM Any API key (OpenAI-compatible endpoint)

Setting Up a Provider

The setup wizard handles this interactively:

php spark agent:setup

Or configure manually in writable/agent/config/providers.json.

Ollama (easiest for local)

# Install Ollama: https://ollama.ai
ollama pull llama3
# PHPClaw connects to http://localhost:11434 by default

OpenAI / ChatGPT

# Get API key from https://platform.openai.com/api-keys
# Set in .env:
OPENAI_API_KEY=sk-...

Claude API

# Get API key from https://console.anthropic.com/settings/keys
# Set in .env:
ANTHROPIC_API_KEY=sk-ant-...

Claude OAuth (use your subscription)

# Generates a setup token from your Claude Pro/Max subscription:
claude setup-token
# Paste the token during setup wizard

How It Works

PHPClaw runs an agent loop:

  1. You type a message
  2. The agent sends it to your LLM with a system prompt describing available tools
  3. The LLM responds with text and/or tool calls
  4. PHPClaw executes the tools (read files, fetch URLs, run commands, etc.)
  5. Results are fed back to the LLM
  6. The loop continues until the LLM responds with no tool calls (task complete)

There's no iteration limit. The agent runs until it's done. If it gets stuck (same calls repeated, or all tools failing), it asks you what to do: continue, stop, or give new instructions.

Built-in Tools

Tool Description
file_read Read file contents
file_write Write content to a file
file_append Append to a file
dir_list List directory contents
mkdir Create directories
move_file Move or rename files
delete_file Delete files
grep_search Search file contents with patterns
shell_exec Execute shell commands
http_get Make HTTP GET requests
browser_fetch Fetch and parse web pages
browser_text Extract text from web pages
system_info Get system information

Chat Commands

While in agent:chat, use slash commands:

Command Description
/help Show available commands
/exit Exit chat
/usage Token usage and cost breakdown
/provider Show active providers
/model Show current model routing
/role [name] Show or set current role
/module [name] Show or set current module
/tools List available tools
/tasks Show active tasks
/memory Show memory stats
/status Show system status
/debug Toggle debug mode (shows per-request tokens)

Token Usage Tracking

PHPClaw tracks token usage and estimates costs, similar to Claude Code:

─ 847 in · 234 out · $0.004 · 2 tools · 1.2s ─

Use /usage for a full session breakdown with per-model costs. Local providers (Ollama, LM Studio) show $0.00.

CLI Commands

# Core
php spark agent:chat              # Interactive chat (main interface)
php spark agent:setup             # Setup wizard
php spark agent:serve             # Start background service
php spark agent:status            # System status

# Providers & Models
php spark agent:providers         # List providers and health
php spark agent:models            # List available models
php spark agent:roles             # List model roles
php spark agent:modules           # List modules

# Authentication
php spark agent:auth status       # Show auth status
php spark agent:auth login <p>    # OAuth/setup-token login
php spark agent:auth token <p>    # Paste token manually
php spark agent:auth refresh <p>  # Force token refresh
php spark agent:auth revoke <p>   # Remove stored token

# Sessions
php spark agent:sessions          # List sessions
php spark agent:session:show <id> # Show session transcript

# Tasks
php spark agent:tasks             # List tasks
php spark agent:task:show <id>    # Show task details
php spark agent:task:tail <id>    # Follow task progress
php spark agent:task:cancel <id>  # Cancel a task

# Memory & Cache
php spark agent:memory:show       # Memory stats and notes
php spark agent:memory:compact    # Run memory compaction
php spark agent:cache:status      # Cache statistics
php spark agent:cache:clear       # Clear all cache
php spark agent:cache:prune       # Prune expired entries
php spark agent:maintain          # Run all maintenance

# Scaffolding
php spark agent:tools             # List tools
php spark agent:tool:scaffold     # Generate new tool from template
php spark agent:provider:scaffold # Generate new provider from template

# Configuration
php spark agent:config            # List config files
php spark agent:config <name>     # Show config with syntax highlighting

Architecture

┌─────────────────────────────────────────────────┐
│                   User Input                     │
│              (Terminal / CLI REPL)                │
└──────────────────────┬──────────────────────────┘
                       │
              ┌────────▼────────┐
              │  Agent Executor  │ ← loops until done
              │   (core loop)   │
              └──┬──────────┬───┘
                 │          │
        ┌────────▼──┐  ┌───▼────────┐
        │  Model     │  │   Tool     │
        │  Router    │  │  Registry  │
        └────┬───────┘  └───┬────────┘
             │              │
     ┌───────▼───────┐  ┌──▼──────────────┐
     │  Providers     │  │  Tools           │
     │  ┌──────────┐  │  │  file_read       │
     │  │ Ollama   │  │  │  file_write      │
     │  │ LMStudio │  │  │  shell_exec      │
     │  │ ChatGPT  │  │  │  browser_fetch   │
     │  │ Claude   │  │  │  grep_search     │
     │  │ OpenLLM  │  │  │  ...13 total     │
     │  └──────────┘  │  └─────────────────┘
     └────────────────┘

Providers are LLM backends. Each has an adapter that normalizes the API.

Roles map tasks to providers. "reasoning" might go to Ollama, "coding" to Claude.

Modules combine a role + prompt + tool set. The "coding" module enables file/shell tools and uses a code-focused prompt.

Sessions persist conversation history, transcripts, and tool events.

Memory extracts key information across sessions with automatic compaction.

Storage Layout

All runtime data is in writable/agent/:

writable/agent/
├── config/          # providers.json, roles.json, modules.json, tools.json
├── sessions/        # Conversation history and transcripts
├── tasks/           # Background task queue and progress
├── memory/          # Global notes, summaries, compacted knowledge
├── cache/           # LLM response and tool caches
├── logs/            # Service and error logs
├── prompts/         # System and module prompt templates
├── state/           # Service state, heartbeat, health
├── queues/          # Task queues
└── locks/           # File locks

No database required. Everything is JSON files and NDJSON logs.

Running as a Service

PHPClaw can run as a background service with a heartbeat loop:

# Start the service
php spark agent:serve

# Or use systemd (Linux)
sudo cp phpclaw.service /etc/systemd/system/
sudo systemctl enable phpclaw
sudo systemctl start phpclaw

The service handles health checks, task execution, memory compaction, and cache pruning on configurable intervals.

Extending PHPClaw

Add a Custom Tool

php spark agent:tool:scaffold MyTool

This generates a tool class from the template. Implement the execute() method and register it in writable/agent/config/tools.json.

Add a Custom Provider

php spark agent:provider:scaffold MyProvider

Implement the chat() and healthCheck() methods. Register in writable/agent/config/providers.json.

Custom Prompts

Edit prompt templates in writable/agent/prompts/:

  • system/default.md — base system prompt
  • modules/*.md — per-module prompts (coding, reasoning, browser, etc.)

Documentation

See the docs/ directory for detailed documentation:

  • Architecture — system design and component overview
  • Providers — provider configuration and custom adapters
  • Tools — tool system and custom tool development
  • Modules — role-based module configuration
  • Routing — model routing and fallback chains
  • Memory — memory system, compaction, and summaries
  • Tasks — background task queue
  • Storage — file storage layout and formats
  • Service — background service configuration
  • Development — development workflow and guidelines

License

MIT License. See LICENSE for details.

About

A tiny openclaw inspired ai agent.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Languages