pi-famulus 0.2.4 → 0.2.6
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/README.md +2 -2
- package/package.json +7 -7
- package/src/config.ts +8 -0
- package/src/index.ts +11 -0
- package/src/manager-client.ts +1 -1
- package/src/monitor.ts +19 -2
- package/src/poll-guard.ts +96 -0
- package/src/prompts.generated.ts +21 -12
- package/src/subagent/hosted-session.ts +167 -28
- package/src/wait-guard.ts +68 -0
package/README.md
CHANGED
|
@@ -82,7 +82,7 @@ Run the full test suite and tell me what fails.
|
|
|
82
82
|
| Ask the agent | What happens |
|
|
83
83
|
| :--- | :--- |
|
|
84
84
|
| `Run the full test suite and tell me what fails.` | `bash` moves the run to the background after 20 seconds; the result arrives when it exits |
|
|
85
|
-
| `Start the dev server and tell me if an error shows up in its output.` | `monitor` batches new output into bounded events; repeated lines are deduplicated within a configurable window.
|
|
85
|
+
| `Start the dev server and tell me if an error shows up in its output.` | `monitor` batches new output into bounded events; repeated lines are deduplicated within a configurable window. A monitor runs until its command exits or you stop it with `task_stop`; pass `timeout_ms` (max 1 hour) only for a watch the user asked to be time-bounded, and expiry stops the monitor and the notice can arrive late while you are busy (no re-arming). If you use timeouts for several monitors, stagger them |
|
|
86
86
|
| `Review these three modules in parallel with subagents.` | `subagent` runs the tasks in parallel; each subagent reports back when it finishes |
|
|
87
87
|
| `Which models can subagents use?` | The agent calls `subagent({action: "models"})` and lists the choices |
|
|
88
88
|
|
|
@@ -129,7 +129,7 @@ pi-famulus starts and stops processes for you. This section states what it guara
|
|
|
129
129
|
- Shells and monitors do not survive the last pi session closing. Five seconds after the last session disconnects, and once no hosted subagent is still warm, the daemon stops what is left and exits. A warm subagent keeps the daemon up after its parent disconnects. It parks at its retention deadline, or earlier when the warm-agent cap needs the slot. Records, output and transcripts stay on disk for 24 hours.
|
|
130
130
|
- A subagent still running when its 30-minute turn budget ends is not killed, unless you set `hardTimeoutMs`. The parent is told and chooses to extend, steer or interrupt it.
|
|
131
131
|
- A subagent with no activity for 5 minutes is resumed once on the same session, with its transcript kept. The timer pauses while a tool runs or a `contact_supervisor` question waits for an answer. If the subagent stalls again, it is marked failed.
|
|
132
|
-
- `monitor`
|
|
132
|
+
- `monitor` runs until its command exits or you stop it with `task_stop`; with neither `timeout_ms` nor `persistent` it is persistent. Pass `timeout_ms` (max 1 hour) only for a watch the user asked to be time-bounded: expiry stops the monitor and the notice can arrive late while you are busy. `persistent:false` without `timeout_ms` keeps a 5-minute timeout. `persistent:true` with `timeout_ms`, or timeout_ms above 1 hour, is rejected. If you use timeouts for several monitors, stagger them. Run a producer you start as the monitor command itself; use `tail -F` / `journalctl -f` for sources you did not start. Without `wake_on`, write edge-triggered commands: normally zero output, one line only for a new problem signature, and one recovery line. Sampling windows must not overlap and must not leave gaps (window = interval), or keep a cursor/last-seen state in the script and report only new items. Status lines may stay if you set `wake_on` to the problem pattern: only matching lines wake the agent, and `task_output` keeps every line. Use `stall_after_ms` instead of heartbeats to learn that the source went silent.
|
|
133
133
|
- `monitor` batches output every 200 ms. Rust-framed repeated complete lines from the same monitor are deduplicated for 60 seconds by default after a representative is delivered; legacy/raw fallback previews are not content-deduplicated, and missing metadata, capacity eviction, and omitted representatives fail open. Exact matching is the default, with timestamp normalization opt-in. Previews are bounded; original output remains readable with `task_output`. Deduplication does not count as overload loss. Admitted batches allow a burst of 10 events, then one event every 2 seconds. Batches over that limit are dropped. The primary overload entry is that drop-ratio: with 200 ms batching and the token bucket, sustained about 1 distinct batch/s (~1 line/s) or more enters via drop ratio within tens of seconds; about 2 distinct lines/s around 30s; below about 0.9 batches/s does not enter. A rolling input average above 5 lines/s over 30s is only a supplementary trigger (draft value). On entry, one notice says individual lines are suppressed, the first summary comes after 30s, and raw output stays on `task_output`; on quiet exit, one notice resumes lines. Cadence after 30s is 60s, then 120s, then every 300s (300s draft value). It stops itself only if input stays near 1000 lines/s for 60s (unverified draft safety backstop).
|
|
134
134
|
- On Linux and macOS, the daemon checks its own executable every 2 seconds. When the file is replaced, the running daemon re-executes itself with the same pid. `pi-famulus upgrade` does the same on demand. Running commands keep going and clients reconnect. The measured gap was 30 to 46 ms.
|
|
135
135
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-famulus",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.6",
|
|
4
4
|
"description": "Keep your main agent's context clean: subagents on cheaper models, long bash in the background, and monitors that wake the agent. One Rust daemon runs the shells.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"pi-package",
|
|
@@ -54,12 +54,12 @@
|
|
|
54
54
|
"pi-famulus": "./bin/pi-famulus.js"
|
|
55
55
|
},
|
|
56
56
|
"optionalDependencies": {
|
|
57
|
-
"pi-famulus-linux-x64": "0.2.
|
|
58
|
-
"pi-famulus-linux-arm64": "0.2.
|
|
59
|
-
"pi-famulus-darwin-x64": "0.2.
|
|
60
|
-
"pi-famulus-darwin-arm64": "0.2.
|
|
61
|
-
"pi-famulus-win-x64": "0.2.
|
|
62
|
-
"pi-famulus-win-arm64": "0.2.
|
|
57
|
+
"pi-famulus-linux-x64": "0.2.6",
|
|
58
|
+
"pi-famulus-linux-arm64": "0.2.6",
|
|
59
|
+
"pi-famulus-darwin-x64": "0.2.6",
|
|
60
|
+
"pi-famulus-darwin-arm64": "0.2.6",
|
|
61
|
+
"pi-famulus-win-x64": "0.2.6",
|
|
62
|
+
"pi-famulus-win-arm64": "0.2.6"
|
|
63
63
|
},
|
|
64
64
|
"pi": {
|
|
65
65
|
"extensions": [
|
package/src/config.ts
CHANGED
|
@@ -21,6 +21,10 @@ export interface FamulusConfig {
|
|
|
21
21
|
messaging?: { enabled: boolean };
|
|
22
22
|
/** End a run that keeps making only no-op/status calls (src/idle-turn-guard.ts). */
|
|
23
23
|
idleTurnGuard?: boolean;
|
|
24
|
+
/** Block bash that waits (`sleep N`, sleep loops) or detaches (`&`, nohup); src/wait-guard.ts. */
|
|
25
|
+
waitGuard?: boolean;
|
|
26
|
+
/** Block task_output/task_list that only check on running work (src/poll-guard.ts). */
|
|
27
|
+
pollGuard?: boolean;
|
|
24
28
|
/** Optional M3 subagent tuning section (design doc §4.6 limits). */
|
|
25
29
|
subagent?: FamulusSubagentConfig;
|
|
26
30
|
}
|
|
@@ -145,6 +149,8 @@ export const DEFAULT_CONFIG: FamulusConfig = {
|
|
|
145
149
|
logLevel: "info",
|
|
146
150
|
messaging: { enabled: false },
|
|
147
151
|
idleTurnGuard: true,
|
|
152
|
+
waitGuard: true,
|
|
153
|
+
pollGuard: true,
|
|
148
154
|
};
|
|
149
155
|
|
|
150
156
|
/** Resolve the pi-famulus base directory. PI_FAMULUS_HOME overrides the default. */
|
|
@@ -220,6 +226,8 @@ export function loadConfig(home: string = getFamulusHome()): FamulusConfig {
|
|
|
220
226
|
config.messaging = { enabled: (obj.messaging as Record<string, unknown>).enabled === true };
|
|
221
227
|
}
|
|
222
228
|
if (obj.idleTurnGuard === false) config.idleTurnGuard = false;
|
|
229
|
+
if (obj.waitGuard === false) config.waitGuard = false;
|
|
230
|
+
if (obj.pollGuard === false) config.pollGuard = false;
|
|
223
231
|
if (typeof obj.foregroundBudgetMs === "number" && obj.foregroundBudgetMs > 0) {
|
|
224
232
|
config.foregroundBudgetMs = obj.foregroundBudgetMs;
|
|
225
233
|
}
|
package/src/index.ts
CHANGED
|
@@ -25,6 +25,8 @@ import { createRegistryCommsHost } from "./comms/registry-host";
|
|
|
25
25
|
import { createAgentMessageTool } from "./comms/tools";
|
|
26
26
|
import { registerReplyCommand } from "./comms/reply-command";
|
|
27
27
|
import { installIdleTurnGuard } from "./idle-turn-guard";
|
|
28
|
+
import { installWaitGuard } from "./wait-guard";
|
|
29
|
+
import { installPollGuard } from "./poll-guard";
|
|
28
30
|
import { describeManagerSearch, getFamulusHome, loadConfig, resolveManagerPath, resolveSubagentConfig, taskOutputPath } from "./config";
|
|
29
31
|
import { ensureNativeManagerInstalled } from "./native-manager.js";
|
|
30
32
|
import { formatDuration, type TaskExitInfo } from "./format";
|
|
@@ -1450,6 +1452,15 @@ function createFamulusRuntime(retiring?: Promise<unknown>): FamulusRuntime {
|
|
|
1450
1452
|
enabled: config.idleTurnGuard !== false,
|
|
1451
1453
|
onTrip: (info) => logEvent("guard.idle-turn", { count: info.count, calls: info.calls }),
|
|
1452
1454
|
});
|
|
1455
|
+
installWaitGuard(pi, {
|
|
1456
|
+
enabled: config.waitGuard !== false,
|
|
1457
|
+
onBlock: (info) => logEvent("guard.wait", info),
|
|
1458
|
+
});
|
|
1459
|
+
installPollGuard(pi, {
|
|
1460
|
+
enabled: config.pollGuard !== false,
|
|
1461
|
+
getIndex: () => workIndex,
|
|
1462
|
+
onBlock: (info) => logEvent("guard.poll", info),
|
|
1463
|
+
});
|
|
1453
1464
|
|
|
1454
1465
|
// A wake entering the model's context (steer / triggerTurn); see wake-delivery.ts.
|
|
1455
1466
|
pi.on("message_end", async (event) => {
|
package/src/manager-client.ts
CHANGED
|
@@ -18,7 +18,7 @@ import { famulusPaths } from "./config";
|
|
|
18
18
|
import { realClock, type Clock, type ClockTimer } from "./clock";
|
|
19
19
|
|
|
20
20
|
const MAX_FRAME_BYTES = 4 * 1024 * 1024; // 4 MiB (§3.3)
|
|
21
|
-
const EXTENSION_VERSION = "0.2.
|
|
21
|
+
const EXTENSION_VERSION = "0.2.6";
|
|
22
22
|
export { EXTENSION_VERSION };
|
|
23
23
|
// 6: hosted subagents. 7: the extension's messaging bridge (`intercom`
|
|
24
24
|
// request plus `intercom`/`intercom_reset` events).
|
package/src/monitor.ts
CHANGED
|
@@ -195,8 +195,7 @@ export class MonitorRegistry {
|
|
|
195
195
|
if (params.fingerprint_mode !== undefined && params.fingerprint_mode !== "exact" && params.fingerprint_mode !== "ignore-timestamps") {
|
|
196
196
|
throw new RangeError("fingerprint_mode must be exact or ignore-timestamps");
|
|
197
197
|
}
|
|
198
|
-
|
|
199
|
-
if (persistent && params.timeout_ms !== undefined) {
|
|
198
|
+
if (params.persistent === true && params.timeout_ms !== undefined) {
|
|
200
199
|
throw new RangeError("timeout_ms and persistent are exclusive: use timeout_ms for a watch that ends within 1 hour, persistent:true for an open-ended or longer watch");
|
|
201
200
|
}
|
|
202
201
|
if (params.timeout_ms !== undefined && params.timeout_ms > MAX_TIMEOUT_MS) {
|
|
@@ -216,6 +215,9 @@ export class MonitorRegistry {
|
|
|
216
215
|
if (params.stall_after_ms !== undefined && (!Number.isSafeInteger(params.stall_after_ms) || params.stall_after_ms < MIN_STALL_MS || params.stall_after_ms > MAX_STALL_MS)) {
|
|
217
216
|
throw new RangeError(`stall_after_ms must be an integer between ${MIN_STALL_MS} and ${MAX_STALL_MS}`);
|
|
218
217
|
}
|
|
218
|
+
// No lifetime given: run until the command exits or the monitor is stopped.
|
|
219
|
+
// persistent:false without timeout_ms keeps the 5-minute default.
|
|
220
|
+
const persistent = params.persistent === true || (params.persistent !== false && params.timeout_ms === undefined);
|
|
219
221
|
let timeoutMs: number | null = null;
|
|
220
222
|
if (!persistent) {
|
|
221
223
|
const requested = params.timeout_ms ?? DEFAULT_TIMEOUT_MS;
|
|
@@ -373,6 +375,21 @@ export class MonitorRegistry {
|
|
|
373
375
|
}
|
|
374
376
|
} else if (deliver.byteLength > 0) {
|
|
375
377
|
// Legacy manager or unavailable replay metadata: fail open, never hash in JS.
|
|
378
|
+
// Raw framing accounts for every COMPLETE line through `entry.cursor`. The
|
|
379
|
+
// manager re-sends records at a cursor it already wrote (`replay_at` in
|
|
380
|
+
// daemon.rs), so a line delivered raw must count as seen or a burst that
|
|
381
|
+
// arrived unframed (post-upgrade MonitorState rebuild) repeats its last
|
|
382
|
+
// line. Complete lines only: a trailing fragment is still framed by the
|
|
383
|
+
// manager's own finish/EOF line record at the same cursor, and under
|
|
384
|
+
// wake_on that fragment has not been admitted yet.
|
|
385
|
+
const lastNewline = deliver.lastIndexOf(0x0a);
|
|
386
|
+
if (lastNewline >= 0) {
|
|
387
|
+
const completed = entry.cursor - deliver.byteLength + lastNewline + 1;
|
|
388
|
+
if (completed > entry.recordCursor) {
|
|
389
|
+
entry.recordCursor = completed;
|
|
390
|
+
entry.lastRecordKind = "line";
|
|
391
|
+
}
|
|
392
|
+
}
|
|
376
393
|
entry.output.flush();
|
|
377
394
|
const cursorStart = Math.max(previousCursor, entry.cursor - deliver.byteLength);
|
|
378
395
|
const text = deliver.toString("utf8");
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Poll guard: blocks task_output/task_list calls that only check on running
|
|
3
|
+
* work with nothing new to read.
|
|
4
|
+
*
|
|
5
|
+
* In the 2026-11-07 log-monitor session (deepseek-flash) the agent made 258
|
|
6
|
+
* task_output calls, 326 of them answered "no new output"; the result text
|
|
7
|
+
* already told it to end its turn. In the 2026-11-08 agent-wait-ready and
|
|
8
|
+
* monitor-not-sleep probes gpt-6-luna kept a monitor running and still called
|
|
9
|
+
* task_list/task_output before the event came. The wait guard
|
|
10
|
+
* (wait-guard.ts) moves sleeps to exactly these calls.
|
|
11
|
+
*
|
|
12
|
+
* A call is a poll when the work it looks at is still active and no wake
|
|
13
|
+
* about it has arrived since the last look:
|
|
14
|
+
* task_output on an active task, without a cursor past 0 (paging on from
|
|
15
|
+
* an earlier read stays allowed; max_bytes alone is a fresh
|
|
16
|
+
* read), and no wake for that task since the last read of it.
|
|
17
|
+
* task_list while any work is active, and no wake, user or peer message
|
|
18
|
+
* since the last list or since work was last started (a list
|
|
19
|
+
* right after starting a task only checks that it runs).
|
|
20
|
+
* Finished work, a wake's details and reads after a new message stay open.
|
|
21
|
+
*
|
|
22
|
+
* The call is refused, not the run: ending the run could leave an agent with
|
|
23
|
+
* nothing that will wake it (a server it started without a monitor), so the
|
|
24
|
+
* reason says to start a monitor in that case.
|
|
25
|
+
*/
|
|
26
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
27
|
+
import { famulusWakeDetails } from "./wake-delivery.ts";
|
|
28
|
+
import { wakeIds } from "./wake.ts";
|
|
29
|
+
import { fill } from "./prompts.generated.ts";
|
|
30
|
+
|
|
31
|
+
export interface PollGuardIndex {
|
|
32
|
+
list(): { id: string; status: string; title?: string }[];
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export interface PollGuardOptions {
|
|
36
|
+
enabled: boolean;
|
|
37
|
+
getIndex: () => PollGuardIndex | null;
|
|
38
|
+
onBlock?: (info: { tool: string; taskId?: string }) => void;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const isActive = (status: string) => status === "pending" || status === "running";
|
|
42
|
+
|
|
43
|
+
/** A tool result that started background work (bash backgrounded, monitor started). */
|
|
44
|
+
const STARTED = /moved to background \(task_id: |Monitor started · task /;
|
|
45
|
+
|
|
46
|
+
function resultText(content: unknown): string {
|
|
47
|
+
if (typeof content === "string") return content;
|
|
48
|
+
if (!Array.isArray(content)) return "";
|
|
49
|
+
return content.map((c: { type?: string; text?: string }) => (c?.type === "text" ? c.text ?? "" : "")).join("\n");
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function installPollGuard(pi: Pick<ExtensionAPI, "on">, opts: PollGuardOptions): void {
|
|
53
|
+
if (!opts.enabled) return;
|
|
54
|
+
/** Task ids with a wake not yet followed by a task_output read of them. */
|
|
55
|
+
const news = new Set<string>();
|
|
56
|
+
/** A wake, user or peer message arrived since the last task_list. */
|
|
57
|
+
let listNews = true;
|
|
58
|
+
|
|
59
|
+
pi.on("message_end", async (event) => {
|
|
60
|
+
const message = event.message as { role?: string; content?: unknown };
|
|
61
|
+
if (message.role === "user") { listNews = true; return; }
|
|
62
|
+
if (message.role === "toolResult") {
|
|
63
|
+
if (STARTED.test(resultText(message.content))) listNews = false;
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
66
|
+
const wake = famulusWakeDetails(event.message);
|
|
67
|
+
if (wake) {
|
|
68
|
+
listNews = true;
|
|
69
|
+
for (const id of wakeIds(wake)) news.add(id);
|
|
70
|
+
return;
|
|
71
|
+
}
|
|
72
|
+
if (message.role === "custom") listNews = true;
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
pi.on("tool_call", async (event) => {
|
|
76
|
+
if (event.toolName !== "task_output" && event.toolName !== "task_list") return;
|
|
77
|
+
const items = opts.getIndex()?.list() ?? [];
|
|
78
|
+
const active = items.filter((i) => isActive(i.status));
|
|
79
|
+
if (active.length === 0) return;
|
|
80
|
+
const input = (event.input ?? {}) as Record<string, unknown>;
|
|
81
|
+
|
|
82
|
+
if (event.toolName === "task_list") {
|
|
83
|
+
if (listNews) { listNews = false; return; }
|
|
84
|
+
opts.onBlock?.({ tool: "task_list" });
|
|
85
|
+
return { block: true, reason: fill("guards.error.poll-list", { count: active.length }) };
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const taskId = typeof input.task_id === "string" ? input.task_id : "";
|
|
89
|
+
const target = active.find((i) => i.id === taskId);
|
|
90
|
+
if (!target) return;
|
|
91
|
+
if (typeof input.cursor === "number" && input.cursor > 0) return;
|
|
92
|
+
if (news.delete(taskId)) return;
|
|
93
|
+
opts.onBlock?.({ tool: "task_output", taskId });
|
|
94
|
+
return { block: true, reason: fill("guards.error.poll-output", { id: taskId }) };
|
|
95
|
+
});
|
|
96
|
+
}
|
package/src/prompts.generated.ts
CHANGED
|
@@ -7,7 +7,11 @@ export const PROMPTS = {
|
|
|
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
8
|
"guards.error.idle-turn": "Not run. pi-famulus ended this run: {{count}} turns in a row made only no-op or status calls ({{calls}}). Such calls do not wait for anything or yield control. Background tasks, monitors and messages from other sessions resume you with a new message when there is news. When no actionable work remains, reply with no tool call.",
|
|
9
9
|
"guards.error.idle-run": "Not run. pi-famulus ended this run: {{count}} turns in this run made only no-op or status calls ({{calls}}). Such calls do not wait for anything or yield control. Background tasks, monitors and messages from other sessions resume you with a new message when there is news. When no actionable work remains, reply with no tool call.",
|
|
10
|
-
"
|
|
10
|
+
"guards.error.wait-sleep": "Not run: this command waits in bash ({{what}}). Waiting in bash holds your turn and sees nothing new in between. To wait for a condition (a process you started, a file, a marker line), start a monitor with persistent:true whose command prints only when the condition is met or fails; it wakes you. If you are waiting for a background task, end your turn: its wake resumes you. Rerun the rest of the command without the wait if you still need it.",
|
|
11
|
+
"guards.error.wait-detach": "Not run: this command starts a process in the background ({{what}}) outside any monitor, so its output and its exit never reach you. Run that process as the monitor command with persistent:true (for example `./run.sh 2>&1 | grep --line-buffered -E 'ALERT|ERROR|done'`), or run it in the foreground: pi moves a long command to the background by itself and wakes you when it finishes.",
|
|
12
|
+
"guards.error.poll-output": "Not run: {{id}} is still running and nothing new has arrived for it since you last looked. Its wake resumes you when there is news (a monitor event, or the command's exit). End your turn now: reply with no tool call. If nothing would wake you (a command that keeps running, like a server, with no monitor on it), start a monitor for what you are waiting for first.",
|
|
13
|
+
"guards.error.poll-list": "Not run: {{count}} background item(s) are still running and no wake or message has arrived since your last task_list. Each one wakes you when there is news. End your turn now: reply with no tool call. If nothing would wake you (a command that keeps running, like a server, with no monitor on it), start a monitor for what you are waiting for first.",
|
|
14
|
+
"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>) when it exits, even while other commands are still running. A command that keeps running (a server, a watcher) never sends that wake: to act once it is ready, start a monitor for it before you end your turn. 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.",
|
|
11
15
|
"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.",
|
|
12
16
|
"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.",
|
|
13
17
|
"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.",
|
|
@@ -22,8 +26,8 @@ export const PROMPTS = {
|
|
|
22
26
|
"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.","Use bash only to perform concrete work or obtain needed information, never to occupy time while awaiting an event. No-op commands such as `true` or `:` do not wait for background work or yield control. If no actionable work remains, end your response without a tool call; the notification will resume you."],
|
|
23
27
|
"tools.bash.param.command": "The bash command to execute",
|
|
24
28
|
"tools.bash.param.timeout": "Hard kill timeout in seconds (optional, no default timeout)",
|
|
25
|
-
"tools.bash.param.run_in_background": "Start the command in the background and return immediately. You will be notified when it
|
|
26
|
-
"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.",
|
|
29
|
+
"tools.bash.param.run_in_background": "Start the command in the background and return immediately. You will be notified when it exits; a command that keeps running (a server, a watcher) never notifies, so to act once it is ready, run it as a monitor command instead.",
|
|
30
|
+
"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. That wake comes only when the command exits. If it keeps running (a server, a watcher) and you need to know when it is ready or prints something, start a monitor for that before you end your turn.",
|
|
27
31
|
"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.",
|
|
28
32
|
"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.",
|
|
29
33
|
"tools.child.agent_message.snippet": "Message sibling subagents in your run",
|
|
@@ -36,13 +40,13 @@ export const PROMPTS = {
|
|
|
36
40
|
"tools.child.contact_supervisor.snippet": "Ask the parent agent for a decision or report progress",
|
|
37
41
|
"tools.child.contact_supervisor.param.reason": "\"need_decision\" blocks until the supervisor (parent agent) replies; \"progress_update\" is fire-and-forget.",
|
|
38
42
|
"tools.child.contact_supervisor.param.message": "Message for the supervisor.",
|
|
39
|
-
"tools.monitor.description": "Start a background monitor process whose stdout lines are injected back to you as <pi-famulus-wake kind=\"monitor\"> messages (batched over 200ms, rate-limited). The command must be line-buffered: each event must be a single line. It must keep running and follow its source. When you start the producer yourself, make it the command (`node app.js | grep --line-buffered ALERT`); do not start it in bash and tail its output. Use `tail -n +1 -F file | grep --line-buffered PATTERN` or `journalctl -f` for a source you did not start. A command that reads once and exits (a plain grep or cat) only reports what is there now. Add `-m1` to grep only when the first match should end the watch. Silence is not success: print explicit success and terminal failures of what you watch. Routine unchanged retries may stay silent; without wake_on, do not print a heartbeat on every check. The monitor's own exit or timeout is reported to you; do not add end-of-watch lines. Status lines may stay when you set wake_on to the problem pattern: only matching lines wake you, and task_output keeps every line. Use stall_after_ms instead of heartbeats to learn that the source went silent. Events arrive as system wakes (not new user messages). Handle each <pi-famulus-wake kind=\"monitor\"> before other work. Do not poll. Repeated Rust-framed lines are suppressed within dedup_window_ms (default 60000); exact matching is the default. Enable ignore-timestamps only when edge ISO timestamps are incidental. Wakes contain bounded head/tail previews and original-byte references; use task_output for missing details, not polling.
|
|
43
|
+
"tools.monitor.description": "Start a background monitor process whose stdout lines are injected back to you as <pi-famulus-wake kind=\"monitor\"> messages (batched over 200ms, rate-limited). The command must be line-buffered: each event must be a single line. It must keep running and follow its source. When you start the producer yourself, make it the command (`node app.js | grep --line-buffered ALERT`); do not start it in bash and tail its output. Use `tail -n +1 -F file | grep --line-buffered PATTERN` or `journalctl -f` for a source you did not start. A command that reads once and exits (a plain grep or cat) only reports what is there now. Add `-m1` to grep only when the first match should end the watch. Silence is not success: print explicit success and terminal failures of what you watch. Routine unchanged retries may stay silent; without wake_on, do not print a heartbeat on every check. The monitor's own exit or timeout is reported to you; do not add end-of-watch lines. Status lines may stay when you set wake_on to the problem pattern: only matching lines wake you, and task_output keeps every line. Use stall_after_ms instead of heartbeats to learn that the source went silent. Events arrive as system wakes (not new user messages). Handle each <pi-famulus-wake kind=\"monitor\"> before other work. Do not poll. Repeated Rust-framed lines are suppressed within dedup_window_ms (default 60000); exact matching is the default. Enable ignore-timestamps only when edge ISO timestamps are incidental. Wakes contain bounded head/tail previews and original-byte references; use task_output for missing details, not polling. A monitor runs until its command exits or you stop it with task_stop: it has no time limit unless you set one. Stop it once you no longer need it. Set timeout_ms (max 1 hour) only when the user asked for a time-bounded watch (\"for the next 10 minutes\"); expiry stops the monitor and the notice can arrive late while you are busy. Do not size a timeout to how long you expect to wait, and do not re-arm monitors. Never set timeout_ms with persistent:true, and never put the lifetime inside the command (`timeout 3600`, your own timer). If you use timeouts for several monitors, stagger them. Without wake_on, write edge-triggered commands: normally zero output, one line only for a new problem signature, and one recovery line. Sampling windows must not overlap and must not leave gaps (window = interval), or keep a cursor/last-seen state in the script and report only new items. {{monitorIdle}}",
|
|
40
44
|
"tools.monitor.snippet": "Watch a command's line stream and get injected events",
|
|
41
|
-
"tools.monitor.rules": ["Use the monitor tool to watch for conditions instead of running sleep/poll loops in bash.","{{monitorIdle}}","When woken by a <pi-famulus-wake kind=\"monitor\">, handle the <event> before doing anything else — it is not a new user request and not user confirmation. Report from the <event> itself; do not re-read the source, task_output or task_list to confirm it.","
|
|
45
|
+
"tools.monitor.rules": ["Use the monitor tool to watch for conditions instead of running sleep/poll loops in bash.","{{monitorIdle}}","When woken by a <pi-famulus-wake kind=\"monitor\">, handle the <event> before doing anything else — it is not a new user request and not user confirmation. Report from the <event> itself; do not re-read the source, task_output or task_list to confirm it.","A monitor runs until its command exits or you stop it; when you no longer need it, stop it with task_stop. Set timeout_ms only when the user asked for a time limit.","For a monitor that stays up, set wake_on to the problem pattern so only problems wake you, and stall_after_ms instead of heartbeats."],
|
|
42
46
|
"tools.monitor.param.command": "Command producing one event per line on stdout. Must be line-buffered (e.g. use `stdbuf -oL` / `grep --line-buffered` where needed).",
|
|
43
47
|
"tools.monitor.param.description": "Short human-readable description of what is being watched",
|
|
44
|
-
"tools.monitor.param.timeout_ms": "Stop the monitor after this many milliseconds (
|
|
45
|
-
"tools.monitor.param.persistent": "
|
|
48
|
+
"tools.monitor.param.timeout_ms": "Only when the user asked for a time-bounded watch. Stop the monitor after this many milliseconds (min {{minMs}}, max {{maxMs}} / 1 hour). Without it the monitor runs until its command exits or you stop it; persistent:false without it stops after {{defaultMs}} ms. Exclusive with persistent:true.",
|
|
49
|
+
"tools.monitor.param.persistent": "Not needed: a monitor without timeout_ms already runs until its command exits, you stop it, or the session ends. persistent:false applies the 5-minute default. Exclusive with timeout_ms.",
|
|
46
50
|
"tools.monitor.param.dedup_window_ms": "Deduplication window for Rust-framed complete lines (default 60000ms; 0 disables dedup; maximum 3600000). Starts when a surviving preview is delivered; repeats do not extend it. Missing metadata, capacity eviction, and omitted representatives fail open rather than hiding unseen output.",
|
|
47
51
|
"tools.monitor.param.wake_on": "JavaScript RegExp source tested against each output line. When set, only matching lines wake you (and only they count for dedup and overload); every line is still recorded for task_output. Exit, timeout and stall notices still arrive. Strongly recommended for persistent monitors: match the problem, e.g. `ERROR|unacked=[1-9]`.",
|
|
48
52
|
"tools.monitor.param.stall_after_ms": "Send one notice when the command prints nothing at all (matching wake_on or not) for this many milliseconds while still running (min {{minMs}}, max {{maxMs}}). The next output re-arms it. Use it instead of heartbeat lines.",
|
|
@@ -112,6 +116,10 @@ export type PromptId = keyof typeof PROMPTS;
|
|
|
112
116
|
export interface PromptVars {
|
|
113
117
|
"guards.error.idle-turn": "count" | "calls";
|
|
114
118
|
"guards.error.idle-run": "count" | "calls";
|
|
119
|
+
"guards.error.wait-sleep": "what";
|
|
120
|
+
"guards.error.wait-detach": "what";
|
|
121
|
+
"guards.error.poll-output": "id";
|
|
122
|
+
"guards.error.poll-list": "count";
|
|
115
123
|
"guidelines.parent": "monitorIdle";
|
|
116
124
|
"tools.agent_message.error.finished-child": "childId" | "name" | "status" | "runId";
|
|
117
125
|
"tools.bash.description": "maxLines" | "maxKb";
|
|
@@ -121,7 +129,7 @@ export interface PromptVars {
|
|
|
121
129
|
"tools.child.bash.error.bare-sleep": "command";
|
|
122
130
|
"tools.monitor.description": "monitorIdle";
|
|
123
131
|
"tools.monitor.rules": "monitorIdle";
|
|
124
|
-
"tools.monitor.param.timeout_ms": "
|
|
132
|
+
"tools.monitor.param.timeout_ms": "minMs" | "maxMs" | "defaultMs";
|
|
125
133
|
"tools.monitor.param.stall_after_ms": "minMs" | "maxMs";
|
|
126
134
|
"tools.monitor.event.stalled": "idle";
|
|
127
135
|
"tools.monitor.result.started": "monitorIdle";
|
|
@@ -167,7 +175,7 @@ export function fillList<K extends keyof PromptVars>(id: K, vars: Record<PromptV
|
|
|
167
175
|
|
|
168
176
|
/** Ablatable spans (eval manifest segment ids). */
|
|
169
177
|
export const PROMPT_SEGMENTS: Record<string, { prompt: PromptId; text?: string; pattern?: string }> = {
|
|
170
|
-
"guidelines.end-turn-after-bg": {"prompt":"guidelines.parent","text":"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."},
|
|
178
|
+
"guidelines.end-turn-after-bg": {"prompt":"guidelines.parent","text":"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>) when it exits, even while other commands are still running. A command that keeps running (a server, a watcher) never sends that wake: to act once it is ready, start a monitor for it before you end your turn. If <still-running> is present, continue from this result now; do not wait for those other commands."},
|
|
171
179
|
"guidelines.wake-handling": {"prompt":"guidelines.parent","text":"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."},
|
|
172
180
|
"guidelines.no-fabrication": {"prompt":"guidelines.parent","text":"Never fabricate or assume a background task's result before its notification arrives."},
|
|
173
181
|
"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."},
|
|
@@ -180,19 +188,20 @@ export const PROMPT_SEGMENTS: Record<string, { prompt: PromptId; text?: string;
|
|
|
180
188
|
"rules.pi-env": {"prompt":"tools.bash.rules","text":"You can inspect PI_* environment variables for current model and session details."},
|
|
181
189
|
"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."},
|
|
182
190
|
"result.bash-bg-instruction": {"prompt":"tools.bash.result.backgrounded","text":"\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."},
|
|
191
|
+
"result.bash-bg-exit-only": {"prompt":"tools.bash.result.backgrounded","text":" That wake comes only when the command exits. If it keeps running (a server, a watcher) and you need to know when it is ready or prints something, start a monitor for that before you end your turn."},
|
|
183
192
|
"result.sleep-block-advice": {"prompt":"tools.bash.error.bare-sleep","text":" 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."},
|
|
184
193
|
"tooldesc.monitor-follow": {"prompt":"tools.monitor.description","text":"It must keep running and follow its source. When you start the producer yourself, make it the command (`node app.js | grep --line-buffered ALERT`); do not start it in bash and tail its output. Use `tail -n +1 -F file | grep --line-buffered PATTERN` or `journalctl -f` for a source you did not start. A command that reads once and exits (a plain grep or cat) only reports what is there now. Add `-m1` to grep only when the first match should end the watch. "},
|
|
185
194
|
"tooldesc.monitor-silence": {"prompt":"tools.monitor.description","text":"Silence is not success: print explicit success and terminal failures of what you watch. Routine unchanged retries may stay silent; without wake_on, do not print a heartbeat on every check. The monitor's own exit or timeout is reported to you; do not add end-of-watch lines. "},
|
|
186
195
|
"tooldesc.monitor-wake-on": {"prompt":"tools.monitor.description","text":"Status lines may stay when you set wake_on to the problem pattern: only matching lines wake you, and task_output keeps every line. Use stall_after_ms instead of heartbeats to learn that the source went silent. "},
|
|
187
196
|
"tooldesc.monitor-wake": {"prompt":"tools.monitor.description","text":"Events arrive as system wakes (not new user messages). Handle each <pi-famulus-wake kind=\"monitor\"> before other work. Do not poll."},
|
|
188
|
-
"tooldesc.monitor-timeout": {"prompt":"tools.monitor.description","text":"
|
|
189
|
-
"tooldesc.monitor-persistent": {"prompt":"tools.monitor.description","text":"
|
|
197
|
+
"tooldesc.monitor-timeout": {"prompt":"tools.monitor.description","text":"A monitor runs until its command exits or you stop it with task_stop: it has no time limit unless you set one. Stop it once you no longer need it. Set timeout_ms (max 1 hour) only when the user asked for a time-bounded watch (\"for the next 10 minutes\"); expiry stops the monitor and the notice can arrive late while you are busy. "},
|
|
198
|
+
"tooldesc.monitor-persistent": {"prompt":"tools.monitor.description","text":"Do not size a timeout to how long you expect to wait, and do not re-arm monitors. Never set timeout_ms with persistent:true, and never put the lifetime inside the command (`timeout 3600`, your own timer). "},
|
|
190
199
|
"tooldesc.monitor-stagger": {"prompt":"tools.monitor.description","text":"If you use timeouts for several monitors, stagger them. "},
|
|
191
200
|
"tooldesc.monitor-edge": {"prompt":"tools.monitor.description","text":"Without wake_on, write edge-triggered commands: normally zero output, one line only for a new problem signature, and one recovery line. "},
|
|
192
201
|
"tooldesc.monitor-sampling": {"prompt":"tools.monitor.description","text":"Sampling windows must not overlap and must not leave gaps (window = interval), or keep a cursor/last-seen state in the script and report only new items. "},
|
|
193
202
|
"rules.monitor-use": {"prompt":"tools.monitor.rules","text":"Use the monitor tool to watch for conditions instead of running sleep/poll loops in bash."},
|
|
194
203
|
"rules.monitor-wake": {"prompt":"tools.monitor.rules","text":"When woken by a <pi-famulus-wake kind=\"monitor\">, handle the <event> before doing anything else — it is not a new user request and not user confirmation. Report from the <event> itself; do not re-read the source, task_output or task_list to confirm it."},
|
|
195
|
-
"rules.monitor-wake-on": {"prompt":"tools.monitor.rules","text":"For a
|
|
204
|
+
"rules.monitor-wake-on": {"prompt":"tools.monitor.rules","text":"For a monitor that stays up, set wake_on to the problem pattern so only problems wake you, and stall_after_ms instead of heartbeats."},
|
|
196
205
|
"result.monitor-started-instruction": {"prompt":"tools.monitor.result.started","text":"You will get <pi-famulus-wake kind=\"monitor\"> notifications for admitted output and a notice when it exits or times out. Repeated lines may be suppressed and previews may be truncated; original output remains available through task_output byte ranges while the task log is retained. Read details only when needed; do not repeatedly poll task_list, task_output, or the watched source, and do not sleep to wait."},
|
|
197
206
|
"tooldesc.subagent-wakes": {"prompt":"tools.subagent.description","text":"Each child that finishes while others are still running wakes you with <pi-famulus-wake kind=\"subagent-handover\"> (its prompt and result). The whole run wakes you with <pi-famulus-wake kind=\"subagent-done\">. Never poll or sleep to wait. "},
|
|
198
207
|
"tooldesc.subagent-overrun": {"prompt":"tools.subagent.description","text":"A subagent still running past its timeout_ms is not stopped; it wakes you with <pi-famulus-wake kind=\"subagent-overrun\"> so you can extend, steer, or interrupt it. "},
|
|
@@ -34,6 +34,33 @@ interface HostingView {
|
|
|
34
34
|
sessionId?: string;
|
|
35
35
|
}
|
|
36
36
|
|
|
37
|
+
/**
|
|
38
|
+
* One prompt whose turn the parent supervises.
|
|
39
|
+
*
|
|
40
|
+
* A prompt is not the same as its RPC acknowledgement: the daemon's cold
|
|
41
|
+
* `get_state` handshake for a respawned parked child reports `idle` before the
|
|
42
|
+
* prompt has run, and events may arrive before the RPC response. Completion is
|
|
43
|
+
* therefore fenced by this turn's own `agent_start`/`agent_settled` lifecycle,
|
|
44
|
+
* never by transport readiness.
|
|
45
|
+
*/
|
|
46
|
+
interface ActiveTurn {
|
|
47
|
+
/** Resolves when this prompt's run lifecycle ends (or it was handled). */
|
|
48
|
+
done: Promise<void>;
|
|
49
|
+
resolve: () => void;
|
|
50
|
+
/** The daemon's RPC response for the dispatch was processed. */
|
|
51
|
+
accepted: boolean;
|
|
52
|
+
/** `disposition` from that response (`started` | `queued` | `handled`). */
|
|
53
|
+
disposition: string | undefined;
|
|
54
|
+
/** A run for this turn is active (observed `agent_start`, or joined live). */
|
|
55
|
+
sawStart: boolean;
|
|
56
|
+
/** An `agent_settled` was observed and no newer run started since. */
|
|
57
|
+
settled: boolean;
|
|
58
|
+
/** The hosted process reported failure before the turn ended. */
|
|
59
|
+
processFailed: boolean;
|
|
60
|
+
/** The prompt was steered into a run already in flight (out-of-band work). */
|
|
61
|
+
joinedRun: boolean;
|
|
62
|
+
}
|
|
63
|
+
|
|
37
64
|
export function createHostedSessionFn(deps: HostedSessionDeps): CreateSessionFn {
|
|
38
65
|
return async (req) => {
|
|
39
66
|
const client = deps.getClient();
|
|
@@ -104,7 +131,8 @@ class HostedRpcSession implements ChildSessionAdapter {
|
|
|
104
131
|
private lastFailure: { stopReason: "error" | "aborted"; errorMessage?: string } | undefined;
|
|
105
132
|
private turns: { role: string; text: string }[] = [];
|
|
106
133
|
private usage: ChildTokenUsage = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
|
|
107
|
-
|
|
134
|
+
/** The prompt turn awaiting its own completion; null between turns. */
|
|
135
|
+
private activeTurn: ActiveTurn | null = null;
|
|
108
136
|
private hostingView: HostingView;
|
|
109
137
|
private disposed = false;
|
|
110
138
|
|
|
@@ -131,10 +159,28 @@ class HostedRpcSession implements ChildSessionAdapter {
|
|
|
131
159
|
}
|
|
132
160
|
|
|
133
161
|
async prompt(text: string): Promise<void> {
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
162
|
+
// A run already in flight is not ours: a user/UI attach or a sibling drove
|
|
163
|
+
// it. Steering delivers this prompt into that run, and its settle is this
|
|
164
|
+
// turn's completion — returning early would report the child finished while
|
|
165
|
+
// the run is still executing.
|
|
166
|
+
const joinedRun = this.streaming;
|
|
167
|
+
// A new prompt supersedes any turn still armed (defensive: the runner
|
|
168
|
+
// serializes generations, so this should not happen).
|
|
169
|
+
if (this.activeTurn) this.finishTurn(this.activeTurn);
|
|
170
|
+
const turn = this.beginTurn(joinedRun);
|
|
171
|
+
try {
|
|
172
|
+
const response = await this.client.agentInput(
|
|
173
|
+
this.childId,
|
|
174
|
+
joinedRun ? "prompt_steer" : "prompt",
|
|
175
|
+
text,
|
|
176
|
+
"parent",
|
|
177
|
+
);
|
|
178
|
+
this.acceptPrompt(turn, response);
|
|
179
|
+
} catch (err) {
|
|
180
|
+
this.finishTurn(turn);
|
|
181
|
+
throw err;
|
|
182
|
+
}
|
|
183
|
+
await turn.done;
|
|
138
184
|
}
|
|
139
185
|
|
|
140
186
|
async steer(text: string): Promise<void> {
|
|
@@ -146,10 +192,15 @@ class HostedRpcSession implements ChildSessionAdapter {
|
|
|
146
192
|
}
|
|
147
193
|
|
|
148
194
|
async abort(): Promise<void> {
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
195
|
+
try {
|
|
196
|
+
await this.client.agentInput(this.childId, "abort", "", "parent");
|
|
197
|
+
} finally {
|
|
198
|
+
// The abort response is sent after the child became idle, so the turn can
|
|
199
|
+
// end now; its `agent_settled` is already drained or no longer relevant.
|
|
200
|
+
// A failed abort (dead child) must not leave the turn supervised forever.
|
|
201
|
+
this.streaming = false;
|
|
202
|
+
if (this.activeTurn) this.finishTurn(this.activeTurn);
|
|
203
|
+
}
|
|
153
204
|
}
|
|
154
205
|
|
|
155
206
|
async park(): Promise<void> {
|
|
@@ -158,8 +209,9 @@ class HostedRpcSession implements ChildSessionAdapter {
|
|
|
158
209
|
}
|
|
159
210
|
|
|
160
211
|
async waitForIdle(): Promise<void> {
|
|
161
|
-
|
|
162
|
-
|
|
212
|
+
const turn = this.activeTurn;
|
|
213
|
+
if (!turn || !this.streaming) return;
|
|
214
|
+
await turn.done;
|
|
163
215
|
}
|
|
164
216
|
|
|
165
217
|
getLastAssistantText(): string | undefined {
|
|
@@ -191,14 +243,71 @@ class HostedRpcSession implements ChildSessionAdapter {
|
|
|
191
243
|
if (this.disposed) return;
|
|
192
244
|
this.disposed = true;
|
|
193
245
|
this.unsubscribe();
|
|
194
|
-
this.
|
|
195
|
-
this.settle = null;
|
|
246
|
+
if (this.activeTurn) this.finishTurn(this.activeTurn);
|
|
196
247
|
}
|
|
197
248
|
|
|
198
|
-
private
|
|
199
|
-
|
|
200
|
-
|
|
249
|
+
private beginTurn(joinedRun: boolean): ActiveTurn {
|
|
250
|
+
let resolve!: () => void;
|
|
251
|
+
const done = new Promise<void>((res) => {
|
|
252
|
+
resolve = res;
|
|
201
253
|
});
|
|
254
|
+
// Failure/result state is turn-scoped: the previous turn's abort error must
|
|
255
|
+
// not describe this one.
|
|
256
|
+
this.lastFailure = undefined;
|
|
257
|
+
const turn: ActiveTurn = {
|
|
258
|
+
done,
|
|
259
|
+
resolve,
|
|
260
|
+
accepted: false,
|
|
261
|
+
disposition: undefined,
|
|
262
|
+
sawStart: joinedRun,
|
|
263
|
+
settled: false,
|
|
264
|
+
processFailed: false,
|
|
265
|
+
joinedRun,
|
|
266
|
+
};
|
|
267
|
+
this.activeTurn = turn;
|
|
268
|
+
return turn;
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/** Apply the prompt RPC's disposition, then wait or finish accordingly. */
|
|
272
|
+
private acceptPrompt(turn: ActiveTurn, response: Record<string, unknown>): void {
|
|
273
|
+
if (this.activeTurn !== turn) return;
|
|
274
|
+
turn.accepted = true;
|
|
275
|
+
turn.disposition = typeof response.disposition === "string" ? response.disposition : undefined;
|
|
276
|
+
if (turn.disposition === "handled" && !turn.joinedRun) {
|
|
277
|
+
// An extension command or input handler consumed the prompt: no run
|
|
278
|
+
// starts for it, so there is nothing to wait for. A handled prompt that
|
|
279
|
+
// was steered into a live run still waits for that run to end.
|
|
280
|
+
this.streaming = false;
|
|
281
|
+
this.finishTurn(turn);
|
|
282
|
+
return;
|
|
283
|
+
}
|
|
284
|
+
if (turn.disposition === "queued") {
|
|
285
|
+
// The prompt joined a run that was already streaming (our view said
|
|
286
|
+
// idle). That run's `agent_settled` is this turn's completion.
|
|
287
|
+
turn.sawStart = true;
|
|
288
|
+
}
|
|
289
|
+
if (turn.processFailed) {
|
|
290
|
+
this.lastFailure = { stopReason: "error", errorMessage: "hosted child process failed" };
|
|
291
|
+
this.finishTurn(turn);
|
|
292
|
+
return;
|
|
293
|
+
}
|
|
294
|
+
this.maybeFinishTurn(turn);
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
private maybeFinishTurn(turn: ActiveTurn): void {
|
|
298
|
+
if (this.activeTurn !== turn || !turn.accepted || !turn.settled) return;
|
|
299
|
+
// `started` (or a legacy response without a disposition) must have shown a
|
|
300
|
+
// run start after this turn was armed: a stale `agent_settled` from the
|
|
301
|
+
// previous generation is not this prompt's completion.
|
|
302
|
+
if (turn.disposition !== "queued" && !turn.sawStart) return;
|
|
303
|
+
this.finishTurn(turn);
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
private finishTurn(turn: ActiveTurn): void {
|
|
307
|
+
if (this.activeTurn !== turn) return;
|
|
308
|
+
this.activeTurn = null;
|
|
309
|
+
this.streaming = false;
|
|
310
|
+
turn.resolve();
|
|
202
311
|
}
|
|
203
312
|
|
|
204
313
|
private onManagerEvent(event: ManagerEvent & Record<string, unknown>): void {
|
|
@@ -213,13 +322,28 @@ class HostedRpcSession implements ChildSessionAdapter {
|
|
|
213
322
|
sessionId: typeof event.session_id === "string" ? event.session_id : this.hostingView.sessionId,
|
|
214
323
|
};
|
|
215
324
|
if (event.activity === "running") this.streaming = true;
|
|
216
|
-
if (event.activity === "idle"
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
325
|
+
if (event.activity === "idle") {
|
|
326
|
+
// Transport/process readiness, not turn completion: a respawned parked
|
|
327
|
+
// child reports idle from its cold get_state handshake before the
|
|
328
|
+
// resumed prompt has run. Completion comes from `agent_settled`.
|
|
329
|
+
this.streaming = false;
|
|
330
|
+
return;
|
|
331
|
+
}
|
|
332
|
+
if (event.activity === "failed") {
|
|
220
333
|
this.streaming = false;
|
|
221
|
-
|
|
222
|
-
|
|
334
|
+
// Explicit process failure is a real terminal signal even before the
|
|
335
|
+
// run starts (the daemon filters stale generations). Before the RPC
|
|
336
|
+
// response the failure is held on the turn and applied on acceptance,
|
|
337
|
+
// so an accepted prompt cannot wait forever for a settle that will
|
|
338
|
+
// never come.
|
|
339
|
+
const turn = this.activeTurn;
|
|
340
|
+
if (turn) {
|
|
341
|
+
turn.processFailed = true;
|
|
342
|
+
if (turn.accepted) {
|
|
343
|
+
this.lastFailure = { stopReason: "error", errorMessage: "hosted child process failed" };
|
|
344
|
+
this.finishTurn(turn);
|
|
345
|
+
}
|
|
346
|
+
}
|
|
223
347
|
}
|
|
224
348
|
return;
|
|
225
349
|
}
|
|
@@ -239,13 +363,28 @@ class HostedRpcSession implements ChildSessionAdapter {
|
|
|
239
363
|
isError?: boolean;
|
|
240
364
|
};
|
|
241
365
|
const type = record.type ?? "";
|
|
242
|
-
if (type === "agent_start")
|
|
366
|
+
if (type === "agent_start") {
|
|
367
|
+
this.streaming = true;
|
|
368
|
+
const turn = this.activeTurn;
|
|
369
|
+
if (turn) {
|
|
370
|
+
turn.sawStart = true;
|
|
371
|
+
// A run that starts after a settle means the record was not terminal
|
|
372
|
+
// for this prompt (Pi is still working), so it cannot close the turn.
|
|
373
|
+
turn.settled = false;
|
|
374
|
+
}
|
|
375
|
+
}
|
|
243
376
|
if (type === "agent_settled") {
|
|
244
377
|
this.streaming = false;
|
|
245
|
-
this.
|
|
246
|
-
|
|
378
|
+
const turn = this.activeTurn;
|
|
379
|
+
if (turn) {
|
|
380
|
+
turn.settled = true;
|
|
381
|
+
this.maybeFinishTurn(turn);
|
|
382
|
+
}
|
|
247
383
|
}
|
|
248
|
-
|
|
384
|
+
// Content bookkeeping belongs only to work the parent is supervising: a
|
|
385
|
+
// late record from a drained generation must not rewrite this turn.
|
|
386
|
+
const owned = this.streaming || this.activeTurn?.sawStart === true;
|
|
387
|
+
if (owned && type === "message_end" && record.message?.role === "assistant") {
|
|
249
388
|
const text = (record.message.content ?? []).map((part) => part.text ?? "").join("");
|
|
250
389
|
if (text) {
|
|
251
390
|
this.lastText = text;
|
|
@@ -271,11 +410,11 @@ class HostedRpcSession implements ChildSessionAdapter {
|
|
|
271
410
|
this.usage.cacheWrite += num(usage.cacheWrite);
|
|
272
411
|
}
|
|
273
412
|
}
|
|
274
|
-
if (type === "message_end" && record.message?.role === "user") {
|
|
413
|
+
if (owned && type === "message_end" && record.message?.role === "user") {
|
|
275
414
|
const text = (record.message.content ?? []).map((part) => part.text ?? "").join("");
|
|
276
415
|
if (text) this.turns.push({ role: "user", text });
|
|
277
416
|
}
|
|
278
|
-
if (type === "tool_execution_end") {
|
|
417
|
+
if (owned && type === "tool_execution_end") {
|
|
279
418
|
const name = record.toolName ?? "tool";
|
|
280
419
|
const text = record.args === undefined ? name : `${name} ${JSON.stringify(record.args)}`;
|
|
281
420
|
this.turns.push({
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Wait guard: blocks bash commands that wait instead of watching.
|
|
3
|
+
*
|
|
4
|
+
* In the 2026-11-07 log-monitor session (deepseek-flash) the agent waited in
|
|
5
|
+
* bash 76 times (`sleep 45; check`, `while …; do sleep 5; done`) and started
|
|
6
|
+
* its producers with `(./run.sh > out 2>&1 &)`, then checked on them with
|
|
7
|
+
* `ps`. The monitor description and rules already said not to; a replay of
|
|
8
|
+
* that session at ten decision points (eval/replay) showed that rewording
|
|
9
|
+
* them did not change the choice. The harness has to refuse it.
|
|
10
|
+
*
|
|
11
|
+
* Two shapes are blocked, with a reason that names the alternative:
|
|
12
|
+
* wait `sleep N` with N >= WAIT_SLEEP_MIN_S, or any while/until/for loop
|
|
13
|
+
* that sleeps: use a persistent monitor, or end the turn.
|
|
14
|
+
* detach a lone `&`, nohup, setsid or disown: run the producer as the
|
|
15
|
+
* monitor command, or in the foreground (pi backgrounds it).
|
|
16
|
+
* Quoted strings, heredoc bodies and comments are ignored, so a sleep or `&`
|
|
17
|
+
* inside `ansible -a '…'`, a Python heredoc or a URL does not count.
|
|
18
|
+
*/
|
|
19
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
20
|
+
import { fill } from "./prompts.generated.ts";
|
|
21
|
+
|
|
22
|
+
/** Shorter sleeps settle a restart; longer ones wait for something. */
|
|
23
|
+
export const WAIT_SLEEP_MIN_S = 10;
|
|
24
|
+
|
|
25
|
+
export type WaitShape = { kind: "wait"; what: string } | { kind: "detach"; what: string };
|
|
26
|
+
|
|
27
|
+
/** Remove what the local shell does not execute as words: heredoc bodies, quotes, comments. */
|
|
28
|
+
export function shellWords(command: string): string {
|
|
29
|
+
let s = command.replace(/<<-?\s*(['"]?)(\w+)\1[^\n]*\n[\s\S]*?\n\s*\2\s*(?=\n|$)/g, "<<heredoc");
|
|
30
|
+
s = s.replace(/'[^']*'/g, "''").replace(/"(?:\\.|[^"\\])*"/g, '""');
|
|
31
|
+
s = s.replace(/(^|\s)#[^\n]*/g, "$1");
|
|
32
|
+
return s;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const SLEEP = /\bsleep\s+(\d+(?:\.\d+)?)/g;
|
|
36
|
+
// A sleep inside a loop body (between `do` and its `done`), not one after the loop.
|
|
37
|
+
const SLEEP_LOOP = /\b(while|until|for)\b[\s\S]*?\bdo\b(?:(?!\bdone\b)[\s\S])*\bsleep\b/;
|
|
38
|
+
const DETACH = /(^|[^&>|])&(?![&>])|\b(nohup|setsid|disown)\b/m;
|
|
39
|
+
|
|
40
|
+
export function waitShape(command: string): WaitShape | null {
|
|
41
|
+
const words = shellWords(command);
|
|
42
|
+
if (SLEEP_LOOP.test(words)) return { kind: "wait", what: "a loop that sleeps" };
|
|
43
|
+
for (const m of words.matchAll(SLEEP)) {
|
|
44
|
+
if (Number(m[1]) >= WAIT_SLEEP_MIN_S) return { kind: "wait", what: `sleep ${m[1]}` };
|
|
45
|
+
}
|
|
46
|
+
const d = DETACH.exec(words);
|
|
47
|
+
if (d) return { kind: "detach", what: d[2] ?? "&" };
|
|
48
|
+
return null;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export interface WaitGuardOptions {
|
|
52
|
+
enabled: boolean;
|
|
53
|
+
onBlock?: (info: { kind: WaitShape["kind"]; what: string }) => void;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function installWaitGuard(pi: Pick<ExtensionAPI, "on">, opts: WaitGuardOptions): void {
|
|
57
|
+
if (!opts.enabled) return;
|
|
58
|
+
pi.on("tool_call", async (event) => {
|
|
59
|
+
if (event.toolName !== "bash") return;
|
|
60
|
+
const command = (event.input as { command?: unknown } | null)?.command;
|
|
61
|
+
if (typeof command !== "string") return;
|
|
62
|
+
const shape = waitShape(command);
|
|
63
|
+
if (!shape) return;
|
|
64
|
+
opts.onBlock?.({ kind: shape.kind, what: shape.what });
|
|
65
|
+
const reason = fill(shape.kind === "wait" ? "guards.error.wait-sleep" : "guards.error.wait-detach", { what: shape.what });
|
|
66
|
+
return { block: true, reason };
|
|
67
|
+
});
|
|
68
|
+
}
|