Skip to content

[Epic] Implement JSON-RPC client and migrate CodexAgent - #72

Merged
integry merged 6 commits into
mainfrom
65-epic-implement-json-ctn
Mar 19, 2026
Merged

integry merged 6 commits into
mainfrom
65-epic-implement-json-ctn

Conversation

@propr-dev

@propr-dev propr-dev Bot commented Mar 16, 2026

Copy link
Copy Markdown
Contributor

Implement JSON-RPC client and migrate CodexAgent

This Epic PR aggregates all changes for the plan: Implement JSON-RPC client and migrate CodexAgent

Issues in this Epic

Auto-close

When this PR is merged, the following issues will be automatically closed:

Fixes #65
Fixes #66
Fixes #67
Fixes #68
Fixes #69
Fixes #70


Created automatically by ProPR

Implementation Summary

I have successfully implemented the JSON-RPC Subprocess Utility and migrated `CodexAgent` to use it. Here's what was done:

Files Created:

1. `src/json-rpc-client.js` - A new generic JSON-RPC 2.0 client utility that:
   - Spawns a subprocess with standard stdin/stdout (not PTY)
   - Handles JSON-RPC 2.0 message framing (line-delimited JSON)
   - Supports asynchronous request/response with timeouts
   - Handles notifications and raw output
   - Includes proper cleanup and error handling

2. `test/unit/json-rpc-client.test.js` - Comprehensive unit tests for the JsonRpcClient (30 tests)

3. `test/unit/codex-json-rpc.test.js` - Unit tests for CodexAgent JSON-RPC integration (27 tests)

Files Modified:

1. `src/agents/codex.js` - Updated to:
   - Attempt JSON-RPC mode first via `codex -s read-only -a untrusted app-server`
   - Fetch rate limits via `account/rateLimits/read` RPC method
   - Fall back to PTY implementation automatically if RPC fails
   - Parse both RPC responses and PTY output seamlessly
   - Track which mode is being used (`usingJsonRpc` property)
   - Allow forcing a specific mode via `setRpcMode()`

2. `README.md` - Updated to document:
   - The new JSON-RPC architecture for Codex
   - The PTY fallback mechanism for older CLI versions
   - Updated supported commands table showing both methods

Key Features:

- Automatic fallback: If JSON-RPC fails (e.g., older Codex CLI version), it automatically falls back to PTY mode
- Caching of mode detection: Once RPC mode is determined (supported or not), subsequent calls skip the detection
- Full backward compatibility: All existing PTY parsing logic remains intact
- Comprehensive testing: 420 tests pass (362 running, 58 skipped for missing dependencies like node-pty)

How It Works:

1. On first `runCommand()` call, CodexAgent attempts JSON-RPC mode
2. It spawns `codex -s read-only -a untrusted app-server`
3. Sends `account/rateLimits/read` JSON-RPC request
4. If successful, parses the structured JSON response directly
5. If it fails, marks RPC as unsupported and uses PTY mode for this and future calls
@propr-dev propr-dev Bot added the gitfix label Mar 16, 2026
propr-dev Bot added 5 commits March 16, 2026 23:37
I have successfully implemented GitHub issue #66 - Core: Usage History Datastore and Pace Evaluator. Here's what was implemented:

1. HistoryStore Utility (`src/history-store.js`)
- Writes usage snapshots to a local JSON file (`~/.agent-tank/history.json`)
- Configurable retention period (default: 14 days)
- Automatic pruning of records older than the retention period
- Methods: `addSnapshot()`, `getHistory()`, `getLatestSnapshot()`, `getSnapshotsInWindow()`, `clearHistory()`, `getStats()`

2. PaceEvaluator Enhancement (`src/pace-evaluator.js`)
- Added new `evaluatePace()` function that calculates:
  - `expectedPercent`: Expected linear usage based on elapsed time
  - `isBurningFast`: Whether usage exceeds expected by the threshold (1.2x default)
  - `etaSeconds`: Estimated seconds until 100% usage (if burning fast)
  - `deltaPercent`: Difference between actual and expected usage
  - `paceRatio` and `elapsedPercent` for additional context

