@tintinweb/pi-subagents

repository·master·Indexed 20 days ago

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

A pi extension that enables autonomous, specialized sub-agents with Claude Code-style capabilities. It allows developers to spawn isolated agents with custom tools, models, and prompts that can run in parallel, be steered mid-run, or be scheduled for later execution using cron, intervals, or timestamps. Includes built-in agent types like general-purpose, Explore, and Plan, as well as support for custom agents defined via Markdown files with YAML frontmatter configuration.

Tokens
19K
Snippets
35
Records
88
Agent score
70%

What's inside @tintinweb/pi-subagents

  1. Configure Model Scope as a guardrail

    master

    Model Scope is an opt-in feature (enabled via /agents → Settings → Scope models) that validates subagent models against the enabledModels list configured in pi settings.

    Scope Behavior by Source

    Model sourceOut-of-scope behavior
    Caller-supplied via Agent({ model: "..." })Hard error returned to the orchestrator, listing allowed models
    Pinned in agent frontmatterWarning toast + the pinned model runs (frontmatter is authoritative)
    Parent-inherited (neither set)Warning toast + parent's model runs

    Implementation Details

    • Format: Only exact provider/modelId entries are honored (e.g., anthropic/claude-haiku-4-5-20251001). Glob patterns, bare IDs, or :thinking suffixes are silently dropped.
    • Settings: It respects both global ~/.pi/agent/settings.json and project-local <cwd>/.pi/settings.json (project overrides global).
  2. How nested subagents and delegation work

    master

    Nested delegation is disabled by default. To allow an agent to spawn its own subagents, you must set the allowed_subagents field in its frontmatter. This creates a privilege boundary: the parent can only delegate to the specific types listed.

    Key Concepts

    • Privilege Boundary: A child runs with its own tools:, extensions:, and isolated: settings. The parent's restrictions are NOT inherited; delegation grants the parent the union of what the listed agents can do.
    • Depth Limit: The default maximum depth is 2 (main session $\rightarrow$ subagent $\rightarrow$ nested child). This can be changed via maxSubagentDepth in subagents.json.
    • Lifecycle: When a parent agent is stopped or ends, its nested children are also stopped.
    • Observability: Nested children write their own .output transcripts in the root session directory. Their token usage is folded into the ancestors' totals.
    • Concurrency: Nested children do not occupy maxConcurrent slots; they are managed by the parent.
    ---
    tools: read, grep, find
    extensions: false
    allowed_subagents: support-file-finder, support-callsite-tracer # or `all`
    ---
  3. Configure tool and extension scoping

    master

    Agent capabilities are controlled by two distinct but composable fields: extensions: (which extensions load) and tools: (which tools are visible to the LLM).

    Scoping Rules

    • extensions: is the sole loading authority. If you use ext:foo/bar in tools:, it will not load the extension foo if it isn't in the extensions: list.
    • exclude_extensions: takes precedence over everything else. An excluded extension will not load and its tools cannot be pulled back via ext: selectors.
    • isolated: true is a hermetic mode that forces extensions: false, skills: false, and removes all ext: selectors, leaving only built-in tools.

    Usage Examples

    Narrowing built-ins only:

    tools: read, grep, find

    All built-ins plus one extension tool:

    tools: "*, ext:mcp/search"
    extensions: [mcp]

    Hermetic specialist (one extension, one tool, no built-ins):

    extensions: [mcp]
    tools: "ext:mcp/search"
    # Example: Specialist mode
    extensions: [mcp]
    tools: "*, ext:mcp/search"
    
    # Example: Hermetic mode
    isolated: true
  4. Manage agent execution and concurrency

    master

    Running agents in parallel

    To run multiple agents for independent work concurrently, send a single message containing multiple tool calls, ensuring run_in_background: true is set on each call.

    Foreground vs Background

    • Foreground (default): Use when you need the agent's results immediately before you can proceed with your next step.
    • Background: Use run_in_background: true for work that doesn't require immediate attention. You will be notified upon completion; do not poll or sleep while waiting.

    Interacting with running agents

    • Resume: Use resume with an agent ID to continue work from a previous agent run.
    • Steer: Use steer_subagent to send mid-run messages to an agent that is currently running in the background.

    Important Lifecycle Notes

    • Fresh Starts: A new Agent call (without resume) starts with no memory of prior runs. The prompt must be self-contained.
    • Results: When an agent finishes, it returns a single message. This result is not automatically visible to the user; you must send a text message with a concise summary to show the user the outcome.
    • Verification: Always verify an agent's work. An agent's summary describes its intent, not necessarily its actual actions. Check code changes before reporting work as complete.
  5. Understand Graceful Max Turns and agent status

    master

    To prevent hard-aborts when an agent reaches its max_turns limit, the system implements a graceful shutdown process:

    1. At max_turns, a steering message is sent: "Wrap up immediately — provide your final answer now."
    2. The agent is granted up to 5 grace turns to finish cleanly.
    3. A hard abort occurs only after the grace period is exceeded.

    Agent Status Codes

    StatusMeaningIcon
    completedFinished naturally green
    steeredHit limit, wrapped up in time yellow
    abortedGrace period exceeded red
    stoppedUser-initiated abort dim
  6. Control subagent nesting depth

    master

    The maxSubagentDepth setting (default 2) defines the maximum allowed level of nested delegation.

    • The main session is level 0.
    • Its direct subagents are level 1.
    • Subagents of subagents are level 2, and so on.

    Setting this value to 0 or 1 effectively disables nesting project-wide, regardless of individual agent configurations like allowed_subagents.

  7. Scheduling restrictions and behavior

    master

    When using the schedule parameter in the Agent tool, note the following rules:

    • Incompatibility: schedule cannot be combined with inherit_context (as no parent conversation exists at the time of firing) or resume (schedules always create fresh agents).
    • Background execution: run_in_background is automatically forced to true when a schedule is provided.
    • Queue priority: Scheduled fires bypass the maxConcurrent queue, meaning they will not be deferred behind long-running manual agents.
    • Headless mode: The pi -p (headless) command does not wait for scheduled subagents to complete.
    • Management: You can list and cancel active schedules via /agents → Scheduled jobs in the UI.
  8. Configure the fallback agent for dispatch

    master

    The fallbackSubagent setting (default general-purpose) determines which agent is used when a requested subagent_type cannot be resolved to a single enabled agent (e.g., the type is unknown, disabled, or ambiguous).

    Configuration Options

    • Agent Name: Any name of an enabled agent will route unresolvable calls to that agent.
    • Strict Mode (none or false): If set to none or false, the system enters strict mode. Unresolvable calls will be refused with an error listing available types. This is recommended for background and scheduled calls to prevent unintended execution.

    Warning: Setting the fallback to an unknown or disabled agent is a misconfiguration and will be reported as an error.

  9. Run agents in isolated Git worktrees

    master

    To prevent an agent from making direct changes to your working directory, set isolation: worktree. This runs the agent in a temporary, isolated git worktree.

    Behavior:

    • No changes made: The worktree is automatically cleaned up.
    • Changes made: The worktree is cleaned up, and changes are committed to a new branch named pi-agent-<id>.
    • Agent commits its own work: A new branch is created at the agent's current HEAD, preserving its commits. Uncommitted leftovers are committed on top first. These commits use --no-verify to bypass local pre-commit hooks.

    Requirements:

    • The project must be a git repository with at least one commit.
    • If git worktree add fails, the Agent tool will return an error rather than running without isolation. isolation: "worktree" is a strict requirement.
    Agent({ subagent_type: "refactor", prompt: "...", isolation: "worktree" })
  10. Schedule sub-agents with the Agent tool

    master

    You can register an agent to fire at a specific time or interval by adding a schedule field to the Agent tool call. Scheduled jobs are session-scoped and stored in <cwd>/.pi/subagent-schedules/<sessionId>.json.

    Agent({
      subagent_type: "Explore",
      prompt: "Look at recent commits and summarize what changed since last week",
      description: "Weekly commit review",
      schedule: "0 0 9 * * 1",   // 9am every Monday (6-field cron)
    })
  11. Best practices for writing agent prompts

    master

    When writing prompts for an agent, treat it like a smart colleague who has no context of your previous work or the current conversation.

    Prompting Guidelines

    • Be Detailed: Explain what you want to accomplish and why. Describe what you have already ruled out.
    • Provide Context: Give enough information so the agent can make judgment calls.
    • Specify Output: If you need a specific format or length, state it (e.g., "report in under 200 words").
    • Avoid Terse Commands: Command-style prompts often result in shallow or generic work.
    • Don't Delegate Understanding: Avoid prompts like "based on your findings, fix the bug." Instead, prove you understand the problem by including specific file paths, line numbers, and the exact changes required.
    • Clarify Intent: Explicitly tell the agent if you expect it to perform research (search, file reads) or to write/edit code.