diff --git a/CLAUDE.md b/CLAUDE.md index 3d847f7e..6db40cfc 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -33,9 +33,10 @@ npx vitest run -t "should create session" # Run tests matching pattern src/ ├── index.ts # CLI entry point (commander) ├── cli.ts # CLI command implementations -├── session.ts # Core: PTY wrapper for Claude CLI +├── session.ts # Core: PTY wrapper for Claude CLI + token tracking ├── session-manager.ts # Manages multiple sessions ├── respawn-controller.ts # Auto-respawn state machine +├── task-tracker.ts # Background task detection and tree display ├── ralph-loop.ts # Autonomous task assignment ├── task.ts / task-queue.ts # Priority queue with dependencies ├── state-store.ts # Persistence to ~/.claudeman/state.json @@ -56,9 +57,11 @@ src/ ### Key Components -- **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. Includes buffer management for long-running sessions (12-24+ hours) with automatic trimming. +- **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`, `autoClear` events. Maintains terminal buffer for reconnections. Includes buffer management for long-running sessions (12-24+ hours) with automatic trimming. Tracks input/output tokens and supports auto-clear at configurable threshold. -- **RespawnController** (`src/respawn-controller.ts`): State machine that keeps interactive sessions productive. Detects idle → sends update prompt → `/clear` → `/init` → repeats. Configurable timeouts and prompts. +- **TaskTracker** (`src/task-tracker.ts`): Detects Claude's background Task tool usage from JSON output. Builds a tree of parent-child task relationships. Emits `taskCreated`, `taskUpdated`, `taskCompleted`, `taskFailed` events. Used by Session to track background work. + +- **RespawnController** (`src/respawn-controller.ts`): State machine that keeps interactive sessions productive. Detects idle → sends update prompt → optionally `/clear` → optionally `/init` → repeats. Configurable timeouts, prompts, and step toggles. - **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. @@ -145,6 +148,28 @@ 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) +- `sendClear`: true (send /clear after update) +- `sendInit`: true (send /init after /clear) + +### Token Tracking & Auto-Clear + +Session tracks input/output tokens from Claude's JSON messages: + +```typescript +{ + tokens: { + input: number; // Total input tokens used + output: number; // Total output tokens used + total: number; // Combined total + }, + autoClear: { + enabled: boolean; // Whether auto-clear is active + threshold: number; // Token threshold (default 100000) + } +} +``` + +When enabled, auto-clear waits for idle state, sends `/clear`, and resets token counts. ### SSE Event Catalog @@ -166,6 +191,15 @@ All events are broadcast to clients connected to `/api/events`. Event format: `{ | `session:working` | `{ id }` | Session is working (activity detected) | | `session:updated` | `{ session }` | Session state updated | | `session:error` | `{ id, error }` | Session error occurred | +| `session:autoClear` | `{ sessionId, tokens, threshold }` | Auto-clear triggered | + +**Task Events:** +| Event | Data | Description | +|-------|------|-------------| +| `task:created` | `{ sessionId, task }` | Background task started | +| `task:updated` | `{ sessionId, task }` | Task status updated | +| `task:completed` | `{ sessionId, task }` | Task finished successfully | +| `task:failed` | `{ sessionId, task, error }` | Task failed | **Respawn Controller Events:** | Event | Data | Description | @@ -178,6 +212,7 @@ All events are broadcast to clients connected to `/api/events`. Event format: `{ | `respawn:stepSent` | `{ sessionId, step, input }` | Command sent (update/clear/init) | | `respawn:stepCompleted` | `{ sessionId, step }` | Command completed | | `respawn:configUpdated` | `{ sessionId, config }` | Configuration changed | +| `respawn:timerStarted` | `{ sessionId, durationMinutes, endAt, startedAt }` | Timed respawn started | | `respawn:log` | `{ sessionId, message }` | Debug/info log message | | `respawn:error` | `{ sessionId, error }` | Error occurred | @@ -230,7 +265,9 @@ POST /api/sessions/:id/interactive-respawn # Start interactive + respawn contro 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 } +POST /api/sessions/:id/respawn/enable # Enable respawn on existing session { config?, durationMinutes? } +PUT /api/sessions/:id/respawn/config # Update config { idleTimeoutMs, updatePrompt, interStepDelayMs, sendClear, sendInit } +POST /api/sessions/:id/auto-clear # Set auto-clear { enabled, threshold? } ``` ### Scheduled Runs diff --git a/README.md b/README.md index 15fcf3f0..813e20d9 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,11 @@ A Claude Code session manager with an autonomous Ralph Loop for task assignment - **Session Management**: Spawn and manage multiple Claude CLI sessions as PTY subprocesses with one-click kill - **Interactive Terminal**: Full terminal access with resize support, buffer persistence, and 60fps batched rendering - **Respawn Controller**: Autonomous state machine that cycles sessions (update docs → /clear → /init) with configurable prompts +- **Enable Respawn on Existing Sessions**: Start respawn on already-running sessions without restarting +- **Timed Respawn**: Set duration limits for respawn loops with countdown timer display +- **Auto-Clear Context**: Automatically send /clear when token count exceeds threshold (default 100k) +- **Token Tracking**: Real-time input/output token tracking per session +- **Background Task Tracking**: Detect and display Claude's background tasks in a tree view - **Timed Runs**: Schedule Claude to work for a specific duration with animated live countdown - **Real-time Output**: Stream Claude's responses in real-time via Server-Sent Events (30 event types) - **Task Queue**: Priority-based task queue with dependency support @@ -82,12 +87,14 @@ The Quick Start button will: | Shortcut | Action | |----------|--------| | `Ctrl+Enter` | Quick Start (create case + interactive session) | +| `Ctrl+N` | New Session | +| `Ctrl+W` | Close current session | +| `Ctrl+Tab` | Switch to next session | | `Ctrl+K` | Kill all sessions | | `Ctrl+L` | Clear terminal | -| `Ctrl+1/2/3` | Switch tabs (Run/Cases/Settings) | | `Ctrl++/-` | Increase/decrease font size | | `Ctrl+?` | Show keyboard shortcuts help | -| `Escape` | Close modals | +| `Escape` | Close panels and modals | #### Additional Features @@ -197,10 +204,16 @@ The respawn controller keeps interactive sessions productive by automatically cy 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 +3. Optionally sends `/clear` command to reset context +4. Optionally sends `/init` to reinitialize 5. Repeats +**New Features:** +- **Enable on Existing Sessions**: Start respawn on already-running sessions +- **Timed Duration**: Set a duration limit (e.g., 30 minutes) after which respawn automatically stops +- **Auto-Clear**: Automatically send /clear when token count exceeds threshold (default 100k) +- **Configurable Steps**: Toggle /clear and /init steps independently + **Configuration via API:** ```bash # Start respawn with custom config @@ -208,10 +221,20 @@ 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"}}' +# Enable respawn on an existing running session with duration +curl -X POST localhost:3000/api/sessions/:id/respawn/enable \ + -H "Content-Type: application/json" \ + -d '{"config": {"updatePrompt": "continue working"}, "durationMinutes": 60}' + +# Enable auto-clear at 100k tokens +curl -X POST localhost:3000/api/sessions/:id/auto-clear \ + -H "Content-Type: application/json" \ + -d '{"enabled": true, "threshold": 100000}' + # 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"}' + -d '{"updatePrompt": "refactor the API layer", "sendClear": true, "sendInit": false}' ``` **State Machine:** @@ -219,6 +242,15 @@ curl -X PUT localhost:3000/api/sessions/:id/respawn/config \ WATCHING → SENDING_UPDATE → WAITING_UPDATE → SENDING_CLEAR → WAITING_CLEAR → SENDING_INIT → WAITING_INIT → WATCHING ``` +**Respawn Config Options:** +| Option | Default | Description | +|--------|---------|-------------| +| `idleTimeoutMs` | 5000 | Time to wait after idle before sending update | +| `updatePrompt` | "update all docs..." | Prompt to send when idle | +| `interStepDelayMs` | 1000 | Delay between respawn steps | +| `sendClear` | true | Send /clear after update prompt | +| `sendInit` | true | Send /init after /clear | + ### Utility ```bash