Install
Install with PiG
pig install npm:pi-guildInstall with Pi
pi install npm:pi-guildPackages run code with your permissions and influence agent behavior. Catalog inclusion is not a security audit. Review the source before installing a third-party package.
Pi manifest JSON
The pi field of package.json.
{
"skills": [
"./skills"
],
"extensions": [
"./extensions/subagent/index.ts"
]
}README
Written by the package's publisher, shown as published in version 0.1.2 (README.md). PiG does not review it.
pi-guild
Agent teams for pi — subagents you can watch, and rescue when they fail. Most subagent implementations dispatch and forget; this one keeps a run ledger per child process, so you can see what each one is doing while it runs, read why it failed, and resume it in its original session instead of starting over.
One subagent_status call, mid-run — the ◐ row is computed from the ledger while the child is still alive:
子任务: 1 运行中 / 1 完成 / 1 卡住
◐- worker 14m idle 6m · 卡在 bash · 7轮/12工具 <sessionId>
任务: Audit the auth middleware for retry loops and list every call site
范围: src/auth, src/http
续跑: subagent_continue({ sessionId: "<sessionId>", cwd: "/repo", agent: "worker", task: "..." })
✓- reviewer 9m 4轮/9工具 <sessionId>
任务: Review the diff
输出: 2 blocking issues: unbounded retry in token refresh; ...
Idle time and the tool it is stuck in come from the same ledger the child writes to, so you intervene while it is alive rather than after it dies. The 续跑: line prints the exact sessionId + cwd pair subagent_continue needs — a mismatched cwd silently opens an empty session. A ## 容量 block at the end carries live slot, load and memory readings.
subagent dispatch (single / parallel / chain)
subagent_list what teams and roles exist
subagent_status this session's runs: stuck > running > finished (all: true = full 24h ledger)
subagent_tell push a mid-run instruction to running subagents
subagent_collect fetch results of background runs
subagent_continue resume a failed run in its original session
Verified by tests, not claims: bun run test → 815 passing, 0 failing across 25 files. bun scripts/mutation-check.ts injects 205 known defects — one per failure mode it guards — and exits non-zero unless every one is caught (a surviving mutant means an assertion is empty). bun run typecheck-gate requires 0 type errors under extensions/subagent/. All three run on every publish via prepublishOnly.
Install
pi install npm:pi-guild
pi install ./pi-agent-teams # 本地源码(不拷贝,改完重开会话即生效)
pi -e ./pi-agent-teams # 一次性试用,不装
pi -e只加载扩展,不加载包内 skills(/skill:agents-team会缺席),而且派出的子进程不带-e,所以子 agent 看不到包内团队。验收一律用pi install。
Requires pi ≥ 1.4.0. Platform: macOS and Linux — verified on macOS only. Windows is untested: dispatch normally reuses the absolute process.execPath, but the fallback path spawns pi from PATH with shell: false, which fails on Windows (pi.cmd), and the chmod-based permissions on run files do not apply there. Desktop notifications are macOS-only (osascript + afplay — the sound is played separately because macOS 26 silently drops sound name); elsewhere notify defaults to off, and passing it explicitly runs the job and reports the degraded notification instead of failing.
Two teams ship with the package:
| Team | Roles | What it's for |
|---|---|---|
pi-dev-team | lead / scout / planner / worker / architect-reviewer / reviewer / verifier | Daily work: recon → plan → implement → review. lead strings the phases together; architect-reviewer asks whether the thing should exist at all, reviewer whether it is correct |
gstack | lead / security-officer / qa-lead / product-reviewer / investigator / designer | Review and release gatekeeping. Three of the six (lead, qa-lead, investigator) do write — their own prompts ship code and bump versions; designer writes design docs |
They're picked to not compete: pi-dev-team implements under review, gstack audits and — for its QA / debugging roles — ships the fix it found. Only security-officer and product-reviewer are read-only, and read-only there means "no write / edit tool", not a sandbox: bash is in their list.
subagent({ agent: "scout", team: "pi-dev-team", task: "Map how auth is wired" })
subagent({ tasks: [{ agent: "reviewer", team: "pi-dev-team", task: "Review the diff" }, { agent: "verifier", team: "pi-dev-team", task: "Prove the tests run" }]})
Choosing a mode
The tool does not read your task text and guess. Mode is fixed by which argument you pass:
| You pass | Mode |
|---|---|
agent + task | single — one child |
tasks: [...] | parallel — independent children at once |
chain: [...] | chain — each step gets the previous result via {previous} |
Both name forms are accepted: agent: "reviewer" works while no other visible team uses that role, and team/role (also team-role) always resolves; a name that repeats across teams is refused with the qualified candidates printed paste-ready.
Children never see their siblings — each receives only its own task, and sharing is explicit ({previous} in a chain, the _board/ directory when resuming). So the decision lives with the dispatcher, before the call:
- Can I just do it? One file, one command, a few seconds — do it inline. Spawning costs a cold start and ~300 MB.
- Is this one job or several? Split only where the parts don't need each other.
- Dependencies: none → parallel; a later step needs an earlier conclusion → chain; one isolated job → single. For staged work that needs a decision midway, hand it to
pi-dev-team-leadand verify the result yourself. - Pick roles by responsibility (scout reads, reviewer judges, worker runs), then cap resources: concurrency defaults to 2, and read-only work gets
readOnly.
Adding your own teams
Teams live in agents/<team>/<role>.md, discovered in three layers — later overrides earlier, per role, not per team:
<package>/agents/ read-only, refreshed on pi update
~/.pi/agent/agents/ yours
<project>/.pi/agents/ project-local
To change one role from a bundled team, drop that one file into your layer; to freeze a whole team, copy the whole directory. Mixing is allowed and logged once (team "pi-dev-team" mixes package and user roles). A role is a markdown file with frontmatter:
---
name: reviewer
description: Reviews diffs for correctness, security, maintainability
tools: read, grep, find, ls, bash
---
You are a reviewer. ...
tools: is an optional whitelist. A role that needs to see images adds requires: vision; the target model's input is checked at dispatch, and a text-only model yields a model-no-vision warning instead of a failed dispatch (only vision is understood; anything else is requires-invalid). agents/index.json is optional metadata (team titles, channels, roleTools, category for subagent_list({ category })) — directories are the source of truth. Your own metadata goes in agents/index.local.json, merged on top but not in files, so it never ships.
Scope
Registered per channel, hidden when empty. Each team declares channels in agents/index.json (terminal, voice, or both); a session only sees teams whose channels include its PI_TASK_ORIGIN (default terminal). If nothing is visible on a channel, the subagent* tools aren't registered at all — a half-visible tool family is worse than none. Filtering is by PI_TASK_ORIGIN, not PI_CHANNEL: the latter has four values (voice / terminal / feishu / wechat) and would hide the chat-bridge teams. A role filtered out by channel is named back by the dispatch precheck, the single-agent path and subagent_list, so a channel mismatch never reads as a broken index.
Tools and model: inherited from pi
A role only declares what it wants to narrow. Everything else follows your pi config:
| Role declares | Child process gets |
|---|---|
| nothing | your defaultTools + your MCP servers + your current model |
tools: read, grep, find, ls | exactly those — and no MCP, because a --tools allowlist without an mcp__ entry stops MCP tools from being declared |
model: x/y | that model; omit it and the child follows the model of the session that dispatched it |
Shipped read-only roles (reviewer, verifier, scout, planner, gstack's security-officer / product-reviewer) declare a list without write / edit and therefore get no MCP either — the intended trade, since a reviewer shouldn't be able to push a branch. worker and gstack's designer declare nothing on purpose: they write, so they inherit everything you have. For the seven shipped roles that appear in both places, the list lives in the role md's tools: and in agents/index.json's roleTools — the index wins at runtime, the md is what a human reads, and bun run check fails when the two disagree. At the nesting ceiling the extension passes --exclude-tools subagent,subagent_*, so recursive dispatch dies there even when the tool set is inherited. Nothing in the shipped teams points at a private model or a specific MCP server — that's what makes the package installable on someone else's machine.
Per-dispatch overrides. A role file ships in the package, so it must not pin a private model. Pass the difference at call time — arguments win over the role, the role wins over your session, and all three work at the top level and per task in tasks[] / chain[]:
| Argument | Effect |
|---|---|
model | --model for this child, inherited by subagent_continue. Use it to lift a 60-turn adversarial review instead of writing model: into a role that ships. Blank or malformed values are ignored |
thinking | --thinking level, applied whenever you pass it. Omitted, the child inherits the dispatcher's level. Setting only a model does not suppress that level |
readOnly | --exclude-tools write,edit. bash stays: reviewers and verifiers run git diff and the test suite through it. Use it instead of writing "只读,不要改文件" into the task text — prose cannot stop bash |
Note —
readOnlyandwriteScopeare least-privilege defaults, not sandboxes.bash(any redirect orsed -i) and everymcp__*tool survive; gstack'sqa-leadgets themcpgateway, and that gateway has no per-server scope — it reaches every configured server, including the ones that push code.readOnlydoes travel down the tree: a child dispatched from a read-only run is read-only too and cannot widen itself. Whatsubagent_statusshows is a ledger field, not a proof: any same-uid process can rewrite it.
Per-role defaults (this machine only). agents/index.local.json — not shipped — maps a team/name to a tier (light/normal/heavy/deep, relative to the model's anchor) or a direct level, and modelBaseline sets that anchor, so changing the model edits one line and the role table never moves. Misconfiguration surfaces in the dispatch result (roleModels-unknown-key) instead of dying silently.
Long tasks: use taskFile, not a giant task string. Nested escaped quotes (\") are how this breaks: the argument JSON gets truncated mid-string and the entire tool call fails, taking every task in the batch with it.
subagent({ agent: "reviewer", task: "审查要点:1. \"foo\" 2. ... 2600 chars ..." }) // ✗ long brief inline
subagent({ agent: "reviewer", taskFile: "briefs/review.md" }) // ✓ write it, pass the path
task and taskFile are mutually exclusive; relative paths resolve against cwd. A missing file fails the whole batch with the member name and the path it tried — synchronously in every mode, including background: true, because the expansion runs at the tool entry before any dispatch. Works in all three modes; guards are a 256 KB cap (the task becomes a child-process argv entry; macOS ARG_MAX is 1 MB), NUL-byte reject (spawn throws on NUL in argv) and empty-body reject. Aim for task under ~800 characters.
Note — The truncation itself has not been reproduced on this machine — the configured 128k output budget swallows a 6300-char task fine. The failure we did see was
Invalid arguments for tool "subagent": Unexpected token 'a'on a call whose"notify"value had lost its quotes — consistent with truncation, but not proof.taskFilehelps regardless: it removes a large, escape-heavy string from the arguments, which is where the risk lives.
Interrupting a batch mid-run
A foreground subagent call blocks the whole turn — that is pi's design: steering messages only land at turn boundaries. Three ways out:
1. Preemption. Type while a foreground batch has run longer than PI_SUBAGENT_PREEMPT_AFTER_MS (default 30s) and the tool returns early with a partial result, the turn ends, and your message is read immediately. The members keep running in background and push their results back at the next turn boundary — unless you already fetched them with subagent_collect. Only fires in ctx.mode === "tui": RPC and the voice app have no keyboard, so hasPendingMessages() there means something else.
2. Mid-run instructions. subagent_tell writes an instruction to a running member; it lands at that member's next turn_end without restarting it. Only still-running members receive it (a finished one shows up in notDeliverable); message is capped at 300 characters, counted in Unicode code points and rejected rather than truncated; broadcast and sessionIds are mutually exclusive. It reads like subagent_tell({ sessionIds: ["sa-..."], message: "跳过集成测试,先跑单测" }). Steering adds to the original task, it does not replace it — measured on a real run, the child executed both paths (7/7 turns); to stop an old direction you have to kill and re-dispatch.
3. Stopping a preempted batch. Ctrl+Option+K (ctrl+alt+k) in the TUI is the primary binding (no built-in conflict); /kill-subagents is the keyboard-free fallback for any mode. Targets are registered only in TUI mode, so elsewhere the command reports "nothing to kill". It kills the process groups of batches that were actually preempted (SIGTERM, then SIGKILL after 5s for survivors) and never touches the rest.
Concurrent writes and stuck runs
Write scopes. Give each task in a batch a writeScope (path prefixes) and overlapping scopes are rejected before anything spawns:
subagent({ tasks: [
{ agent: "worker", task: "Rewire the session store", writeScope: ["src/auth"] },
{ agent: "verifier", task: "Cover the same paths", writeScope: ["src/auth/login.ts"] },
]})
// 并行批的写范围重叠,已拒绝派活(一个文件都不写):worker 与 verifier 都要写 src/auth
Overlap means one prefix covers the other at a path boundary: src/auth collides with src/auth/login.ts, not with src/authx. Scopes are anchored to each task's cwd, any .. collapses to "whole repo", and a malformed writeScope already in the ledger is treated as "whole repo". Only tasks inside one concurrent batch are compared — chain steps run one after another. Across batches the check reads the ledger, so it sees runs written by other pi processes, and refuses a dispatch whose scope overlaps something still running. A task with no writeScope is unrestricted, and subagent_status marks it 范围: 未声明(无限制).
This is a pre-dispatch check, not a sandbox and not a security boundary: the reservations live in a ledger any same-uid process — including a child agent with bash — can rewrite, and tampering is silent (delete an entry and its reservation disappears). Real write interception needs a guard extension inside the child (P3, not built). Two batches in the same event-loop tick both read an empty ledger (TOCTOU); subagent_continue skips the gate on purpose.
Names and cwds are checked before anything spawns. A batch with one unparseable role name, or a cwd that is not a directory, is rejected whole in milliseconds — because a parallel batch is one await, so a member that dies at 0 ms is only reported when its siblings finish (measured once at 18 minutes). The rejection names the offending slot (tasks[1]:…) and lists paste-ready candidates. Single mode is exempt: it returns in the same turn with a ledger row and a resume handle.
Stuck runs. A run is stuck when it is still running, has produced no event for longer than its idle window, no tool is in progress, and it got past its first turn (a 3–10 s cold start is not "stuck"). "A tool is in progress" is bounded: once the silent time reaches the run's own timeoutMs, the tool no longer counts. The window is min(5 min, timeoutMs / 4) with a floor of twice the ledger write interval — 5 minutes at the default timeout, 60 seconds at timeoutMs: 240000. Nothing is killed by the detector, but a stuck run shows up in subagent_status (◐2 verifier 8m idle 6m · 3轮/2工具) and the main agent gets one sendMessage when it is detected (⚠ 子任务疑似卡住…**没有杀它**), so a background run that goes quiet reaches you instead of waiting for a poll. stuckAt is written to the ledger, so 曾卡住: 5m 前检出 survives the run; the notification fires once.
timeoutMs is a per-round budget, not a cap — and it's reported. A run still making progress gets up to 3 extra rounds, each as long as the original, then a 5-minute grace; the real worst case is timeoutMs × 4 + 5 min. Every extension is written where the caller sees it: extended in the ledger, run.extend in the feed, 续命: N 轮 in subagent_status, [已续 N 轮…] in the result text.
Logs and retention
Five files under ~/.pi/agent/subagent-runs/, each with its own lifetime — and they are not interchangeable:
| File | Lifetime | What it is |
|---|---|---|
<sessionId>.json | 24h | Ledger: status, turns, last tool, declared budget, token usage (input/output/cacheRead), batchId. 2-second overwrite — the disk holds the last frame, not a history |
<sessionId>.aN.out.json | 24h | Full output, usage, stderr tail, transcriptPath, and errorMessage — the last assistant's own error; output is the mid-run progress line on failure, errorMessage is why it died. 0600, redacted on write |
_feed.jsonl | forever | Activity timeline: run.start / run.end / run.extend / run.stuck / run.reject / run.retry / gate.reject / deliver.fail. Human-facing only — no code makes decisions from it |
_errors.log | 1MB × 3 shards | Mechanism errors (spawn failed, ledger unwritable, notification undeliverable). Rotates to <name>.<ts>-<pid> so two processes never overwrite each other's evidence |
_index.jsonl | forever (4MB shards) | sessionId → transcript path. The ledger dies in 24h; the pi session transcript lives for months. bun run transcript <sessionId> reads it |
A crashed pi leaves a stale running record. After 90 minutes with no update the ledger is rewritten to failed/stale on the next read. stale means "nobody updated this for 90 minutes", not "the process is dead": a background child is its own process group and can still finish after the parent pi is killed. Read the transcript before deleting anything. The ledger's usage accumulates across resume attempts while .aN.out.json's is per-attempt only, so aggregate per role or batch from the ledger (filter by batchId) and never by summing .out.json files. Secrets are redacted before they hit disk. The task text lands on disk in three places (ledger, _errors.log, the feed's run.start summary), all through redactForDisk (token prefixes, Bearer/Basic, 32+ character random strings); a hit count is recorded (taskRedacted / redacted). The 32+ rule is deliberately trigger-happy — bare commit hashes get replaced too. .out.json holds the child's output, not the task, so it is not redacted; it is 0600 and pruned in 24h. What a child reads also lands in the parent session transcript, which pi writes 0644 with no retention policy — clean up after sensitive work.
Tuning
| Env var | Default | Meaning |
|---|---|---|
PI_SUBAGENT_MAX_DEPTH | 2 | Nesting depth. At the ceiling the subagent* tools are removed from the child, not denied after a call |
PI_SUBAGENT_MAX_CHILDREN | 4 | Concurrent children per process — not a global cap |
PI_SUBAGENT_DEPTH | 0 | Set by the extension when spawning; don't set it yourself |
PI_TASK_ORIGIN | terminal | Which channel this session counts as. Decides which teams are visible |
PI_SUBAGENT_READONLY | unset | Set by the extension when a readOnly dispatch spawns. A child inherits it and cannot widen itself |
PI_DISABLE_PACKAGE_AGENTS | unset | Set to anything to skip the package-level agents/ layer (tests use this) |
PI_MUTATION_LOCK_WAIT_MS | 600000 | How long mutation-check waits for another instance before giving up (exit 4) |
PI_SUBAGENT_PREEMPT | 1 | Foreground preemption master switch. 0 = off |
PI_SUBAGENT_PREEMPT_AFTER_MS | 30000 | How long a foreground batch must have run before an interruption can preempt it. 0 = immediately |
PI_SUBAGENT_OVERFLOW | 4 | Extra slots only when the child limit is hit and a preempted batch is still running. 0 = off |
PI_SUBAGENT_STEER | 1 | Mid-run instruction channel master switch. 0 = subagent_tell refuses to write |
PI_SUBAGENT_STEER_DIR | set by extension | Where a child looks for pending instructions. Don't set it yourself |
PI_SUBAGENT_MAX_STEER_TURNS | 8 | How many instructions one child may receive. 0 = inject nothing |
PI_SUBAGENT_ROLE_MODELS | on | on / no-default / off. no-default keeps roleModels but skips the per-model default level; off ignores the config layer. Unknown values fail open |
PI_CHANNEL_SENDER | ~/.pi/agent/channel-sender.mjs | ESM module exporting sendToChannel, used for cross-channel broadcast. Missing module → desktop notification only, dispatching unaffected |
PI_SUBAGENT_MAX_CHILDREN is a per-process limit; each child is a separate pi process with its own counter. Count overflow too: per layer it's MAX_CHILDREN + PI_SUBAGENT_OVERFLOW = 4 + 4 = 8, so at depth 2 the worst case is 8 + 8×8 = 72 processes (~14 GB at the 200 MB median, ~45 GB at the 635 MB peak). If that's too much, set PI_SUBAGENT_MAX_DEPTH=1 (cap 8) or shrink PI_SUBAGENT_OVERFLOW.
Module map
One file, one job; arrows are the only allowed import directions.
result.ts (399) outcome model, silent window ← zero I/O, anyone may depend on it
scope.ts (306) write-scope gate: in-batch + cross-batch, path anchoring ← zero I/O
agents.ts (1547) who may be dispatched + argv + precheck + child interpreter → result
errlog.ts (510) mechanism error log + disk redaction + folding ← zero repo deps
runs.ts (1099) ledger / full output / transcript index / stale rewrite / scope table → result, errlog
stuck.ts (219) stuck criteria / watcher / notice text → runs
feed.ts (312) activity feed: envelope / normalize / merge / append+read → errlog, runs
board.ts (469) parallel conclusions on disk: one file per member → errlog, runs
steer.ts (522) parent → child instructions: one dir per session, wx create, rename consume → runs
preempt.ts (157) preemption registry + tick decision + partial-result text ← zero I/O
release.ts (57) batch registration release: drained / force ← zero I/O
overflow.ts (147) shouldOverflow / overflowLimit / capacityText ← zero I/O
notify.ts (235) desktop notifications → result, errlog
render.ts (864) TUI rendering → result, agents
index.ts (5024) dispatch + retry + six tool registrations + wiring → all
concurrency.ts (57) concurrency pool: one failure doesn't lose its siblings' results
Development
bun run test # unit tests; bare `bun test` also sweeps the agents/ playwright suites
bun scripts/mutation-check.ts # prove the tests actually catch regressions
bun run typecheck-gate # types in extensions/subagent (gate: 0 errors)
bun run check-docs # docs consistency, incl. generated team inventory
bun run release # all gates + build:dist + npm publish ./dist
agents/ holds 25 teams in this repo; only pi-dev-team and gstack ship, and build:dist turns that into a directory you can ls (one extra team and it exits 1). bun run typecheck is not judged green — tests/ and scripts/ have dozens of errors from the deliberately absent @types/node; typecheck-gate judges only extensions/subagent/, with TypeScript pinned at 5.9.3. bun run verify is a manual tool, not a gate: it spawns real subagents (tokens, 1–3 minutes per case) to prove stuck / cross / feed / board actually fire on real processes. mutation-check runs in a throwaway clone ($TMPDIR/pi-mutation-<pid>-*), because this repo doubles as a pi runtime that a starting pi imports.
Uninstall
pi remove npm:pi-guild (git: / npm: installs). Your ~/.pi/agent/agents/ is never touched — the package only reads its own bundled directory, so removing it removes the tools, not your data. License: MIT.