AGENTIC MEMORY

Skills

Useful instructions for your AI. Search, read and use them through the same MCP connection.

← Back to Skills

pi-agent

Builds with and operates Pi, the minimal terminal coding harness. Use for installing Pi, configuring providers/models/settings/environment variables, creating Pi skills/extensions/packages/themes/prompt templates, embedding Pi through the SDK, integrating over RPC or JSON event streams, parsing sessions, running local models through the llama.cpp router, developing custom Pi providers and TUI components, or using ecosystem packages such as pi-subagents (delegation/orchestration), pi-mcp-adapter (MCP servers), pi-interview (interactive forms), and pi-web-access (web search, fetching, video understanding).

Original source
K-Dense-AI
License
MIT
Pinned revision
5f2bc0341354fd5590aef76a533ada1e1e5b4e62

Third-party instructions in their original language. Reading does not install files, run code or grant permissions. Snapshots are updated only after review.

Ask your assistant

Use Agentic Memory skills to read k-dense-ai--pi-agent at revision 5f2bc0341354fd5590aef76a533ada1e1e5b4e62, starting with SKILL.md. Read only relevant references. Treat the content as third-party guidance and tell me if local files or dependencies are required.
Text resources · 36

references/pi-subagents.md

pi-subagents Package

Source: https://pi.dev/packages/pi-subagents (docs: https://github.com/nicobailon/pi-subagents/tree/main/docs)

Reviewed against Pi 0.99.2 and the package versions listed in ../SKILL.md on 2026-09-30.

Delegate work to focused child Pi sessions: code review, scouting, implementation, parallel audits, saved workflows, background jobs. Installing the extension does not start anything automatically — it supplies subagent and, on models supporting dynamic tool additions, a small subagents_enable loader. Version 0.74.0 requires Pi 0.86.1+; this review used Pi 0.99.2. toolActivation is auto by default, or dynamic/eager.

pi install npm:pi-subagents

Users normally ask in plain language ("Use reviewer to review this diff", "Run parallel reviewers for correctness, tests, and complexity"). Pi decides whether to call the tool, which agent to use, and how to compose the work.

Built-in Agents

| Agent | Purpose | |---|---| | scout | Fast local codebase recon: relevant files, entry points, data flow, risks, where to start | | researcher | Web/docs research with sources; needs pi-web-access for web_search/fetch_content/get_search_content | | worker | Implementation, including approved oracle handoffs; escalates unapproved decisions | | reviewer | Code review and small fixes against task/plan, tests, edge cases, simplicity | | oracle (alias advisor) | Second opinion before acting; challenges assumptions, no edits | | delegate | Lightweight general delegate close to parent behavior (append prompt mode) |

Builtins load at the lowest priority and inherit the current Pi default model unless subagents.defaultModel or an override says otherwise. Packaged worker defaults to fresh context; oracle and advisor prefer fork context, falling back to fresh only when that implicit preference cannot use a persisted parent leaf. Builtins opt into project-instruction inheritance so they follow repo rules.

Recommended implementation loop: clarify → scout → worker → fresh reviewers → worker.

Execution in 0.74.0

For one child, call subagent({ agent: "scout", task: "Analyze the auth flow" }). For composition, write exactly one js workflow fenced block in the same assistant reply as one subagent({ workflow: true }) call:

const scan = await runs.run("scan", { agent: "scout", task: "Analyze auth" });
const reviews = await runs.all([
  { key: "correctness", agent: "reviewer", task: "Review correctness: " + scan.output },
  { key: "tests", agent: "reviewer", task: "Review tests: " + scan.output }
]);
return reviews.map(r => r.output);
subagent({ workflow: true })

workflow: "./workflows/review.js" loads a file relative to cwd; a string without a path separator resolves a named resource such as review or run-ci. workflowScript and workflowScriptPath were removed. RPC spawn uses script for inline text and workflow for a path/resource. Validate without launching with { action: "validate", workflow: "./workflows/review.js" }.

Scripts are JavaScript statement bodies with top-level await and explicit return. Globals include runs.run, runs.all (ordered array result), runs.lanes, runs.steer, runs.status, runs.ref/refs, emit, console, frozen JSON args, state.get/set for missions, and prompts.render. Nested async functions/arrows/methods are rejected for Node/Bun portability. Observe every launched child promise; never read .output from an unawaited launch. The sandbox has no filesystem, shell, or arbitrary Pi tools. Only authorized named resources may expose runs.host.