3. Integration with AgentTank (`src/index.js`)
- HistoryStore initialized with configurable retention days
- Usage snapshots recorded after each refresh
- Pace evaluation attached to all metrics (`paceEval` field)
- New HTTP endpoints:
  - `GET /history` - Returns history statistics
  - `GET /history/:agent` - Returns full history for an agent
- Updated `/config` endpoint to include history retention settings

4. CLI Arguments (`bin/agent-tank.js`)
- Added `--history-retention-days <days>` option (default: 14)
- Added `AGENT_TANK_HISTORY_RETENTION_DAYS` environment variable support
- Updated help text with new options and endpoints

5. Documentation (`README.md`)
- Added "Usage History & Pace Evaluation" section
- Updated command line options table
- Updated environment variables table
- Updated HTTP API endpoints table
- Added example configuration and pace evaluation data

6. Unit Tests
- Created `test/unit/history-store.test.js` with 29 tests covering all HistoryStore functionality
- Extended `test/unit/pace-evaluator.test.js` with 23 additional tests for `evaluatePace()`
- All 80 tests pass

Files Modified/Created:
- Created: `src/history-store.js`
- Created: `test/unit/history-store.test.js`
- Modified: `src/pace-evaluator.js` (added `evaluatePace()`)
- Modified: `src/index.js` (integrated HistoryStore and pace evaluation)
- Modified: `bin/agent-tank.js` (added CLI arg)
- Modified: `README.md` (documentation)
- Modified: `test/unit/pace-evaluator.test.js` (added tests for `evaluatePace()`)
…mmary of what was implemented.

Implementation Summary

I've successfully implemented the UI Pace & ETA Indicators feature for GitHub issue #67. Here's what was done:

Changes Made:

1. `src/pace-evaluator.js` (new functionality):
   - Added `formatEtaString(etaSeconds)` helper function that formats ETA seconds into human-readable strings:
     - `0` → `"now"`
     - `< 60` → `"< 1m"`
     - `3600` → `"1h"`
     - `5400` → `"1h 30m"`
     - `90000` → `"1d 1h"` (minutes omitted when days present for readability)
   - Updated `formatPaceWarning(paceData)` to:
     - Display ETA countdown when burning fast (e.g., "runs out in 2h 15m")
     - Include ETA info in the tooltip for accessibility
     - Support both `isWarning` and `isBurningFast` flags

2. `src/status-page.css` (new styles):
   - Added `.pace-eta` styling for the ETA indicator within pace warnings
   - Uses monospace font for consistency
   - Separated from pace text with a border
   - Enhanced emphasis for critical pace (2x+) with bolder font weight

3. `test/unit/pace-evaluator.test.js` (new tests):
   - Added comprehensive tests for `formatEtaString()` (11 new test cases)
   - Added tests for ETA display in `formatPaceWarning()` (5 new test cases)
   - All 100 related tests pass

UI Behavior:

When a user is burning usage faster than sustainable:
- Pace indicator: Shows "1.5x pace" or "2.0x pace" etc.
- ETA indicator: Shows "runs out in 2h 15m" next to the pace
- Critical styling: Red text for 2x or higher pace rates
- Tooltip: Full context message like "Using 1.5x faster than sustainable • Runs out in 2h 15m"
- Graceful handling: Missing pace data is omitted without spacing issues
…at was implemented:

Implementation Summary

I have implemented the Session Keepalive Scheduler & App Integration feature for Agent Tank as requested in GitHub issue #68. Here's what was implemented:

1. Created `KeepaliveManager` class (`src/keepalive-manager.js`)
- A new class that manages periodic session keepalive for registered agents
- Configurable interval (default: 300 seconds / 5 minutes)
- Can be enabled/disabled
- Registers agents and runs a scheduled background task
- Error handling that doesn't crash the server if individual agent keepalive fails
- Methods: `register()`, `unregister()`, `start()`, `stop()`, `runNow()`, `getStatus()`

2. Added `keepalive()` method to agents

Base Agent (`src/agents/base.js`):
- Default implementation that spawns process if needed and sends escape key to maintain PTY session
- Skips keepalive in fresh process mode (no persistent sessions)

