omp packages

@gtheys/pi-interactive-subagents0.2.0

Interactive subagents for pi - spawn, orchestrate, and manage sub-agent sessions in herdr background tabs

gtheys Published 2 days ago MIT ~0 downloads/mo

Untested on omp

This is a pi package. No one has reported whether it works on omp yet. If you try it, add your result below.

Did it work for you?

Result

One report per person. A new report replaces your old one.

Reports 0

No reports yet.

Readme

pi-interactive-subagents

Async subagents for pi — spawn a team of AI agents that work in background tabs while you keep coding. Ask them questions mid-run, let them ask you, give them their own git worktrees, and never lose track of a run — even if your parent session dies.

https://github.com/user-attachments/assets/30adb156-cfb4-4c47-84ca-dd4aa80cba9f

Why

Orchestrating agents usually means one of two bad deals: block your main session while a child runs, or fire and forget and lose the thread. This extension takes a third path, ported from pi-herdsman (see Acknowledgements):

  • Never blocks. subagent() returns in milliseconds. The child runs in a background herdr tab; your pane, focus, and flow never move.
  • Never loses work. Results, assignments, and control messages are durable files, not screen scrapes. Kill the parent, relaunch, and subagents_list rediscovers every orphaned child — with a resume hint.
  • Talks both ways. Children can ask blocking questions (ask_owner), send fire-and-forget updates (message_owner), and message each other (message_peer). The parent answers with answer_subagent and the conversation continues in the same child session.

How it works

1. Agent calls subagent()         → returns immediately ("launched in background")
2. Child runs in a herdr tab      → widget shows live status + activity + cost
3. You keep working               → main session fully interactive
4. Child finishes                 → result steered back, parent wakes and continues

The widget above your input tracks every run — click a row to open that agent's tab:

╭─ Subagents ───────────────────────────── 2 running · 41.2k tok $0.18 ─╮
│ ● Scout: Auth (scout)         active (bash 12s) · 12.3k tok $0.04    │
│ ● Worker: migrations (worker)          waiting 2m · 28.9k tok $0.14  │
╰────────────────────────────────────────────────────────────────────────╯

States: starting → active (with the current tool and elapsed time) → waiting, plus stalled when a child's heartbeat goes silent — and a steer to the parent so it can react. Status comes from a child-written snapshot file, never from watching screen pixels.

Prompt cache stability

Repeated spawns of the same role are shaped to keep the prompt prefix stable so provider-side prompt caching can latch onto it:

  • Role identity rides the system prompt via --append-system-prompt flag files — stable per role and byte-identical across spawns of that role.
  • The first user message is modeHint + task + summaryInstruction. It is dynamic, but spawns of the same role diverge only at the task text, after an identical modeHint prefix.
  • aven-context is gated off in child sessions, so no per-spawn aven blob lands at the front of the message stream, and role identity is no longer inlined into the dynamic first message.

Known remaining sources of prefix divergence, both benign:

  • The trailing cwd section of the system prompt differs per worktree spawn — this is pi-core behavior and out of scope here.
  • /skill: follow-up prompts trail the task text, so the stable prefix ahead of them is preserved.

This contract is enforced by the request-composition tests in test/task-composition.test.ts (the "request composition" describe block).

The flows

Parallel scouting

subagent({ name: "Scout: Auth", agent: "scout", task: "Analyze auth module" });
subagent({ name: "Scout: DB", agent: "scout", task: "Map database schema" });
// Both return immediately; results steer back independently as they land.

A child that asks before it acts

// Inside the child:
ask_owner({ question: "Two migration files conflict — use v1 or v2?" });
// Child blocks (widget: "blocked"). Parent wakes with the question, answers:
answer_subagent({ name: "Worker", message: "Use v2, v1 is deprecated" });
// Answer arrives as the child's next user message — same session, full context.

Answers travel through a durable mailbox (asks/ records + reply sidecars), not pane typing — nothing gets mangled, and ingestion is acknowledged on both ends.

Non-blocking updates from the trenches

