omp packages

@eggmasonvalue/pi-subagent3.0.0

Thin Pi subagent primitive: isolated, resumable child sessions with live progress, timeout supervision, settings.json model policy, structured results for codemode workflows, and a live /subagents transcript browser.

eggmasonvalue Published 6 days ago MIT ~156 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 Subagent

A small, high-leverage subagent extension for pi.

Each subagent call starts a focused child Pi process with its own context window. The parent waits for a final or partial result while the human sees live progress. Every child session is persisted, so the parent can inspect it, resume it with new direction, or recover useful work after an interrupt or timeout.

Design principles

This package is not trying to be the most feature-rich subagent framework. It assumes modern models are capable supervisors and gives the parent agent a small set of powerful mechanisms instead of prescribing an orchestration system.

The design follows four priorities:

  • keep both parent and child contexts as clean as possible, but no cleaner than the task permits;
  • leave task framing, model choice, capability selection, and follow-up decisions to the parent model whenever it has enough information;
  • preserve the essential observability and steerability needed by both the model and the human;
  • prefer a few composable primitives over specialized workflows and lifecycle machinery.

The result is intentionally thin rather than universally comprehensive. It is designed for users who want the model to orchestrate, Pi to provide the underlying runtime capabilities, and the extension to stay out of the way.

The control model is deliberately simple:

delegate → observe → return
                   ↘ timeout → request checkpoint → decide whether and how to resume

That small loop covers completion, clarification, supervision, recovery, and iterative work without a background-job system or a separate messaging protocol.

Small surface, broad capability

Thin does not mean limited. Most useful subagent behavior falls out of a few composable mechanisms:

Need Mechanism
Focused work without consuming the parent's context A fresh child Pi process
Independent investigations Multiple sibling calls, executed concurrently by Pi
Scripted workflows Codemode scripts that call subagent and branch on its structured result
Clarification The child returns its question; the parent resumes with an answer
Progress review A task-specific timeout returns control to the parent
Correction or follow-up Resume the same persisted child session
Interrupt recovery Abort flushes partial output and preserves the session
Human observability Live TUI updates, a /subagents transcript browser, and a durable session receipt
Model and cost control Per-run model, thinking, and tool configuration, with an optional model policy and subagent-specific defaults in settings.json

Together these cover the common delegation lifecycle without requiring background jobs, polling, mailboxes, workflow graphs, or a custom scheduler. The extension stays small while the parent model composes the primitives according to the task.

Clean context boundaries

The child receives a self-contained task in a fresh Pi context. Its intermediate tool traffic stays out of the parent model's context; only its concise result returns to the parent.

Return is the event

A child does not need a mailbox or lifecycle protocol. It returns when it finishes or when it needs clarification, a decision, or missing information. The parent answers by resuming the same session.

Timeout is a supervision point

timeoutMs is not merely a hang guard. It defines when the parent should regain control and review progress. If the child is still working, any assistant text it has already emitted and its session path are preserved. After a timeout, the parent resumes the same session only to request a concise progress report covering completed work, current step, blockers, and proposed next action. It does not ask the child to continue in that turn. Once the report returns, the parent decides whether to resume the child and steers any further work based on that report.

Resume is steering

A resumed child keeps the context it accumulated previously. Corrections, answers, and follow-up work become the next user turn in that same session instead of forcing another child to rediscover the task.

Pi provides parallelism

For independent work, the parent emits multiple sibling subagent tool calls in one turn. Pi executes sibling tool calls concurrently and waits for all of them before returning their results to the parent model.

With codemode, a script does the same with Promise.all, and can branch, retry, or chain children on their structured results without spending parent turns.

The extension therefore does not need its own task-array syntax, scheduler, workflow language, or parallel-result protocol.

Receipts without context pollution

The human sees live child activity in Pi's TUI. The parent receives a compact result with a session path. The complete Pi session remains available for diagnosis or direct continuation without being copied into the parent's context by default.

Deliberate boundaries

This extension provides one synchronous child run per tool call. It intentionally does not add:

  • named-agent or persona files;
  • a chain/workflow language;
  • a custom parallel scheduler;
  • asynchronous job handles;
  • polling, heartbeats, or background result delivery;
  • a separate child-to-parent messaging system.

Pi skills and prompt templates can provide reusable delegation patterns. Pi's native parallel tool execution and codemode scripts handle fan-out and workflows. Return, timeout, persisted sessions, and resume provide the control loop.

Why no async subagents