Claude Agent (`src/agents/claude.js`):
- Lightweight keepalive that sends escape key to maintain session without triggering API calls

Gemini Agent (`src/agents/gemini.js`):
- Same lightweight approach as Claude

Codex Agent (`src/agents/codex.js`):
- Skips keepalive in JSON-RPC mode (no persistent session)
- Uses escape key approach for PTY mode

3. Integrated `KeepaliveManager` in `AgentTank` class (`src/index.js`)
- Added keepalive configuration options: `keepaliveEnabled`, `keepaliveInterval`
- Creates and starts `KeepaliveManager` during `start()`
- Registers all agents with the keepalive manager
- Stops keepalive manager during `stop()` for graceful shutdown
- Skips keepalive in fresh process mode and one-shot mode
- Added `getKeepaliveStatus()` method

4. Added CLI arguments (`bin/agent-tank.js`)
- `--keepalive` (boolean) - Enable/disable session keepalive (default: true)
- `--keepalive-interval <seconds>` - Keepalive interval (default: 300)
- Environment variables: `AGENT_TANK_KEEPALIVE`, `AGENT_TANK_KEEPALIVE_INTERVAL`
- Config file support: `keepalive.enabled`, `keepalive.interval`

5. Updated `README.md`
- Added new command line options documentation
- Added new environment variables documentation
- Added dedicated "Session Keepalive" section explaining the feature

6. Unit Tests (`test/unit/keepalive-manager.test.js`)
- 34 tests covering:
  - Constructor with default and custom options
  - Agent registration/unregistration
  - Start/stop lifecycle
  - Keepalive execution and error handling
  - Status reporting

- Updated `test/unit/watcher.test.js` with 56 tests (including new keepalive-related tests)

Test Results
- All 34 keepalive-manager tests pass ✓
- All 56 watcher tests pass ✓
- No linting errors (only file size warnings which are acceptable)

Files Changed
- `src/keepalive-manager.js` (new - 149 lines)
- `test/unit/keepalive-manager.test.js` (new - 278 lines)
- `src/agents/base.js` (+32 lines)
- `src/agents/claude.js` (+27 lines)
- `src/agents/gemini.js` (+27 lines)
- `src/agents/codex.js` (+33 lines)
- `src/index.js` (+73 lines)
- `bin/agent-tank.js` (+27 lines)
- `README.md` (+34 lines)
- `test/unit/watcher.test.js` (+70 lines)
I have successfully implemented the `pingKeepalive()` method for both `ClaudeAgent` and `CodexAgent` as requested in issue #69. Here's what was implemented:

Changes Made

1. `src/agents/claude.js` (lines 383-462)
Added `pingKeepalive()` method that:
- Spawns a fresh CLI process independently from the main persistent process
- Sends `/status` command to refresh the session token
- Uses a 10-second timeout (shorter than the regular command timeout)
- Handles trust prompts and terminal capability queries
- Tears down the process cleanly after completion
- Returns `true` on success, `false` on failure
- Does NOT modify `this.usage` or `this.error` state

2. `src/agents/codex.js` (lines 377-460)
Added `pingKeepalive()` method that:
- Skips the ping when using JSON-RPC mode (session is managed by RPC)
- Spawns a fresh CLI process for PTY mode
- Sends `/status` command to refresh the session token
- Handles interactive prompts (trust, update screens, continuation prompts)
- Uses the same 10-second timeout
- Tears down the process cleanly
- Returns `true` on success, `false` on failure
- Does NOT modify `this.usage` or `this.error` state

3. `test/unit/parsers.test.js`
Added comprehensive unit tests for both agents' `pingKeepalive()` methods:
- ClaudeAgent pingKeepalive tests (6 tests):
  - Spawns a fresh process for session refresh
  - Returns false on spawn failure
  - Returns false on timeout
  - Sends /status command when CLI is ready
  - Does not affect usage or error state
  - Tears down process cleanly after completion