// Inside the child — fire-and-forget, keeps working:
message_owner({ message: "Schema scan done, 3 hotspots found, moving to API layer" });
// Parent's next status tick delivers a coalesced subagent_message steer.

Peer-to-peer

Sibling subagents discover each other through presence files and talk directly:

list_peers();                                    // who else is running?
message_peer({ peer: "scout-auth", message: "Found the session store — stop looking" });

Isolated worktrees, one call

subagent({
  name: "Worker: payments",
  agent: "worker",
  worktree: true,   // or { base: "release/2.4" }
  task: "Implement the refund flow",
});
// git worktree add → child spawned with cwd = the new worktree.
// Your checkout is untouched; the branch and path ride along in the result.

Surviving the crash

Every spawn writes a durable assignment record. Parent dies? Relaunch pi and:

subagents_list();
// ● scout-auth — ORPHANED (parent gone). Resume: subagent_resume({ sessionPath: "…" })

Children with records are deliberately spared when a parent shuts down. Completed runs settle into a durable result store; crash-inferred endings are marked lost — never invented state.

/iterate and /plan

  • /iterate Fix the off-by-one in pagination — forks your full conversation into a subagent, keeps your main context clean.
  • /plan Add dark mode — orchestrates investigate → plan → execute → review with bundled agents (planner, scout, worker, reviewer, visual-tester).

Feature tour

Feature What you get
Background tabs tab create --no-focus — children never steal your screen; click widget rows to visit them
Durable results Semantic refs (results/<childId>.json) — full output survives compaction and restart
Request/ack interrupts subagent_interrupt confirms the child actually stopped its turn
Usage rollup Live per-row · 12.3k tok $0.04 in the widget, transitive tree totals in subagents_list
Context retirement Opt-in (contextRetirement.enabled): settled child payloads shrink to refs under compaction pressure — long orchestrations stop bloating the parent context
Governed spawning spawning: manager-approval frontmatter: the model can't spawn that agent on its own — your /subagent command is the approval
Version gate Preflight rejects herdr < 0.9.1 with an actionable message instead of weird failures

Install

pi install git:github.com/HazAT/pi-interactive-subagents

Requires herdr >= 0.9.1 (tested against 0.9.5 and pi-coding-agent 0.85.1):

herdr pi

[!CAUTION] This extension only runs inside a herdr session. Children live in herdr panes, so pi must be started via herdr pi with herdr on PATH and the herdr server running (version >= 0.9.1 — the preflight gate). Without that, pane and worktree operations (subagent(), subagent_resume, subagent_interrupt, worktree: true) refuse with an actionable herdr preflight failed error result — there is no fallback mode and nothing is silently degraded. See Requirements and the version-gate row in the Feature tour.


Reference

Tools

Main session:

Tool Description
subagent Spawn a sub-agent in a background tab (async — returns immediately)
subagent_interrupt Interrupt a running Pi-backed subagent's current turn (ack-confirmed)
subagents_list Agent definitions and live assignment records (running / orphaned / lost, usage, resume hints)
subagent_resume Resume a previous sub-agent session (async)
answer_subagent Answer a child's outstanding ask_owner question

Subagent-side (auto-injected, never deniable):

Tool Description
subagent_done Finish and return results to the parent
caller_ping Ask for help and exit — parent resumes the session with guidance
ask_owner Blocking question to the parent; answer arrives in the same session
message_owner Fire-and-forget update to the parent
list_peers / message_peer Discover and message sibling subagents

Commands

Command Description
/plan Planning pipeline — create-plan (Jira ID) / feature-plan (free text) / bundled generic workflow
/iterate Fork into a subagent for quick fixes
/subagent <agent> <task> Spawn a named agent directly (user-initiated — bypasses manager-approval gates)
/subagents Open the subagent dashboard
/subagent prune Run the retention sweep on demand (requires retentionDays config; warns if unset)

Note: a bare /subagent prune (no task text) is intercepted as the retention sweep. An agent literally named prune remains spawnable with an explicit task — /subagent prune <task> falls through to agent resolution.

subagent() parameters