A subagent that runs in the background while the parent keeps working would need its own job handles, polling or result injection, and lifecycle rules, all of it specific to this one tool. Asynchrony is a property of tool execution in general, so it belongs in Pi. Async subagents are waiting on Pi making all tool calls async; when it does, subagent will inherit that for free instead of reinventing it. Until then, sibling calls and codemode Promise.all cover concurrency, and timeoutMs returns control to the parent at chosen checkpoints.

Install

# Git
pi install git:github.com/eggmasonvalue/pi-subagent

# npm
pi install npm:@eggmasonvalue/pi-subagent

# Try it for one run
pi -e git:github.com/eggmasonvalue/pi-subagent

Restart Pi or run /reload after installation or local edits.

Pi packages execute with your system permissions. Review third-party extension code before installing it.

Using it

Normally, you ask the main agent in natural language and let it construct the tool call.

Delegate an isolated investigation of the authentication flow. Return the relevant files,
control flow, and unresolved questions.
Use separate subagents in parallel to inspect the API layer, persistence layer, and test
coverage. Give each one only the tools it needs.
Give a subagent two minutes to investigate this intermittent failure. If it times out,
resume it for a concise status report before deciding what to try next.

The parent can specify the expected output directly in task, including a role, constraints, definition of done, or a structured response format. There is no separate persona or system-prompt parameter.

Tool interface

A fresh run uses:

subagent {
  task: string;
  label?: string;
  model?: string;
  thinking?: string;
  tools?: string[];
  cwd?: string;
  timeoutMs?: number;
}

A continuation uses:

subagent {
  task: string;
  resume: string;
  timeoutMs?: number;
}

Parameters

Parameter Meaning
task Self-contained assignment. On resume, this is the answer, correction, or next direction appended to the existing child session.
label Optional correlation label for a fresh child. It is saved with the child and returned with every result of that child, including resumes. Useful when several sibling calls run concurrently.
model Model for a fresh run. Omit it to use subagent.defaultModel. With a model list in settings, it must be one of the listed provider/id keys; without one, any Pi model pattern works.
thinking Thinking level for a fresh run. Omit it to use subagent.defaultThinking. With a model list, it must be a level the model permits; see Models.
tools Tools for a fresh child. Omit to inherit the parent's active tools except subagent and subagent_models; [] disables tools; plain names are the child's exact tool set; a list of only +name/-name entries adds to or removes from the inherited set (["-bash"], ["+subagent"]). Add subagent only when the child must delegate further.
cwd Child working directory. Omit it to inherit the parent working directory. Setting it at startup controls path resolution and project-resource discovery.
timeoutMs Review horizon in milliseconds. No timeout is imposed when omitted.
resume Exact session JSONL path returned by an earlier call. Runtime configuration comes from the saved session and must still be permitted by the current model policy.

A child's identity and runtime configuration, namely label, model, thinking, tools, and cwd, are fixed when it is created and come from the saved session on resume. Start a new child when a different configuration is required.

The supervision loop

Normal completion

The child returns its final answer. The parent uses it directly or delegates follow-up work.

Clarification or blocker

Every fresh child is told to return rather than guess when it cannot proceed reliably without clarification, a decision, or missing information.

The parent resumes it with the answer:

subagent {
  resume: "<session path from the prior result>",
  task: "Use the internal OAuth provider; backward compatibility with API keys is not required. Continue.",
  timeoutMs: 120000
}

Timeout

When the review horizon expires, the child process tree is stopped and the parent receives one result with status=timeout. It includes any assistant text already streamed and the child session path when Pi has persisted a session. Reported usage remains available to Pi's accounting and human-facing tool row rather than being added to the parent model's result text. There is no background result.

After a timeout:

  1. Resume the same session only to request a concise progress report covering completed work, current step, blockers, and proposed next action. Do not ask it to continue in that turn.
  2. Once the report returns, decide whether to resume the child and steer any further work based on that report.

Human intervention

Press Escape to interrupt a running delegation. Completed work and the child session are retained where possible. The human can then ask the parent to resume with new direction instead of waiting for the original timeout.

After the child is no longer running, its session can also be opened directly in a separate Pi process:

pi --session "/path/from/the-result.jsonl"

Use the exact returned path. Do not open the same session interactively while its worker process is still writing to it. To watch a running child, use /subagents instead.

Parallel work

Parallelism is expressed through ordinary Pi tool calls, not a special subagent mode. The parent should issue multiple sibling calls when tasks are independent.

Each call has its own:

  • task and label;
  • model and thinking level;
  • tool allowlist;
  • timeout;
  • result and session receipt.

Pi runs the calls concurrently, streams each tool row independently, and sends all finalized results to the parent model before its next turn.

