pi-famulus 0.1.8 → 0.2.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.
@@ -1,5 +1,9 @@
1
- import { accessSync, constants, readFileSync, statSync } from "node:fs";
1
+ import { spawnSync } from "node:child_process";
2
+ import { accessSync, closeSync, constants, mkdirSync, openSync, readFileSync, realpathSync, rmSync, statSync, writeFileSync, writeSync } from "node:fs";
2
3
  import { createRequire } from "node:module";
4
+ import { homedir } from "node:os";
5
+ import { dirname, join, resolve, sep } from "node:path";
6
+ import { fileURLToPath } from "node:url";
3
7
  import { getSystemErrorMap } from "node:util";
4
8
 
5
9
  // Filesystem failures mean this optional package is unusable, regardless of the syscall code.
@@ -11,8 +15,10 @@ const resolutionErrorCodes = new Set([
11
15
  "ERR_INVALID_MODULE_SPECIFIER", "ERR_UNSUPPORTED_RESOLVE_REQUEST",
12
16
  ]);
13
17
 
18
+ const modulePath = fileURLToPath(import.meta.url);
14
19
  const packageVersion = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
15
20
  const resolveInstalled = createRequire(import.meta.url).resolve;
21
+ const RESTORE_HINT = "not installed; run `npm install --include=optional pi-famulus`";
16
22
 
17
23
  /** The native optional packages are selected by npm's os/cpu constraints. */