Parameter Type Default Description
name string required Display name (widget + tab label)
task string required Task prompt for the sub-agent
agent string — Load defaults from an agent definition
fork boolean false Force full-context fork for this spawn
worktree boolean | {base?} false Spawn in a fresh git worktree (~/.herdr/worktrees/<repo>/<branch>); removal is manual
interactive boolean derived Don't wake the parent on stall/recovery (default: inverse of auto-exit)
model string — Override agent's default model
systemPrompt string — Append to system prompt
skills string — Comma-separated skill names
tools string — Comma-separated tool names
cwd string — Working directory (mutually exclusive with worktree)

Bundled agents

Agent Model Role
planner Opus (medium thinking) Brainstorming, plans, todos
scout Haiku Fast codebase reconnaissance
worker Sonnet Implements tasks, runs tests
reviewer Opus (medium thinking) Bugs, security, correctness
visual-tester Sonnet Visual QA via Chrome CDP

Discovery precedence: project-local (.pi/agents/) > global (~/.pi/agent/agents/) > bundled.

Agent frontmatter

Full field reference with defaults, valid values, and recipes: docs/agent-frontmatter.md.

---
name: my-agent
description: Does something specific
model: anthropic/claude-sonnet-4-6
tools: read, bash, edit, write
session-mode: lineage-only
spawning: manager-approval
auto-exit: true
---

You are a specialized agent that does X...
Field Description
session-mode standalone (default), lineage-only (linked, no copied turns), fork (inherits conversation)
spawning true (default), false (deny spawn tools), "manager-approval" (model calls denied; /subagent is the approval)
deny-tools Comma-separated extension tools to deny
auto-exit Shut down when the turn finishes; any user input disables it permanently
interactive Override stall-ping behavior (default: inverse of auto-exit)
cwd Default working directory
disable-model-invocation Hide from listings; still invokable by explicit name

The /plan workflow

/plan IMP-7070                → create-plan skill (Jira flow)
/plan Add a dark mode toggle  → feature-plan skill / bundled generic workflow

Generic pipeline: investigate → interactive planning → todo review → execute → review, with tab titles tracking the phase (🔍 → 💬 → 🔨 1/3 → 🔎 → ✅).

Interrupt semantics

subagent_interrupt is a turn-level interrupt, not a kill: Escape is delivered to the child, the .ack handshake confirms the turn stopped, the widget moves to waiting, and the session stays alive for follow-ups. Pi-backed children only.

caller_ping — the escalator

// Inside a worker subagent:
caller_ping({ message: "Found two conflicting migration files — v1 or v2?" });
// Session EXITS. Parent gets the ping and resumes the session with guidance:
subagent_resume({ sessionPath: "…", message: "Use v2 — v1 is deprecated" });

Unlike ask_owner (blocks, stays alive), caller_ping ends the session — use it when the child is done until further notice.

Replay safety for child side-effect tools

Child side-effect tools are replay-safe across interrupted runs: each call is keyed by a durable effect memo (tool-effects/) plus the effect's own records (ask record, recipient inbox, .exit payload). On replay after a crash:

  • ask_owner — replays the original askId; no second ask record, no misleading outstanding-ask error. After a formal resume wipe, the fresh ask carries an explicit orphan notice naming the dead askId.
  • caller_ping / subagent_done — the original .exit payload is preserved verbatim; identical replays don't rewrite it, and a conflicting payload is reported explicitly, never overwritten.
  • message_owner / message_peer — a memo hit or durable inbox evidence means the message is reported as already delivered, never sent twice; a send with no durable evidence is re-sent fresh with the normal delivery text (the explicit interrupted-or-conflict report exists only for the exit tools above). Additionally, a message_peer send durably binds its resolved recipient (childId + session file) before the inbox write (peer-bindings/), so a replay never retargets a reused peer name: if the bound recipient has died or been superseded by a new generation, the send fails closed instead of delivering to the wrong child, and a failed first write retries against the original recipient.

Replay matches exactly: a rephrased message or a differently-spelled peer is a new logical effect, not a replay.

Boundary: generic tools (Bash, file edits) have no exactly-once protection. A crash after a generic side effect may replay it — keep non-idempotent shell work out of interruptible children.

