@maheidem/pi-delegate 0.7.3 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,20 @@
1
+ # Changelog
2
+
3
+ ## [0.9.0]
4
+
5
+ - Security: strict `toolCallId` allowlist in `ask.ts` (read + write paths) — path traversal refused, fails closed.
6
+ - Security: strict env allowlist for child spawns (`buildChildEnv`) — parent environment (secrets) no longer inherited.
7
+ - Correctness: removed `.unref()` from safety timers in `runner.ts` (hard/inactivity/handoff grace/enforce/kill escalation/handoff settle); only the periodic progress heartbeat stays unref'd. Header contract updated.
8
+ - Robustness: `run-store.ts` silent catches now emit a debug-gated diagnostic (never throws).
9
+ - Robustness: nested `progressReports` and `askParent` config validated field-by-field with diagnostics; `PI_DELEGATE_ASK_DIR` validated (absolute, stays inside agent dir, created 0700) and timeout/max clamped.
10
+ - Housekeeping: removed stray root `dbg3.mts`; README security notes; AGENTS.md stale line ref fixed.
11
+
12
+ ## [0.8.0]
13
+
14
+ - Move the runtime code to `extensions/`. The pi entry is `./extensions/index.ts`.
15
+ - Import the shared UI parts from `@maheidem/pi-panel-kit`. The local copies are gone.
16
+ - Export `CONFIG_PATH` from `extensions/config.ts`. `/delegate paths` prints it.
17
+ - Use the canonical test runner and tarball test of the kit.
18
+ - Export `COMMAND_NAME` from `extensions/metadata.ts`. The command name stays `delegate`.
19
+ - Align `package.json` with the standard: every peer is `*`, the dev host packages match pi 1.6.1, `engines.node` is `>=18`.
20
+ - Stop tracking `.planning/`. The files stay on disk, ignored.
package/README.md CHANGED
@@ -10,17 +10,14 @@ structured metadata, full transcript on disk), and can put the parent session
10
10
  into a **strict coordinator mode** where the parent may only delegate — the
11
11
  gate is an allowlist and exceptions fail closed.
12
12
 
13
- ## Install (source of truth: this workspace)
13
+ ## Install
14
14
 
15
15
  ```bash
16
- # development: run from a pi session in this repo
17
- pi # /delegate is auto-discovered from .pi/extensions or ~/.pi/agent/extensions
16
+ pi install npm:@maheidem/pi-delegate@<x.y.z>
18
17
  ```
19
18
 
20
- Register globally by copying/symlinking `custom-extensions/delegate` into
21
- `~/.pi/agent/extensions/delegate` and adding it to
22
- `~/.pi/agent/settings.json → packages`, then `/reload`. No automated install
23
- is performed by this package.
19
+ Use the exact version. Then run `/reload` in each open pi session.
20
+ To try a local checkout without an install, run `pi -e ./extensions/index.ts` in this repo.
24
21
 
25
22
  ## Usage
26
23
 
@@ -48,8 +45,8 @@ Any unrecognized first word is shorthand for `run general …`.
48
45
 
49
46
  ### Terminal UI (v0.3.0)
50
47
 
51
- One centralized experience built on the vendored canonical `SettingsPanel`
52
- (never a bespoke panel). Everything reachable from the panel is also reachable
48
+ One centralized experience built on the `SettingsPanel` of
49
+ `@maheidem/pi-panel-kit` (never a bespoke panel). Everything reachable from the panel is also reachable
53
50
  as a nested command and from headless stdout — the same application method.
54
51
 
