pi-harness-runtime
[BETA] Codex-style /usage status + autonomous coding harness for pi. Not production ready — expect breaking changes.
Package details
Install pi-harness-runtime from npm and Pi will load the resources declared by the package manifest.
$ pi install npm:pi-harness-runtime- Package
pi-harness-runtime- Version
1.1.33- Published
- Aug 31, 2026
- Downloads
- 10.2K/mo · 1,974/wk
- Author
- manotluijiu
- License
- MIT
- Types
- extension, skill, prompt
- Size
- 6.3 MB
- Dependencies
- 8 dependencies · 4 peers
Pi manifest JSON
{
"skills": [
"./skills"
],
"prompts": [
"./prompts"
],
"extensions": [
"./index.ts"
]
}Security note
Pi packages can execute code and influence agent behavior. Review the source before installing third-party packages.
README
Pi Harness Runtime
!️ Beta Notice — Not Production Ready !️ This project is in active development. Core features work.
Autonomous AI coding harness for pi: local token tracking + provider mirror + task orchestration.
Two Flavors
1. /usage — Token Tracking (stable ✅)
Codex-style usage tracking with local tokens + provider mirror.
2. /harness — Autonomous Coding Loop (beta 🔨)
Give the runtime a requirement. It keeps working, survives interruption, and returns with code ready for review.
Install
pi install npm:pi-harness-runtime
Requires Pi v0.37.3+.
Headless Server Setup (herdr clipboard bridge)
If running on a headless server via herdr SSH, install the clipboard bridge plugin to enable copy/paste between server and local machine:
# 1. Link the plugin (already included in this package)
cd ~/.config/herdr/plugins
ln -s ~/.config/herdr/plugins/moocoding.clipboard-bridge moocoding.clipboard-bridge 2>/dev/null || true
# 2. Add keybindings to ~/.config/herdr/config.toml
cat >> ~/.config/herdr/config.toml << 'EOF'
[[keys.command]]
key = "prefix+y"
type = "plugin_action"
command = "moocoding.clipboard-bridge.copy"
description = "Copy selected text via bridge"
[[keys.command]]
key = "prefix+p"
type = "plugin_action"
command = "moocoding.clipboard-bridge.paste"
description = "Paste from clipboard bridge"
EOF
# 3. Reload herdr config
herdr server reload-config
todo-bd-sync (Auto Task Tracker)
Automatic two-way sync between rpiv-todo overlay and bd issue tracker.
When you use bd for issue tracking, this feature automatically syncs tasks.
Important:
bdis not implemented or bundled bypi-harness-runtime. It is the external Beads CLI from the upstream project:https://github.com/gastownhall/beadsInstall it system-wide from upstream, then initialize it in your own project:
# Install beads CLI (system-wide - don't clone this repo into your project)
curl -fsSL https://raw.githubusercontent.com/gastownhall/beads/main/scripts/install.sh | bash
# Initialize in YOUR project
cd your-project
bd init
# Optional: refresh or install richer instructions for your agent
bd setup codex # Codex CLI - installs skill, AGENTS.md guidance, and hooks
bd setup claude # Claude Code - installs hooks/settings
bd setup factory # Factory.ai Droid - creates/updates AGENTS.md
- Install dependencies:
# Install rpiv-todo overlay
pi install npm:@juicesharp/rpiv-todo
# Verify bd is available from your upstream beads install
bd --version
- Works automatically: Just use prompts with multiple steps, and tasks sync to bd
- Manual commands:
/bd-todo-sync # Force sync all mapped tasks
/bd-todo-status # Show sync status
Note: Auto-reminder is disabled by default (bug fix for transcript growth). See docs/todo-bd-sync.md for details.
Usage Commands
/usage # show full status (local tracking + provider mirror)
/usage refresh # force refresh quota from provider console
/usage today # today's usage + 5h window
/usage week # this week's usage + lifetime totals
/usage reset # clear provider mirror
/bd-todo-sync # Force sync all mapped tasks (todo <-> bd)
/bd-todo-status # Show todo-bd sync status and dependencies
Harness Commands
/harness start <requirement> # Start a new harness job (beta)
/harness status # Show current job status
/harness tasks # List all tasks
/harness pause # Pause when quota low
/harness resume # Resume after quota reset
/harness cancel # Cancel job
Example Session
/harness start Build a REST API with JWT authentication
# Runtime creates task graph:
# task-001: Analyze requirements -> ready
# task-002: Implement API -> depends on task-001
# task-003: Write tests -> depends on task-002
# task-004: Code review -> depends on task-003
/harness status
# Job: job-123, Status: running
# Tasks: 1/4 done, 1 running
# When quota runs low:
/harness pause
# Job paused. Resume when quota resets.
# When quota resets:
/harness resume
# Job resumed. Continue working.
# When all tasks complete:
/harness status
# Job: job-123, Status: ready_for_client
# Tasks: 4/4 done [x]
Architecture
pi-harness-runtime/
+-- index.ts # Extension entry point
+-- footer-status.ts # Footer bar renderer (local vs. mirror mode)
+-- mirror.ts # Per-provider quota mirror (mirror.json)
+-- harness/
| +-- job-state-machine.ts # 14-state lifecycle machine
| +-- task-graph.ts # DAG-based task management
| +-- master-planner.ts # Requirement -> task graph
| +-- loop-runtime.ts # Core execution loop
| +-- repair-engine.ts # Auto-fix failures
| +-- blackboard.ts # Agent coordination
| +-- context-window-manager.ts # Context tracking
| +-- agent-handoff.ts # Clean agent transitions
| +-- auto-quota-resume.ts # 5h quota auto-resume scheduler
| +-- glm-quota-countdown.ts # GLM countdown + notifications
| +-- glm-quota-logger.ts # Structured GLM quota logging
| +-- notification-events.ts # LINE/mobile notifications
| +-- e2e/
| | +-- minimax-quota-scraper.ts # Playwright MiniMax scraper
| | +-- glm-quota-scraper.ts # GLM API quota scraper
| | +-- playwright-runner.ts # Browser automation
| +-- project-detector/
| +-- detector.ts # Auto-detect project type
+-- packages/
| +-- cookie-sanitizer/ # Live cookie-file sync via chokidar
| +-- providers/ # MiniMax, OpenAI, Codex adapters
| +-- quota-manager/ # Quota signal collection
| +-- auth/ # MiniMax browser auth
| +-- worktree/ # Git worktree per task
+-- skills/
+-- harness-runtime/
+-- SKILL.md # Skill documentation
Job State Machine
created -> planning -> queued -> running -> testing -> reviewing
v v v v v
cancelled blocked waiting_human repairing ready_for_client
v v
paused_quota archived
Key Features
- Resumable: Every state change is checkpointed to disk
- Quota-aware: Detects quota exhaustion, pauses, resumes after reset
- GLM Auto-Resume: Parses 429 errors, countdown timer, notifications at 15/5/1 min, auto-resume before reset
- Provider-agnostic: MiniMax, OpenAI, GLM, Claude adapters
- Task DAG: Dependencies tracked, topological execution
- Auto-repair: Failure classification + retry with exponential backoff
- E2E testing: Scenario-based Playwright integration (coming soon)
- Project detection: Auto-detects Frappe, Next.js, React, Django, Laravel
- Per-provider mirror: Each LLM provider maintains its own quota record
- Structured logging: GLM quota events logged to
~/.pi/harness-logs/glm-quota.log
Data Directory
All data stored locally in ~/.pi/:
~/.pi/
+-- usage-status/ # /usage data
| +-- usage.jsonl
| +-- mirror.json # per-provider quota mirror
+-- harness/ # /harness data
| +-- jobs/
| | +-- <job-id>/
| | +-- checkpoint.json
| | +-- events.jsonl
| | +-- task-graph.json
| | +-- blackboard/
| | +-- repair-tasks.jsonl
| +-- inbox/ # task inbox (RFC-0101)
+-- harness-logs/ # GLM quota logs
| +-- glm-quota.log # countdown, auto-resume, notifications
+-- okf/ # (optional) Your custom OKF knowledge
Custom OKF Knowledge (Optional)
Create ~/.pi/okf/ to add your custom knowledge that the runtime reads during context compilation:
~/.pi/okf/
+-- <skill-name>.md # Your custom skill/procedure
+-- <domain>.md # Domain-specific knowledge
+-- <project>.md # Project-specific rules
The runtime automatically detects and reads these files. If the folder doesn't exist, compilation proceeds without them.
Example:
# my-custom-skill
## When to use
This skill applies when...
## Procedure
1. Step one
2. Step two
See packages/context-compiler/ for how OKF concepts are loaded.
Safety Properties
- ✅ Local-first: All data stays on disk
- ✅ No credentials stored: No passwords, tokens, or cookies
- ✅ Human-on-the-loop: Clear intervention points
- ✅ Checkpointed: Resume from any state
- ✅ Idempotent: Safe to run multiple times
Testing
bun test # ~1500+ tests across harness and packages
Automatic Quota Fetching
Quota data is automatically surfaced per-provider:
| Provider | Source | Notes |
|---|---|---|
| MiniMax | Live cookie-file watch + Playwright scrape | Drop folder: ~/.pi-harness-runtime/cookies/ |
| OpenAI / OpenAI Codex | TUI message capture | Signal on first limit hit |
| GLM (Z.ai / Zhipu) | TUI message capture | Signal on first limit hit |
| Anthropic | TUI message capture | Signal on first limit hit |
| OpenRouter | TUI message capture | Signal on first limit hit |
| Other / unknown | (no data — footer shows hint) | — |
The footer line carries the provider label, so you always know which LLM the data is from:
MiniMax: 5h: 92% left · week: 80% left # continuous (cookie scrape)
OpenAI: 5h: -- · week: -- (no signal yet) # pending first limit hit
GLM: 5h quota hit, resets Aug 25 01:47 # TUI signal with countdown
GLM: ⏳ 4h 32m (5h quota) # active countdown
GLM Auto-Resume with Countdown
When GLM 5h quota is exhausted (429 error), the runtime:
- Parses the reset time from the error message (e.g.,
"reset at 2026-08-25 01:47:16") - Starts a countdown timer showing time until reset
- Sends notifications at 15min, 5min, and 1min before reset
- Auto-resumes the job 10 seconds before reset time
- Logs all events to
~/.pi/harness-logs/glm-quota.log
Log File Location
~/.pi/harness-logs/glm-quota.log
Log Levels
| Level | Events |
|---|---|
INFO |
Countdown started, ticks, resume triggered, notifications sent |
WARN |
Notification failed, mirror update failed, parse error |
ERROR |
Auto-resume failed, critical errors |
Log Format
[2026-08-25T01:47:00.000Z] [INFO] [job-001] Countdown started: 4h 32m until 2026-08-25T06:19:00.000Z
[2026-08-25T01:48:00.000Z] [INFO] [job-001] Notification sent: 15 minutes before reset
[2026-08-25T06:18:50.000Z] [INFO] [job-001] Countdown complete, triggering auto-resume
[2026-08-25T06:18:51.000Z] [INFO] [job-001] Auto-resume succeeded, job resumed
View Logs
# Tail the log in real-time
tail -f ~/.pi/harness-logs/glm-quota.log
# View recent entries
tail -50 ~/.pi/harness-logs/glm-quota.log
# Filter by job
grep "job-001" ~/.pi/harness-logs/glm-quota.log
# Filter by errors only
grep "\[ERROR\]" ~/.pi/harness-logs/glm-quota.log
MiniMax Setup (one-time)
The runtime watches ~/.pi-harness-runtime/cookies/ for cookie files. Drop any cookie export there — it syncs within ~1 second:
Install EditThisCookie Chrome extension -> export from
platform.minimax.ioCreate the drop folder:
mkdir -p ~/.pi-harness-runtime/cookiesDrop your cookie file in the folder — any filename, any format (Netscape
.txtor EditThisCookie JSON.json):cp ~/Downloads/platform.minimax.io_cookies.txt \ ~/.pi-harness-runtime/cookies/ # …or use the EditThisCookie JSON export — same folder works.The
cookie-sanitizerpackage (@pi-harness/cookie-sanitizer) runs chokidar on this folder, normalizes everything to standard Netscape, and writes the canonical cache at~/.config/minimax-cookies.txt. Live update latency: <1 second after drop.Done! Quota auto-refreshes every ~15 minutes. Cookie file changes sync immediately.
Override: set QUOTA_COOKIE_FILE=/path/to/your/cookies.txt to bypass the sanitizer
and read a specific file directly.
herdr Integration (Clipboard Bridge)
⚠️ This only applies when using herdr.dev
If you're using a normal terminal (iTerm2, Terminal.app, etc.), clipboard works fine — no special setup needed.
When running on a headless server via herdr.dev, clipboard operations need special setup because:
- herdr's
copy_on_selectuses OSC52 which fails in VS Code's integrated terminal PTY - UTF-8 box-drawing characters (
┌─┐│└) get corrupted to garbled text - Server-side clipboard tools (
xclip,wl-copy) don't exist
Quick Setup
# Copy the example config (includes clipboard bridge keybinding)
cp config.toml.example ~/.config/herdr/config.toml
# Reload herdr config
herdr server reload-config
Usage
- Select text with mouse in herdr terminal
- Press
prefix+y(prefix isctrl+bby default) - Text is copied via the bridge to your local clipboard
How It Works
Select text in herdr
↓
Press prefix+y (plugin action)
↓
~/.herdr-clipboard (bridge file)
↓
SSH reverse tunnel or tmux buffer
↓
Your local machine clipboard
Files
| File | Purpose |
|---|---|
config.toml.example |
Template for ~/.config/herdr/config.toml |
~/.herdr-clipboard |
Bridge file between herdr and clipboard |
~/.config/herdr/plugins/moocoding.clipboard-bridge/ |
herdr plugin |
LINE Notification Setup
Get notified on your phone when tasks complete! LINE notifications via the LINE Messaging API.
Step-by-Step Setup
1. Create a LINE Messaging API channel
- Go to LINE Developers Console
- Log in with your LINE account
- Click Create a channel → select Messaging API
- Fill in the required fields (channel name, description, etc.)
- Once created, go to the Messaging API tab
2. Get your Channel Access Token
- In the Messaging API tab, scroll to Long-term channel access token
- Click Issue to generate the token
- Copy the token (starts with
eyJ...)
3. Get your User ID
- Go to your channel's Basic settings tab
- Find Your user ID (a long alphanumeric string like
U123456...) - Copy this ID
Configuration
Add to your config.toml:
[notification.line]
enabled = true
channelAccessToken = "YOUR_CHANNEL_ACCESS_TOKEN" # from Messaging API tab
userId = "YOUR_USER_ID" # from Basic settings tab
How It Works
Task event triggered (e.g., TaskCompleted)
↓
Notification payload created with event details
↓
LineAdapter.send() called
↓
POST to https://api.line.me/v2/bot/message/push
↓
Push notification sent to your LINE app
Supported Events
| Event | Emoji | Description |
|---|---|---|
JobStarted |
🚀 | Job execution started |
TaskCompleted |
✅ | Task completed successfully |
TaskFailed |
❌ | Task failed with error |
QuotaPaused |
⏸️ | Quota limit reached, countdown started, auto-resume pending |
ResumeScheduled |
▶️ | Resume scheduled |
ContextCompacted |
📦 | Context window compacted |
OutputLimitContinued |
🔄 | Output limit exceeded, continued |
E2EFailed |
🧪 | E2E test failed |
HumanReviewNeeded |
👤 | Human review required |
ReadyForClient |
🎉 | All tasks done, ready for new work |
JobCancelled |
🚫 | Job was cancelled |
Error |
⚠️ | Runtime error occurred |
Example Notification
✅ Task Completed
Implement login flow
Task: Implement login flow
Job: feature-auth
Other Providers
No setup needed. The runtime reads TUI messages and captures quota-exhaustion signals.
Once any limit is hit (e.g. OpenAI: context length exceeded, reset in 3 hr 27 min), the
footer updates immediately and the data persists in mirror.json.
Roadmap
- Core harness infrastructure (job state machine, task graph)
- Master planner
- Repair engine
- Shared blackboard
- MiniMax Web automatic quota detection
- Cookie-file drop folder + live sync (
cookie-sanitizer) - Per-provider quota mirror (
mirror.jsonkeyed by provider) - Multi-provider TUI signal capture (OpenAI, GLM, Anthropic, OpenRouter)
- LINE notification adapter (Thai mobile notifications)
- E2E test engine integration
- Claude adapter
- Production stress testing
- RFC-0101: Autonomous Operations Runtime (background execution, task inbox, lease protocol)
License
MIT © 2026 MooCoding
Related
- pi-coding-agent — Underlying pi agent
- context-mode — Context window tracking
- pi-web-access — Web search for pi
RFCs
The project tracks 101 design documents:
| RFC | Title | Status |
|---|---|---|
| 0001–0034 | Loop Runtime, Provider Adapter, Quota Manager, Playwright, Git Worktree, Checkpoint, Scheduler, Provider Router, Shared Context, Context Window Manager, Shared Blackboard, Agent Handoff, E2E Test Engine, Project Detector, Job State Machine, Task Graph, Master Planner, Repair Engine, Auto Compact & Continue, Output Token Limit, Partial Response Recovery, Notification Center, Local Browser Agent, Local Runtime Agent, Command Executor, Workspace Manager, Runtime API, Policy Engine, DeepAgents Adapter, Agent Worker Interface, Provider Adapter SDK, Checkpoint Engine, Session Manager | Proposed |
| 0035–0100 | Observability, Roadmap V1, Code Review, Code Generation, Framework Detector, Test Data Generator, Framework Plugin SDK, Prompt Compiler, Context Compiler, Requirement Compiler, Task Compiler, Project Analyzer, Dependency Analyzer, Repo Knowledge Graph, Code Merge Engine, Conflict Resolution, Documentation Generator, Capability Registry, Skill Registry, Model Registry, Cost Optimizer, Performance Optimizer, Evaluation Engine, Learning Engine, Experience Replay, Memory Engine OKF, Frappe/Next.js/React/Django/Laravel/Generic Web Plugins, CLI Plugin SDK, MCP Adapter, A2A Adapter, Codex Adapter, Requirement Intake, Project Bootstrap, Architecture Generator, Sprint Planner, Milestone Manager, Backlog Manager, Human Approval Gate, Release Manager, Version Manager, Deployment Pipeline, Multi-User Runtime, RBAC, Audit Trail, Dashboard, Analytics, Distributed Runtime, Cluster Manager, Runtime Federation, High Availability, Disaster Recovery, + 17 Autonomous Architectures | Proposed |
| 0101 | Autonomous Operations Runtime — durable Task Inbox, Background Worker, Task Lease protocol, Privilege Broker, Approval Class policy engine, abstract Scheduler, Notification pipeline, Recovery semantics | Proposed |
Why This Matters
These RFCs address real runtime failures:
- MiniMax auto-compacts but does not automatically resume.
- A model may stop because max output token limit is reached.
- Partial responses must be preserved and continued.
- The human needs mobile/tablet notifications.
- Headless servers cannot open interactive login windows for MiniMax usage console.
- The runtime must continue executing after the chat session ends, the SSH session disconnects, or the provider quota exhausts.