@wierdbytes/pi-wierdr 0.0.0-stage → 0.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,8 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0
4
+
5
+ - **New:** `@wierdbytes/pi-herdr` (0.6.1) and `@wierdbytes/pi-agents` (0.1.3) in one package, nothing else changed: `agent.*` labels, the `limits` document, bash in herdr-core terminals and sub-agents.
6
+ - **Change:** settings in one file, `~/.pi/agent/@wierdbytes/pi-wierdr/settings.json` (`bash`, and the sub-agents' keys under `agents`); the old packages' files are read until it exists.
7
+ - **Change:** sub-agents' run files in `~/.pi/agent/@wierdbytes/pi-wierdr/runs`.
8
+ - **Change:** the RPC client for other extensions is `@wierdbytes/pi-wierdr/client`.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Leo Henon
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,225 @@
1
- # Temporary Holding Version
1
+ # @wierdbytes/pi-wierdr
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [pi](https://github.com/earendil-works/pi) for [herdr](https://herdr.dev) and Wierdr. One extension, two halves:
4
+
5
+ - **[herdr](#labels)** — tells herdr which model, reasoning effort and context size each pi runs with ([Labels](#labels)), how much of your Claude and Codex subscription limits is used ([Limits](#limits)), and runs pi's bash commands in herdr-core terminals under pi's, so you can watch each one live in herdr ([Bash](#bash)). Formerly `@wierdbytes/pi-herdr`.
6
+ - **[sub-agents](#sub-agents)** — each sub-agent is its own interactive pi in a herdr-core terminal nested under the agent that started it ([Sub-agents](#sub-agents)). Formerly `@wierdbytes/pi-agents`.
7
+
8
+ ```
9
+ ◌ Fix login redirect loop Opus 5.5 @high 228k
10
+ ├ ◌ find-auth-code Explore Sonnet 5.5 @low
11
+ └ ✓ review-session-store general-purpose Opus 5.5 @medium
12
+ ```
13
+
14
+ The source lives in the [Wierdr](https://github.com/wierdbytes/wierdr) repository next to its Claude Code and Codex plugins, which write the same labels and the same document.
15
+
16
+ ## Install
17
+
18
+ ```bash
19
+ pi install npm:@wierdbytes/pi-wierdr
20
+ pi remove npm:@wierdbytes/pi-herdr # replaced by this one
21
+ pi remove npm:@wierdbytes/pi-agents # replaced by this one
22
+ pi remove npm:@tintinweb/pi-subagents # same tool names: keep only one
23
+ ```
24
+
25
+ pi must run inside a herdr-core terminal (`HC_TERMINAL_ID` / `HC_TERMINAL_SOCKET` set, as in every herdr pane). Elsewhere it does nothing: no labels, bash stays in pi, the sub-agent tools aren't registered and the RPC's `ping` answers `available: false`.
26
+
27
+ ## Settings
28
+
29
+ Optional, in `~/.pi/agent/@wierdbytes/pi-wierdr/settings.json`, every key optional:
30
+
31
+ ```json
32
+ {
33
+ "bash": true,
34
+ "agents": {
35
+ "command": ["pi"],
36
+ "extraArgs": ["--no-voice", "--no-peon"],
37
+ "maxDepth": 1,
38
+ "inheritEnv": true
39
+ }
40
+ }
41
+ ```
42
+
43
+ | Key | Default | |
44
+ |---|---|---|
45
+ | `bash` | `true` | Run bash commands in herdr-core terminals ([Bash](#bash)). `false` keeps them in pi's own process |
46
+ | `agents.command` | `["pi"]` | How to start pi in a sub-agent's terminal |
47
+ | `agents.extraArgs` | `[]` | Extra pi arguments for every sub-agent — e.g. silence pi-voice and pi-peon in sub-agents. Only list flags of extensions you have installed |
48
+ | `agents.maxDepth` | `1` | `2` lets sub-agents start their own sub-agents |
49
+ | `agents.inheritEnv` | `true` | Sub-agents get the parent's environment (PATH, API keys) minus terminal identity (`HC_*`, `TERM*`, the parent's `PI_SESSION_*`) |
50
+
51
+ Until this file exists, `~/.pi/agent/@wierdbytes/pi-herdr/settings.json` (`bash`) and `~/.pi/agent/@wierdbytes/pi-agents/settings.json` (the `agents` keys, at the top) are read instead.
52
+
53
+ ## Labels
54
+
55
+ Pi already reports its status (working, blocked, done) over OSC 7501, but that report has no room for the model. This extension writes it as `agent.*` labels on the herdr-core terminal pi runs in, so a herdr agent list can show a second line under each pi:
56
+
57
+ ```
58
+ D Fix login redirect loop ◌
59
+ A\ Opus 5.5 @high ⑂ 2 228k 4m
60
+ ```
61
+
62
+ | Label | Example | |
63
+ |---|---|---|
64
+ | `agent.app` | `pi` | Who wrote the labels |
65
+ | `agent.pid` | `88638` | pi's process id: a reader compares it with the terminal's foreground pid and ignores labels left behind by a pi that crashed |
66
+ | `agent.model` | `Claude Opus 5.5` | Model display name (`ctx.model.name`, else its id) |
67
+ | `agent.model_id` | `claude-opus-5-5` | Model id |
68
+ | `agent.provider` | `anthropic` | Provider id |
69
+ | `agent.effort` | `high` | Thinking level, or the model's own word for it (`max`, a token budget). Absent when off or the model doesn't reason |
70
+ | `agent.ctx` | `228432` | Tokens in the context now. Absent while unknown (right after compaction) |
71
+ | `agent.ctx_max` | `1000000` | Context window |
72
+ | `agent.session` | `019f8940-4b3b-7d72-8112-3a9ebd007d5c` | The open session's id (`pi --session <id>` opens it again). Follows `/new`, `/resume` and forks; absent for `--no-session` |
73
+ | `agent.cache_until` | `1793534700000` | When the prompt cache of the current branch expires (epoch ms), as pi-statusline's countdown reads it: the last request or cache warming that touched the cache, plus the model's cache lifetime. Stays after expiry (compare with now); absent when the cache was never touched or the model's cache lifetime is unknown |
74
+ | `agent.cache_ttl` | `300000` | How long that cache entry lives from its last refresh (ms): the model's short or long tier. Set with `agent.cache_until`; together they give the share of the lifetime left |
75
+ | `agent.subagents` | `2` | [`@tintinweb/pi-subagents`](https://github.com/tintinweb/pi-subagents) agents queued or running (in-process, so herdr can't see them). Absent when none. This package's own sub-agents are terminals of their own and aren't counted |
76
+
77
+ Read them in a herdr mod from `terminals()`:
78
+
79
+ ```js
80
+ const t = terminals().find((t) => t.address === agent.address);
81
+ const meta = t?.labels?.["agent.pid"] === String(t?.foreground?.pid) ? t.labels : {};
82
+ meta["agent.model"]; // "Claude Opus 5.5"
83
+ ```
84
+
85
+ - Updates on session start, `/model` and model cycling, effort changes, every assistant request and reply, turn end, compaction, tree navigation and cache warming.
86
+ - Changes within 150 ms collapse into one `terminal.label` request over herdr-core's JSON-RPC socket; unchanged values are never sent. No `hc` process is spawned.
87
+ - Only the interactive pi owns the terminal: `pi -p`, RPC hosts and in-process sub-agents never write labels.
88
+ - Quitting pi removes every label it set (the `limits` document stays: it belongs to the subscription, not to this pi). Switching sessions and `/reload` keep them and the next session republishes.
89
+
90
+ ## Limits
91
+
92
+ Every Claude and Codex response carries the subscription's usage windows (Anthropic's `anthropic-ratelimit-unified-*` headers, Codex's `x-codex-*` headers or `codex.rate_limits` stream event). pi-wierdr folds them into one herdr-core document, `limits`, on the machine pi runs on. Any herdr-core client reads it with `doc.get {name: "limits"}` and hears about changes as `doc` events (`events.subscribe`), so the herdr app, Wierdr or a script all show the same numbers, also from other machines (`on`).
93
+
94
+ ```json
95
+ {
96
+ "schema": 1,
97
+ "updated_at": 1794310000,
98
+ "accounts": {
99
+ "claude.1a2b3c4d": {
100
+ "provider": "claude", "account": "1a2b3c4d", "plan": "max",
101
+ "status": "ok", "binding": "5h", "source": "header", "host": "mentoair", "at": 1794310000,
102
+ "windows": {
103
+ "5h": { "id": "5h", "label": "5 hours", "window_s": 18000, "used": 67, "resets_at": 1794321600, "status": "ok", "at": 1794310000 },
104
+ "7d": { "id": "7d", "label": "7 days", "window_s": 604800, "used": 36, "resets_at": 1794571200, "status": "ok", "at": 1794310000 }
105
+ }
106
+ }
107
+ }
108
+ }
109
+ ```
110
+
111
+ - Accounts are keyed `<provider>.<account>`; `account` is the first 8 hex digits of sha256 of the provider's account id (`main` without one), the same as pi-langfuse's `rl.<provider>.<account>.<window>` scores. Codex accounts carry the e-mail pi signs in with as `label`.
112
+ - Window ids: `5h`, `7d`, `7d_oi` (weekly with extra usage), `7d_opus`, `7d_sonnet` for Claude; `5h`, `7d` and `<family>.<window>` for extra Codex limit families. `used` is in percent and can pass 100. Times are unix seconds; `at` is when a window was last read, so readers can tell live from stale.
113
+ - Several pi processes write it: each reads the document, folds its reading in and writes it back at that version, retrying when another pi wrote in between. Within one window (same reset, give or take two minutes) `used` only grows; a later window replaces it.
114
+ - Every reading is written, even with the same numbers: `at` is when a provider last reported the window. Nothing is written between responses. Readings within 500 ms go out as one write.
115
+ - Every pi writes, not only the interactive one: `pi -p` runs and sub-agents spend the same subscription. Windows a provider stops reporting stay until a later reading replaces them.
116
+
117
+ ## Bash
118
+
119
+ Every command pi runs, the model's `bash` tool calls and your `!` / `!!` commands, gets a herdr-core terminal of its own (`terminal.run`, what `hc run` does), a child of pi's. Herdr shows it under pi while it runs:
120
+
121
+ - the screen starts with `$ <command>`, then the output as it comes;
122
+ - the title is the command's first line, and the program in front is the command itself (`bash -c '<command>'`, or the program when it is a single one);
123
+ - the label `pi-herdr.bash` (named before the move, kept) is `tool` or `user`, for mods that want to tell these terminals apart;
124
+ - ctrl+c typed into it stops the command, and pi reports the exit code.
125
+
126
+ In pi, the model's commands are drawn in pi-facelift's frame (the shared renderer from `@wierdbytes/pi-common/tool-frame/bash`), with or without pi-facelift installed: the command in the top border, the output on the rail, duration and `✓ exit 0` / `✗ exit N` in the bottom border. `!` commands keep pi's own look.
127
+
128
+ ```
129
+ ╭── bash npm test ──────────────────────────────── t14s ─
130
+ │ 12 passed
131
+ ╰── 3.2s ──────────────────────────────────────────────────
132
+ ```
133
+
134
+ The terminal is removed as soon as the command ends; when pi quits, running ones are ended and removed.
135
+
136
+ Commands run as with pi's own bash: stdin is `/dev/null`, stdout and stderr are one pipe (no colors, no pagers, no prompts). `tee` copies it to the terminal and to a file pi reads, so pi gets the exact output however long it is, and the command's exit code. What it starts in the background (`server &`) outlives the terminal, as before. Inside, `HC_TERMINAL_ID` is pi's: `hc run` starts terminals under pi, `hc send $HC_TERMINAL_ID` reaches pi.
137
+
138
+ Commands that call `hc wait` run in pi's own process: in a terminal under pi they would wait for themselves (`hc wait --children all`). So does a command herdr-core can't start a terminal for (the core is down or refuses), and everything when pi's shell isn't bash (`shellPath`) or on Windows.
139
+
140
+ Only one extension can own `bash`, and pi won't start when two register it, so pi-wierdr registers its tool at session start, and only over pi's built-in one. With another extension that replaces `bash`, the model's commands stay in pi's process and pi-wierdr says so once at start; `!` commands still run in herdr terminals. pi-facelift (0.8.0+) can leave `bash` to pi: switch it off in `/facelift` → Tools, then `/reload`.
141
+
142
+ ## Sub-agents
143
+
144
+ Each sub-agent is its own interactive `pi`, started in a herdr-core terminal as a **child of the terminal the parent pi runs in**. Herdr already understands that relation: its agent list nests sub-agents under the agent that started them, shows their status (working / blocked / done) and, through the labels above, their model and context. You can peek at any of them, type into it, or take it over.
145
+
146
+ Replaces [`@tintinweb/pi-subagents`](https://github.com/tintinweb/pi-subagents) — same tool names, so models keep using them the way they know.
147
+
148
+ ### Tools
149
+
150
+ | Tool | What it does |
151
+ |---|---|
152
+ | `Agent` | Start a sub-agent: `description` (its title in herdr, like a session name), `prompt`, optional `subagent_type`, `model` (`provider/id` or fuzzy: `"sonnet"`), `thinking` (`off` … `max`), `cwd`, `run_in_background`. Foreground (default) waits and returns its report, with live progress; background returns at once. |
153
+ | `get_subagent_result` | State now, or `wait: true` until it finishes (optional `timeout` seconds). |
154
+ | `steer_subagent` | Type a message into it: a steer while it works, a follow-up turn once it has finished (context intact). |
155
+ | `stop_subagent` | End it and close its terminal. |
156
+
157
+ - **Defaults:** the agent type's model / effort, else the parent session's.
158
+ - **Background results** arrive as one message per batch when the parent is idle (or right after its current run), and start a turn. Results already collected with `get_subagent_result` are not repeated.
159
+ - **Blocked:** a sub-agent waiting on a dialog shows as blocked in herdr; the parent gets a note (no turn) and `wait` returns, so nothing hangs on it.
160
+ - **Lifecycle:** a finished sub-agent stays open and idle — inspect it in herdr or send a follow-up. `stop_subagent`, `/agents → Stop`, or quitting the parent pi ends it. After `/reload` the parent picks its sub-agents up again.
161
+ - **Depth:** sub-agents don't get these tools (`agents.maxDepth: 1`).
162
+ - `/agents` lists the sub-agents; pick one to peek at it in herdr (`herdr-app do terminal.peek`) or stop it.
163
+
164
+ ### Agent types
165
+
166
+ Built in: `general-purpose` (all tools), `Explore` and `Plan` (read-only: `read, bash, grep, find, ls`). Add your own as Markdown in `~/.pi/agent/agents/*.md` or, in trusted projects, `.pi/agents/*.md` — the same files pi-subagents reads:
167
+
168
+ ```md
169
+ ---
170
+ name: reviewer
171
+ description: Reviews a diff for bugs and risky changes
172
+ model: anthropic/claude-sonnet-5-5 # optional; "inherit" = the parent's
173
+ thinking: medium # optional
174
+ tools: read, grep, find, ls, bash # optional allowlist → pi --tools
175
+ disallowed_tools: write, edit # optional denylist → pi --exclude-tools
176
+ ---
177
+ Review only what you were pointed at. Report each finding with file:line and severity.
178
+ ```
179
+
180
+ The body is added to the sub-agent's system prompt (pi-subagents' `prompt_mode: replace` is treated as append). A file named like a built-in replaces it.
181
+
182
+ ### For other extensions: `pi.events` RPC
183
+
184
+ ```ts
185
+ import { agentsClient } from "@wierdbytes/pi-wierdr/client";
186
+
187
+ const agents = agentsClient(pi.events);
188
+ if ((await agents.ping()).available) {
189
+ const a = await agents.spawn({ description: "Review diff", prompt: "…", model: "sonnet", thinking: "low" });
190
+ const done = await agents.wait(a.id); // until it finishes or needs a person
191
+ console.log(done.status, done.result);
192
+ }
193
+ agents.on("completed", (a) => { /* … */ });
194
+ ```
195
+
196
+ Without the client: emit `agents:rpc:<method>` with a `requestId`, listen on `agents:rpc:<method>:reply:<requestId>` for `{ success: true, data } | { success: false, error }`.
197
+
198
+ | Method | Params | Data |
199
+ |---|---|---|
200
+ | `ping` | — | `{ version, available }` |
201
+ | `spawn` | `{ prompt, description, subagent_type?, model?, thinking?, cwd?, notify? }` | snapshot. Always background; the parent model hears about it only with `notify: true` |
202
+ | `get` / `stop` | `{ id }` | snapshot |
203
+ | `wait` | `{ id, timeoutMs? }` | snapshot once it isn't working |
204
+ | `steer` | `{ id, message }` | snapshot + `mode: "steer" \| "follow-up"` |
205
+ | `list` | — | snapshots |
206
+
207
+ Broadcasts: `agents:spawned`, `agents:running`, `agents:blocked`, `agents:completed`, `agents:failed`, `agents:stopped`, each with the snapshot (`id`, `address`, `status`, `description`, `type`, `model`, `thinking`, `result`, `error`, `activity`, …). `id` is the herdr terminal name (`find-auth-code`); `address` its hc address (`t8c`) — both work wherever an id is asked for.
208
+
209
+ ### How it works
210
+
211
+ - **Start:** herdr-core `terminal.run` over `HC_TERMINAL_SOCKET` with `parent` = this pi's terminal, `no_notify` (pi-wierdr reports to the model itself instead of hc typing notes into pi), labels `pi-agents.run` / `pi-agents.pid` (named before the move, kept), and `pi --model … --thinking … --name <description> [--tools …] -- <prompt>`. The terminal is named after the description (Cyrillic transliterated, `-2` on collisions).
212
+ - **Child side:** the same extension, loaded in the sub-agent, sees `PI_AGENTS_RUN`: it adds a `<subagent>` system-prompt section (role, report format, the type's instructions), inherits the parent's project trust, and writes `~/.pi/agent/@wierdbytes/pi-wierdr/runs/<run>.json` — settled-run count, last assistant message, tool activity. It takes `PI_AGENTS_*` out of its environment, so a pi that a tool of the sub-agent starts doesn't take itself for the sub-agent.
213
+ - **Parent side:** one `events.subscribe {children_of}` stream (status, exit), `fs.watch` on the run files and a 2 s safety poll. A record finishes when the child's settled-run count moves past where it was when the work was handed over, so a fresh pi's startup idle never counts as done. A pi that exits without a result fails with its last screen.
214
+ - Run files older than 7 days are pruned.
215
+
216
+ ## Development
217
+
218
+ ```bash
219
+ cd Integrations/pi
220
+ bun install
221
+ bun run test
222
+ pi -ne -e ./index.ts # try it without the installed copy
223
+ ```
224
+
225
+ Published to npm by [`.github/workflows/publish-pi.yml`](../../.github/workflows/publish-pi.yml) on push to `master`, when `version` in `package.json` isn't on npm yet: bump it, add a matching `## <version>` entry at the top of `CHANGELOG.md`, push.
@@ -0,0 +1,154 @@
1
+ /**
2
+ * Agent types: built-in `general-purpose`, `Explore` and `Plan`, plus
3
+ * Markdown files in `~/.pi/agent/agents/*.md` and (trusted projects only)
4
+ * `<cwd>/.pi/agents/*.md` — the same places and frontmatter as
5
+ * pi-subagents, so existing definitions keep working:
6
+ *
7
+ * ```md
8
+ * ---
9
+ * name: reviewer # default: the file name
10
+ * description: Reviews a diff for bugs
11
+ * model: anthropic/claude-sonnet-5-5 # optional, "inherit" = the parent's
12
+ * thinking: medium # optional
13
+ * tools: read, grep, find, ls, bash # optional allowlist (pi --tools)
14
+ * disallowed_tools: write, edit # optional denylist (pi --exclude-tools)
15
+ * ---
16
+ * Instructions, added to the sub-agent's system prompt.
17
+ * ```
18
+ *
19
+ * A file named like a built-in replaces it; project files win over user files.
20
+ */
21
+
22
+ import { readdirSync, readFileSync } from "node:fs";
23
+ import { basename, join } from "node:path";
24
+ import { getAgentDir } from "@earendil-works/pi-coding-agent";
25
+
26
+ export interface AgentType {
27
+ name: string;
28
+ description: string;
29
+ /** Instructions added to the child's system prompt. */
30
+ prompt: string;
31
+ model?: string;
32
+ thinking?: string;
33
+ tools?: string[];
34
+ excludeTools?: string[];
35
+ source: "builtin" | "user" | "project";
36
+ }
37
+
38
+ export const DEFAULT_TYPE = "general-purpose";
39
+
40
+ const READ_ONLY = ["read", "bash", "grep", "find", "ls"];
41
+
42
+ export const BUILTIN_TYPES: AgentType[] = [
43
+ {
44
+ name: "general-purpose",
45
+ description:
46
+ "General-purpose agent for researching complex questions, searching for code, and executing multi-step tasks. All tools.",
47
+ prompt: "",
48
+ source: "builtin",
49
+ },
50
+ {
51
+ name: "Explore",
52
+ description:
53
+ 'Fast read-only agent for locating code: find files by pattern, grep for symbols, answer "where is X / what uses Y". Say how thorough to be: "quick", "medium" or "very thorough".',
54
+ tools: READ_ONLY,
55
+ prompt: [
56
+ "READ-ONLY MODE: you search and analyze; you never create, modify, move or delete files, and never run commands that change system state (bash only for ls, git status/log/diff/show, cat, head, tail).",
57
+ "Prefer the find, grep and read tools over their bash equivalents. Make independent calls in parallel.",
58
+ "Match the thoroughness the task asks for. Report absolute file paths with line numbers, and quote the code that answers the question.",
59
+ ].join("\n"),
60
+ source: "builtin",
61
+ },
62
+ {
63
+ name: "Plan",
64
+ description:
65
+ "Read-only software architect: designs an implementation plan, identifies the critical files and weighs trade-offs. Returns a step-by-step plan.",
66
+ tools: READ_ONLY,
67
+ prompt: [
68
+ "READ-ONLY MODE: you never create, modify or delete files.",
69
+ "Explore the code until you understand how the change fits, then return a plan: the approach and why, the files to change and what changes in each, the order of steps, risks and open questions.",
70
+ "Name exact files and symbols. Keep the plan concrete enough that another agent can implement it without re-exploring.",
71
+ ].join("\n"),
72
+ source: "builtin",
73
+ },
74
+ ];
75
+
76
+ /** Minimal frontmatter: `key: value` lines between `---` fences. */
77
+ export function parseFrontmatter(text: string): { fm: Record<string, string>; body: string } {
78
+ const m = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/.exec(text);
79
+ if (!m) return { fm: {}, body: text.trim() };
80
+ const fm: Record<string, string> = {};
81
+ for (const line of m[1]!.split(/\r?\n/)) {
82
+ const kv = /^([A-Za-z_][\w-]*)\s*:\s*(.*)$/.exec(line);
83
+ if (!kv) continue;
84
+ let value = kv[2]!.replace(/\s+#.*$/, "").trim();
85
+ if (/^(["']).*\1$/.test(value)) value = value.slice(1, -1);
86
+ fm[kv[1]!] = value;
87
+ }
88
+ return { fm, body: m[2]!.trim() };
89
+ }
90
+
91
+ const csv = (v: string | undefined): string[] | undefined => {
92
+ if (!v) return undefined;
93
+ const list = v
94
+ .replace(/^\[|\]$/g, "")
95
+ .split(",")
96
+ .map((s) => s.trim().replace(/^["']|["']$/g, ""))
97
+ .filter(Boolean);
98
+ return list.length ? list : undefined;
99
+ };
100
+
101
+ export function parseAgentFile(file: string, text: string, source: AgentType["source"]): AgentType | undefined {
102
+ const { fm, body } = parseFrontmatter(text);
103
+ const name = (fm.name || basename(file, ".md")).trim();
104
+ if (!name) return undefined;
105
+ const model = fm.model && fm.model !== "inherit" ? fm.model : undefined;
106
+ const thinking = fm.thinking && fm.thinking !== "inherit" ? fm.thinking : undefined;
107
+ return {
108
+ name,
109
+ description: fm.description || name,
110
+ prompt: body,
111
+ model,
112
+ thinking,
113
+ tools: csv(fm.tools),
114
+ excludeTools: csv(fm.disallowed_tools ?? fm.disallowedTools ?? fm.exclude_tools),
115
+ source,
116
+ };
117
+ }
118
+
119
+ function loadDir(dir: string, source: AgentType["source"]): AgentType[] {
120
+ let files: string[];
121
+ try {
122
+ files = readdirSync(dir).filter((f) => f.endsWith(".md"));
123
+ } catch {
124
+ return [];
125
+ }
126
+ const out: AgentType[] = [];
127
+ for (const f of files.sort()) {
128
+ try {
129
+ const t = parseAgentFile(f, readFileSync(join(dir, f), "utf8"), source);
130
+ if (t) out.push(t);
131
+ } catch {
132
+ // An unreadable file is skipped, not fatal.
133
+ }
134
+ }
135
+ return out;
136
+ }
137
+
138
+ export function loadAgentTypes(cwd: string, projectTrusted: boolean): Map<string, AgentType> {
139
+ const types = new Map<string, AgentType>();
140
+ for (const t of BUILTIN_TYPES) types.set(t.name, t);
141
+ for (const t of loadDir(join(getAgentDir(), "agents"), "user")) types.set(t.name, t);
142
+ if (projectTrusted) for (const t of loadDir(join(cwd, ".pi", "agents"), "project")) types.set(t.name, t);
143
+ return types;
144
+ }
145
+
146
+ /** Exact name first, then case-insensitive. */
147
+ export function findType(types: Map<string, AgentType>, name: string | undefined): AgentType | undefined {
148
+ const wanted = (name ?? DEFAULT_TYPE).trim() || DEFAULT_TYPE;
149
+ const exact = types.get(wanted);
150
+ if (exact) return exact;
151
+ const lower = wanted.toLowerCase();
152
+ for (const t of types.values()) if (t.name.toLowerCase() === lower) return t;
153
+ return undefined;
154
+ }
@@ -0,0 +1,224 @@
1
+ /**
2
+ * Child side: this pi was started by pi-wierdr as a sub-agent (`PI_AGENTS_RUN` is set).
3
+ * It tells the model it is a sub-agent, inherits the parent's project trust
4
+ * and keeps `<runs>/<runId>.json` current so the parent can collect the
5
+ * result without scraping the screen.
6
+ */
7
+
8
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
9
+ import { ENV, ENV_PREFIX } from "./launch.ts";
10
+ import { type ChildState, type LastStatus, readMeta, type RunMeta, writeState } from "./runs.ts";
11
+
12
+ export interface ChildInfo {
13
+ runId: string;
14
+ dir: string;
15
+ depth: number;
16
+ /** The parent's answer to "is this project trusted?", when it had one. */
17
+ trust?: "yes" | "no";
18
+ meta?: RunMeta;
19
+ }
20
+
21
+ export function childFromEnv(env: NodeJS.ProcessEnv = process.env): ChildInfo | undefined {
22
+ const runId = env[ENV.RUN];
23
+ const dir = env[ENV.DIR];
24
+ if (!runId || !dir) return undefined;
25
+ const depth = Number.parseInt(env[ENV.DEPTH] ?? "1", 10);
26
+ const trust = env[ENV.TRUST];
27
+ return {
28
+ runId,
29
+ dir,
30
+ depth: Number.isFinite(depth) && depth > 0 ? depth : 1,
31
+ trust: trust === "yes" || trust === "no" ? trust : undefined,
32
+ meta: readMeta(dir, runId),
33
+ };
34
+ }
35
+
36
+ /** Where {@link takeChildEnv} keeps what it took, for the life of the process (named before pi-agents became pi-wierdr). */
37
+ const TAKEN = Symbol.for("@wierdbytes/pi-agents/child-env");
38
+
39
+ /**
40
+ * Takes `PI_AGENTS_*` out of `env` and returns them. Left in place, everything
41
+ * this pi starts would inherit them — a bash command, the `pi -p` another
42
+ * extension runs to summarize a page — and a pi among those would load
43
+ * pi-wierdr, take itself for this sub-agent and write its run file: the
44
+ * parent would get that pi's answer as this sub-agent's result.
45
+ *
46
+ * pi imports extensions anew (no module cache) on /reload, /new, /resume and
47
+ * /fork, so what was taken stays on `holder` for the next load to find.
48
+ */
49
+ export function takeChildEnv(
50
+ env: NodeJS.ProcessEnv = process.env,
51
+ holder: Record<symbol, unknown> = globalThis as unknown as Record<symbol, unknown>,
52
+ ): Record<string, string> {
53
+ let taken = holder[TAKEN] as Record<string, string> | undefined;
54
+ if (!taken) {
55
+ taken = {};
56
+ for (const [k, v] of Object.entries(env)) if (k.startsWith(ENV_PREFIX) && v !== undefined) taken[k] = v;
57
+ holder[TAKEN] = taken;
58
+ }
59
+ for (const k of Object.keys(env)) if (k.startsWith(ENV_PREFIX)) delete env[k];
60
+ return { ...taken };
61
+ }
62
+
63
+ export function subagentSection(meta: RunMeta | undefined): string {
64
+ const lines = [
65
+ `You are a sub-agent${meta ? ` ("${meta.description}", type ${meta.type})` : ""}, started by another agent${
66
+ meta ? ` in terminal ${meta.parent}` : ""
67
+ } to do one task. It sees nothing of your work except your final message.`,
68
+ "- Work autonomously on the task in the first message. Don't ask the user questions unless you are truly blocked; make reasonable assumptions and state them.",
69
+ "- Your last message is returned to the parent verbatim as your report. Make it self-contained: what you found or did, exact file paths and line numbers, what you changed, what is left or uncertain.",
70
+ "- Stay within the scope you were given. Don't start other agents.",
71
+ '- Later messages from the agent that started you arrive wrapped in <hc from="…">: treat them as its instructions and answer in your final message. Never reply with `hc send`; your final message reaches it automatically.',
72
+ ];
73
+ if (meta?.typePrompt) lines.push("", meta.typePrompt);
74
+ return lines.join("\n");
75
+ }
76
+
77
+ interface TextBlock {
78
+ type: string;
79
+ text?: string;
80
+ }
81
+
82
+ /** The last assistant message on the branch: its text, and how it ended. */
83
+ export function lastAssistant(entries: readonly unknown[]): { text: string; status: LastStatus; error?: string } | undefined {
84
+ for (let i = entries.length - 1; i >= 0; i--) {
85
+ const e = entries[i] as { type?: string; message?: any };
86
+ if (e?.type !== "message" || e.message?.role !== "assistant") continue;
87
+ const m = e.message;
88
+ const text = Array.isArray(m.content)
89
+ ? (m.content as TextBlock[])
90
+ .filter((b) => b?.type === "text" && typeof b.text === "string")
91
+ .map((b) => b.text)
92
+ .join("\n")
93
+ .trim()
94
+ : typeof m.content === "string"
95
+ ? m.content.trim()
96
+ : "";
97
+ if (m.stopReason === "error") return { text, status: "error", error: String(m.errorMessage ?? "error") };
98
+ if (m.stopReason === "aborted") return { text, status: "aborted" };
99
+ return { text, status: "done" };
100
+ }
101
+ return undefined;
102
+ }
103
+
104
+ /** A one-line hint of what a tool call is about: a path, a pattern, a command. */
105
+ export function toolDetail(args: unknown): string | undefined {
106
+ if (!args || typeof args !== "object") return undefined;
107
+ const a = args as Record<string, unknown>;
108
+ for (const k of ["path", "file_path", "pattern", "command", "query", "url", "description", "prompt"]) {
109
+ const v = a[k];
110
+ if (typeof v === "string" && v.trim()) return v.trim().split("\n")[0]!.slice(0, 120);
111
+ }
112
+ return undefined;
113
+ }
114
+
115
+ export function setupChild(pi: ExtensionAPI, info: ChildInfo): void {
116
+ const state: ChildState = {
117
+ v: 1,
118
+ runId: info.runId,
119
+ pid: process.pid,
120
+ seq: 0,
121
+ running: false,
122
+ activity: { tools: 0, turns: 0, at: Date.now() },
123
+ updatedAt: Date.now(),
124
+ };
125
+ let ctx: ExtensionContext | undefined;
126
+ let timer: ReturnType<typeof setTimeout> | undefined;
127
+
128
+ const flush = () => {
129
+ if (timer) clearTimeout(timer);
130
+ timer = undefined;
131
+ state.updatedAt = Date.now();
132
+ try {
133
+ writeState(info.dir, state);
134
+ } catch {
135
+ // The parent falls back to the screen; never disturb this pi.
136
+ }
137
+ };
138
+ /** Picks up the context in use; true when it moved. */
139
+ const readContext = (next?: ExtensionContext): boolean => {
140
+ if (next) ctx = next;
141
+ let usage: ReturnType<ExtensionContext["getContextUsage"]>;
142
+ try {
143
+ usage = ctx?.getContextUsage();
144
+ } catch {
145
+ return false;
146
+ }
147
+ if (!usage || usage.tokens == null || usage.contextWindow <= 0) return false;
148
+ const a = state.activity!;
149
+ if (a.context?.tokens === usage.tokens && a.context.window === usage.contextWindow) return false;
150
+ a.context = { tokens: usage.tokens, window: usage.contextWindow };
151
+ a.at = Date.now();
152
+ return true;
153
+ };
154
+ const soon = () => {
155
+ if (timer) return;
156
+ timer = setTimeout(flush, 400);
157
+ timer.unref?.();
158
+ };
159
+
160
+ const trust = info.trust;
161
+ if (trust) pi.on("project_trust", async () => ({ trusted: trust }));
162
+
163
+ pi.on("session_start", async (_e, next) => {
164
+ ctx = next;
165
+ try {
166
+ state.sessionId = next.sessionManager.getSessionId();
167
+ state.sessionFile = next.sessionManager.getSessionFile();
168
+ } catch {
169
+ // Ephemeral sessions have neither.
170
+ }
171
+ flush();
172
+ });
173
+
174
+ pi.on("before_agent_start", async (event) => {
175
+ const sections = event.systemPromptOptions?.sections;
176
+ if (sections) sections.subagent = subagentSection(info.meta);
177
+ });
178
+
179
+ pi.on("agent_start", async () => {
180
+ state.running = true;
181
+ flush();
182
+ });
183
+
184
+ pi.on("tool_execution_start", async (event, next) => {
185
+ readContext(next);
186
+ const a = state.activity!;
187
+ a.tools++;
188
+ a.tool = event.toolName;
189
+ a.detail = toolDetail(event.args);
190
+ a.at = Date.now();
191
+ soon();
192
+ });
193
+
194
+ pi.on("turn_end", async (_e, next) => {
195
+ state.activity!.turns++;
196
+ readContext(next);
197
+ soon();
198
+ });
199
+
200
+ // Final: pi won't continue on its own. pi reports done/error over OSC 7501
201
+ // at the same moment, so the parent hears about it from either side.
202
+ pi.on("agent_settled", async (event, next) => {
203
+ readContext(next);
204
+ let last: ReturnType<typeof lastAssistant>;
205
+ try {
206
+ last = ctx ? lastAssistant(ctx.sessionManager.getBranch()) : undefined;
207
+ } catch {
208
+ last = undefined;
209
+ }
210
+ state.seq++;
211
+ state.running = false;
212
+ state.last = {
213
+ status: event.aborted ? "aborted" : (last?.status ?? "done"),
214
+ text: last?.text ?? "",
215
+ error: last?.error,
216
+ at: Date.now(),
217
+ };
218
+ flush();
219
+ });
220
+
221
+ pi.on("session_shutdown", async () => {
222
+ if (timer) flush();
223
+ });
224
+ }