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 · 24000

(see below) |

Environment: PI_SUBAGENT_MAX_DEPTH (nesting; default 2), PI_SUBAGENT_MAX_SPAWNS_PER_SESSION, PI_SUBAGENT_MAX_SPAWNS_PER_RUN, PI_SUBAGENT_TOOL_TIMEOUT_MS, PI_SUBAGENT_WAIT_TOOL_ENABLED, PI_SUBAGENT_PI_BINARY (override the child Pi launch command), PI_SUBAGENT_TASK_DELIVERY (auto default writes tasks over 8000 chars to a temp task.md; file always does, for hosts whose EDR kills children with long argv), PI_SUBAGENTS_WORKTREE_DIR. PI_SUBAGENT_DEPTH is internal — do not set it.

The worktree setup hook runs once per created worktree with an absolute, ~/, or repo-relative path (bare command names rejected). stdin is JSON with repoRoot, worktreePath, agentCwd, branch, index, runId, baseCommit; stdout must be one JSON object such as { "syntheticPaths": [".venv", ".env.local"] }, whose worktree-relative paths are removed before diff capture. Tracked files can never be marked synthetic. Default timeout 30000 ms.

Worktrees and Acceptance Gates

Set worktree: true on runs.run/runs.all items (or at the top level to make it the default, overridable per child with worktree: false) to give each writing child its own managed git worktree. Each branches from clean HEAD, journals ownership before launch, captures a patch and handoff manifest, then removes cleanly captured temporary worktrees and branches; the manifest path stays in the child's artifactPaths. Keep one writer when parallel writes are not intentionally isolated. action: "worktree.discard" requires the aggregate handoffPath.

{ agent: "worker", task: "Implement the fix", acceptance: {
  level: "verified",
  criteria: ["Patch the bug without widening scope"],
  evidence: ["changed-files", "tests-added", "commands-run", "residual-risks", "no-staged-files"],
  verify: [{ id: "focused", command: "npm test", timeoutMs: 120000 }]
} }

Levels are auto (default), none, attested, checked, and verified; review is a separate gate under acceptance.review. Inference uses only declared acceptanceRole: writer gets checked evidence, plus required reviewer gating when async or dynamic; read-only gets none; an omitted role gets lightweight attestation. Task wording, perceived risk, and agent names do not change inference. The role does not grant or revoke tools.

gate: "npm test" is shorthand for one host-run verification command (acceptance.level: "verified" with that single command). Results are memoized per tracked workspace state and effective environment, so an unchanged tree does not rerun it; with worktree: true it runs inside the child's worktree. gate cannot combine with acceptance except deprecated false, and is rejected on retained resume items. Object gates { command, output: "json", schema?, timeoutMs? } validate bounded stdout as structured output; they cannot coexist with outputSchema.

Evidence statuses: claimed, attested, checked, verified (runtime verification commands passed — child-reported success does not count), review-required, reviewed, rejected. Bare "none" is rejected (use { level: "none", reason }); "reviewed" is not a settable policy level. For attested or stricter, the child prompt asks for a fenced acceptance-report JSON block; fences are stripped from output artifacts while per-child metadata keeps the full acceptance ledger. Explicit failed gates fail the run; inferred gates stay observable without failing it. Checked writers reject staged files by default. preserveStagedIndex: true explicitly permits a reviewed starting index only if its Git tree is unchanged at completion; it does not stage or restore anything and is unsuitable for concurrent writers sharing a worktree.

Missions and Schedules

Ordinary workflow launches create one enclosing mission by default, stored under ~/.pi/agent/missions/projects/<project-hash>/ and linking objectives, run ids, lifecycle status, decisions, artifact paths, and delivery receipts. Children do not create separate missions. details.missionId is authoritative and human receipts end with Mission: <id> (<status>). Pass mission: false for an ephemeral workflow with no mission and no state global, or missions.enabled: false to disable automatic creation (explicit fields and actions still work). Automatic persistence failures are reported as details.missionWarning without blocking the run; explicit missionId/mission requests are strict before launch.

An explicit mission object needs exactly one non-empty title or summary (objective and labels optional). goal: true requires budget: { tokens } and turns the mission into a continuation driver: after each parent turn an idle goal mission emits one needs-attention notice with its title, remaining budget, and next ready action (from state.nextReadyAction, state.nextAction, a ready state item, an open decision, or linked-run state). Reaching the budget sets budget-exhausted and stops notices. The extension never launches or replans goal work itself.

state.get(key) / state.set(key, value) give a workflow durable JSON state through its mission, shared across later workflows attached with the same missionId. Each set takes the state-file lock and merges with the latest on-disk state; missing keys return undefined, and the whole state file is capped at 256 KiB.

