@maheidem/pi-delegate 0.8.0 → 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 +9 -0
- package/README.md +24 -0
- package/extensions/ask.ts +50 -0
- package/extensions/config.ts +55 -20
- package/extensions/index.ts +17 -8
- package/extensions/run-store.ts +28 -8
- package/extensions/runner.ts +36 -22
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,14 @@
|
|
|
1
1
|
# Changelog
|
|
2
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
|
+
|
|
3
12
|
## [0.8.0]
|
|
4
13
|
|
|
5
14
|
- Move the runtime code to `extensions/`. The pi entry is `./extensions/index.ts`.
|
package/README.md
CHANGED
|
@@ -322,6 +322,30 @@ never free text we hope has the right shape:
|
|
|
322
322
|
- Research requires a Firecrawl-capable tool path in the parent session;
|
|
323
323
|
Reddit is supplementary.
|
|
324
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
|
+
|
|
325
349
|
## Development
|
|
326
350
|
|
|
327
351
|
```bash
|
package/extensions/ask.ts
CHANGED
|
@@ -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
|
}
|
package/extensions/config.ts
CHANGED
|
@@ -118,7 +118,8 @@ const MAX_VALUES: Partial<Record<keyof DelegateConfigV1, number>> = {
|
|
|
118
118
|
*/
|
|
119
119
|
export function normalizeConfig(
|
|
120
120
|
raw: unknown,
|
|
121
|
-
): { config: DelegateConfigV1; unknownKeys: string[] } {
|
|
121
|
+
): { config: DelegateConfigV1; unknownKeys: string[]; diagnostics: string[] } {
|
|
122
|
+
const diagnostics: string[] = [];
|
|
122
123
|
const base: DelegateConfigV1 = {
|
|
123
124
|
...DEFAULT_DELEGATE_CONFIG,
|
|
124
125
|
// nested blocks are shared references in the default — copy so a
|
|
@@ -149,16 +150,16 @@ export function normalizeConfig(
|
|
|
149
150
|
extras[key] = record[key];
|
|
150
151
|
continue;
|
|
151
152
|
}
|
|
152
|
-
applyKnownField(base, key, record[key]);
|
|
153
|
+
applyKnownField(base, key, record[key], diagnostics);
|
|
153
154
|
}
|
|
154
155
|
} else if (raw !== undefined && raw !== null) {
|
|
155
156
|
throw new Error("config must be a JSON object");
|
|
156
157
|
}
|
|
157
158
|
|
|
158
|
-
return { config: base, unknownKeys };
|
|
159
|
+
return { config: base, unknownKeys, diagnostics };
|
|
159
160
|
}
|
|
160
161
|
|
|
161
|
-
function applyKnownField(config: DelegateConfigV1, key: string, value: unknown): void {
|
|
162
|
+
function applyKnownField(config: DelegateConfigV1, key: string, value: unknown, diagnostics: string[] = []): void {
|
|
162
163
|
if (key === "schemaVersion") return;
|
|
163
164
|
if (key === "defaultRole") {
|
|
164
165
|
if ((ROLE_NAMES as readonly string[]).includes(String(value))) {
|
|
@@ -175,32 +176,66 @@ function applyKnownField(config: DelegateConfigV1, key: string, value: unknown):
|
|
|
175
176
|
return;
|
|
176
177
|
}
|
|
177
178
|
if (key === "progressReports") {
|
|
178
|
-
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
179
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
180
|
+
diagnostics.push("progressReports: expected an object, ignored");
|
|
181
|
+
return;
|
|
182
|
+
}
|
|
179
183
|
const raw = value as Record<string, unknown>;
|
|
180
|
-
if (
|
|
181
|
-
|
|
182
|
-
|
|
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");
|
|
183
192
|
}
|
|
184
|
-
if (
|
|
185
|
-
|
|
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");
|
|
186
197
|
}
|
|
187
|
-
if (
|
|
188
|
-
|
|
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");
|
|
189
202
|
}
|
|
190
|
-
if (
|
|
191
|
-
|
|
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
|
+
}
|
|
192
212
|
}
|
|
193
213
|
return;
|
|
194
214
|
}
|
|
195
215
|
if (key === "askParent") {
|
|
196
|
-
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
216
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
217
|
+
diagnostics.push("askParent: expected an object, ignored");
|
|
218
|
+
return;
|
|
219
|
+
}
|
|
197
220
|
const raw = value as Record<string, unknown>;
|
|
198
|
-
if (
|
|
199
|
-
|
|
200
|
-
|
|
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");
|
|
224
|
+
}
|
|
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");
|
|
201
229
|
}
|
|
202
|
-
if (
|
|
203
|
-
|
|
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
|
+
}
|
|
204
239
|
}
|
|
205
240
|
return;
|
|
206
241
|
}
|
package/extensions/index.ts
CHANGED
|
@@ -26,7 +26,7 @@ import { COMMAND_NAME } from "./metadata.ts";
|
|
|
26
26
|
import * as fsSync from "node:fs";
|
|
27
27
|
import { delegateVersion } from "./version.ts";
|
|
28
28
|
import { HandoffToolParams, validateHandoffSubmission, type HandoffSubmission } from "./handoff.ts";
|
|
29
|
-
import { CHILD_NOTE_TYPE, CHILD_QUESTION_TYPE, registerAskParentTool } from "./ask.ts";
|
|
29
|
+
import { CHILD_NOTE_TYPE, CHILD_QUESTION_TYPE, registerAskParentTool, resolveAskEnv } from "./ask.ts";
|
|
30
30
|
import { parseDelegateCommand, delegateCompletions, type DelegateIntent } from "./commands.ts";
|
|
31
31
|
import { DELEGATE_ROLES, isRoleName, resolveRole } from "./roles.ts";
|
|
32
32
|
import { STRICT_OVERLAY, STRICT_ACTIVE_TOOLS, syncStrictToolSet, resetBlockedCounters } from "./mode.ts";
|
|
@@ -201,13 +201,22 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
201
201
|
// R17/R18: background children get the ask_parent channel (a
|
|
202
202
|
// foreground child asking would deadlock the parent turn by
|
|
203
203
|
// construction — enforced here at registration, not by prompt).
|
|
204
|
-
const
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
askDir,
|
|
208
|
-
timeoutMs:
|
|
209
|
-
maxQuestions:
|
|
210
|
-
}
|
|
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);
|
|
211
220
|
}
|
|
212
221
|
return;
|
|
213
222
|
}
|
package/extensions/run-store.ts
CHANGED
|
@@ -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
|
);
|
package/extensions/runner.ts
CHANGED
|
@@ -2,7 +2,11 @@
|
|
|
2
2
|
* delegate — child process + RPC lifecycle for one foreground run.
|
|
3
3
|
*
|
|
4
4
|
* Owns exactly one child `pi` process per run (FR-007, POL-007): owned,
|
|
5
|
-
* tracked, killable; never detached
|
|
5
|
+
* tracked, killable; never detached. Safety timers (hard, inactivity,
|
|
6
|
+
* handoffSettle, killEscalate, handoffGrace, handoffEnforce) are NOT unref'd
|
|
7
|
+
* so they can always fire before exit; only the progress heartbeat
|
|
8
|
+
* (background runs) is unref'd — it is the sole detached timer and may never
|
|
9
|
+
* keep the process alive on its own. The task travels over RPC
|
|
6
10
|
* stdin, never argv (POL-004). The full stdout capture and stderr stay on
|
|
7
11
|
* disk; only a bounded handoff + diagnostics return to the caller
|
|
8
12
|
* (FR-013/FR-014).
|
|
@@ -142,6 +146,35 @@ export interface RunnerSpawnRequest {
|
|
|
142
146
|
askMaxQuestions?: number;
|
|
143
147
|
}
|
|
144
148
|
|
|
149
|
+
/**
|
|
150
|
+
* Explicit env allowlist for the untrusted child: only PATH, HOME, TMPDIR,
|
|
151
|
+
* LANG/LC_*, TERM, USER (plus XDG_*) and the PI_DELEGATE_* contract vars.
|
|
152
|
+
* Everything else the parent has (API keys, tokens, cloud creds) is dropped.
|
|
153
|
+
*/
|
|
154
|
+
export function buildChildEnv(req: RunnerSpawnRequest, askEnabled: boolean): NodeJS.ProcessEnv {
|
|
155
|
+
const env: NodeJS.ProcessEnv = {};
|
|
156
|
+
for (const [key, value] of Object.entries(process.env)) {
|
|
157
|
+
if (value === undefined) continue;
|
|
158
|
+
if (
|
|
159
|
+
key === "PATH" || key === "HOME" || key === "TMPDIR" || key === "TERM" || key === "USER" ||
|
|
160
|
+
key === "LANG" || key.startsWith("LC_") || key.startsWith("XDG_")
|
|
161
|
+
) {
|
|
162
|
+
env[key] = value;
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
env.PATH = env.PATH ?? "/usr/local/bin:/usr/bin:/bin";
|
|
166
|
+
env.PI_DELEGATE_CHILD = "1";
|
|
167
|
+
env.PI_DELEGATE_RUN_ID = req.runId;
|
|
168
|
+
env.PI_DELEGATE_PARENT_PID = String(process.pid);
|
|
169
|
+
if (askEnabled) {
|
|
170
|
+
env.PI_DELEGATE_BACKGROUND = "1";
|
|
171
|
+
env.PI_DELEGATE_ASK_DIR = req.askDir;
|
|
172
|
+
env.PI_DELEGATE_ASK_TIMEOUT_MS = String(req.askTimeoutMs);
|
|
173
|
+
env.PI_DELEGATE_ASK_MAX = String(req.askMaxQuestions ?? 5);
|
|
174
|
+
}
|
|
175
|
+
return env;
|
|
176
|
+
}
|
|
177
|
+
|
|
145
178
|
export function buildChildArgs(
|
|
146
179
|
req: RunnerSpawnRequest,
|
|
147
180
|
role: DelegateRole,
|
|
@@ -168,20 +201,7 @@ export function buildChildArgs(
|
|
|
168
201
|
args.push("--no-skills", "--no-prompt-templates", "--no-themes");
|
|
169
202
|
args.push("--append-system-prompt", role.promptPath);
|
|
170
203
|
args.push(req.projectTrusted ? "--approve" : "--no-approve");
|
|
171
|
-
const env
|
|
172
|
-
...process.env,
|
|
173
|
-
PI_DELEGATE_CHILD: "1",
|
|
174
|
-
PI_DELEGATE_RUN_ID: req.runId,
|
|
175
|
-
PI_DELEGATE_PARENT_PID: String(process.pid),
|
|
176
|
-
...(askEnabled
|
|
177
|
-
? {
|
|
178
|
-
PI_DELEGATE_BACKGROUND: "1",
|
|
179
|
-
PI_DELEGATE_ASK_DIR: req.askDir,
|
|
180
|
-
PI_DELEGATE_ASK_TIMEOUT_MS: String(req.askTimeoutMs),
|
|
181
|
-
PI_DELEGATE_ASK_MAX: String(req.askMaxQuestions ?? 5),
|
|
182
|
-
}
|
|
183
|
-
: {}),
|
|
184
|
-
};
|
|
204
|
+
const env = buildChildEnv(req, askEnabled);
|
|
185
205
|
return { args, env, promptId: `delegate:${req.runId}:prompt` };
|
|
186
206
|
}
|
|
187
207
|
|
|
@@ -475,7 +495,6 @@ export class DelegateRunner {
|
|
|
475
495
|
// Timers: inactivity (reset by activity) + hard (from spawn).
|
|
476
496
|
this.armInactivity();
|
|
477
497
|
this.hardTimer = setTimeout(() => this.cancel("timed_out_hard"), this.cfg.hardTimeoutMs);
|
|
478
|
-
this.hardTimer.unref();
|
|
479
498
|
|
|
480
499
|
// R23: progress-report heartbeat (background runs only — the hook is
|
|
481
500
|
// wired solely by the background spawn path).
|
|
@@ -546,7 +565,6 @@ export class DelegateRunner {
|
|
|
546
565
|
? this.cfg.stuckToolTimeoutMs ?? this.cfg.hardTimeoutMs
|
|
547
566
|
: this.cfg.inactivityTimeoutMs;
|
|
548
567
|
this.inactivityTimer = setTimeout(() => this.cancel("timed_out_idle"), budget);
|
|
549
|
-
this.inactivityTimer.unref();
|
|
550
568
|
}
|
|
551
569
|
|
|
552
570
|
private handleRecord(record: RpcRecord): void {
|
|
@@ -855,7 +873,6 @@ export class DelegateRunner {
|
|
|
855
873
|
this.handoffPhase = "none";
|
|
856
874
|
this.startKillEscalation(0);
|
|
857
875
|
}, stepMs);
|
|
858
|
-
this.handoffSettleTimer.unref();
|
|
859
876
|
}
|
|
860
877
|
|
|
861
878
|
/** SIGTERM → killGrace → SIGKILL escalation (one shared implementation). */
|
|
@@ -877,7 +894,6 @@ export class DelegateRunner {
|
|
|
877
894
|
}
|
|
878
895
|
}, this.cfg.killGraceMs);
|
|
879
896
|
}, delayMs);
|
|
880
|
-
this.killEscalateTimer.unref();
|
|
881
897
|
}
|
|
882
898
|
|
|
883
899
|
/** R2: the child settled after our abort — offer it the handoff prompt. */
|
|
@@ -902,7 +918,6 @@ export class DelegateRunner {
|
|
|
902
918
|
if (this.cancelRequested) this.finish(this.cancelRequested, undefined, this.partialHandoffExtra());
|
|
903
919
|
}
|
|
904
920
|
}, grace);
|
|
905
|
-
this.handoffGraceTimer.unref();
|
|
906
921
|
}
|
|
907
922
|
|
|
908
923
|
/** R2: build the partial-handoff `extra`. The structured submission
|
|
@@ -1008,8 +1023,7 @@ export class DelegateRunner {
|
|
|
1008
1023
|
this.handoffPhase = "none";
|
|
1009
1024
|
this.finalizeFreeTextFallback();
|
|
1010
1025
|
}, this.cfg.handoffEnforceTimeoutMs ?? 60_000);
|
|
1011
|
-
|
|
1012
|
-
return; // wait for the enforcement turn to settle
|
|
1026
|
+
return; // wait for the enforcement turn to settle
|
|
1013
1027
|
}
|
|
1014
1028
|
}
|
|
1015
1029
|
if (!final || !final.text.trim()) {
|