55
52
  - **Home dashboard** (`/delegate`, TUI) — health summary (version · mode,
@@ -75,8 +72,7 @@ as a nested command and from headless stdout — the same application method.
75
72
  - **Destructive actions** (cancel, strict on/off) require confirmation.
76
73
 
77
74
  Headless (`pi -p` / child mode) prints the same status/doctor/paths text, so
78
- panel ≡ command ≡ headless. Screens with pixel evidence live in
79
- `.planning/ui-redesign-2026-09-04/evidence/` (see `manifest.json`).
75
+ panel ≡ command ≡ headless. The screen captures of the UI work are not in this repo.
80
76
 
81
77
  ### Timeouts
82
78
 
@@ -284,6 +280,14 @@ never free text we hope has the right shape:
284
280
  apply after `/reload` in that session — the version line makes a stale
285
281
  copy self-evident instead of indistinguishable from a regression.
286
282
 
283
+ ## Configuration
284
+
285
+ - The user config file is `<agent dir>/delegate/config.json`. The agent dir comes from `getAgentDir()` (normally `~/.pi/agent`). The code exports the path as `CONFIG_PATH` from `extensions/config.ts`.
286
+ - A project file `<project>/.pi/delegate/config.json` overlays the user config key by key (see "Timeouts").
287
+ - The run store is `<agent dir>/delegate/runs/`. It keeps the newest `maxRuns` terminal receipts (default 50).
288
+ - `/delegate paths` prints the config file, the run store and the agent dir.
289
+ - The dashboard edits the same keys. A corrupt file is kept as evidence and the defaults load.
290
+
287
291
  ## Safety model (selected invariants)
288
292
 
289
293
  - The delegated task travels over child **RPC stdin**, never argv.
@@ -311,32 +315,63 @@ never free text we hope has the right shape:
311
315
  repairs are recorded on the receipt in a `curationNote` field (one-time
312
316
  2026-09-03 repair: receipts clobbered by pre-0.1.5 orphan recovery and
313
317
  later removed by retention were reconstructed from the parent sessions'
314
- delegate tool results — see `.planning/`, excluded from the npm tarball).
318
+ delegate tool results; the evidence is not in this repo).
315
319
  - Strict mode is session-scoped, replayed per branch (tree/resume/fork safe),
316
320
  persisted via session custom entries; persistence failures degrade loudly
317
321
  but never silently disable the gate.
318
322
  - Research requires a Firecrawl-capable tool path in the parent session;
319
323
  Reddit is supplementary.
320
324
 
325
+ ## Security notes
326
+
327
+ - **Env allowlist for children.** The child process inherits only `PATH`,
328
+ `HOME`, `TMPDIR`, `LANG`/`LC_*`, `TERM`, `USER`, `XDG_*` plus the
329
+ `PI_DELEGATE_*` contract vars (`PI_DELEGATE_CHILD`, `PI_DELEGATE_RUN_ID`,
330
+ `PI_DELEGATE_PARENT_PID`, and the ask-channel vars for background runs).
331
+ Everything else — API keys, tokens, cloud credentials — is dropped. A
332
+ missing `PATH` falls back to a minimal default.
333
+ - **Ask-id validation.** The `ask_parent` tool reads and writes
334
+ `<askDir>/<toolCallId>.json`. The id is validated against a strict
335
+ allowlist (`^[A-Za-z0-9._-]{1,128}$`, no `/`, no `..`); anything else
336
+ fails closed (the read returns null, the write throws). `PI_DELEGATE_ASK_DIR`
337
+ itself is resolved to an absolute path at registration (relative paths are
338
+ resolved against the agent dir and must stay inside it) and created with
339
+ mode `0700`; junk values disable the channel instead of breaking the run.
340
+ - **Timer contract.** Safety timers (hard, inactivity, handoffSettle,
341
+ killEscalate, handoffGrace, handoffEnforce) are NOT `unref()`'d — they
342
+ always get a chance to fire. The only unref'd timer is the periodic
343
+ progress heartbeat (background runs), which must never keep the process
344
+ alive on its own.
345
+ - The run store is `0700` / `0600` files; the child never inherits more
346
+ than the allowlist above. Failures in single-file store reads/writes are
347
+ logged (debug-gated via `PI_DELEGATE_DEBUG=1`) but never fail the run.
348
+
321
349
  ## Development
322
350
 
323
351
  ```bash
352
+ npm install
324
353
  npm run typecheck # strict tsc, no emit
325
- npm test # unit + runner (real RPC children) + application + UI + load
354
+ npm test # tests/run.mjs: each tests/*.test.ts file with an isolated HOME
326
355
  npm run test:e2e # real pi session E2E (needs a working default model)
327
356
  # E2E_SCENARIOS=D,F runs a targeted subset
357
+ npm pack --dry-run # the packed file list
328
358
  ```
329
359
 
330
- Design: `types.ts`/`config.ts`/`mode.ts`/`run-store.ts`/`rpc-jsonl.ts`/
331
- `runner.ts`/`application.ts` are Pi-free domain modules; `index.ts` is the
332
- sole Pi adapter (loads through jiti exactly as pi loads extensions; registers
333
- only `/delegate`, the `delegate` tool, and the `delegate-handoff` renderer).
360
+ `npm test` never starts a live pi. `@maheidem/pi-panel-kit` supplies the generic UI parts and the test runner.
361
+
362
+ Design: the runtime code is in `extensions/`. `types.ts`/`config.ts`/`mode.ts`/`run-store.ts`/`rpc-jsonl.ts`/
363
+ `runner.ts`/`application.ts` are Pi-free domain modules; `extensions/index.ts` is the
364
+ sole Pi adapter (loads through jiti exactly as pi loads extensions). The role prompts are in `roles/`.
334
365
 
