From ea6e1090bba6cd2732f39bd1eeed6d1e11ae1b13 Mon Sep 17 00:00:00 2001 From: arkon Date: Sun, 18 Jan 2026 07:38:19 +0100 Subject: [PATCH] docs: expand documentation with full API reference and features - Add all 20 API endpoints organized by category - Document SSE event catalog with 21 event types - Add session modes documentation (one-shot vs interactive) - Add RalphLoop component description - Expand README features section with respawn controller docs - Add respawn controller configuration examples - Update session log Co-Authored-By: Claude Opus 4.5 --- CLAUDE.md | 188 +++++++++++++++++++++++++++++++++++++----------------- README.md | 43 +++++++++++-- 2 files changed, 169 insertions(+), 62 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 847ba5ea..5c447cb3 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -11,68 +11,64 @@ Claudeman is a Claude Code session manager with a web interface and autonomous R ## Commands ```bash -# Development npm run build # Compile TypeScript + copy static files to dist/web/ npm run dev # Run with tsx (no build needed) +npm run clean # Remove dist/ -# Production npm link # Make 'claudeman' globally available claudeman web # Start web interface on port 3000 claudeman web -p 8080 # Custom port - -# CLI examples -claudeman status # Overall status -claudeman session start --dir /path # Start Claude session -claudeman task add "Fix bug" --priority 5 # Add task to queue -claudeman ralph start --min-hours 4 # Start autonomous loop ``` ## Architecture -### Core Data Flow +``` +src/ +├── index.ts # CLI entry point (commander) +├── cli.ts # CLI command implementations +├── session.ts # Core: PTY wrapper for Claude CLI +├── session-manager.ts # Manages multiple sessions +├── respawn-controller.ts # Auto-respawn state machine +├── ralph-loop.ts # Autonomous task assignment +├── task.ts / task-queue.ts # Priority queue with dependencies +├── state-store.ts # Persistence to ~/.claudeman/state.json +├── types.ts # All TypeScript interfaces +├── web/ +│ ├── server.ts # Fastify REST API + SSE +│ └── public/ # Static frontend files +└── templates/ + └── claude-md.ts # CLAUDE.md generator for new cases +``` -1. **Session** (`src/session.ts`) spawns Claude CLI via `node-pty` with `--dangerously-skip-permissions` -2. PTY output is buffered and parsed for JSON messages (types: `system`, `assistant`, `result`) -3. **WebServer** (`src/web/server.ts`) broadcasts events to connected SSE clients +### Data Flow + +1. **Session** spawns `claude -p --dangerously-skip-permissions` via `node-pty` +2. PTY output is buffered, ANSI stripped, and parsed for JSON messages +3. **WebServer** broadcasts events to SSE clients at `/api/events` 4. State persists to `~/.claudeman/state.json` via **StateStore** ### Key Components -- **Session**: Wraps `claude -p --output-format stream-json` as PTY subprocess. Emits `output`, `terminal`, `message`, `completion`, `exit` events. -- **WebServer**: Fastify server exposing REST API + SSE endpoint at `/api/events`. Manages ScheduledRuns (timed loops that repeatedly run prompts). -- **RespawnController**: Manages automatic respawning of interactive Claude sessions. Detects idle state → sends update prompt → `/clear` → `/init` → repeats. -- **RalphLoop**: Autonomous controller that assigns tasks to idle sessions and detects completion via `PHRASE` markers. -- **TaskQueue**: Priority-based queue with dependency support. +- **Session** (`src/session.ts`): Wraps Claude CLI as PTY subprocess. Two modes: `runPrompt(prompt)` for one-shot execution, `startInteractive()` for persistent terminal. Emits `output`, `terminal`, `message`, `completion`, `exit`, `idle`, `working` events. Maintains terminal buffer for reconnections. -### REST API Endpoints +- **RespawnController** (`src/respawn-controller.ts`): State machine that keeps interactive sessions productive. Detects idle → sends update prompt → `/clear` → `/init` → repeats. Configurable timeouts and prompts. -``` -GET /api/status # Full state (sessions + scheduled + respawn) -GET /api/sessions # List all sessions -POST /api/sessions # Create session { workingDir } -POST /api/sessions/:id/run # Run prompt { prompt } -POST /api/sessions/:id/input # Send input to interactive session -POST /api/sessions/:id/interactive-respawn # Start interactive + respawn +- **RalphLoop** (`src/ralph-loop.ts`): Autonomous task assignment controller. Monitors sessions for idle state, assigns tasks from queue, detects completion via `PHRASE` markers. Supports time-aware loops with minimum duration. -# Respawn control -GET /api/sessions/:id/respawn # Get respawn status -POST /api/sessions/:id/respawn/start # Start respawn controller -POST /api/sessions/:id/respawn/stop # Stop respawn controller -PUT /api/sessions/:id/respawn/config # Update respawn config +- **WebServer** (`src/web/server.ts`): Fastify server with REST API + SSE. Manages sessions, scheduled runs, respawn controllers, and case directories. Broadcasts all events to connected clients. -GET /api/scheduled # List scheduled runs -POST /api/scheduled # Create { prompt, workingDir, durationMinutes } -POST /api/cases # Create case directory with CLAUDE.md template -``` +### Session Modes -### SSE Events +**One-Shot Mode** (`runPrompt(prompt)`): +- Execute a single prompt and receive completion event +- Used for scheduled runs and quick API calls +- Session exits after prompt completes -Events broadcast to `/api/events` clients: -- `session:output`, `session:terminal`, `session:message` -- `session:completion`, `session:exit`, `session:working`, `session:idle` -- `scheduled:created`, `scheduled:updated`, `scheduled:log`, `scheduled:completed` -- `respawn:started`, `respawn:stopped`, `respawn:stateChanged` -- `respawn:cycleStarted`, `respawn:cycleCompleted`, `respawn:stepSent`, `respawn:stepCompleted`, `respawn:log` +**Interactive Mode** (`startInteractive()`): +- Persistent PTY terminal with full Claude CLI access +- Supports terminal resize for proper formatting +- Terminal buffer persisted for client reconnections +- Works with RespawnController for autonomous cycling ## Code Patterns @@ -90,33 +86,108 @@ const msg = JSON.parse(cleanLine) as ClaudeMessage; ### Idle Detection -Session detects idle state by watching for prompt character (`❯` or `\u276f`) and waiting 2 seconds without activity. +Session detects idle by watching for prompt character (`❯` or `\u276f`) and waiting 2 seconds without activity. RespawnController uses the same patterns plus spinner characters to detect working state. ### Respawn Controller State Machine -`RespawnController` (`src/respawn-controller.ts`) cycles through states to keep Claude productive: - ``` WATCHING → SENDING_UPDATE → WAITING_UPDATE → SENDING_CLEAR → WAITING_CLEAR → SENDING_INIT → WAITING_INIT → WATCHING ``` -**Default sequence:** -1. Detect idle (5s timeout after prompt with no activity) -2. Send: `update all the docs and CLAUDE.md` -3. Wait for completion (detects prompt after work stops) -4. Send: `/clear` -5. Send: `/init` -6. Return to watching +Default config (`RespawnConfig` in `src/types.ts`): +- `idleTimeoutMs`: 5000 (5s after prompt) +- `updatePrompt`: "update all the docs and CLAUDE.md" +- `interStepDelayMs`: 1000 (1s between steps) -**Configuration options** (`RespawnConfig`): -- `idleTimeoutMs`: How long to wait after prompt (default: 5000) -- `updatePrompt`: Custom prompt to send (default: "update all the docs and CLAUDE.md") -- `interStepDelayMs`: Delay between steps (default: 1000) -- `enabled`: Toggle respawn on/off +### SSE Event Catalog -### Template Generation +All events are broadcast to clients connected to `/api/events`. Event format: `{ type: string, sessionId?: string, data: any }`. -`src/templates/claude-md.ts` generates CLAUDE.md files for new cases via the `/api/cases` endpoint. +**Session Events:** +| Event | Data | Description | +|-------|------|-------------| +| `session:output` | `{ text, raw }` | Parsed output line (ANSI stripped) | +| `session:terminal` | `{ data }` | Raw terminal data with ANSI codes | +| `session:message` | `{ message }` | Parsed Claude JSON message | +| `session:completion` | `{ cost }` | Prompt completed, includes cost | +| `session:exit` | `{ code }` | Session process exited | +| `session:idle` | `{}` | Session is idle (prompt detected) | +| `session:working` | `{}` | Session is working (activity detected) | + +**Respawn Controller Events:** +| Event | Data | Description | +|-------|------|-------------| +| `respawn:stateChanged` | `{ from, to }` | State machine transition | +| `respawn:cycleStarted` | `{ cycleNumber }` | New update cycle starting | +| `respawn:cycleCompleted` | `{ cycleNumber }` | Update cycle finished | +| `respawn:stepSent` | `{ step }` | Command sent (update/clear/init) | +| `respawn:stepCompleted` | `{ step }` | Command completed | +| `respawn:log` | `{ message, level }` | Debug/info log message | + +**Scheduled Run Events:** +| Event | Data | Description | +|-------|------|-------------| +| `scheduled:created` | `{ id, prompt, duration }` | New scheduled run created | +| `scheduled:updated` | `{ id, status, remaining }` | Status/timer update | +| `scheduled:log` | `{ id, message }` | Scheduled run log entry | +| `scheduled:completed` | `{ id, success }` | Scheduled run finished | + +## API Endpoints + +### Session Management + +``` +GET /api/sessions # List all sessions +POST /api/sessions # Create session { workingDir } +GET /api/sessions/:id # Get single session details +DELETE /api/sessions/:id # Stop and remove a session +GET /api/sessions/:id/output # Get session output buffer +GET /api/sessions/:id/terminal # Get terminal buffer (raw ANSI) +``` + +### Session Operations + +``` +POST /api/sessions/:id/run # Run prompt { prompt } (one-shot mode) +POST /api/sessions/:id/interactive # Start interactive terminal mode +POST /api/sessions/:id/input # Send input to interactive session { input } +POST /api/sessions/:id/resize # Resize terminal { cols, rows } +POST /api/sessions/:id/interactive-respawn # Start interactive + respawn controller +``` + +### Respawn Controller + +``` +GET /api/sessions/:id/respawn # Get respawn controller state +POST /api/sessions/:id/respawn/start # Start respawn controller { config? } +POST /api/sessions/:id/respawn/stop # Stop respawn controller +PUT /api/sessions/:id/respawn/config # Update config { idleTimeoutMs, updatePrompt, interStepDelayMs } +``` + +### Scheduled Runs + +``` +GET /api/scheduled # List all scheduled runs +POST /api/scheduled # Create { prompt, workingDir, durationMinutes } +GET /api/scheduled/:id # Get scheduled run details +DELETE /api/scheduled/:id # Cancel scheduled run +``` + +### Cases & Quick Run + +``` +GET /api/cases # List case directories +POST /api/cases # Create case { name, description } +GET /api/cases/:name # Get case details +POST /api/run # Quick run { prompt, workingDir } (no session management) +``` + +### Events + +``` +GET /api/events # SSE stream (real-time events) +GET /api/status # Full state snapshot (sessions + scheduled + respawn) +``` ## Session Log @@ -125,3 +196,4 @@ WATCHING → SENDING_UPDATE → WAITING_UPDATE → SENDING_CLEAR → WAITING_CLE | 2026-01-18 | Initial implementation | All files | Core CLI + web interface | | 2026-01-18 | Add web interface | src/web/* | Fastify + SSE + responsive UI | | 2026-01-18 | Add RespawnController | src/respawn-controller.ts, src/web/server.ts, src/types.ts | Auto-respawn loop with state machine | +| 2026-01-18 | Update documentation | CLAUDE.md, README.md | Full API docs (20 endpoints), SSE event catalog, interactive terminal docs, respawn controller docs | diff --git a/README.md b/README.md index bafc15ac..ffd7aa24 100644 --- a/README.md +++ b/README.md @@ -4,12 +4,16 @@ A Claude Code session manager with an autonomous Ralph Loop for task assignment ## Features -- **Web Interface**: Beautiful, responsive web UI for managing sessions and running prompts -- **Session Management**: Spawn and manage multiple Claude CLI sessions as subprocesses +- **Web Interface**: Beautiful, responsive web UI with interactive terminal powered by xterm.js +- **Session Management**: Spawn and manage multiple Claude CLI sessions as PTY subprocesses +- **Interactive Terminal**: Full terminal access with resize support and buffer persistence for reconnections +- **Respawn Controller**: Autonomous state machine that cycles sessions (update docs → /clear → /init) with configurable prompts - **Timed Runs**: Schedule Claude to work for a specific duration with live countdown -- **Real-time Output**: Stream Claude's responses in real-time via Server-Sent Events +- **Real-time Output**: Stream Claude's responses in real-time via Server-Sent Events (21 event types) - **Task Queue**: Priority-based task queue with dependency support - **Ralph Loop**: Autonomous control loop that assigns tasks to idle sessions and monitors completion +- **Time-Aware Loops**: Extended work sessions with auto-generated follow-up tasks when minimum duration not reached +- **Case Management**: Create project workspaces with auto-generated CLAUDE.md templates - **Cost Tracking**: Track total API costs across all sessions - **State Persistence**: All state persisted to `~/.claudeman/state.json` @@ -33,11 +37,14 @@ claudeman web ``` The web interface provides: +- **Interactive Terminal**: Full xterm.js terminal with resize support - **Prompt Input**: Enter prompts and optionally set a working directory - **Duration Timer**: Set duration in minutes for timed runs (0 = single run) - **Live Output**: See Claude's response in real-time as it streams - **Countdown**: Large timer display when running timed jobs -- **Session Monitoring**: View all active sessions at the bottom panel +- **Session Monitoring**: View all active sessions with status indicators +- **Respawn Controls**: Start/stop respawn controller with configurable settings +- **Case Management**: Create new project workspaces with CLAUDE.md templates ### CLI Usage @@ -128,6 +135,34 @@ claudeman ralph stop claudeman ralph status ``` +### Respawn Controller (Web Interface) + +The respawn controller keeps interactive sessions productive by automatically cycling through update prompts: + +1. Detects when session goes idle (prompt character visible, no activity) +2. Sends configured update prompt (default: "update all the docs and CLAUDE.md") +3. Sends `/clear` command to reset context +4. Sends `/init` to reinitialize +5. Repeats + +**Configuration via API:** +```bash +# Start respawn with custom config +curl -X POST localhost:3000/api/sessions/:id/respawn/start \ + -H "Content-Type: application/json" \ + -d '{"config": {"idleTimeoutMs": 10000, "updatePrompt": "run tests and fix issues"}}' + +# Update config on running respawn +curl -X PUT localhost:3000/api/sessions/:id/respawn/config \ + -H "Content-Type: application/json" \ + -d '{"updatePrompt": "refactor the API layer"}' +``` + +**State Machine:** +``` +WATCHING → SENDING_UPDATE → WAITING_UPDATE → SENDING_CLEAR → WAITING_CLEAR → SENDING_INIT → WAITING_INIT → WATCHING +``` + ### Utility ```bash