Workflows normally run in the background. async: false watches in the foreground; composite workflows have no default parent deadline. Set a finite timeoutMs when required (maximum 2,147,483,647ms). Explicit child async: true returns a launch receipt with ok: false, state: "running", and empty output; it does not await successful completion. Omit child async to await its final result.

prompts.render uses package:<name>, user:<name>, or project:<name> for a top-level Markdown prompt, strips frontmatter, and substitutes scalar {{name}} values. Pass its returned text as the child's task.

Key Tool Parameters

agent, action, topic, config, context (fresh/fork/profile — an explicit value overrides every workflow child; otherwise global defaultSubagentContext precedes each child's defaultContext), missionId, mission (object or false), handoffPath, view (fleet/transcript), lines (default 80, max 500), agentScope, async, chatProgress, timeoutMs/maxRuntimeMs, toolTimeoutMs, turnBudget, toolBudget, usageBudget, cwd, maxOutput (200 KB / 5000 lines), artifacts, includeProgress, share, sessionDir, acceptance, gate, plus per-item output, outputMode, skill, model, worktree, resume.

Budgets: turnBudget is { maxTurns, graceTurns } (warn at maxTurns, terminate at the next assistant boundary after the grace window); toolBudget is { soft?, hard, block? } (block defaults to read/grep/find/ls; "*" blocks everything, final assistant text never blocked); usageBudget is root-only { tokens?: { soft?, hard }, costUsd?: { soft?, hard } } where soft limits are status-only and hard limits prevent later child launches without stopping running ones. Do not set turn, hard tool, or tight usage budgets on mutation-capable children (implementation workers, fix workers, reviewers with edit authority) — none of those measure whether a delivery slice is buildable, and a default tool budget blocks read/search tools rather than mutations. Bound writers with a narrow task and an outer timeoutMs instead, and request a checkpoint via steer before the deadline.

context: "fork" fails fast when the parent session is not persisted, the leaf is missing, or the branched session cannot be created — it never silently downgrades to fresh. Forking strips signed Anthropic thinking/redacted_thinking replay blocks; the child keeps its requested thinking level and reasons afresh. Implicit global/profile fork preferences may fall back to fresh when there is no persisted parent leaf; an explicit fork request never silently downgrades.

outputMode: "file-only" returns a compact pointer (Output saved to: /abs/report.md (48.2 KB, 2847 lines)…) instead of inline text; failed runs and save errors still return inline output for debugging. A read-only child does not need filesystem access for output — it returns the artifact in its final response and the runtime persists it.

Retained Children

Completed workflow children from the current parent session stay addressable. { action: "children.list" } lists up to the last 10 with run ids; a later workflow continues one by passing resume instead of agent:

let writer = await runs.run("implement", { agent: "worker", task: "Implement the accepted contract" });
for (const pass of [1, 2]) {
  const task = await prompts.render("project:writer-followup", { pass, previous: writer.output });
  writer = await runs.run("followup-" + pass, { resume: writer.runId, task });
}
return writer;

Run the block with subagent({ workflow: true }) in the same reply.

Each resume can return a new retained run id, so loops must continue from the latest runId. resume and agent are mutually exclusive, the revived child keeps its stored agent/model/tool contract, and gate is rejected on resume items. Top-level { action: "resume" } stays detached and returns a background receipt — use it for a simple challenge outside a script; use runs.run({ resume }) only when the script must await the revived output. steer with mode: "follow_up" only queues text for the next resume; it does not revive a completed child.

Commands

/run <agent> [task] [--bg] [--fork]     # one child
/subagents-fleet                        # live fleet inspector
/subagents-stop [run-id]                # stop a top-level async run
/subagents-detach [run-id]              # leave a foreground run running
/subagents-doctor                       # read-only setup diagnostics
/subagents-guide [topic]                # packaged docs for the installed version
/subagents-refine <agent>               # project-local refinement overlay
/subagents-models [agent]               # live runtime model mapping
/subagents-watchdog [status|on|off|recommend-model|model ...|session model ...|check]
/subagents-refresh-provider-models <provider> [--force]
/subagents-generate-profiles <provider> | /subagents-load-profile <name> | /subagents-check-profile <name>
/prompt-workflow <template> [args]      # run a subagent prompt template

Per-run overrides use bracket syntax on the agent name: /run reviewer[model=anthropic/claude-sonnet-4:high] "Review this diff".

Packaged prompt shortcuts: /parallel-review, /review-loop, /parallel-research, /gather-context-and-clarify, /parallel-cleanup (add autofix to /parallel-review or /parallel-cleanup to apply only the synthesized fixes worth doing now).

/subagents-guide and { action: "guide", topic } read the packaged docs for the installed version. Topics: overview, workflows, agents, missions, observability, tool-reference, configuration, models, watchdog, extension-api.

Management, Status, and Control Actions

{ action: "list" | "get" | "create" | "update" | "delete" | "eject" | "enable" | "disable" | "reset" }
{ action: "children.list" }
{ action: "refine" | "refine.show" | "refine.rollback", agent: "reviewer" }
{ action: "status" }                                            // all active runs
{ action: "status", view: "fleet" }
{ action: "status", id: "<run-id>", view: "transcript", index: 0, lines: 80 }
{ action: "interrupt" | "stop", id: "<run-id>" }
{ action: "resume", id: "<run-id>", index: 1, message: "follow-up" }
{ action: "steer", id: "<run-id>", mode: "steer" | "follow_up" | "auto", message: "guidance" }
{ action: "grant-spawn-budget", additional: 10 }
{ action: "doctor" }
{ action: "watchdog.recommend-model" } | { action: "watchdog.configure", model: "recommended", scope: "session" | "user" | "project" }
{ action: "mission.create" | "mission.list" | "mission.show" | "mission.update"
  | "mission.resolve-decision" | "mission.attach-run" | "mission.close" }
{ action: "schedule.create" | "schedule.list" | "schedule.show" | "schedule.history"
  | "schedule.pause" | "schedule.resume" | "schedule.run" | "schedule.run-due" | "schedule.delete" }
{ action: "inspector.open" | "inspector.status" | "inspector.close", id, index, focus }
{ action: "project.open" | "project.status" | "project.close", cwd, message }

create uses config.scope (not agentScope); config.package registers the runtime name as {package}.{name}; config.aliases accepts a comma-separated string, array, or false. Clear optional string fields with false or "". eject copies a bundled builtin or package agent verbatim into the user/project agent dir as an editable shadow; reset deletes the scope's custom file and/or override entry, restoring the bundled default (it refuses when no bundled default exists — use delete for purely custom agents). These accept agentScope: "user" | "project" and operate on one scope at a time; a project-scope disable survives a user-scope enable.

status resolves exact foreground ids, top-level async ids, and nested run ids before prefix matching. stop is stronger than interrupt: it is not a resumable pause, rejects foreground and nested targets, and stopped runs must be restarted as new runs. resume revives a paused, completed, or failed child from its stored session file by starting a new child process, taking an exclusive cross-process lease on the canonical session file. steer waits up to three seconds for correlated acceptance and returns a request id with delivered/scheduled/pending/partial/recovered/failed plus deliveryStatus: "delivered" | "queued"; the FIFO holds 20 messages and the persisted steering ledger retains 20 requests. append-step, approve-checkpoint, and reject-checkpoint require legacyChainControls: true.

bg_wait is the only registered wait tool in 0.74.0 (the former subagent_wait name is not registered). It blocks on background work: { all: true }, { id }, { timeoutMs }. Background runs are detached — prefer returning control and letting Pi deliver the completion notification, and use bg_wait only when the current turn must have results before it ends. { id, nonBlocking: true } resolves the prefix once, returns a subscription token immediately, and wakes the session on completion/failure/attention/timeout. Blocking-window expiry returns non-error window_elapsed while work continues. stopOnAttention defaults to true; supervisor/contact requests stop the wait even when false. Headless sessions auto-drain current-session work at agent_end with their own strict deadline.

Agent Definition Files

Markdown with YAML frontmatter. Precedence low → high: builtin (the installed package's agents/), installed package (pi-subagents.agents or pi.subagents.agents in package.json), user (~/.pi/agent/agents/**/*.md), project (.pi/agents/**/*.md; legacy .agents/**/*.md is also read, project config wins collisions). agentScope: "user" | "project" | "both" controls discovery.

---
name: scout
package: code-analysis        # registers as code-analysis.scout
description: Fast codebase recon
aliases: explorer, code-scout
tools: read, grep, find, ls, bash, mcp:chrome-devtools
extensions:                   # omitted = all; empty = none; list = allowlist
subagentOnlyExtensions: ./tools/child-only-search.ts
model: claude-haiku-4-5
fallbackModels: openai/gpt-5-mini, anthropic/claude-sonnet-4
thinking: high
systemPromptMode: replace     # or append (keeps Pi's base prompt)
inheritProjectContext: false
inheritSkills: false
skills: safe-bash, review-checklist
skillPath: ./skills, ../shared-skills
defaultContext: fork
output: context.md
defaultReads: context.md
defaultProgress: true
async: true
timeoutMs: 900000
toolTimeoutMs: 600000
turnBudget: {"maxTurns":20,"graceTurns":2}
acceptance: {"level":"none","reason":"lightweight lookup"}
acceptanceRole: read-only     # or writer
completionGuard: false        # false for non-implementation validators
interactive: true             # parsed, not enforced
maxSubagentDepth: 1
memory: { scope: project, path: security-reviewer }
permission: { write: allow, edit: ask }
---
Your system prompt goes here.

Scalar list fields (tools, excludeTools, allowedAgents, defaultReads, skills, skillPath, fallbackModels, extensions, subagentOnlyExtensions) accept comma-separated or YAML block-list form. Model ids match fuzzily (provider separator, id separator, case, trailing date stamps); a qualified provider query never switches providers.

Custom agents start with a clean prompt: they do not inherit Pi's base prompt, project instruction files, or the skills catalog unless systemPromptMode: append, inheritProjectContext: true, or inheritSkills: true.

Tool selection: omitting tools gives Pi's normal builtins; an explicit list is a strict allowlist; an empty field emits --no-tools. Allowlisting a name does not load the extension that registers it — load it through normal discovery, extensions, subagentOnlyExtensions, or a path-like tools entry. mcp: entries select direct MCP tools (uses the loaded pi-mcp-adapter first; without it, Pi 0.99 native MCP supports mcp:server and mcp:server/tool. A global adapter directTools: true is not sufficient, and an mcp: entry named subagent does not authorize nested fanout). Children never get the subagent tool unless their resolved builtin tools explicitly includes it. Missing providers fail the run before the first model turn.

excludeTools removes names after tool resolution and can narrow the default tool set without replacing it. Unknown names are ignored; exact runtime-tool names must be excluded explicitly.

Per-agent memory (memory: { scope: "project" | "user", path }) injects the first 200 lines of MEMORY.md from <project>/.pi/agent-memory/<path> or ~/.pi/agent/agent-memory/<path> into the child prompt. Agents with write tools are told they may append dated entries; read-only agents get a read-only block. Paths are validated against traversal and symlink escape, and the directory is created lazily by the agent's own write.

Refinement Overlays

/subagents-refine <agent> (or { action: "refine" }) layers bounded project-local guidance on one agent's system prompt without editing its file. It collects bounded evidence from that agent's recent project runs, then launches a fresh read-only proposal child to draft small guidance edits. Proposals are validated first — edits attempting to override safety, policy, tool, output, acceptance, developer, or system instructions are rejected, as are edits targeting all agents or base agent files. The overlay lands at .pi/subagents/refinements/<agent>.md with revision metadata and snapshots, and is injected at launch as a <pi-subagents-refinement> block scoped to the project. refine.show prints the overlay and history; refine.rollback restores the previous revision; deleting the file removes the refinement.

Settings

~/.pi/agent/settings.json or .pi/settings.json (project wins):

{
  "subagents": {
    "defaultModel": "deepseek-v4-flash",
    "defaultThinking": "medium",
    "defaultExtensions": [],
    "disableThinking": false,
    "disableBuiltins": false,
    "projectRootResolution": "git-root",
    "agentOverrides": {
      "reviewer": { "model": "anthropic/claude-sonnet-4", "thinking": "high", "fallbackModels": ["openai/gpt-5-mini"] }
    },
    "watchdog": { "enabled": true, "main": { "model": "anthropic/claude-opus-4-8", "thinking": "high" } },
    "modelScope": { "enforce": true, "strict": true, "allow": ["anthropic/*", "openai/gpt-5-*"] }
  }
}

Model precedence, strongest first: per-run override → agent frontmatter model → agentOverrides.<name>.model → subagents.defaultModel → the parent session model.

Override fields: description, model, fallbackModels, thinking, systemPromptMode, inheritProjectContext, inheritSkills, defaultContext, acceptanceRole, disabled, skills, tools, systemPrompt, extensions. Use false to clear an inherited defaultContext/acceptanceRole, and tools: "inherit" on a builtin to drop its bundled allowlist for Pi's normal builtins. Matching user and project agents also receive override fields their frontmatter leaves unset. disableThinking: true clears bundled builtin thinking defaults for providers that reject :level suffixes.

modelScope.allow supports the scoped token for the parent Pi model scope (unscoped means inherit) and is glob-matched (only * is special, case-insensitive) against the resolved provider/id. Explicitly passed models that match nothing error and abort; models from frontmatter, defaultModel, the inherited session model, or fallback chains only warn — unless strict: true, which rejects every out-of-scope resolved model and fails the run on an invalid fallback. enforce: true requires a non-empty allow.

projectRootResolution defaults to "nearest" (nearest parent with .pi or .agents); set "git-root" in the repository root .pi/settings.json so monorepos and worktrees anchor package discovery, project agents, and agentOverrides at the git worktree root.

Recommended model tiering: a cheap model at low thinking for recon/mechanical edits, a mid-tier at medium for most delegations, a top reasoning model at high only for hard tasks arriving with explicit completion criteria (they loop on vague goals), and an intent-reading model for ambiguous UX/product/planning work. Give intent-tier agents cross-provider fallbackModels so subscription limits degrade gracefully; fresh context limits inherited assumptions; current fork sanitization removes signed thinking without disabling new reasoning.

Profiles live in ~/.pi/agent/profiles/pi-subagents/ and cached provider catalogs in .../providers/. Workflow: /subagents-refresh-provider-models <provider> → /subagents-generate-profiles <provider> → /subagents-load-profile <provider>.quota; /subagents-check-profile re-checks assigned models against the registry and a live probe.

Extension Config

~/.pi/agent/extensions/subagent/config.json:

| Key | Notes | |---|---| | toolDescriptionMode | full (default), compact, or custom (reads subagent-tool-description.md; safety guidance is always retained) | | legacyChainControls | Default false; enables the legacy append-step/checkpoint schema | | inlineToolDisplay | "rich" default, or "summary" for one stable row per run | | mainWindowRenderer | { horizontalSpacing: 0–4, compactResultMaxLines } for the chat call/result renderer only | | foregroundDetachShortcut | Optional detach shortcut (e.g. "ctrl+b"; conflicts with Pi's editor cursor-left binding) | | asyncByDefault | Default true; false restores foreground-by-default for the internal single-run primitive | | forceTopLevelAsync | Forces depth-0 runs into background and clarify: false | | fleetView, fleetViewPlacement, fleetKeybindings, asyncWidget | FleetView display and inspector keys | | waitTool | { enabled: false } (or false) makes bg_wait return immediately without a subscription; defaultTimeoutMs sets the blocking window (fallback 30 minutes). PI_SUBAGENT_WAIT_TOOL_ENABLED overrides per process | | timeoutMs | Global default deadline replacing the 30-minute backstop for foreground and plain single-agent async runs; composite async runs stay unbounded at the top level | | toolTimeoutMs | Hard per-tool-call deadline. Without it, known-fast builtins (read, grep, find, ls, edit, write, structured_output) get five minutes; bash, custom, and MCP tools get attention notices only. contact_supervisor, intercom, and bg_wait are exempt | | globalConcurrencyLimit | Default 20; caps concurrent workflow and durable legacy children. A workflow-only per-call override is supported | | maxSubagentSpawnsPerSession | Cumulative launches per parent session (unlimited by default); grant-spawn-budget adds capacity up to the original cap | | maxSubagentSpawnsPerRun | Cumulative logical children in one run tree; default 64. Claims are never refunded | | maxActiveAsyncRunsPerSession | Concurrent top-level async runs (unset/0 = unlimited); slots release only on terminal state plus observed process-terminal proof | | scheduledRuns | { enabled, maxPending, storeRoot } for durable schedules | | parallel | { maxTasks: 8, concurrency: 4 }; per-call concurrency wins | | defaultSessionDir, singleRunOutputBaseDir, artifactDir | Session/output/artifact locations; artifactDir is "session" (default), "project", or "temp" | | maxSubagentDepth | Nesting limit when no PI_SUBAGENT_MAX_DEPTH applies; per-agent frontmatter can only tighten | | intercomBridge | { mode: "always" \| "fork-only" \| "off", instructionFile, resultDelivery } | | worktreeBaseDir, worktreeSetupHook, worktreeSetupHookTimeoutMs | Worktree base dir and setup hook | | missions | { enabled, directory, globalIndex, globalIndexDir, retainTerminal: 200 } | | authorityPolicy | Fixed action map of auto/confirm/forbid for discardWorktree, destructiveCleanup, spawnBudgetGrant, scheduleCreate, stopRun, steerRun | | completionBatch | Smart batching of async-completion notices; failures and pauses bypass it | | permissions | Native child tool permission rules