335
366
  ## Provenance / attribution
336
367
 
337
368
  Built against `@earendil-works/pi-coding-agent` 0.84.4 and its official
338
- `subagent` and `plan-mode` extension examples (MIT). `ui/settings-panel.ts`
339
- is vendored from the local `/loop` extension's control panel (same author,
340
- same workspace; pi-extension-builder v0.1.0 template). RPC protocol shapes
369
+ `subagent` and `plan-mode` extension examples (MIT). The `SettingsPanel` came
370
+ from the `/loop` extension's control panel (same author). It is now part of
371
+ `@maheidem/pi-panel-kit`. RPC protocol shapes
341
372
  follow the installed pi RPC documentation (`docs/rpc.md`) in
342
373
  `@earendil-works/pi-coding-agent`.
374
+
375
+ ## License
376
+
377
+ MIT
@@ -67,6 +67,50 @@ export function validateAskSubmission(params: unknown): { ok: true; value: AskSu
67
67
  return { ok: true, value: { kind: raw.kind as "question" | "note", topic, text } };
68
68
  }
69
69
 
70
+ /**
71
+ * Strict allowlist for a toolCallId used to build a filename. Anything else
72
+ * (slashes, `..`, leading dots, over-long, control chars) is rejected —
73
+ * fail closed so the id can never escape the ask dir.
74
+ */
75
+ export function assertSafeAskId(id: string): string {
76
+ if (!/^[A-Za-z0-9._-]{1,128}$/.test(id) || id.includes("..") || /^\.+$/.test(id)) {
77
+ throw new Error("E_ASK: unsafe toolCallId");
78
+ }
79
+ return id;
80
+ }
81
+
82
+ /**
83
+ * Resolve and validate the ask_parent env contract for a child process.
84
+ * Returns null when the channel must not be registered (junk/empty askDir).
85
+ * Relative askDir resolves against the agent dir; a relative path that
86
+ * escapes it (e.g. ../) is rejected. Timeout/max are clamped to sane bounds.
87
+ */
88
+ export function resolveAskEnv(
89
+ raw: { askDir?: string; timeoutMs?: string; maxQuestions?: string },
90
+ agentDir: string,
91
+ ): { askDir: string; timeoutMs: number; maxQuestions: number } | null {
92
+ const rawDir = raw.askDir?.trim();
93
+ if (!rawDir || rawDir.includes("\0")) return null;
94
+ let askDir: string;
95
+ if (path.isAbsolute(rawDir)) {
96
+ askDir = path.normalize(rawDir);
97
+ } else {
98
+ const resolved = path.resolve(agentDir, rawDir);
99
+ const root = path.resolve(agentDir);
100
+ if (resolved !== root && !resolved.startsWith(root + path.sep)) return null;
101
+ askDir = resolved;
102
+ }
103
+ const timeoutRaw = Number(raw.timeoutMs);
104
+ const timeoutMs = Number.isFinite(timeoutRaw) && timeoutRaw > 0
105
+ ? Math.min(3_600_000, Math.max(5_000, Math.trunc(timeoutRaw)))
106
+ : 600_000;
107
+ const maxRaw = Number(raw.maxQuestions);
108
+ const maxQuestions = Number.isFinite(maxRaw) && maxRaw > 0
109
+ ? Math.min(20, Math.max(1, Math.trunc(maxRaw)))
110
+ : 5;
111
+ return { askDir, timeoutMs, maxQuestions };
112
+ }
113
+
70
114
  export interface AskEnv {
71
115
  askDir?: string;
72
116
  timeoutMs: number;
@@ -100,6 +144,11 @@ export function registerAskParentTool(pi: ExtensionAPI, env: AskEnv): void {
100
144
  const notesFiled = { count: 0 };
101
145
  const sleep = env.sleep ?? ((ms: number) => new Promise<void>((r) => setTimeout(r, ms)));
102
146
  const readAnswer = env.readAnswer ?? ((toolCallId: string) => {
147
+ try {
148
+ assertSafeAskId(toolCallId);
149
+ } catch {
150
+ return null;
151
+ }
103
152
  const file = path.join(env.askDir ?? "", `${toolCallId}.json`);
104
153
  try {
105
154
  const raw = JSON.parse(fs.readFileSync(file, "utf8")) as { answeredBy?: string; answer?: string };
@@ -186,6 +235,7 @@ export interface AskAnswerFile {
186
235
  }
187
236
 
188
237
  export function writeAskAnswerFile(askDir: string, toolCallId: string, payload: AskAnswerFile): void {
238
+ assertSafeAskId(toolCallId);
189
239
  fs.mkdirSync(askDir, { recursive: true, mode: 0o700 });
190
240
  fs.writeFileSync(path.join(askDir, `${toolCallId}.json`), JSON.stringify(payload), { mode: 0o600 });
191
241
  }
@@ -5,6 +5,7 @@
5
5
 
6
6
  import * as fs from "node:fs";
7
7
  import * as path from "node:path";
8
+ import { getAgentDir } from "@earendil-works/pi-coding-agent";
8
9
  import type { RoleName } from "./types.ts";
9
10
  import { ROLE_NAMES } from "./types.ts";
10
11
 
@@ -117,7 +118,8 @@ const MAX_VALUES: Partial<Record<keyof DelegateConfigV1, number>> = {
117
118
  */
118
119
  export function normalizeConfig(
119
120
  raw: unknown,
120
- ): { config: DelegateConfigV1; unknownKeys: string[] } {
121
+ ): { config: DelegateConfigV1; unknownKeys: string[]; diagnostics: string[] } {
122
+ const diagnostics: string[] = [];
121
123
  const base: DelegateConfigV1 = {
122
124
  ...DEFAULT_DELEGATE_CONFIG,
123
125
  // nested blocks are shared references in the default — copy so a
@@ -148,16 +150,16 @@ export function normalizeConfig(
148
150
  extras[key] = record[key];
149
151
  continue;
150
152
  }
151
- applyKnownField(base, key, record[key]);
153
+ applyKnownField(base, key, record[key], diagnostics);
152
154
  }
153
155
  } else if (raw !== undefined && raw !== null) {
154
156
  throw new Error("config must be a JSON object");
155
157
  }
156
158
 
157
- return { config: base, unknownKeys };
159
+ return { config: base, unknownKeys, diagnostics };
158
160
  }
159
161
 
160
- function applyKnownField(config: DelegateConfigV1, key: string, value: unknown): void {
162
+ function applyKnownField(config: DelegateConfigV1, key: string, value: unknown, diagnostics: string[] = []): void {
161
163
  if (key === "schemaVersion") return;
162
164
  if (key === "defaultRole") {
163
165
  if ((ROLE_NAMES as readonly string[]).includes(String(value))) {
@@ -174,32 +176,66 @@ function applyKnownField(config: DelegateConfigV1, key: string, value: unknown):
174
176
  return;
175
177
  }
176
178
  if (key === "progressReports") {
177
- if (!value || typeof value !== "object" || Array.isArray(value)) return;
179
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
180
+ diagnostics.push("progressReports: expected an object, ignored");
181
+ return;
182
+ }
178
183
  const raw = value as Record<string, unknown>;
179
- if (typeof raw.enabled === "boolean") config.progressReports.enabled = raw.enabled;
180
- if (Number.isFinite(Number(raw.minToolMs))) {
181
- config.progressReports.minToolMs = Math.min(3_600_000, Math.max(5_000, Number(raw.minToolMs)));
184
+ if ("enabled" in raw) {
185
+ if (typeof raw.enabled === "boolean") config.progressReports.enabled = raw.enabled;
186
+ else diagnostics.push("progressReports.enabled: not a boolean, ignored");
187
+ }
188
+ if ("minToolMs" in raw) {
189
+ const n = Number(raw.minToolMs);
190
+ if (Number.isFinite(n)) config.progressReports.minToolMs = Math.min(3_600_000, Math.max(5_000, n));
191
+ else diagnostics.push("progressReports.minToolMs: not a finite number, ignored");
182
192
  }
183
- if (Number.isFinite(Number(raw.intervalMs))) {
184
- config.progressReports.intervalMs = Math.min(3_600_000, Math.max(60_000, Number(raw.intervalMs)));
193
+ if ("intervalMs" in raw) {
194
+ const n = Number(raw.intervalMs);
195
+ if (Number.isFinite(n)) config.progressReports.intervalMs = Math.min(3_600_000, Math.max(60_000, n));
196
+ else diagnostics.push("progressReports.intervalMs: not a finite number, ignored");
185
197
  }
186
- if (Number.isFinite(Number(raw.minGapMs))) {
187
- config.progressReports.minGapMs = Math.min(1_800_000, Math.max(30_000, Number(raw.minGapMs)));
198
+ if ("minGapMs" in raw) {
199
+ const n = Number(raw.minGapMs);
200
+ if (Number.isFinite(n)) config.progressReports.minGapMs = Math.min(1_800_000, Math.max(30_000, n));
201
+ else diagnostics.push("progressReports.minGapMs: not a finite number, ignored");
188
202
  }
189
- if (Number.isFinite(Number(raw.maxPerRun))) {
190
- config.progressReports.maxPerRun = Math.min(20, Math.max(1, Math.trunc(Number(raw.maxPerRun))));
203
+ if ("maxPerRun" in raw) {
204
+ const n = Number(raw.maxPerRun);
205
+ if (Number.isFinite(n)) config.progressReports.maxPerRun = Math.min(20, Math.max(1, Math.trunc(n)));
206
+ else diagnostics.push("progressReports.maxPerRun: not a finite number, ignored");
207
+ }
208
+ for (const k of Object.keys(raw)) {
209
+ if (!["enabled","minToolMs","intervalMs","minGapMs","maxPerRun"].includes(k)) {
210
+ diagnostics.push(`progressReports.${k}: unknown nested key, ignored`);
211
+ }
191
212
  }
192
213
  return;
193
214
  }
194
215
  if (key === "askParent") {
195
- if (!value || typeof value !== "object" || Array.isArray(value)) return;
216
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
217
+ diagnostics.push("askParent: expected an object, ignored");
218
+ return;
219
+ }
196
220
  const raw = value as Record<string, unknown>;
197
- if (typeof raw.enabled === "boolean") config.askParent.enabled = raw.enabled;
198
- if (Number.isFinite(Number(raw.timeoutMs))) {
199
- config.askParent.timeoutMs = Math.min(3_600_000, Math.max(5_000, Number(raw.timeoutMs)));
221
+ if ("enabled" in raw) {
222
+ if (typeof raw.enabled === "boolean") config.askParent.enabled = raw.enabled;
223
+ else diagnostics.push("askParent.enabled: not a boolean, ignored");
200
224
  }
201
- if (Number.isFinite(Number(raw.maxPerRun))) {
202
- config.askParent.maxPerRun = Math.min(20, Math.max(1, Math.trunc(Number(raw.maxPerRun))));
225
+ if ("timeoutMs" in raw) {
226
+ const n = Number(raw.timeoutMs);
227
+ if (Number.isFinite(n)) config.askParent.timeoutMs = Math.min(3_600_000, Math.max(5_000, n));
228
+ else diagnostics.push("askParent.timeoutMs: not a finite number, ignored");
229
+ }
230
+ if ("maxPerRun" in raw) {
231
+ const n = Number(raw.maxPerRun);
232
+ if (Number.isFinite(n)) config.askParent.maxPerRun = Math.min(20, Math.max(1, Math.trunc(n)));
233
+ else diagnostics.push("askParent.maxPerRun: not a finite number, ignored");
234
+ }
235
+ for (const k of Object.keys(raw)) {
236
+ if (!["enabled","timeoutMs","maxPerRun"].includes(k)) {
237
+ diagnostics.push(`askParent.${k}: unknown nested key, ignored`);
238
+ }
203
239
  }
204
240
  return;
205
241
  }
@@ -213,6 +249,9 @@ function applyKnownField(config: DelegateConfigV1, key: string, value: unknown):
213
249
  ) as never;
214
250
  }
215
251
 
252
+ /** The config file of this extension: `<agent dir>/delegate/config.json`. */
253
+ export const CONFIG_PATH = path.join(getAgentDir(), "delegate", "config.json");
254
+
216
255
  export interface ConfigLoadResult {
217
256
  config: DelegateConfigV1;
218
257
  unknownKeys: string[];
@@ -21,11 +21,12 @@ import {
21
21
  } from "@earendil-works/pi-coding-agent";
22
22
  import { Text } from "@earendil-works/pi-tui";
23
23
 
24
- import { formatDuration, loadConfig, parseDuration, saveConfig } from "./config.ts";
24
+ import { CONFIG_PATH, formatDuration, loadConfig, parseDuration, saveConfig } from "./config.ts";
25
+ import { COMMAND_NAME } from "./metadata.ts";
25
26
  import * as fsSync from "node:fs";
26
27
  import { delegateVersion } from "./version.ts";
27
28
  import { HandoffToolParams, validateHandoffSubmission, type HandoffSubmission } from "./handoff.ts";
28
- import { CHILD_NOTE_TYPE, CHILD_QUESTION_TYPE, registerAskParentTool } from "./ask.ts";
29
+ import { CHILD_NOTE_TYPE, CHILD_QUESTION_TYPE, registerAskParentTool, resolveAskEnv } from "./ask.ts";
29
30
  import { parseDelegateCommand, delegateCompletions, type DelegateIntent } from "./commands.ts";
30
31
  import { DELEGATE_ROLES, isRoleName, resolveRole } from "./roles.ts";
31
32
  import { STRICT_OVERLAY, STRICT_ACTIVE_TOOLS, syncStrictToolSet, resetBlockedCounters } from "./mode.ts";
@@ -39,9 +40,9 @@ import type {
39
40
  RunStreamUpdate,
40
41
  SessionEntryLike,
41
42
  } from "./types.ts";
42
- import { SettingsPanel, type PanelSnapshot, type PanelActionResult, type PanelSection, type PanelRow } from "./ui/settings-panel.ts";
43
- import { shortModel, formatTokens, formatCost, stateGlyph, progressBar, projectValueCell } from "./ui/format.ts";
44
- import { renderToolCallCard, renderToolPlainCard, renderToolResultCard, type ToolCardLine } from "./ui/tool-card.ts";
43
+ import { SettingsPanel, type PanelSnapshot, type PanelActionResult, type PanelSection, type PanelRow } from "@maheidem/pi-panel-kit";
44
+ import { shortModel, formatTokens, formatCost, stateGlyph, progressBar, projectValueCell } from "@maheidem/pi-panel-kit";
45
+ import { renderToolCallCard, renderToolPlainCard, renderToolResultCard, type ToolCardLine } from "@maheidem/pi-panel-kit";
45
46
  import { RunningView, type RunningViewState } from "./ui/running-view.ts";
46
47
  import { PeekView } from "./ui/peek-view.ts";
47
48
  import { FeedRing, feedEventsFromTranscript, renderFeedEvents } from "./transcript-feed.ts";
@@ -200,21 +201,33 @@ export default function delegateExtension(pi: ExtensionAPI) {
200
201
  // R17/R18: background children get the ask_parent channel (a
201
202
  // foreground child asking would deadlock the parent turn by
202
203
  // construction — enforced here at registration, not by prompt).
203
- const askDir = process.env.PI_DELEGATE_ASK_DIR;
204
- if (askDir) {
205
- registerAskParentTool(pi, {
206
- askDir,
207
- timeoutMs: Number(process.env.PI_DELEGATE_ASK_TIMEOUT_MS) > 0 ? Number(process.env.PI_DELEGATE_ASK_TIMEOUT_MS) : 600_000,
208
- maxQuestions: Number(process.env.PI_DELEGATE_ASK_MAX) > 0 ? Number(process.env.PI_DELEGATE_ASK_MAX) : 5,
209
- });
204
+ const askAgentDir = process.env.PI_DELEGATE_AGENT_DIR || getAgentDir();
205
+ const ask = resolveAskEnv(
206
+ {
207
+ askDir: process.env.PI_DELEGATE_ASK_DIR,
208
+ timeoutMs: process.env.PI_DELEGATE_ASK_TIMEOUT_MS,
209
+ maxQuestions: process.env.PI_DELEGATE_ASK_MAX,
210
+ },
211
+ askAgentDir,
212
+ );
213
+ if (ask) {
214
+ try {
215
+ fsSync.mkdirSync(ask.askDir, { recursive: true, mode: 0o700 });
216
+ } catch {
217
+ // read-only/unwritable ask dir — fail closed below.
218
+ }
219
+ registerAskParentTool(pi, ask);
210
220
  }
211
221
  return;
212
222
  }
213
223
  // 2. Construct state — no child, no timers at load time.
214
224
  // PI_DELEGATE_AGENT_DIR is a test override; production uses getAgentDir().
215
- const agentDir = process.env.PI_DELEGATE_AGENT_DIR || getAgentDir();
225
+ const agentDirOverride = process.env.PI_DELEGATE_AGENT_DIR;
226
+ const agentDir = agentDirOverride || getAgentDir();
216
227
  const { config, unknownKeys, recoveredFromCorrupt, corruptEvidencePath } = loadConfig(agentDir);
217
228
  const app = new DelegateApplicationImpl({ agentDir, config });
229
+ // The paths verb prints CONFIG_PATH. The test override moves the file below its own dir.
230
+ const configPath = agentDirOverride ? app.paths().configPath : CONFIG_PATH;
218
231
  // Startup orphan recovery (§10.6): receipts only; never kills PIDs.
219
232
  app.markOrphansOnStartup();
220
233
 
@@ -1178,7 +1191,7 @@ export default function delegateExtension(pi: ExtensionAPI) {
1178
1191
 
1179
1192
  // ── 4. /delegate command ───────────────────────────────────────────────
1180
1193
 
1181
- pi.registerCommand("delegate", {
1194
+ pi.registerCommand(COMMAND_NAME, {
1182
1195
  description: "Delegate tasks to isolated child Pi sessions; strict delegation mode gate.",
1183
1196
  getArgumentCompletions: (prefix: string) => {
1184
1197
  const items = delegateCompletions(prefix, app.recentRunIds(6)).map((v) => ({ value: v, label: v }));
@@ -1192,7 +1205,7 @@ export default function delegateExtension(pi: ExtensionAPI) {
1192
1205
  return;
1193
1206
  case "paths": {
1194
1207
  const p = app.paths();
1195
- say(ctx, ["[delegate paths]", `config: ${p.configPath}`, `runs: ${p.runsDir}`, `agent: ${p.agentDir}`].join("\n"));
1208
+ say(ctx, ["[delegate paths]", `config: ${configPath}`, `runs: ${p.runsDir}`, `agent: ${p.agentDir}`].join("\n"));
1196
1209
  return;
1197
1210
  }
1198
1211
  case "doctor":
@@ -1664,7 +1677,7 @@ export default function delegateExtension(pi: ExtensionAPI) {
1664
1677
  }
1665
1678
  if (action === "paths") {
1666
1679
  const p = app.paths();
1667
- say(ctx, [`[delegate paths]`, `config: ${p.configPath}`, `runs: ${p.runsDir}`].join("\n"));
1680
+ say(ctx, [`[delegate paths]`, `config: ${configPath}`, `runs: ${p.runsDir}`].join("\n"));
1668
1681
  continue;
1669
1682
  }
1670
1683
  if (action === "inspect-last") {
@@ -0,0 +1,2 @@
1
+ /** Names that pi sees. Keep them stable: users and scripts type them. */
2
+ export const COMMAND_NAME = "delegate";
@@ -12,7 +12,8 @@ import * as url from "node:url";
12
12
  import type { DelegateRole, RoleName } from "./types.ts";
13
13
  import { ROLE_NAMES } from "./types.ts";
14
14
 
15
- const HERE = path.dirname(url.fileURLToPath(import.meta.url));
15
+ // The roles/ folder is at the package root, one level above extensions/.
16
+ const HERE = path.dirname(path.dirname(url.fileURLToPath(import.meta.url)));
16
17
 
17
18
  const GENERAL_TOOLS = ["read", "bash", "edit", "write", "grep", "find", "ls"] as const;
18
19
  const RESEARCH_TOOLS = [
@@ -22,6 +22,16 @@ import type {
22
22
  import { EMPTY_USAGE, isTerminalRunState } from "./types.ts";
23
23
  import { atomicWriteJson } from "./config.ts";
24
24
 
25
+ /** Debug-gated, secret-free diagnostic for non-fatal store failures. */
26
+ export function logStoreError(operation: string, error: unknown): void {
27
+ if (process.env.PI_DELEGATE_DEBUG !== "1" && process.env.PI_DELEGATE_DEBUG !== "true") return;
28
+ try {
29
+ console.error(`[delegate] run-store: ${operation}: ${(error as Error)?.message ?? String(error)}`);
30
+ } catch {
31
+ // never throw from a diagnostic path
32
+ }
33
+ }
34
+
25
35
  export function makeRunId(now: Date = new Date()): string {
26
36
  // del_<UTC-basic-timestamp>_<8-random-hex>, e.g. del_20260901T143022Z_a1b2c3d4
27
37
  const stamp = now.toISOString().replace(/[-:]/g, "").replace(/\.\d{3}Z$/, "Z");
@@ -55,8 +65,9 @@ function ensurePrivateDir(dir: string): void {
55
65
  // mkdir mode does not re-tighten existing directories; enforce 0700.
56
66
  try {
57
67
  fs.chmodSync(dir, 0o700);
58
- } catch {
68
+ } catch (error) {
59
69
  // best effort on platforms without POSIX chmod semantics
70
+ logStoreError("ensurePrivateDir chmod", error);
60
71
  }
61
72
  }
62
73
 
@@ -197,7 +208,8 @@ export function readRunMetadata(agentDir: string, runId: string): RunMetadataV1
197
208
  const paths = runPaths(agentDir, runId);
198
209
  try {
199
210
  return JSON.parse(fs.readFileSync(paths.metadataPath, "utf8")) as RunMetadataV1;
200
- } catch {
211
+ } catch (error) {
212
+ logStoreError("readRunMetadata", error);
201
213
  return null;
202
214
  }
203
215
  }
@@ -222,7 +234,8 @@ export function listRuns(agentDir: string, limit = 50): RunSummary[] {
222
234
  let names: string[];
223
235
  try {
224
236
  names = fs.readdirSync(p.runsDir);
225
- } catch {
237
+ } catch (error) {
238
+ logStoreError("listRuns readdir", error);
226
239
  return [];
227
240
  }
228
241
  const summaries: RunSummary[] = [];
@@ -239,7 +252,8 @@ export function listRuns(agentDir: string, limit = 50): RunSummary[] {
239
252
  let mtimeMs = 0;
240
253
  try {
241
254
  mtimeMs = fs.statSync(path.join(p.runsDir, name)).mtimeMs;
242
- } catch {
255
+ } catch (error) {
256
+ logStoreError("listRuns stat", error);
243
257
  mtimeMs = 0;
244
258
  }
245
259
  summaries.push({
@@ -257,8 +271,9 @@ export function listRuns(agentDir: string, limit = 50): RunSummary[] {
257
271
  ...(meta.background ? { background: true } : {}),
258
272
  ...(meta.description ? { description: meta.description } : {}),
259
273
  });
260
- } catch {
274
+ } catch (error) {
261
275
  // unreadable metadata: leave alone; retention will not touch it
276
+ logStoreError("listRuns metadata", error);
262
277
  }
263
278
  }
264
279
  summaries.sort((a, b) => b.mtimeMs - a.mtimeMs || (b.createdAt > a.createdAt ? 1 : -1));
@@ -294,7 +309,8 @@ export function pidCommandLine(pid: number): string | null {
294
309
  .replace(/\0+/g, " ")
295
310
  .trim();
296
311
  return text.length > 0 ? text : null;
297
- } catch {
312
+ } catch (error) {
313
+ logStoreError("pidCommandLine /proc", error);
298
314
  return null;
299
315
  }
300
316
  }
@@ -306,7 +322,8 @@ export function pidCommandLine(pid: number): string | null {
306
322
  if (out.error || out.status !== 0) return null;
307
323
  const text = (out.stdout ?? "").trim();
308
324
  return text.length > 0 ? text : null;
309
- } catch {
325
+ } catch (error) {
326
+ logStoreError("pidCommandLine ps", error);
310
327
  return null;
311
328
  }
312
329
  }
@@ -367,8 +384,9 @@ export function markOrphanedRuns(agentDir: string): string[] {
367
384
  }));
368
385
  if (next.state === "crashed") touched.push(summary.runId);
369
386
  }
370
- } catch {
387
+ } catch (error) {
371
388
  // skip
389
+ logStoreError("markOrphanedRuns", error);
372
390
  }
373
391
  }
374
392
  return touched;
@@ -393,6 +411,7 @@ export function enforceRetention(
393
411
  try {
394
412
  all = listRuns(agentDir, 10_000);
395
413
  } catch (error) {
414
+ logStoreError("enforceRetention listRuns", error);
396
415
  return { removed: 0, warnings: [`E_STORE: could not list runs: ${(error as Error).message}`] };
397
416
  }
398
417
 
@@ -423,6 +442,7 @@ export function enforceRetention(
423
442
  }
424
443
  removed += 1;
425
444
  } catch (error) {
445
+ logStoreError("enforceRetention remove", error);
426
446
  warnings.push(
427
447
  `E_STORE: retention could not remove ${candidate.runId}: ${(error as Error).message}`,
428
448
  );