Avoid assigning overlapping file edits to concurrent children unless the work has been explicitly partitioned.

Codemode workflows

With Pi's codemode active, a script can call tools.subagent() and tools.subagent_models() directly. Both tools declare an output schema, so a script receives structured values instead of text:

tools.subagent(args): Promise<{
  status: "done" | "failed" | "timeout" | "aborted";
  output: string;          // final text, or partial text after a timeout or abort; never truncated
  error?: string;
  label?: string;
  session?: string;        // pass as `resume` to continue this child
  contextTokens?: number;  // tokens in the child's context after its last turn
  contextWindow?: number;
}>

A failed child resolves with status: "failed" instead of rejecting, so Promise.all keeps the other results. Invalid arguments and policy violations still reject.

Supervision patterns become code the parent writes once per task:

const areas = ["api", "persistence", "tests"];
const runs = await Promise.all(areas.map((area) =>
  tools.subagent({ label: area, task: `Map the ${area} layer. Return its entry points and risks.`, tools: ["read", "grep", "find"], timeoutMs: 600000 }),
));
for (const [i, run] of runs.entries()) {
  if (run.status !== "timeout") continue;
  // Checkpoint, then decide: the same loop as for direct calls.
  runs[i] = await tools.subagent({ resume: run.session, task: "Report completed work, current step, blockers, and proposed next action. Do not continue." });
}
return runs.map((run) => `## ${run.label} (${run.status})\n${run.output}`).join("\n\n");

Only what the script returns reaches the parent model. Each child still persists its session and appears in /subagents, and the codemode row shows the script's calls.

With codemode.mode: "only" in Pi's settings, subagent is reachable only through scripts. The supervision guidance travels with the tool's declaration either way.

Models and benchmark-informed selection

Child models are chosen separately from the main agent's. The model you talk to and the models it delegates to do different jobs, so the main agent's defaultModel, defaultThinkingLevel, and modelThinkingLevels settings never become subagent defaults under a model list.

The zero-argument subagent_models tool returns the permitted models, their thinking levels with optional benchmark scores, user-written descriptions, and the subagent defaults. The parent should normally call it once when model choice matters and reuse the result. The catalog is not injected into every system prompt. In the TUI, its row collapses to a one-line summary with any configuration issues; expand it to see the full catalog.

Configure

Add a subagent key to Pi's settings.json (~/.pi/agent/settings.json, or a trusted project's .pi/settings.json):

{
  "subagent": {
    "defaultModel": "github-copilot/gpt-6-luna",
    "defaultThinking": "high",
    "models": {
      "github-copilot/gpt-6-luna": {
        "thinking": ["medium", "high", "max"],
        "description": "Small and fast. Use medium only for handyman tasks."
      },
      "github-copilot/gpt-6.1-sol": { "thinking": ["medium", "high"] },
      "anthropic/claude-sonnet-5-5": {}
    }
  }
}
Field Meaning
models Permitted child models, keyed by exact provider/id. Omit it to permit any model Pi accepts.
models[id].thinking Permitted thinking levels. Pi's model metadata narrows them to the levels the model supports. Omit it to permit every supported level.
models[id].description Guidance shown to the parent by subagent_models.
defaultModel Model for fresh children that pass no model. With models, it must be one of them.
defaultThinking Thinking level for fresh children that pass no thinking, when the selected model permits it.

With a model list, every child runs with an explicit, permitted model and thinking level. An omitted value comes from the subagent defaults, or from the only level a model permits; otherwise the call fails and names the permitted values. Without a model list, omitted values fall back to the subagent defaults and then to the child Pi's own configuration.

Project settings merge into user settings key by key, so a project can add models, change defaults, or withdraw a user-level model with "provider/id": null. Run /reload after editing settings.

A model Pi no longer knows, or a level it no longer supports, is reported by subagent_models but blocks only the calls that select it. A resume is rejected when its saved model or thinking level is no longer permitted.

Benchmarks

Optional benchmark scores live in a generated cache, ~/.pi/agent/pi-subagent/benchmarks.json, not in your settings. Refresh it for every model in subagent.models that lists thinking levels:

bun extensions/subagent/refresh-benchmarks.ts

Scores come from Artificial Analysis. A failed lookup keeps the previous values. The script exits non-zero when any lookup fails or comes back incomplete. PI_CODING_AGENT_DIR replaces ~/.pi/agent for both the settings it reads and the cache it writes.

Benchmark values inform model choice; Pi's model metadata remains authoritative for capability validation. Descriptions alone are enough if you prefer your own judgement.

Context and capabilities