Receive-side delivery dedup (delivered sentinels) is a separate mechanism (PMR-KY0E) and is unchanged by this.

Co-extension state events #state-events

Other extensions can observe subagent state without parsing the status widget, importing internal stores, or reading durable records. This extension publishes versioned snapshots on the Pi extension event bus (ExtensionAPI.events). Declarations below are the public contract, reproduced from pi-extension/subagents/state-events.ts.

export const SUBAGENT_STATE_CHANNEL = 'pi-my-rifle-subagents:state'

export const SUBAGENT_STATE_EVENT_VERSION = 1

export type SubagentStateStatus =
  | 'starting'
  | 'working'
  | 'blocked'
  | 'waiting'
  | 'stalled'
  | 'lost'

export interface SubagentStateEntry {
  id: string
  name: string
  status: SubagentStateStatus
}

export interface SubagentStateEvent {
  type: 'snapshot' | 'stopped'
  version: 1
  incarnation: string
  seq: number
  emittedAt: string
  agents: SubagentStateEntry[]
}
Semantics
  • Push-only full snapshots. No deltas. Every event carries the complete set of live agents, so a consumer replaces its view instead of merging.
  • Disappearance = settled. A child that completed or was lost is simply absent from the next snapshot. 'lost' is a reserved status value that is never emitted live; it stays in the union so exhaustive switch statements are forward-stable.
  • Durable records stay authoritative for outcome detail. The exit status, result payload, activity file, etc. are not in this event — read the durable assignment/result records (or inspectResultRef) for that. The state event is observation only.
  • Envelope. version (schema version, currently 1), incarnation (UUID per publisher module load — a /reload starts a new incarnation and seq restarts at 1), seq (1-based, strictly monotonic within an incarnation), emittedAt (ISO 8601), type ('snapshot' | 'stopped').
  • 'stopped'. Emitted once, with agents: [], when the parent session shuts down cleanly. Use it to clear your view.
  • Ordering. Track the latest incarnation you have seen and drop events from older ones. Use seq only to detect out-of-order or duplicated delivery inside the current incarnation — it is not a cross-restart cursor.
  • Nothing else is projected. Per entry only id, name, status. Task prompts, message bodies, cwd, session/activity file paths, claim PIDs, pane and tab ids, worktree paths, and usage are deliberately excluded and are covered by a key-set contract test.
Subscribing

Subscribe at extension-body load, not inside your own session_start handler. The publisher emits its initial snapshot from the parent session's session_start; if you wait for your own session_start you may miss it and see nothing until the next transition.

// The subscriber's own copy of the contract, trimmed to the fields it reads.
// Type-only imports of the published declarations are fine; importing the
// publisher's module to READ state is not (see "Dual module instances").
type StateEventView = {
  type: 'snapshot' | 'stopped'
  incarnation: string
  seq: number
  agents: Array<{ id: string; name: string; status: string }>
}

export default function (pi: ExtensionAPI) {
  // Extension-body load — guarantees receipt of the initial snapshot.
  pi.events.on('pi-my-rifle-subagents:state', (event: StateEventView) => {
    // v1 is additive-only: read the documented keys, ignore unknown fields.
    if (event.type === 'stopped') return // publisher session ended
    renderAgentList(event.agents) // full snapshot: replace, never merge
  })
}

Keep a 'lost' arm in any exhaustive switch on status even though it never arrives live — it is part of the v1 union and removing it would be a breaking change.

Scope caveats
  • Per-process bus only. There is no cross-process delivery. Subscribers must run in the same Pi process as the publisher.
  • Children never publish. Only the parent session emits; subagent sessions do not publish state events even though their own session_start / session_shutdown hooks run.
  • Dual module instances. Pi loads this extension's entrypoint directly, while a co-extension may import the same source through the workspace package root — those can be distinct module instances, and only the entrypoint instance wires emissions. Subscribe via pi.events; never read state from a module import (importing the types is fine, importing the sequencer or a store is not).
  • Status refresh disabled. With status.enabled: false the 1s status tick does not run, so live kind drift (stalled, waiting, recovered) is not published. Spawn, working, settlement and stopped emissions still fire — they hang on the durable/Map seams, not the tick.
