pi-subagents

repository·main·Indexed 22 days ago

https://github.com/nicobailon/pi-subagents

A Pi extension (v0.37.2) that allows a parent session to delegate tasks to focused child agents. It supports foreground and background execution, parallel workflows, and a TUI FleetView for monitoring. Includes specialized builtin agents such as scout, researcher, planner, worker, reviewer, context-builder, oracle, and delegate, as well as an opt-in adversarial watchdog for repository edit verification.

Tokens
44.1K
Snippets
80
Records
186
Agent score
84%

What's inside pi-subagents

  1. Configure and use the subagent watchdog

    main

    The watchdog is an opt-in adversarial reviewer that checks repository edits at the agent_end boundary. It is distinct from the reviewer subagent.

    Key Features

    • Trigger: Runs only when a writer agent changes the final repo state. It skips unchanged/reverted diffs and .pi-subagents/ or tmp/ artifacts.
    • LSP Integration: Automatically checks changed TS/JS files using typescript-language-server. Errors are blockers; warnings are concerns.
    • Model Pairing: It is recommended to use a strong, complementary model to your main session (e.g., if using Opus, use GPT).

    Commands

    • /subagents-watchdog on: Enables the watchdog.
    • /subagents-watchdog recommend-model: Asks for the current recommended strong pairing.
    • /subagents-watchdog model <model_id>: Sets the watchdog model (e.g., anthropic/claude-opus-4-8:high).
    • /subagents-watchdog check: Manually triggers a check.

    Configuration

    Configure the watchdog in settings using subagents.watchdog:

    • Main Watchdog: subagents.watchdog.main.model and subagents.watchdog.main.thinking.
    • Child Watchdogs: subagents.watchdog.children.model (default) or subagents.watchdog.children.overrides.<agent>.model.
    • LSP Bounds: subagents.watchdog.lsp.enabled, timeoutMs, maxFiles, and maxDiagnostics.
    {
      "subagents": {
        "watchdog": {
          "enabled": true,
          "main": {
            "model": "anthropic/claude-opus-4-8",
            "thinking": "high"
          }
        }
      }
    }
  2. How pi-subagents works

    main

    In this model, Pi acts as the parent session, and a subagent is a focused child Pi session with a specific job.

    When you request a subagent, Pi starts the child session, assigns the task, and returns the result to the parent.

    • Foreground runs: Results stream directly into your current conversation.
    • Background runs: These continue working independently and can be checked later.

    Note: Installing the extension does not automatically start background agents. To ensure every implementation is reviewed, you must explicitly request it in your prompt or include it in your project instructions (e.g., When you finish implementing, run a reviewer subagent before summarizing.).

  3. Implement the Oracle Workflow for advisory review

    main

    The oracle agent is a forked advisory thread that inherits the parent session history. It is intended to be used as a 'smart-friend' escalation for trajectory and architectural concerns rather than simple diff inspection.

    The Oracle Loop Pattern:

    1. Fork to Oracle: The main agent forks to oracle to review direction, drift, assumptions, and risks.
    2. Coordinate: oracle can coordinate back via contact_supervisor if the bridge allows.
    3. Approve: The main agent decides which direction to approve.
    4. Implement: Only after approval does a worker agent implement the task.

    When to use oracle:

    • Architectural boundaries or model capability routing.
    • Merge conflicts or reviewer disagreements.
    • Context drift after long work sessions.
    • When a worker is about to invent a new pattern or requires product/scope tradeoffs.
    // 1. Advisory review in a branched thread
    subagent({
      agent: "oracle",
      task: "Review my current direction, challenge assumptions, and propose the best next move."
    })
    
    // 2. Implementation only after explicit approval
    subagent({
      agent: "worker",
      task: "Implement the approved approach: ..."
    })
  4. Use the Staged Fix Orchestration technique

    main

    When dealing with a broad diff with multiple reviewer findings, use a three-stage chain to keep the worktree safe and avoid multiple writers competing in the same space.

    The Three Stages:

    1. Planning (Parallel Read-Only): Multiple reviewer agents (one per issue cluster) inspect the diff and return proposed fixes/validation plans. They must not edit.
    2. Implementation (Single Writer): One worker receives the planning summaries via {previous} and is the sole agent allowed to edit the active worktree.
    3. Validation (Parallel Read-Only): Multiple reviewer agents inspect the worker's diff from fresh context to report pass/fail and remaining blockers.

    Best Practices:

    • Use async: true and context: "fresh" for planners/validators.
    • Use outputMode: "file-only" for large summaries.
    • Use as and {outputs.name} to pass specific results between stages instead of the entire {previous} blob.
    • Use phase and label to make the async status readable.
    subagent({
      async: true,
      context: "fresh",
      chain: [
        { parallel: [
          { agent: "reviewer", phase: "Planning", label: "Deploy docs", as: "deployPlan", task: "Plan fixes for deploy docs/workflow. Inspect the current diff. Do not modify project/source files; returning findings via the configured output artifact is allowed.", output: "plans/deploy.md", outputMode: "file-only" },
          { agent: "reviewer", phase: "Planning", label: "Scheduler contract", as: "schedulerPlan", task: "Plan fixes for scheduler contract. Inspect the current diff. Do not modify project/source files; returning findings via the configured output artifact is allowed.", output: "plans/scheduler.md", outputMode: "file-only" },
          { agent: "reviewer", phase: "Planning", label: "Sandbox/security", as: "sandboxPlan", task: "Plan fixes for sandbox/security. Inspect the current diff. Do not modify project/source files; returning findings via the configured output artifact is allowed.", output: "plans/sandbox.md", outputMode: "file-only" }
        ], concurrency: 3 },
        { agent: "worker", phase: "Implementation", label: "Apply accepted fixes", as: "workerResult", task: "Apply only the accepted fixes from these planning summaries. You are the sole writer for the active worktree. Run focused validation and report changed files, commands, failures, and remaining issues.\n\nDeploy plan:\n{outputs.deployPlan}\n\nScheduler plan:\n{outputs.schedulerPlan}\n\nSandbox plan:\n{outputs.sandboxPlan}", output: "worker/fixes.md", outputMode: "file-only", progress: true },
        { parallel: [
          { agent: "reviewer", phase: "Validation", label: "Deploy/scheduler validation", task: "Validate the post-worker diff for deploy and scheduler fixes. Start from the worker result: {outputs.workerResult}. Do not modify project/source files; returning findings via the configured output artifact is allowed.", output: "validation/deploy-scheduler.md", outputMode: "file-only" },
          { agent: "reviewer", phase: "Validation", label: "Sandbox validation", task: "Validate the post-worker diff for sandbox/security fixes. Start from the worker result: {outputs.workerResult}. Do not modify project/source files; returning findings via the configured output artifact is allowed.", output: "validation/sandbox.md", outputMode: "file-only" }
        ], concurrency: 2 }
      ]
    })
  5. Understand capability ceilings in Pi Subagents

    main

    Parent extensions can register session-scoped, out-of-band ceilings via pi-subagents/capability-ceiling.

    When a ceiling is registered:

    • Child tools are intersected with every active registration and inherited snapshot.
    • denyExtensions can be used to remove ambient/provider extension loading while retaining the package protocol runtime.

    Important Constraints:

    • Do not add a model-visible ceiling field.
    • Do not rely on role selection for enforcement.
    • Restricted schedules are rejected unless their ceiling can be persisted safely.
  6. Use the Parallel Cleanup technique

    main

    After implementation, launch two fresh-context reviewer tasks to reduce 'AI-slop'.

    Tasks:

    • Deslop pass: Removes unnecessary verbosity or redundant code.
    • Verbosity pass: Ensures concise output.

    Guidelines:

    • Use output: false and progress: false for these tasks.
    • If deslop or verbosity-cleaner skills are available, pass them to the reviewer.
    • Explicitly instruct: "Do not modify project/source files; returning findings through the configured output artifact is allowed."
  7. Understand subagent lifecycle artifacts and observability

    main

    Async runs generate machine-readable lifecycle artifacts for observability.

    File Structure

    For a top-level async run, details.asyncDir points to a directory containing:

    • status.json: Contains stable v1 fields like runId, state, startedAt, endedAt, totalTokens, totalCost, and results.
    • events.jsonl: A log of lifecycle transitions (e.g., subagent.run.started, subagent.step.completed, subagent.run.stopped).
    • output-<index>.log: Standard output logs.
    • subagent-log-<runId>.md: A markdown log of the subagent's activity.

    Final summaries are written to the Pi subagent results directory as <runId>.json.

    Process Proofs

    Lifecycle artifact v3 includes process-terminal-candidate.json (private) and process-terminal.json (public proof). A proof is only marked as observed once the parent observes the exact detached runner's close event and all child writers have closed. If the observer is unavailable, the status is unknown.

  8. Register agents with names and packages

    main

    When defining agents, you can use frontmatter or package metadata to control their runtime name. If you provide both a name and a package, the agent is registered under a combined runtime name in the format package.name.

    For example, an agent with name: scout and package: code-analysis will be identified at runtime as code-analysis.scout. During serialization, the name and package fields remain separate.

    name: scout
    package: code-analysis
  9. Use the Parallel Handoff-Plan technique

    main

    Use this to produce a solution brief or implementation-ready handoff by combining external research and local context.

    Workflow:

    1. Parallel Step: Run researcher (external) and context-builder (local) in parallel.
    2. Synthesis Step: A final context-builder reads the previous outputs and writes a handoff/final-handoff-plan.md containing the recommended approach, constraints, risks, and a compact implementation-ready meta-prompt.
    subagent({
      chain: [
        { parallel: [
          { agent: "researcher", task: "Research the external reference and transferable implementation ideas for: ...", output: "handoff/external-reference.md" },
          { agent: "context-builder", task: "Build local codebase context for: ...", output: "handoff/local-context.md" },
          { agent: "context-builder", task: "Compare evidence and propose implementation strategy for: ...", output: "handoff/implementation-strategy.md" }
        ] },
        { agent: "context-builder", task: "Read {previous} and synthesize the final handoff plan and implementation-ready meta-prompt.", output: "handoff/final-handoff-plan.md" }
      ],
      context: "fresh"
    })
  10. Use the Review-Loop technique

    main

    This technique implements an iterative loop where a worker implements fixes and reviewer agents inspect the results until no more significant issues are found.

    Workflow:

    1. Worker: An async worker implements or fixes code.
    2. Reviewer: Fresh-context reviewer agents inspect the actual repo/diff.
    3. Synthesis: The parent synthesizes accepted fixes.
    4. Application: An async forked worker applies the fixes.

    Constraints:

    • Async Mode: Use async: true to unblock the main chat. Do not use clarify: true unless explicitly requested.
    • Loop Termination: Stop when reviewers find no blockers, an unapproved decision is reached, or the max review-round cap (default 3) is hit.
    • Safety: Do not pass turnBudget or toolBudget to mutation-capable children (workers/reviewers with edit authority). Instead, use a narrow task with an elapsed deadline and request a checkpoint.
  11. Configure agent prompt assembly and inheritance

    main

    By default, subagents are narrow and do not automatically inherit Pi's base prompt, project instructions, or skills. Use the following fields in the agent's YAML frontmatter to control context inheritance:

    FieldEffect
    systemPromptMode: appendAppends the agent prompt to Pi's normal base prompt.
    inheritProjectContext: trueKeeps inherited project instructions (e.g., from AGENTS.md or CLAUDE.md).
    inheritSkills: trueAllows the child to see Pi's discovered skills catalog.
    defaultContext: forkUses forked session context if a launch omits context (explicit context: "fresh" still wins).