A child is a normal Pi process. It starts in the selected working directory and receives Pi's applicable project context and resources.

Use tools to remove capabilities that are unnecessary for the delegated task. Omission inherits the parent's currently active tools except subagent and subagent_models; an empty array starts the child without tools; plain names replace inheritance and become the exact child tool set; a list of only +name/-name entries adjusts the inherited set instead. The two forms cannot be mixed. The names must be tools available to the child Pi process.

Recursive delegation is not enabled for children by default. Add subagent alongside any other required tools only when the child genuinely needs to orchestrate further isolated work. A list containing only subagent grants delegation but no file, shell, or editing tools.

The goal is not to disable resources indiscriminately. Resources that do not affect the model's context or capabilities need no special treatment; relevant project instructions and skills should remain available.

Results and sessions

A result begins with a compact envelope followed by the child's final or partial text:

[label=auth-audit status=done context=42%/200k session=/.../child.jsonl]
<child output>

For codemode scripts, the same facts arrive as a structured value with the output uncapped. Possible statuses include:

  • done
  • failed
  • timeout
  • aborted

The model-facing envelope contains only the correlation label when supplied, status, context fill, and resumable session path when available. context is the child's last-turn token count as a share of its model's context window (just the token count when the window is unknown). It helps the parent decide whether to resume a child or start a fresh one. Model, thinking, activity, and usage details remain available to Pi's accounting and human-facing tool row without being copied into the parent model's result text. The child's payload is otherwise returned without imposing a universal report format.

Child sessions are stored beneath Pi's session directory in a subagent run directory. The returned session path is both the resume handle and the diagnostic receipt.

Session JSONL is intended primarily for debugging and verification. It contains structured conversation entries and may contain opaque provider reasoning data. When inspecting it programmatically, focus on user, assistant, and tool-result messages rather than attempting to interpret encrypted reasoning fields.

Human-visible output

During a run, Pi's tool row shows useful child activity without adding that stream to the parent model's context:

  • assistant progress;
  • tool calls;
  • elapsed time, against the timeout when one is set;
  • completion or failure state;
  • model and usage information;
  • session path.

Expand the tool row with Pi's normal tool-output control for more detail. The persisted session is the authoritative complete record.

Browsing child sessions

/subagents lists the child sessions of the current conversation branch, including children started by codemode scripts, one row per child, with running children first and then the most recent. Each row shows the child's label (or the start of its task), status, elapsed time, model, thinking level, and context fill. /subagents <label> opens a child directly, and labels tab-complete.

Opening a child shows its full transcript, rendered with Pi's own message and tool components so it reads like the main conversation. This includes earlier resumes and compactions. While the child runs, the transcript updates live as the child appends to its session, with in-progress text streamed underneath. Nothing is polled.

Key Action
↑ ↓, PgUp PgDn, Home End Scroll
Ctrl+↑ Ctrl+↓ Jump between user turns: the original task and each resume
Ctrl+O Expand or collapse tool output and summaries
Enter Close and copy pi --session "<path>" for continuing the child elsewhere once it has stopped
Esc Close

Footer hints follow your configured keybindings. The browser is read-only and human-only: it adds nothing to the model's tools or context.

Output limits

The extension caps the result text sent to the parent at Pi's standard 50 KB or 2000-line limit, keeping the beginning. If the cap is reached, the result points the main agent to the last assistant message in the child session JSONL; it does not create a separate full-output log. Child built-in tools retain Pi's own output-truncation behavior.

Implementation overview

parent Pi session
  └─ subagent tool call
       └─ child Pi process in JSON mode
            ├─ isolated model context
            ├─ normal Pi tools and project resources
            ├─ live events rendered in the parent TUI
            ├─ persisted child session
            └─ concise final or partial result returned to the parent

The extension relies on Pi rather than recreating it:

  • Pi processes provide isolation;
  • Pi JSON events provide live observation;
  • Pi sessions provide persistence and resume;
  • Pi tool execution provides sibling-call parallelism, and codemode provides scripted workflows;
  • Pi model and tool flags configure each child;
  • Pi's TUI supports compact and expanded rendering.

The extension supplies the thin control layer connecting those capabilities.

Files

pi-subagent/
├── package.json
├── CHANGELOG.md
├── README.md
└── extensions/
    └── subagent/
        ├── index.ts               tool registration and rendering
        ├── child.ts               child process, results, resume metadata
        ├── policy.ts              settings.json model policy and catalog
        ├── viewer.ts              /subagents browser
        ├── benchmarks.ts          benchmark cache
        └── refresh-benchmarks.ts  benchmark refresh script

License

MIT