Versioning policy

SUBAGENT_STATE_EVENT_VERSION is 1 and v1 is additive-only: consumers MUST ignore unknown fields, and publishers MAY add fields without bumping the version. Breaking changes (removed or renamed fields, changed semantics) bump the constant. A key-set contract test pins the current payload so any addition is a deliberate version-policy decision rather than silent drift.

Configuration

Config lives at ~/.pi/agent/pi-subagents/config.json (created with defaults on first run).

Option Type Default Description
status.enabled boolean true Live status widget and refresh loop
status.hideWhenIdle boolean true Hide the "Subagents · N running" widget completely while no subagent exists; set false to keep the box visible at zero
contextRetirement.enabled boolean false Retire settled subagent payloads to durable refs when compaction pressure hits
watchdog.enabled boolean true Dead-turn stall watchdog: age frozen present+active snapshots into stalled and escalate dead child turns. false restores the legacy never-age behavior
watchdog.streamStallAfterMs number 150000 Deadline (ms) for the frozen streaming scope — silence there means the model turn died mid-generation
watchdog.quietStallAfterMs number 1800000 Deadline (ms) for provider/tool/turn/unknown scopes and sustained snapshot loss. provider is deliberately long-bucket: pre-first-token silence (large prompt processing, 429/529 retry backoff) emits no events, so a short provider deadline false-kills healthy children mid-request
retentionDays integer unset (no pruning) Opt-in: prune inactive subagent data-root records whose newest activity is older than this many days. Live, current, and resumable state is never pruned. Runs automatically at session start and on demand via /subagent prune
{
  "$schema": "https://json-schema.org/schema",
  "status": {
    "enabled": true,
    "hideWhenIdle": true
  },
  "contextRetirement": {
    "enabled": false
  },
  "watchdog": {
    "enabled": true,
    "streamStallAfterMs": 150000,
    "quietStallAfterMs": 1800000
  }
}

retentionDays is opt-in and intentionally absent from the shipped defaults — add it to enable pruning:

{
  "$schema": "https://json-schema.org/schema",
  "retentionDays": 30
}

Data retention policy

When retentionDays is set, a maintenance sweep runs automatically at session start and on demand via /subagent prune, removing inactive data-root records whose newest relevant activity is older than the configured age. The sweep reports what it removed and never aborts session startup. The automatic session-start sweep stays silent unless it removes something — a sweep that removes nothing (including one degraded by persistent failures, e.g. an unreadable data root) posts no notification; run /subagent prune on demand to surface skip reasons and failures.

Safety rules:

  • Never pruned: result-ref-reservations/ and spawn-seq/ — monotonic counters; pruning them would silently reuse result refs and childIds.
  • Age-eligible: results/, retired/ — removed once older than the cutoff.
  • Session-checked: assignments/, peers/, asks/, inbox/, delivered/, interrupts/, tool-effects/, peer-bindings/ — pruned only when aged out and liveness is verifiably dead and the resume-source session file no longer exists. Live, current, resumable, unreadable, or unverifiable records are always kept; any inspection failure skips the record.
  • Ref expiry: pruned results/ records can never silently resolve to different content — reservation markers are never pruned and their target identity is immutable. The inspectResultRef API reports a pruned target loudly as expired ("result expired by retention policy"); runtime result consumers today keep their own pre-prune record path and surface a pruned record as a plain missing-record error.
  • pi-flow run journals are never touched.

Requirements

  • pi — the coding agent
  • herdr >= 0.9.1

Acknowledgements

The coordination architecture — durable file-based channels (results, assignments, mailboxes), blocking ask_owner semantics, presence and peer messaging, usage rollup, context retirement, and governed spawning — is ported from pi-herdsman by @boadij (Apache-2.0). Herdsman proved these mechanisms in production; this package re-implements them on herdr's tab model with pi-native session files as the authority. Thank you for the blueprint.

The sub-agent status supervision and turn-only interruption features were inspired by RepoPrompt's sub-agent snapshot polling and run cancellation features.

License

MIT