Durable schedules are enabled by default under .pi/subagents/schedules/<id>/ (or scheduledRuns.storeRoot):

{ action: "schedule.create", id: "evening-review", name: "Evening review", at: "+30m",
  workflow: "./workflows/review.js" }
{ action: "schedule.create", id: "backlog", every: "6h", catchUp: "latest", workflow: "./workflows/review.js" }

Fixed intervals support m/h/d/w and advance from the planned time without completion drift. Scheduled runs always launch async with fresh context and disable automatic mission creation. overlap is fixed to skip; catchUp supports latest (default) and none; schedule.run-due lets an external launcher start due work without making pi-subagents a daemon. Calendar/cron recurrence, queue/replace overlap, and a schedule TUI inspector are deferred.

For substantial work in another codebase, prefer a Herdr project pane (project.open) over ordinary child nesting; use an explicit cwd only for small bounded cross-project work.

Watchdog and Child Permissions

The watchdog is an opt-in adversarial reviewer for repo edits — not the reviewer agent, and not configured by defaultModel/agentOverrides.reviewer. It runs at the agent_end boundary only when the repo's final state changed during the turn; multiple edits coalesce into one review, unchanged/reverted diffs are skipped, and .pi/subagents//tmp/ artifacts do not trigger it. In orchestrated runs each writing child can review its own worktree while the parent reviews the aggregate diff.

Use a strong complementary model: /subagents-watchdog recommend-model (inspect the installed recommendation and available authenticated models; avoid hardcoding a recommendation across releases). session model recommended changes only this session; model recommended saves to settings without enabling. Settings keys: watchdog.main.model/.thinking (omitting main.model uses the session model; setting it without a thinking suffix runs with thinking off), watchdog.children.model, watchdog.children.overrides.<agent>.model.

Scope monitoring keeps a bounded in-memory current-scope artifact from real user prompts and prepends it to review input (watchdog.scope.enabled), so the reviewer can flag scope-drift; newer prompts supersede older ones and watchdog auto-follow prompts are not recorded as scope. watchdog.cadence.everyNTools adds Scopey-style non-blocking reviews every N tool results, delivered transcript-visibly via steer after the current tool boundary — pick a cheap model for frequent monitoring. watchdog.autoFollow (blockers, maxAttempts, stalemateRepeats) can queue a visible follow-up asking the agent to address a blocker, stopping on repeated identical blockers.

LSP diagnostics: when enabled, the watchdog checks changed TypeScript/JavaScript files for fresh language-server diagnostics before the model review, auto-detecting typescript-language-server from node_modules/.bin or PATH (never installing anything or scanning the workspace). Errors become blockers, warnings concerns; bound with watchdog.lsp.enabled, timeoutMs, maxFiles, maxDiagnostics.

Native child permissions are opt-in and apply only to Pi child runtimes. Configure non-bash rules under permissions.rules in the extension config ("read": "allow", "write": "ask", "edit": "deny"), overridable by an agent's permission:/permissions: frontmatter block. Omitted and unknown tools default to allow, explicit allow removes an inherited restriction, and the gate is not registered when no ask/deny rule resolves. An ask pauses that exact call and sends a bounded, redacted preview to a one-call arbiter owned by the child watchdog, which returns only approve/deny — enable and configure subagents.watchdog.children first, since a disabled watchdog, missing model/auth, timeout, or malformed response denies the call. Decisions are written to bounded audit JSONL with decisionSource: "watchdog". bash is always passed through and bash rules are rejected rather than parsed — use pi-guard for command-level policy. External CLI profiles are opaque processes, so a launch with effective ask/deny rules is rejected rather than claiming enforcement.

Supervisor Coordination

Native, no pi-intercom required: children call contact_supervisor({ reason, message }) with reason ∈ need_decision, interview_request, progress_update; the parent replies with subagent_supervisor({ action: "reply", replyTo, message }) or checks { action: "pending" }. Requests are scoped to the exact Pi session id that spawned the child, so a second Pi session in the same repository does not receive them. If no external pi-intercom owns the name, the native channel also exposes intercom as a compatibility fallback. A foreground child may detach while awaiting a reply: reply first, then bg_wait({ id: runId }). Children should not ask for clarification when the only conflict is review-only/no-edit versus progress- or artifact-writing instructions — no-edit wins.

Child-safety boundaries are enforced at runtime: spawned children never receive the bundled pi-subagents skill; forked child context is filtered to strip parent-only orchestration instructions, slash/status/control messages, and prior parent subagent tool history; and children get boundary instructions that they are not the orchestrator. The exception is an agent whose resolved builtin tools includes subagent, which gets a child-safe tool bounded by maxSubagentDepth.

Observability