18
24
  export function nativePackageName(platform, arch) {
@@ -23,20 +29,263 @@ export function nativePackageName(platform, arch) {
23
29
  return `pi-famulus-${packageOs}-${arch}`;
24
30
  }
25
31
 
32
+ /**
33
+ * Cache for the exact platform package. `pi update --extensions` reinstalls
34
+ * with npm, and `omit=optional` (user or project npmrc) deletes optional
35
+ * dependencies during that install. The cache is outside the famulus runtime
36
+ * home and outside pi's package tree, so the next update does not remove it.
37
+ */
38
+ export function nativeCacheDir({
39
+ version = packageVersion,
40
+ platform = process.platform,
41
+ arch = process.arch,
42
+ env = process.env,
43
+ home = homedir(),
44
+ } = {}) {
45
+ const base = platform === "win32"
46
+ ? join(env.LOCALAPPDATA || join(home, "AppData", "Local"), "pi-famulus", "native")
47
+ : join(env.XDG_CACHE_HOME || join(home, ".cache"), "pi-famulus", "native");
48
+ return join(base, version, `${platform}-${arch}`);
49
+ }
50
+
51
+ function isIgnoredResolveError(error) {
52
+ return error instanceof SyntaxError || systemErrorCodes.has(error?.code) || resolutionErrorCodes.has(error?.code);
53
+ }
54
+
55
+ function executableFile(path) {
56
+ try {
57
+ const stat = statSync(path);
58
+ if (!stat.isFile() || stat.size <= 0) return false;
59
+ accessSync(path, constants.X_OK);
60
+ return true;
61
+ } catch (error) {
62
+ if (isIgnoredResolveError(error)) return false;
63
+ throw error;
64
+ }
65
+ }
66
+
67
+ /** Usable exact-version binary inside one package directory, or null. */
68
+ function binaryInPackage(dir, name) {
69
+ let metadata;
70
+ try {
71
+ metadata = JSON.parse(readFileSync(join(dir, "package.json"), "utf8"));
72
+ } catch (error) {
73
+ if (isIgnoredResolveError(error)) return null;
74
+ throw error;
75
+ }
76
+ if (!metadata || metadata.name !== name || metadata.version !== packageVersion) return null;
77
+ const exported = metadata.exports?.["./bin/pi-famulus"];
78
+ const rel = typeof exported === "string" ? exported : metadata.main;
79
+ if (typeof rel !== "string" || !rel.startsWith("./") || rel.split("/").includes("..")) return null;
80
+ const binary = join(dir, rel);
81
+ const root = dir.endsWith(sep) ? dir : dir + sep;
82
+ if (!binary.startsWith(root)) return null;
83
+ return executableFile(binary) ? binary : null;
84
+ }
85
+
86
+ function walkNodeModules(startFile, stopAt) {
87
+ const dirs = [];
88
+ let dir = dirname(startFile);
89
+ const seen = new Set();
90
+ const boundary = stopAt ? resolve(stopAt) : null;
91
+ while (!seen.has(dir)) {
92
+ seen.add(dir);
93
+ dirs.push(join(dir, "node_modules"));
94
+ if (boundary && (dir === boundary || !dir.startsWith(boundary.endsWith(sep) ? boundary : boundary + sep))) break;
95
+ const parent = dirname(dir);
96
+ if (parent === dir) break;
97
+ dir = parent;
98
+ }
99
+ return dirs;
100
+ }
101
+
102
+ function legacyResolve(name, resolve) {
103
+ const metadata = JSON.parse(readFileSync(resolve(`${name}/package.json`), "utf8"));
104
+ if (!metadata || metadata.name !== name || metadata.version !== packageVersion) return null;
105
+ const binary = resolve(`${name}/bin/pi-famulus`);
106
+ const stat = statSync(binary);
107
+ if (!stat.isFile() || stat.size <= 0) return null;
108
+ accessSync(binary, constants.X_OK);
109
+ return binary;
110
+ }
111
+
112
+ function searchNative({ platform = process.platform, arch = process.arch, from, stopAt, cacheDir } = {}) {
113
+ const name = nativePackageName(platform, arch);
114
+ if (!name) return { name: null, path: null, detail: `unsupported ${platform}/${arch}` };
115
+ let start = from ?? modulePath;
116
+ if (!from) {
117
+ try { start = realpathSync(modulePath); } catch { /* keep the URL path */ }
118
+ }
119
+ const seen = new Set();
120
+ for (const nodeModules of walkNodeModules(start, stopAt)) {
121
+ const dir = join(nodeModules, name);
122
+ if (seen.has(dir)) continue;
123
+ seen.add(dir);
124
+ const binary = binaryInPackage(dir, name);
125
+ if (binary) return { name, path: binary, detail: "" };
126
+ }
127
+ // NODE_PATH and other resolver roots. An explicit `from` is a hermetic walk.
128
+ if (!from) {
129
+ try {
130
+ const resolved = dirname(resolveInstalled(`${name}/package.json`));
131
+ if (!seen.has(resolved)) {
132
+ const binary = binaryInPackage(resolved, name);
133
+ if (binary) return { name, path: binary, detail: "" };
134
+ }
135
+ } catch (error) {
136
+ if (!isIgnoredResolveError(error)) throw error;
137
+ }
138
+ }
139
+ if (cacheDir !== false) {
140
+ const dir = join(cacheDir ?? nativeCacheDir({ platform, arch }), "node_modules", name);
141
+ const binary = binaryInPackage(dir, name);
142
+ if (binary) return { name, path: binary, detail: "" };
143
+ }
144
+ return { name, path: null, detail: RESTORE_HINT };
145
+ }
146
+
26
147
  /** Resolve the exact-version optional package without loading native executable bytes. */
27
- export function resolveNativeManagerPath({ platform = process.platform, arch = process.arch, resolve = resolveInstalled } = {}) {
148
+ export function resolveNativeManagerPath({ platform = process.platform, arch = process.arch, resolve, from, stopAt, cacheDir } = {}) {
28
149
  const name = nativePackageName(platform, arch);
29
150
  if (!name) return null;
151
+ // Injected resolvers stay hermetic: tests use them to simulate one install tree.
152
+ if (resolve) {
153
+ try {
154
+ return legacyResolve(name, resolve);
155
+ } catch (error) {
156
+ if (isIgnoredResolveError(error)) return null;
157
+ throw error;
158
+ }
159
+ }
160
+ return searchNative({ platform, arch, from, stopAt, cacheDir }).path;
161
+ }
162
+
163
+ /** `npm <package> <path>` or why that exact platform package was not usable. */
164
+ export function describeNativeLookup(options) {
165
+ const name = nativePackageName(options?.platform ?? process.platform, options?.arch ?? process.arch);
166
+ if (!name) return `npm native manager (unsupported ${options?.platform ?? process.platform}/${options?.arch ?? process.arch})`;
167
+ if (options?.resolve) {
168
+ const path = resolveNativeManagerPath(options);
169
+ return path ? `npm ${name} ${path}` : `npm ${name} (missing or unusable, ignored)`;
170
+ }
171
+ const found = searchNative(options);
172
+ return found.path ? `npm ${name} ${found.path}` : `npm ${name} (${found.detail})`;
173
+ }
174
+
175
+ function pidAlive(pid) {
30
176
  try {
31
- const metadata = JSON.parse(readFileSync(resolve(`${name}/package.json`), "utf8"));
32
- if (!metadata || metadata.name !== name || metadata.version !== packageVersion) return null;
33
- const binary = resolve(`${name}/bin/pi-famulus`);
34
- const stat = statSync(binary);
35
- if (!stat.isFile() || stat.size <= 0) return null;
36
- accessSync(binary, constants.X_OK);
37
- return binary;
177
+ process.kill(pid, 0);
178
+ return true;
38
179
  } catch (error) {
39
- if (error instanceof SyntaxError || systemErrorCodes.has(error?.code) || resolutionErrorCodes.has(error?.code)) return null;
40
- throw error;
180
+ return error?.code === "EPERM";
181
+ }
182
+ }
183
+
184
+ function sleepMs(ms) {
185
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
186
+ }
187
+
188
+ /** A lock left by a dead process, or held far longer than one npm install, can be replaced. */
189
+ function installLockIsStale(lockPath) {
190
+ try {
191
+ const age = Date.now() - statSync(lockPath).mtimeMs;
192
+ const pid = Number(readFileSync(lockPath, "utf8").trim());
193
+ if (Number.isInteger(pid) && pid > 0) return !pidAlive(pid) || age > 150_000;
194
+ return age > 5_000;
195
+ } catch {
196
+ return true;
197
+ }
198
+ }
199
+
200
+ /**
201
+ * One npm install per cache directory. Another startup either waits until that
202
+ * install publishes a binary or takes over a stale lock. Returns the open lock,
203
+ * or null when waiting itself produced a usable binary.
204
+ */
205
+ function acquireInstallLock(dir, lookup) {
206
+ mkdirSync(dir, { recursive: true });
207
+ const lockPath = `${dir}.install.lock`;
208
+ const deadline = Date.now() + 130_000;
209
+ while (Date.now() <= deadline) {
210
+ try {
211
+ const fd = openSync(lockPath, "wx");
212
+ try { writeSync(fd, String(process.pid)); } catch { /* the fd is still the lock */ }
213
+ return { fd, lockPath };
214
+ } catch (error) {
215
+ if (error?.code !== "EEXIST") throw error;
216
+ const ready = resolveNativeManagerPath(lookup);
217
+ if (ready) return null;
218
+ if (installLockIsStale(lockPath)) {
219
+ rmSync(lockPath, { force: true });
220
+ continue;
221
+ }
222
+ sleepMs(200);
223
+ }
224
+ }
225
+ return null;
226
+ }
227
+
228
+ function releaseInstallLock(lock) {
229
+ if (!lock) return;
230
+ try { closeSync(lock.fd); } catch { /* already closed */ }
231
+ rmSync(lock.lockPath, { force: true });
232
+ }
233
+
234
+ /**
235
+ * Install the exact platform package into the versioned cache when the
236
+ * optional dependency is missing. No-ops when a usable binary is already
237
+ * resolvable. `PI_FAMULUS_NO_NATIVE_FETCH=1`, `PI_OFFLINE=1`, and Vitest skip
238
+ * the install. Directory, manifest, and npm failures return null so startup
239
+ * degrades instead of throwing.
240
+ */
241
+ export function ensureNativeManagerInstalled({
242
+ platform = process.platform,
243
+ arch = process.arch,
244
+ cacheDir,
245
+ env = process.env,
246
+ npmCommand,
247
+ spawn = spawnSync,
248
+ from,
249
+ stopAt,
250
+ } = {}) {
251
+ const lookup = { platform, arch, cacheDir, from, stopAt };
252
+ try {
253
+ const existing = resolveNativeManagerPath(lookup);
254
+ if (existing) return existing;
255
+ if (!nativePackageName(platform, arch)) return null;
256
+ if (env.PI_FAMULUS_NO_NATIVE_FETCH === "1" || env.PI_OFFLINE === "1" || env.VITEST) return null;
257
+ if (cacheDir === false) return null;
258
+ const dir = cacheDir ?? nativeCacheDir({ platform, arch, env });
259
+ const lockedLookup = { ...lookup, cacheDir: dir };
260
+ const lock = acquireInstallLock(dir, lockedLookup);
261
+ if (!lock) return resolveNativeManagerPath(lockedLookup);
262
+ try {
263
+ const manifest = join(dir, "package.json");
264
+ try {
265
+ readFileSync(manifest);
266
+ } catch {
267
+ writeFileSync(manifest, `${JSON.stringify({ private: true, name: "pi-famulus-native-cache", version: "0.0.0" })}\n`);
268
+ }
269
+ const command = npmCommand ?? (platform === "win32" ? "npm.cmd" : "npm");
270
+ const name = nativePackageName(platform, arch);
271
+ let result;
272
+ try {
273
+ result = spawn(command, [
274
+ "install", `${name}@${packageVersion}`,
275
+ "--prefix", dir,
276
+ "--ignore-scripts", "--no-fund", "--no-audit", "--loglevel=error",
277
+ ], { timeout: 120_000, windowsHide: true, encoding: "utf8" });
278
+ } catch {
279
+ return resolveNativeManagerPath(lockedLookup);
280
+ }
281
+ const found = resolveNativeManagerPath(lockedLookup);
282
+ if (found) return found;
283
+ if (!result || result.error || result.status !== 0) return null;
284
+ return null;
285
+ } finally {
286
+ releaseInstallLock(lock);
287
+ }
288
+ } catch {
289
+ return null;
41
290
  }
42
291
  }
@@ -0,0 +1,123 @@
1
+ /**
2
+ * Find the pi command a hosted subagent should be. The daemon never searches
3
+ * PATH; the extension resolves it where pi is already running.
4
+ */
5
+ import { existsSync, realpathSync } from "node:fs";
6
+ import { createRequire } from "node:module";
7
+ import { basename } from "node:path";
8
+ export type PiCommand = { argv: string[] } | { error: string };
9
+
10
+ export function resolvePiArgv(configured?: string | null, argv: readonly string[] = process.argv): PiCommand {
11
+ const raw = (configured && configured.trim()) || process.env.PI_FAMULUS_PI?.trim() || "";
12
+ if (raw) {
13
+ if (raw.startsWith("[")) {
14
+ try {
15
+ const parsed = JSON.parse(raw) as unknown;
16
+ if (Array.isArray(parsed) && parsed.length > 0 && parsed.every((part) => typeof part === "string" && part.length > 0)) {
17
+ return { argv: parsed as string[] };
18
+ }
19
+ } catch {
20
+ return { error: `PI_FAMULUS_PI / subagent.piCommand is not a JSON argv array: ${raw}` };
21
+ }
22
+ return { error: `PI_FAMULUS_PI / subagent.piCommand is not a JSON argv array: ${raw}` };
23
+ }
24
+ return { argv: raw.includes(" ") ? splitCommand(raw) : [raw] };
25
+ }
26
+ const fromProcess = runningPiArgv(argv);
27
+ if (fromProcess) return { argv: fromProcess };
28
+ const exec = process.execPath;
29
+ try {
30
+ const req = createRequire(import.meta.url);
31
+ const pkg = req.resolve("@earendil-works/pi-coding-agent/package.json");
32
+ const cli = pkg.replace(/package\.json$/, "dist/cli.js");
33
+ if (existsSync(cli)) return { argv: [exec, cli] };
34
+ } catch {
35
+ // The host did not load pi as a resolvable package.
36
+ }
37
+ return {
38
+ error:
39
+ "cannot find the pi executable that is running this session. Set subagent.piCommand in config.json or PI_FAMULUS_PI to the pi command.",
40
+ };
41
+ }
42
+
43
+ const PARENT_FLAGS = new Set([
44
+ "-ne",
45
+ "--no-extensions",
46
+ "-ns",
47
+ "--no-skills",
48
+ "-np",
49
+ "--no-prompt-templates",
50
+ "-nc",
51
+ "--no-context-files",
52
+ "--offline",
53
+ "--no-mcp",
54
+ ]);
55
+
56
+ /**
57
+ * Flags from the pi process that is spawning the subagent. The child is a new
58
+ * process, so it only sees providers and tools that its own command line loads.
59
+ * Eval and SDK hosts pass those as `-e` on argv (`-ne` plus an explicit faux
60
+ * provider extension); forwarding them is what lets the child use the same model.
61
+ */
62
+ export function parentResourceArgs(argv: readonly string[] = process.argv.slice(2)): string[] {
63
+ const out: string[] = [];
64
+ for (let i = 0; i < argv.length; i++) {
65
+ const arg = argv[i];
66
+ if (arg === "-e" || arg === "--extension") {
67
+ const value = argv[i + 1];
68
+ if (value && !value.startsWith("-")) {
69
+ out.push("-e", value);
70
+ i++;
71
+ }
72
+ continue;
73
+ }
74
+ if (PARENT_FLAGS.has(arg)) out.push(arg);
75
+ }
76
+ return out;
77
+ }
78
+
79
+ /**
80
+ * The pi process that loaded this extension. `node_modules/.bin/pi` is a
81
+ * symlink (eval and `npm exec`); its path does not contain `pi-coding-agent`,
82
+ * so matching only that substring misses the process that is actually running.
83
+ */
84
+ function runningPiArgv(argv: readonly string[]): string[] | null {
85
+ const entry = argv[1] ?? "";
86
+ if (!entry || !existsSync(entry)) return null;
87
+ let real = entry;
88
+ try {
89
+ real = realpathSync(entry);
90
+ } catch {
91
+ // A broken symlink still has a path; keep the original.
92
+ }
93
+ const base = basename(entry).toLowerCase();
94
+ const namedPi = base === "pi" || base === "pi.cmd" || base === "pi.exe" || entry.includes("pi-coding-agent") || real.includes("pi-coding-agent");
95
+ if (!namedPi) return null;
96
+ if (/\.[cm]?js$/i.test(real)) return [process.execPath, real];
97
+ return [entry];
98
+ }
99
+
100
+ function splitCommand(raw: string): string[] {
101
+ const parts: string[] = [];
102
+ let current = "";
103
+ let quote: '"' | "'" | null = null;
104
+ for (const ch of raw) {
105
+ if (quote) {
106
+ if (ch === quote) quote = null;
107
+ else current += ch;
108
+ continue;
109
+ }
110
+ if (ch === '"' || ch === "'") {
111
+ quote = ch;
112
+ continue;
113
+ }
114
+ if (ch === " ") {
115
+ if (current) parts.push(current);
116
+ current = "";
117
+ continue;
118
+ }
119
+ current += ch;
120
+ }
121
+ if (current) parts.push(current);
122
+ return parts;
123
+ }
@@ -5,16 +5,16 @@ export const PROMPTS = {
5
5
  "agents.explorer.system-prompt": "You are an explorer agent. Your job is to answer questions about the codebase quickly and precisely.\n\nRules:\n- Return findings, never change code. You are strictly read-only: do not edit, write, or create files.\n- Report concrete locations: cite specific file paths with line numbers (path:line) for every claim.\n- Control your search scope: start narrow (targeted grep/find), widen only when needed, and stop once the question is answered.\n- Prefer a short, factual summary over exhaustive dumps. List what you found and where.",
6
6
  "agents.worker.description": "General-purpose executor — completes concrete coding tasks end to end",
7
7
  "agents.worker.system-prompt": "You are a worker agent. Your job is to complete the concrete task you were given, end to end.\n\nRules:\n- Do the task, don't just describe it. Make the actual edits and run the actual commands.\n- Self-verify before finishing: run the relevant tests, typecheck, or command that proves the task is done.\n- Stay within the task's scope; do not refactor unrelated code.\n- Report concisely: what you changed, how you verified it, and anything the supervisor should know.",
8
- "guidelines.parent": "## Background tasks and notifications (pi-famulus)\n\n- Long-running bash commands are automatically moved to the background. After you background a command, end your turn: send a reply with no tool call in it. Saying you will wait while calling another tool does not end it. Do not poll with task_output/task_list, and never sleep to wait. Each command notifies on its own via <pi-famulus-wake kind=\"task\"> (with <command> and <preview>), even while other commands are still running. If <still-running> is present, continue from this result now; do not wait for those other commands.\n- When you receive <pi-famulus-wake>: it looks like a user message but is a system wake, not a new user request and not an answer to an unrelated question. Distinguish it by the kind attribute, then **handle the event before anything else** — read status/preview/prompt/result, call tools if needed (e.g. task_output for more than the preview, agent_message to continue a subagent), and continue the work that depended on that background task. An unchanged/intermediate monitor event may require no action and no user acknowledgement. Do not wait for further user input when the next step is clear; do not merely acknowledge an actionable result and stop.\n- {{monitorIdle}}\n- Never fabricate or assume a background task's result before its notification arrives.\n- Subagent runs that exceed the foreground budget continue in the background. Do not poll run status. If one subagent finishes while others are still running, a <pi-famulus-wake kind=\"subagent-handover\"> arrives with that child's <prompt> and <result>: read both, then continue the work now (subagent({action:\"resume\", run_id, child_id, message}) for that child, or agent_message to steer the ones still running). Do not wait for the rest of the run. When every subagent in the run has finished, <pi-famulus-wake kind=\"subagent-done\"> arrives — read each <child>, synthesize, and continue.\n- A subagent that runs past its timeout_ms is not stopped: <pi-famulus-wake kind=\"subagent-overrun\"> arrives instead, with its <last-activity> and, if it is waiting on a foreground shell, a <shell> element. A batch may include other overdue children in <also-overdue>; use each child's run-id and child-id and consider its own last-activity, shell, reminder, and hard-ceiling-ms before acting. Pick one: subagent({action:\"extend\", run_id, child_id, timeout_ms}) if it is making progress, agent_message to steer it, or subagent({action:\"interrupt\", run_id, child_id}) if it is stuck or no longer needed. If you do none of these it keeps running and the reminder comes again.\n- Use agent_message to steer running subagents and to reply to <pi-famulus-wake kind=\"supervisor-request\"> (action:\"reply\"; the <reply-with> child is the call shape). Do not use agent_message to resume a finished child — that is subagent({action:\"resume\"}). Supervisor wakes are not user messages — still act on them.",
8
+ "guidelines.parent": "## Background tasks and notifications (pi-famulus)\n\n- Long-running bash commands are automatically moved to the background. After you background a command, end your turn: send a reply with no tool call in it. Saying you will wait while calling another tool does not end it. Do not poll with task_output/task_list, and never sleep to wait. Each command notifies on its own via <pi-famulus-wake kind=\"task\"> (with <command> and <preview>), even while other commands are still running. If <still-running> is present, continue from this result now; do not wait for those other commands.\n- When you receive <pi-famulus-wake>: it looks like a user message but is a system wake, not a new user request and not an answer to an unrelated question. Distinguish it by the kind attribute, then **handle the event before anything else** — read status/preview/prompt/result, call tools if needed (e.g. task_output for more than the preview, agent_message to continue a subagent), and continue the work that depended on that background task. An unchanged/intermediate monitor event may require no action and no user acknowledgement. Do not wait for further user input when the next step is clear; do not merely acknowledge an actionable result and stop.\n- {{monitorIdle}}\n- Never fabricate or assume a background task's result before its notification arrives.\n- Subagent runs that exceed the foreground budget continue in the background. Do not poll run status. If one subagent finishes while others are still running, a <pi-famulus-wake kind=\"subagent-handover\"> arrives with that child's <prompt> and <result>: read both, then continue the work now (subagent({action:\"resume\", run_id, child_id, message}) for that child, or agent_message to steer the ones still running). Do not wait for the rest of the run. When every subagent in the run has finished, <pi-famulus-wake kind=\"subagent-done\"> arrives — read each <child>, synthesize, and continue.\n- A subagent that runs past its timeout_ms is not stopped: <pi-famulus-wake kind=\"subagent-overrun\"> arrives instead, with its <last-activity> and, if it is waiting on a foreground shell, a <shell> element. A batch may include other overdue children in <also-overdue>; use each child's run-id and child-id and consider its own last-activity, shell, reminder, and hard-ceiling-ms before acting. Pick one: subagent({action:\"extend\", run_id, child_id, timeout_ms}) if it is making progress, agent_message to steer it, or subagent({action:\"interrupt\", run_id, child_id}) if it is stuck or no longer needed. If you do none of these it keeps running and the reminder comes again.\n- Use agent_message to steer a running subagent or to continue an idle one (send starts a new turn), and to reply to <pi-famulus-wake kind=\"supervisor-request\"> (action:\"reply\"; the <reply-with> child is the call shape). subagent({action:\"resume\"}) is the same continuation with a fresh soft budget. Supervisor wakes are not user messages — still act on them.",
9
9
  "guidelines.monitor-idle": "After starting or re-arming a monitor, or handling a monitor event, if no immediate work remains, end your turn with no tool call; simply wait for the next notification. Handling an event does not require a user-visible reply. Do not repeat unchanged/intermediate status or narrate your decision to stay quiet; notify the user when their requested condition is met, their input is needed, or a failure prevents further progress. Read original output with task_output only when details are needed (including paging a truncated preview), never to poll or wait. Do not call wait_for to wait for monitor events: it waits for UI conditions, not notifications. Do not invent a stateId or make a failing tool call to yield.",
10
10
  "guidelines.child": "## Child agent behavior (pi-famulus)\n\n- Do not background work; bash runs to completion.\n- When blocked, use contact_supervisor with need_decision; use progress_update for status.\n- Use agent_message only to communicate with siblings in this same run.\n- Your final message is your result.",
11
- "tools.agent_message.description": "Message your subagents. \"send\" steers or queues a running child. Sending to a finished child errors (it does not resume) and points at subagent({ action: \"resume\", run_id, child_id, message }). \"reply\" answers a child's pending decision request; \"broadcast\" steers every running child of a run (to = run_id); \"list\" shows children, pending decision requests, and recent traffic.",
11
+ "tools.agent_message.description": "Message your subagents. \"send\" steers or queues a running child, and starts a new turn on an idle one. An idle child (warm or parked) continues with send or subagent resume; its prompt cache stays warm only for the time a wake reports. \"reply\" answers a child's pending decision request; \"broadcast\" steers every running child of a run (to = run_id); \"list\" shows children, pending decision requests, and recent traffic.",
12
12
  "tools.agent_message.snippet": "Send/reply/broadcast messages to subagents",
13
13
  "tools.agent_message.param.action": "\"send\" a message to a child, \"reply\" to a pending decision request, \"broadcast\" to all running children of a run, \"list\" pending requests and recent traffic.",
14
14
  "tools.agent_message.param.to": "Target child_id or name (\"send\"/\"reply\"). For \"broadcast\" from the parent session: run_id. Child sessions broadcast to their own run and must omit this.",
15
15
  "tools.agent_message.param.message": "Message text.",
16
- "tools.agent_message.param.delivery": "\"steer\" (default) delivers to a running child after its current tool call/turn finishes; \"queue\" delivers after its current turn. Sending to a finished child is an error — resume with subagent({action:\"resume\"}).",
17
- "tools.agent_message.error.finished-child": "Child {{childId}} ({{name}}) has finished ({{status}}). agent_message does not resume children. Use subagent({ action: \"resume\", run_id: \"{{runId}}\", child_id: \"{{childId}}\", message: \"...\" }).",
16
+ "tools.agent_message.param.delivery": "\"steer\" (default) delivers to a running child after its current tool call/turn finishes; \"queue\" delivers after its current turn. Sending to an idle child starts a new turn.",
17
+ "tools.agent_message.error.finished-child": "Child {{childId}} ({{name}}) has finished ({{status}}), and this host cannot start another turn. Use subagent({ action: \"resume\", run_id: \"{{runId}}\", child_id: \"{{childId}}\", message: \"...\" }).",
18
18
  "tools.bash.description": "Execute a bash command in the current working directory. Returns stdout and stderr. Output is truncated to last {{maxLines}} lines or {{maxKb}}KB (whichever is hit first). Foreground commands that exceed the foreground budget are automatically moved to the background; you will be notified when they complete. Optionally provide a timeout in seconds (hard kill limit), or run_in_background to background immediately.",
19
19
  "tools.bash.snippet": "Execute bash commands (ls, grep, find, etc.)",
20
20
  "tools.bash.rules": ["You can inspect PI_* environment variables for current model and session details.","Long-running bash commands are moved to the background automatically; do not poll or sleep to wait for them. End your turn (a reply with no tool call) and resume from the task wake when it arrives."],
@@ -23,7 +23,7 @@ export const PROMPTS = {
23
23
  "tools.bash.param.run_in_background": "Start the command in the background and return immediately. You will be notified when it completes.",
24
24
  "tools.bash.result.backgrounded": "Command \"{{command}}\" moved to background (task_id: {{taskId}}). Output: {{outputPath}}.\nYou will be notified when it completes, even if other commands are still running. Do not poll or sleep: reply to the user now with no tool call, and continue from the <pi-famulus-wake kind=\"task\"> when it arrives.",
25
25
  "tools.bash.error.bare-sleep": "Refusing to run a bare sleep/idle-loop command: {{command}}. Do not sleep to wait for background work; completion is delivered via notification. Use the monitor tool to watch for a condition, or run_in_background for long commands.",
26
- "tools.child.agent_message.description": "Message sibling subagents in your run, or list pending requests. \"send\" delivers to a running sibling. Sending to a finished sibling errors and does not resume it; resume with subagent({ action: \"resume\", run_id, child_id, message }). \"broadcast\" steers every running sibling in your run; \"list\" shows pending decision requests and recent traffic. Cross-run messaging is rejected.",
26
+ "tools.child.agent_message.description": "Message sibling subagents in your run, or list pending requests. \"send\" delivers to a running sibling and starts a new turn on an idle one. \"broadcast\" steers every running sibling in your run; \"list\" shows pending decision requests and recent traffic. Cross-run messaging is rejected.",
27
27
  "tools.child.agent_message.snippet": "Message sibling subagents in your run",
28
28
  "tools.child.bash.description": "Execute a bash command in the current working directory. Returns stdout and stderr. Output is truncated to last {{maxLines}} lines or {{maxKb}}KB (whichever is hit first). The command runs to completion (or the optional timeout in seconds, after which it is killed). There is no background execution inside subagents.",
29
29
  "tools.child.bash.snippet": "Execute bash commands (ls, grep, find, etc.)",
@@ -158,11 +158,10 @@ export const PROMPT_SEGMENTS: Record<string, { prompt: PromptId; text?: string;
158
158
  "guidelines.no-fabrication": {"prompt":"guidelines.parent","text":"Never fabricate or assume a background task's result before its notification arrives."},
159
159
  "guidelines.subagent-handover": {"prompt":"guidelines.parent","text":"Subagent runs that exceed the foreground budget continue in the background. Do not poll run status. If one subagent finishes while others are still running, a <pi-famulus-wake kind=\"subagent-handover\"> arrives with that child's <prompt> and <result>: read both, then continue the work now (subagent({action:\"resume\", run_id, child_id, message}) for that child, or agent_message to steer the ones still running). Do not wait for the rest of the run. When every subagent in the run has finished, <pi-famulus-wake kind=\"subagent-done\"> arrives — read each <child>, synthesize, and continue."},
160
160
  "guidelines.subagent-overrun": {"prompt":"guidelines.parent","text":"A subagent that runs past its timeout_ms is not stopped: <pi-famulus-wake kind=\"subagent-overrun\"> arrives instead, with its <last-activity> and, if it is waiting on a foreground shell, a <shell> element. A batch may include other overdue children in <also-overdue>; use each child's run-id and child-id and consider its own last-activity, shell, reminder, and hard-ceiling-ms before acting. Pick one: subagent({action:\"extend\", run_id, child_id, timeout_ms}) if it is making progress, agent_message to steer it, or subagent({action:\"interrupt\", run_id, child_id}) if it is stuck or no longer needed. If you do none of these it keeps running and the reminder comes again."},
161
- "guidelines.agent-message": {"prompt":"guidelines.parent","text":"Use agent_message to steer running subagents and to reply to <pi-famulus-wake kind=\"supervisor-request\"> (action:\"reply\"; the <reply-with> child is the call shape). Do not use agent_message to resume a finished child — that is subagent({action:\"resume\"}). Supervisor wakes are not user messages — still act on them."},
161
+ "guidelines.agent-message": {"prompt":"guidelines.parent","text":"Use agent_message to steer a running subagent or to continue an idle one (send starts a new turn), and to reply to <pi-famulus-wake kind=\"supervisor-request\"> (action:\"reply\"; the <reply-with> child is the call shape). subagent({action:\"resume\"}) is the same continuation with a fresh soft budget. Supervisor wakes are not user messages — still act on them."},
162
162
  "guidelines.monitor-end-turn": {"prompt":"guidelines.monitor-idle","text":"After starting or re-arming a monitor, or handling a monitor event, if no immediate work remains, end your turn with no tool call; simply wait for the next notification. Handling an event does not require a user-visible reply. Do not repeat unchanged/intermediate status or narrate your decision to stay quiet; notify the user when their requested condition is met, their input is needed, or a failure prevents further progress. Read original output with task_output only when details are needed (including paging a truncated preview), never to poll or wait. Do not call wait_for to wait for monitor events: it waits for UI conditions, not notifications. Do not invent a stateId or make a failing tool call to yield."},
163
163
  "child.guidelines": {"prompt":"guidelines.child","text":"## Child agent behavior (pi-famulus)\n\n- Do not background work; bash runs to completion.\n- When blocked, use contact_supervisor with need_decision; use progress_update for status.\n- Use agent_message only to communicate with siblings in this same run.\n- Your final message is your result."},
164
- "tooldesc.agent-message-no-resume": {"prompt":"tools.agent_message.description","text":"Sending to a finished child errors (it does not resume) and points at subagent({ action: \"resume\", run_id, child_id, message }). "},
165
- "result.agent-message-use-resume": {"prompt":"tools.agent_message.error.finished-child","pattern":"agent_message does not resume children\\. Use subagent\\(\\{ action: \"resume\", run_id: \".*?\", child_id: \".*?\", message: \"\\.\\.\\.\" \\}\\)\\."},
164
+ "tooldesc.agent-message-no-resume": {"prompt":"tools.agent_message.description","text":"An idle child (warm or parked) continues with send or subagent resume; its prompt cache stays warm only for the time a wake reports. "},
166
165
  "tooldesc.bash-autobg": {"prompt":"tools.bash.description","text":"Foreground commands that exceed the foreground budget are automatically moved to the background; you will be notified when they complete. "},
167
166
  "rules.pi-env": {"prompt":"tools.bash.rules","text":"You can inspect PI_* environment variables for current model and session details."},
168
167
  "rules.bash-no-poll": {"prompt":"tools.bash.rules","text":"Long-running bash commands are moved to the background automatically; do not poll or sleep to wait for them."},