- CodexAgent pingKeepalive tests (9 tests):
  - Skips ping when using JSON-RPC mode
  - Spawns a fresh process when not in JSON-RPC mode
  - Returns false on spawn failure
  - Returns false on timeout
  - Sends /status command when CLI is ready
  - Does not affect usage or error state
  - Handles interactive prompts during ping
  - Tears down process cleanly after completion
  - Handles unknown RPC support state (null)

Acceptance Criteria Met
✅ Calling `pingKeepalive()` refreshes the underlying CLI auth session - The method spawns a fresh CLI process and sends `/status` to trigger session refresh
✅ The ping operates silently and tears down its process cleanly - Uses a dedicated process that's killed after completion without affecting the main process
✅ The main status UI does not flicker or show errors if a background keepalive fails - Returns boolean success/failure without modifying `usage` or `error` state
…of the implementation:

Implementation Summary

I have successfully implemented GitHub issue #70 - Activity-Based Polling via Local Log Monitoring. Here's what was implemented:

New Files Created:
1. `src/activity-monitor.js` - ActivityMonitor utility class that:
   - Watches known log directories for Claude (`~/.config/claude/projects/`, `~/.claude/`), Codex (`~/.codex/sessions/`, `~/.codex/`), and Gemini (`~/.config/gemini/`, `~/.gemini/`) using `fs.watch`
   - Supports configurable debounce interval (default: 5000ms)
   - Triggers callbacks when activity is detected
   - Provides status methods to check monitoring state

2. `test/unit/activity-monitor.test.js` - Comprehensive unit tests (47 tests) covering:
   - Constructor options and defaults
   - Start/stop functionality
   - File change handling and debouncing
   - Activity triggering and callbacks
   - Status reporting

Modified Files:
1. `src/index.js` - Updated AgentTank class:
   - Added `autoRefreshMode` configuration with 3 modes: `'none'`, `'interval'`, `'activity'` (default)
   - Added `activityDebounce` configuration option
   - Implemented `_startActivityBasedRefresh()` for activity mode
   - Implemented `_handleActivityDetected()` and `_runActivityRefreshCycle()` for on-demand refresh cycles
   - Preserved `_startIntervalBasedRefresh()` for traditional polling
   - Added `getActivityMonitorStatus()` and `getAutoRefreshConfig()` methods
   - Exported `AUTO_REFRESH_MODES` constant

2. `bin/agent-tank.js` - Updated CLI:
   - Added `--auto-refresh-mode` option (none, interval, activity)
   - Added `--activity-debounce` option (milliseconds)
   - Updated help text with new options and mode descriptions
   - Added environment variable support: `AGENT_TANK_AUTO_REFRESH_MODE`, `AGENT_TANK_ACTIVITY_DEBOUNCE`
   - Added config file support for `autoRefresh.mode` and `autoRefresh.activityDebounce`

3. `README.md` - Updated documentation:
   - Added new "Activity-Based Polling" section explaining the feature
   - Updated command line options table
   - Updated environment variables table
   - Added configuration examples

4. `test/unit/watcher.test.js` - Updated tests (74 tests, 27 new):
   - Tests for `autoRefreshMode` configuration
   - Tests for `activityDebounce` configuration
   - Tests for `getActivityMonitorStatus()` method
   - Tests for `getAutoRefreshConfig()` method
   - Tests for `AUTO_REFRESH_MODES` constant
   - Tests for backwards compatibility with `autoRefreshEnabled: false`

Acceptance Criteria Met:
- ✅ `autoRefreshMode` logic safely handles the three options (`none`, `interval`, `activity`), defaulting to `activity`
- ✅ `ActivityMonitor` successfully detects changes in target directories for Claude, Codex, and Gemini
- ✅ Refreshes are triggered based on the provided debounce interval
- ✅ During active usage, polling functions as an interval loop; during idle periods, polling is disabled to save resources
- ✅ CLI and README are updated with the new configurations

Test Results:
- ActivityMonitor tests: 47 passed
- Watcher tests: 74 passed
- Total new tests: 121 passed
@integry
integry marked this pull request as ready for review March 19, 2026 11:49
@integry
integry merged commit 5a1bb8d into main Mar 19, 2026
1 check passed
@integry
integry deleted the 65-epic-implement-json-ctn branch March 19, 2026 11:49
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

1 participant