FleetView below the editor (or above, via fleetViewPlacement) keeps active work visible as a compact summary; with the editor empty, ↓/← expands it into main plus active children with agent, state, elapsed time, and token totals, ↑↓/jk selects, and Enter inspects. /subagents-fleet opens the live inspector: Shift+K/Shift+J scroll a line, PgUp/PgDn a page, x/Ctrl+O toggle tool details, r refresh, Esc close, s compose an acknowledged message to a live async child (Tab cycles steer/follow_up/auto), D stop after confirmation, H open a Herdr inspector pane (Herdr 0.7.5+). Ctrl+Alt+F opens it mid-turn. Successful background completions stay quiet so inactive tabs are not marked unread; failures and pauses notify immediately.

Async runs write lifecycle artifacts under <tmpdir>/pi-subagents-<scope>/async-subagent-runs/<id>/: status.json, events.jsonl, output-<n>.log, subagent-log-<runId>.md, with the final summary as <runId>.json in Pi's results directory (details.asyncDir points at the run directory). Stable v1 status fields: lifecycleArtifactVersion, runId/id, sessionId, mode, state, timestamps, durationMs, cwd, asyncDir, sessionFile, outputFile, workflowGraph, steps, results, totalTokens, totalCost, model/attemptedModels/modelAttempts, toolCount, turnCount, optional launchResolvedExtensions and runtimeAcknowledgedExtensions, and nested children. Read these files rather than scraping terminal output, and ignore unknown fields.

The result file is consumed and deleted once its completion notice is delivered; before deletion the watcher writes a versioned replay record under <resultsDir>/completion-replay/<runId>.json and a bounded output archive under <resultsDir>/output-archives/<runId>.json (64 KiB of result tail when no child output/session file exists). bg_wait surfaces a slim projection in details.completions. Lifecycle artifact v3 adds process-terminal-candidate.json and process-terminal.json; a proof is observed only when the live parent saw the runner's close event, every recorded child writer has a close record, and any tracked session lease is free — otherwise unknown. Never infer exit from endedAt, result-file existence, PID disappearance, or lease absence.

Child-protocol bounds: a child JSONL line above 16 MiB fails with protocolError code protocol_output_limit (oversized turn_end/agent_end aggregates are replaced with bounded lifecycle records while preserving agent_end.willRetry); stderr retains its latest 128 KiB; agent_settled is the terminal watermark on current Pi builds.

Debug artifacts live under {sessionDir}/subagent-artifacts/, .pi/subagents/artifacts/ for project-scoped runs, or a temp dir: {runId}_{agent}_input.md, _output.md, .jsonl, _meta.json (timing, usage, exit code, final/attempted models, fallback outcomes, resolved acceptance ledger). For npm package projects, project-scoped artifacts need a .npmignore/files rule — pi-subagents warns when package settings could publish .pi/subagents/.

Extension Integration

Versioned in-process event-bus RPC: listen for subagents:rpc:v1:ready, emit on subagents:rpc:v1:request ({ version: 1, requestId, method, params }), read subagents:rpc:v1:reply:<requestId>. Methods: ping, status, cost, spawn (inline script or a workflow path/resource, async-only), steer, interrupt, stop, resume. cost returns versioned parent/child spend plus unresolvedAsyncChildren; unresolved usage is not zero. ping.capabilities advertises events.asyncComplete, launchResolvedExtensions, runtimeAcknowledgedExtensions, processTerminalProof, nonRecoveringSteer, resume, and fleetStatus: { version: 1 } (successful status replies then include a bounded data.fleet DTO that never exposes run, async, or tool IDs). RPC steering disables pause-and-revive recovery so the caller keeps authority over the child it spawned.

Also exported:

  • pi-subagents/preflight — resolveSubagentLaunchContract(...) resolves an ordinary single-agent launch contract side-effect-free (agent identity and shadowed candidates, parsed-definition digest, context/model/tools/skills/MCP/extensions, artifact and async paths, capability-ceiling audit data, launchContractDigest). Failure codes: missing_agent, ambiguous_agent, missing_skill, denied_required_tool, invalid_artifact_dir, invalid_cwd, unsupported_mode; host-only facts appear as host_required diagnostics.
  • pi-subagents/delegation — SUBAGENT_DELEGATION_REQUEST_EVENT / SUBAGENT_DELEGATION_RESPONSE_EVENT run one configured foreground leaf agent. ownerRunId + nodeId is the logical identity (requestId is one attempt; a second active attempt gets duplicate_node), result mode is explicit (text stays literal, structured returns schema-validated JSON), schemas cap at 64 KiB and values at 1 MiB. Foreground-only; requires an active extension context.
  • pi-subagents/capability-ceiling — registerSubagentCapabilityCeiling({ sessionId, source, ceiling }) enforces a session-scoped ceiling (allowedAgents, allowedTools, denyExtensions). Active registrations intersect allowlists and OR denyExtensions; non-allowlisted agents fail before spawn and stay visible in list as non-executable; the snapshot propagates monotonically to nested/async children.
  • pi-subagents/background-work — registerBackgroundWorkProvider({ name, wakeChannels, listActiveWork, reconcile }) makes another extension's jobs visible to bg_wait, keyed by stable provider-local id plus owning session id.
  • pi-subagents/project-panes — PROJECT_PANES_API_VERSION (currently 1), openProjectPane, getProjectPaneStatus, closeProjectPane.

Bus events: subagent:async-started (payload includes truncated task and workflow-level goal), subagent:async-complete, subagent:control-intercom, subagent:result-intercom, subagent:process-terminal, plus child-emitted subagent:acknowledge-extension. pi.events is in-process only — use file artifacts or pi-intercom across processes.

Herdr integration: when HERDR_ENV=1 and HERDR_PANE_ID are set, pi-subagents reports active async-run counts through pane metadata, emits herdr:blocked/herdr:busy, and restores state after /reload or /resume. Herdr 0.7.5+ adds on-demand inspector panes (inspector.open/status/close, a raw dashboard reading lifecycle artifacts — closing it never stops the run) and project panes (project.open/status/close, a Pi session rooted in another repo that owns its own subagents; bindings at <projectRoot>/.pi/subagents/project-panes/herdr.json).

Skills and the Bundled Skill

Skills are SKILL.md files selected per agent; discovery is project-first (project config skills/, project/task packages, project settings, ~/.pi/agent/skills/, user packages, user settings). Set them via agent defaults, per-run skill: "tmux, safe-bash", or skill: false; top-level skill in a chain is additive and a step-level value overrides. Missing skills warn instead of failing. When an agent has an explicit tools allowlist plus resolved skills, read is added so skill files can be loaded. Agent-local skillPath candidates never enter Pi's global catalog — pair inheritSkills: false with explicit skills and skillPath for a child that should receive only its private skills.

The package bundles a pi-subagents skill for the orchestrating parent only, covering delegation patterns, prompt-workflow recipes, role-agent prompting, safety boundaries, intercom conventions, and control/diagnostics.

External CLI Runners

An agent profile can run a local one-shot command instead of a Pi child:

runner:
  type: external-cli
  command: node
  args: ["./scripts/local-reviewer.mjs"]
  promptDelivery: stdin
async: true

They are async-only, receive one combined system/task prompt over stdin, and use argv arrays without a shell. Supported: status artifacts, stdout/stderr logs, timeout, stop (full output goes to log files; in-memory final stdout/stderr keep the last 64 KiB). Not supported: foreground/clarify, steer/resume/interrupt-as-pause, Pi models/tools/extensions, skills, structured output, nested subagents, fallback models, and native permission enforcement.

Recursion Guard

Subagents can call subagent only when their resolved builtin tools explicitly include it — intended for delegated fanout agents, not ordinary workers or reviewers. Nesting defaults to two levels (main → subagent → sub-subagent); deeper calls are blocked with guidance to finish directly. Nested runs appear in the parent status tree, and status, interrupt, and resume can target one by its nested id. Configure with PI_SUBAGENT_MAX_DEPTH, config.maxSubagentDepth, or agent frontmatter (which can only tighten).

Session Sharing

share: true exports the full session to HTML, uploads it to a secret GitHub Gist through your gh credentials, and returns a https://shittycodingagent.ai/session/?<gistId> URL. Disabled by default — session data may contain source code, paths, environment variables, or credentials.

Upgrade and capability boundaries

Current configuration can set disabledFeatures to remove tool feature groups. Disabling workflow-scripts replaces scripts with top-level tasks (parallel) and chain (sequential/parallel blocks); those forms are otherwise not the public execution API. scheduledRuns.enabled: false also removes scheduling fields.

Children follow parent project trust. Adapter MCP selectors read mcp-adapter.json; native selectors read Pi mcp.json. Native extension-registered MCP servers work in background children. codemode is available to child tools when allowed, but subagent, subagents_enable, supervisor/contact, and structured-output tools are model-only and cannot be invoked inside codemode.

A runtime replacement (/reload/resume/project switch) marks an async workflow stopped with workflow.stopCause: "runtime-replaced" while its awaited async children continue. Relaunching the same script and JSON args in that session can reuse successfully finished or still-running keyed children; failures rerun. A completed/user-stopped workflow does not grant this reuse. Check workflow receipts and terminal proof instead of interpreting successful dispatch as delivered work.

All authenticated child launches are illustrative. This audit loaded the extension, validated both documented workflow bodies, executed the first with mocked child results, and checked nested-async rejection. It did not bill hosted child/watchdog calls or execute worktree, schedule, supervisor, Herdr, or sharing flows.