@maheidem/pi-delegate 0.1.3 → 0.1.5
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 +26 -1
- package/application.ts +85 -19
- package/commands.ts +1 -1
- package/config.ts +79 -0
- package/index.ts +58 -6
- package/package.json +1 -1
- package/run-store.ts +96 -10
- package/runner.ts +39 -5
- package/types.ts +21 -1
package/README.md
CHANGED
|
@@ -59,6 +59,14 @@ Three levels, highest priority first:
|
|
|
59
59
|
3. **User-wide** — `~/.pi/agent/delegate/config.json`
|
|
60
60
|
(`hardTimeoutMs` default 30 min, `inactivityTimeoutMs` default 5 min).
|
|
61
61
|
|
|
62
|
+
The dashboard (`/delegate`) shows the effective base timeout with its source
|
|
63
|
+
(`user-wide` or `project`) and has an editable **Timeouts (base)** section:
|
|
64
|
+
`Hard · user-wide`, `Hard · project` (merges one key into
|
|
65
|
+
`<project>/.pi/delegate/config.json`), and `Idle · user-wide` (the no-output
|
|
66
|
+
watchdog, capped at half of the hard timeout for any source). Inputs accept
|
|
67
|
+
durations (`30m`, `2h`, `1d`) or bare ms. Headless `/delegate status` prints
|
|
68
|
+
the same base-timeout line.
|
|
69
|
+
|
|
62
70
|
Tool (`delegate`) is available to models: same semantics, JSON result with
|
|
63
71
|
`ok`/`handoff`/`details` (usage, paths, state) or structured `error`.
|
|
64
72
|
|
|
@@ -72,8 +80,24 @@ Tool (`delegate`) is available to models: same semantics, JSON result with
|
|
|
72
80
|
ignored, never dropped.
|
|
73
81
|
- Cancellation is idempotent (first wins): RPC abort → SIGTERM → SIGKILL;
|
|
74
82
|
every finalization reaps the child exactly once.
|
|
83
|
+
- Startup orphan recovery only marks a nonterminal run `crashed` /
|
|
84
|
+
`E_ORPHANED_RUN` when its stored pid is dead or provably not a pi process
|
|
85
|
+
(recycled pid). A live pi process owns its runs — a concurrent pi session
|
|
86
|
+
(the multi-session pattern) never clobbers a run that another live pi
|
|
87
|
+
process is running or finalizing; live pids with unreadable command lines
|
|
88
|
+
are left alone (fail-safe, never clobber on doubt). This process never kills
|
|
89
|
+
a pid it finds in stale metadata.
|
|
90
|
+
- Every terminal failure state carries a specific error payload: timeout and
|
|
91
|
+
cancel states reached without one (timers, user cancels) synthesize
|
|
92
|
+
`E_TIMEOUT_IDLE` / `E_TIMEOUT_HARD` / `E_CANCELLED` with a descriptive
|
|
93
|
+
message at finalization, in both the receipt and the tool text — the error
|
|
94
|
+
line never degrades to `unknown failure`.
|
|
75
95
|
- Run-store is `0700` with `0600` receipt/transcript/stderr files; corrupt
|
|
76
|
-
config is preserved as evidence and defaults are loaded.
|
|
96
|
+
config is preserved as evidence and defaults are loaded. Manual data
|
|
97
|
+
repairs are recorded on the receipt in a `curationNote` field (one-time
|
|
98
|
+
2026-09-03 repair: receipts clobbered by pre-0.1.5 orphan recovery and
|
|
99
|
+
later removed by retention were reconstructed from the parent sessions'
|
|
100
|
+
delegate tool results — see `.planning/`, excluded from the npm tarball).
|
|
77
101
|
- Strict mode is session-scoped, replayed per branch (tree/resume/fork safe),
|
|
78
102
|
persisted via session custom entries; persistence failures degrade loudly
|
|
79
103
|
but never silently disable the gate.
|
|
@@ -86,6 +110,7 @@ Tool (`delegate`) is available to models: same semantics, JSON result with
|
|
|
86
110
|
npm run typecheck # strict tsc, no emit
|
|
87
111
|
npm test # unit + runner (real RPC children) + application + UI + load
|
|
88
112
|
npm run test:e2e # real pi session E2E (needs a working default model)
|
|
113
|
+
# E2E_SCENARIOS=D,F runs a targeted subset
|
|
89
114
|
```
|
|
90
115
|
|
|
91
116
|
Design: `types.ts`/`config.ts`/`mode.ts`/`run-store.ts`/`rpc-jsonl.ts`/
|
package/application.ts
CHANGED
|
@@ -33,10 +33,8 @@ import type {
|
|
|
33
33
|
SessionEntryLike,
|
|
34
34
|
} from "./types.ts";
|
|
35
35
|
import { decodeTranscriptRecord } from "./types.ts";
|
|
36
|
-
import { applyProjectOverlay,
|
|
36
|
+
import { applyProjectOverlay, clampConfigField, formatDuration, normalizeConfig, parseDuration, projectConfigPath, resolveRunTimeouts, saveConfig, saveProjectConfig, type DelegateConfigV1 } from "./config.ts";
|
|
37
37
|
import { EMPTY_USAGE } from "./types.ts";
|
|
38
|
-
|
|
39
|
-
const MIN_INACTIVITY = 1_000;
|
|
40
38
|
import { isRoleName, resolveRole, rolePromptExists, DELEGATE_ROLES } from "./roles.ts";
|
|
41
39
|
import {
|
|
42
40
|
replayModeEntries,
|
|
@@ -116,8 +114,8 @@ export class DelegateApplicationImpl implements DelegateApplication {
|
|
|
116
114
|
patchConfig(key: string, rawValue: string): string | null {
|
|
117
115
|
const current = this.liveConfig as unknown as Record<string, unknown>;
|
|
118
116
|
if (!(key in current)) return `Unknown setting '${key}'.`;
|
|
119
|
-
const num =
|
|
120
|
-
if (
|
|
117
|
+
const num = parseSettingValue(rawValue);
|
|
118
|
+
if (num === null) return settingParseError(rawValue);
|
|
121
119
|
try {
|
|
122
120
|
const { config } = normalizeConfig({ ...current, [key]: num });
|
|
123
121
|
saveConfig(this.ports.agentDir, config);
|
|
@@ -128,6 +126,25 @@ export class DelegateApplicationImpl implements DelegateApplication {
|
|
|
128
126
|
}
|
|
129
127
|
}
|
|
130
128
|
|
|
129
|
+
/**
|
|
130
|
+
* Live-edit one numeric knob of the PROJECT overlay file
|
|
131
|
+
* (`<root>/.pi/delegate/config.json`): merged in, only the given key
|
|
132
|
+
* changes, clamped by the same bounds as the user config.
|
|
133
|
+
*/
|
|
134
|
+
patchProjectConfig(projectRoot: string, key: string, rawValue: string): string | null {
|
|
135
|
+
if (!projectRoot) return "No project root available.";
|
|
136
|
+
const num = parseSettingValue(rawValue);
|
|
137
|
+
if (num === null) return settingParseError(rawValue);
|
|
138
|
+
const clamped = clampConfigField(key, num);
|
|
139
|
+
if (clamped === null) return `Unknown setting '${key}'.`;
|
|
140
|
+
try {
|
|
141
|
+
saveProjectConfig(projectRoot, { [key]: clamped } as Partial<DelegateConfigV1>);
|
|
142
|
+
return null;
|
|
143
|
+
} catch (error) {
|
|
144
|
+
return `Save failed: ${(error as Error).message}`;
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
131
148
|
// ── Mode ───────────────────────────────────────────────────────────────
|
|
132
149
|
|
|
133
150
|
isStrict(): boolean {
|
|
@@ -199,19 +216,16 @@ export class DelegateApplicationImpl implements DelegateApplication {
|
|
|
199
216
|
baseCfg = { ...(rest as unknown as DelegateConfigV1) } as DelegateConfigV1;
|
|
200
217
|
}
|
|
201
218
|
|
|
202
|
-
//
|
|
203
|
-
//
|
|
204
|
-
//
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
),
|
|
213
|
-
}
|
|
214
|
-
: baseCfg;
|
|
219
|
+
// Timeout resolution: per-invocation > project > user (baseCfg carries
|
|
220
|
+
// the project overlay). Inactivity is capped at half of hard for ANY
|
|
221
|
+
// source, so a long-silent child can never outlive its watchdog. A
|
|
222
|
+
// per-run copy so overrides never leak into later runs.
|
|
223
|
+
const timeouts = resolveRunTimeouts(baseCfg, request.timeoutMs);
|
|
224
|
+
const cfg: DelegateConfigV1 = {
|
|
225
|
+
...baseCfg,
|
|
226
|
+
hardTimeoutMs: timeouts.hardMs,
|
|
227
|
+
inactivityTimeoutMs: timeouts.inactivityMs,
|
|
228
|
+
};
|
|
215
229
|
|
|
216
230
|
// 2. Validate task (line endings, blank, byte limit).
|
|
217
231
|
const taskResult = validateTask(request.task, cfg.maxTaskBytes);
|
|
@@ -344,17 +358,45 @@ export class DelegateApplicationImpl implements DelegateApplication {
|
|
|
344
358
|
|
|
345
359
|
// ── Status ─────────────────────────────────────────────────────────────
|
|
346
360
|
|
|
347
|
-
getStatus(activeTools: string[] | "degraded"): DelegateStatus {
|
|
361
|
+
getStatus(activeTools: string[] | "degraded", projectRoot?: string): DelegateStatus {
|
|
348
362
|
const cfg = this.liveConfig;
|
|
349
363
|
const runs = listRuns(this.ports.agentDir, 10);
|
|
350
364
|
const active = this.activeRun;
|
|
351
365
|
const last = runs.find((r) => r.runId !== active?.id) ?? runs[0];
|
|
366
|
+
let timeouts: DelegateStatus["timeouts"] = {
|
|
367
|
+
hardMs: cfg.hardTimeoutMs,
|
|
368
|
+
inactivityMs: cfg.inactivityTimeoutMs,
|
|
369
|
+
source: "user",
|
|
370
|
+
userHardMs: cfg.hardTimeoutMs,
|
|
371
|
+
userInactivityMs: cfg.inactivityTimeoutMs,
|
|
372
|
+
};
|
|
373
|
+
if (projectRoot) {
|
|
374
|
+
const overlay = applyProjectOverlay(cfg, projectRoot) as unknown as DelegateConfigV1 & {
|
|
375
|
+
projectOverrides: string[];
|
|
376
|
+
projectCorrupt?: string;
|
|
377
|
+
};
|
|
378
|
+
const { projectOverrides, projectCorrupt, ...rest } = overlay;
|
|
379
|
+
const eff = rest as unknown as DelegateConfigV1;
|
|
380
|
+
const projectSetsHard = projectOverrides.includes("hardTimeoutMs");
|
|
381
|
+
timeouts = {
|
|
382
|
+
hardMs: eff.hardTimeoutMs,
|
|
383
|
+
inactivityMs: eff.inactivityTimeoutMs,
|
|
384
|
+
source: projectSetsHard ? "project" : "user",
|
|
385
|
+
userHardMs: cfg.hardTimeoutMs,
|
|
386
|
+
userInactivityMs: cfg.inactivityTimeoutMs,
|
|
387
|
+
...(projectSetsHard ? { projectHardMs: eff.hardTimeoutMs } : {}),
|
|
388
|
+
projectPath: projectConfigPath(projectRoot),
|
|
389
|
+
projectOverrides,
|
|
390
|
+
...(projectCorrupt ? { projectCorrupt } : {}),
|
|
391
|
+
};
|
|
392
|
+
}
|
|
352
393
|
return {
|
|
353
394
|
modeEnabled: this.isStrict(),
|
|
354
395
|
activeTools: this.isStrict() ? ["delegate"] : activeTools,
|
|
355
396
|
activeRun: active ? { runId: active.id, role: active.role, startedAt: active.startedAt } : null,
|
|
356
397
|
lastRun: last ? { runId: last.runId, role: last.role, state: last.state, finishedAt: last.finishedAt, durationMs: last.durationMs } : null,
|
|
357
398
|
defaultRole: cfg.defaultRole,
|
|
399
|
+
timeouts,
|
|
358
400
|
store: pathsForAgentDir(this.ports.agentDir),
|
|
359
401
|
};
|
|
360
402
|
}
|
|
@@ -486,6 +528,30 @@ export class DelegateApplicationImpl implements DelegateApplication {
|
|
|
486
528
|
}
|
|
487
529
|
}
|
|
488
530
|
|
|
531
|
+
/** Parse a dashboard input: bare ms number or a duration string. */
|
|
532
|
+
function parseSettingValue(raw: string): number | null {
|
|
533
|
+
const trimmed = (raw ?? "").trim();
|
|
534
|
+
if (!trimmed) return null;
|
|
535
|
+
if (/^\d+$/.test(trimmed)) return Number(trimmed);
|
|
536
|
+
try {
|
|
537
|
+
const parsed = parseDuration(trimmed);
|
|
538
|
+
return parsed === undefined ? null : parsed;
|
|
539
|
+
} catch {
|
|
540
|
+
return null;
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
function settingParseError(raw: string): string {
|
|
545
|
+
const trimmed = (raw ?? "").trim();
|
|
546
|
+
if (!trimmed) return "Value is empty.";
|
|
547
|
+
try {
|
|
548
|
+
parseDuration(trimmed);
|
|
549
|
+
return "Value must be a duration (e.g. 30m, 2h, 1d) or bare ms.";
|
|
550
|
+
} catch (error) {
|
|
551
|
+
return (error as Error).message;
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
|
|
489
555
|
function isTerminal(state: string): boolean {
|
|
490
556
|
return ["succeeded", "failed", "cancelled", "timed_out_idle", "timed_out_hard", "crashed"].includes(state);
|
|
491
557
|
}
|
package/commands.ts
CHANGED
|
@@ -23,7 +23,7 @@ export type DelegateIntent =
|
|
|
23
23
|
| { kind: "invalid"; token: string; usage: string };
|
|
24
24
|
|
|
25
25
|
export const DELEGATE_USAGE = [
|
|
26
|
-
"/delegate dashboard (TUI) or status (headless)",
|
|
26
|
+
"/delegate dashboard (TUI: edit base timeouts) or status (headless)",
|
|
27
27
|
"/delegate on enable strict delegation mode",
|
|
28
28
|
"/delegate off disable strict delegation mode",
|
|
29
29
|
"/delegate status mode, active run, last run",
|
package/config.ts
CHANGED
|
@@ -183,6 +183,85 @@ export function clampTimeoutMs(value: number): number {
|
|
|
183
183
|
return Math.min(max, Math.max(min, Math.trunc(value)));
|
|
184
184
|
}
|
|
185
185
|
|
|
186
|
+
/** Clamp one numeric config field; null when the key is not a numeric knob. */
|
|
187
|
+
export function clampConfigField(key: string, value: number): number | null {
|
|
188
|
+
if (key === "schemaVersion" || key === "defaultRole") return null;
|
|
189
|
+
if (!Number.isFinite(value)) return null;
|
|
190
|
+
const min = MIN_VALUES[key as keyof DelegateConfigV1];
|
|
191
|
+
const max = MAX_VALUES[key as keyof DelegateConfigV1];
|
|
192
|
+
if (min === undefined && max === undefined) return null;
|
|
193
|
+
return Math.min(max ?? Number.MAX_SAFE_INTEGER, Math.max(min ?? 0, Math.trunc(value)));
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/**
|
|
197
|
+
* Resolve the effective run timeouts. Priority: per-invocation > project
|
|
198
|
+
* > user (baseCfg already carries the project overlay). The inactivity
|
|
199
|
+
* watchdog is capped at half of the hard timeout regardless of source, so
|
|
200
|
+
* a long-silent child can never outlive its watchdog.
|
|
201
|
+
*/
|
|
202
|
+
export function resolveRunTimeouts(
|
|
203
|
+
baseCfg: DelegateConfigV1,
|
|
204
|
+
timeoutMs?: number,
|
|
205
|
+
): { hardMs: number; inactivityMs: number } {
|
|
206
|
+
const hardMs = timeoutMs !== undefined ? clampTimeoutMs(timeoutMs) : baseCfg.hardTimeoutMs;
|
|
207
|
+
const inactivityMs = Math.min(
|
|
208
|
+
baseCfg.inactivityTimeoutMs,
|
|
209
|
+
Math.max(1_000, Math.floor(hardMs / 2)),
|
|
210
|
+
);
|
|
211
|
+
return { hardMs, inactivityMs };
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/** Human-readable duration for TUI display and prefilled inputs. */
|
|
215
|
+
export function formatDuration(ms: number): string {
|
|
216
|
+
if (!Number.isFinite(ms) || ms < 0) return "?";
|
|
217
|
+
if (ms < 1_000) return `${Math.round(ms)}ms`;
|
|
218
|
+
const totalSec = Math.round(ms / 1_000);
|
|
219
|
+
if (totalSec < 60) return `${totalSec}s`;
|
|
220
|
+
const m = Math.floor(totalSec / 60);
|
|
221
|
+
const s = totalSec % 60;
|
|
222
|
+
if (m < 60) return s ? `${m}m ${s}s` : `${m}m`;
|
|
223
|
+
const h = Math.floor(m / 60);
|
|
224
|
+
const remM = m % 60;
|
|
225
|
+
if (h < 24) return remM ? `${h}h ${remM}m` : `${h}h`;
|
|
226
|
+
const d = Math.floor(h / 24);
|
|
227
|
+
const remH = h % 24;
|
|
228
|
+
return remH ? `${d}d ${remH}h` : `${d}d`;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/**
|
|
232
|
+
* Merge fields into the project-wide config file (overlay semantics: only
|
|
233
|
+
* the given keys change; other project keys are preserved). A corrupt
|
|
234
|
+
* existing file is preserved as timestamped evidence and replaced.
|
|
235
|
+
*/
|
|
236
|
+
export function saveProjectConfig(projectRoot: string, fields: Partial<DelegateConfigV1>): string {
|
|
237
|
+
const pPath = projectConfigPath(projectRoot);
|
|
238
|
+
let existing: Record<string, unknown> = {};
|
|
239
|
+
try {
|
|
240
|
+
const raw = JSON.parse(fs.readFileSync(pPath, "utf8"));
|
|
241
|
+
if (raw && typeof raw === "object" && !Array.isArray(raw)) {
|
|
242
|
+
existing = raw as Record<string, unknown>;
|
|
243
|
+
} else {
|
|
244
|
+
throw new Error("project config is not a JSON object");
|
|
245
|
+
}
|
|
246
|
+
} catch (error) {
|
|
247
|
+
if ((error as NodeJS.ErrnoException).code !== "ENOENT") {
|
|
248
|
+
try {
|
|
249
|
+
const evidence = `${pPath}.corrupt-${Date.now()}`;
|
|
250
|
+
fs.renameSync(pPath, evidence);
|
|
251
|
+
fs.chmodSync(evidence, 0o600);
|
|
252
|
+
} catch {
|
|
253
|
+
// evidence rename failed; still start fresh
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
const known = new Set<string>(Object.keys(DEFAULT_DELEGATE_CONFIG));
|
|
258
|
+
for (const [key, value] of Object.entries(fields)) {
|
|
259
|
+
if (known.has(key)) existing[key] = value;
|
|
260
|
+
}
|
|
261
|
+
fs.mkdirSync(path.dirname(pPath), { recursive: true });
|
|
262
|
+
return atomicWriteJson(pPath, existing);
|
|
263
|
+
}
|
|
264
|
+
|
|
186
265
|
/**
|
|
187
266
|
* Parse a human duration into milliseconds: "90s", "10m", "2h", "1d",
|
|
188
267
|
* or a bare number (already ms). Returns undefined for empty input;
|
package/index.ts
CHANGED
|
@@ -21,7 +21,7 @@ import {
|
|
|
21
21
|
} from "@earendil-works/pi-coding-agent";
|
|
22
22
|
import { Text } from "@earendil-works/pi-tui";
|
|
23
23
|
|
|
24
|
-
import { loadConfig, parseDuration, saveConfig } from "./config.ts";
|
|
24
|
+
import { formatDuration, loadConfig, parseDuration, saveConfig } from "./config.ts";
|
|
25
25
|
import { parseDelegateCommand, delegateCompletions, type DelegateIntent } from "./commands.ts";
|
|
26
26
|
import { DELEGATE_ROLES, isRoleName, resolveRole } from "./roles.ts";
|
|
27
27
|
import { STRICT_OVERLAY, syncStrictToolSet, resetBlockedCounters } from "./mode.ts";
|
|
@@ -467,7 +467,7 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
467
467
|
};
|
|
468
468
|
|
|
469
469
|
const statusText = (ctx: ExtensionContext): string => {
|
|
470
|
-
const s = app.getStatus(pi.getActiveTools());
|
|
470
|
+
const s = app.getStatus(pi.getActiveTools(), ctx.cwd ?? process.cwd());
|
|
471
471
|
const lines = ["[delegate]", `mode: ${s.modeEnabled ? "strict" : "normal"}`];
|
|
472
472
|
lines.push(`parent tools: ${s.modeEnabled ? "delegate only" : "normal active set"}`);
|
|
473
473
|
lines.push(`active run: ${s.activeRun ? `${s.activeRun.runId} (${s.activeRun.role})` : "none"}`);
|
|
@@ -478,6 +478,13 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
478
478
|
lines.push("last run: none");
|
|
479
479
|
}
|
|
480
480
|
lines.push(`default role: ${s.defaultRole}`);
|
|
481
|
+
lines.push(
|
|
482
|
+
`base timeout: ${formatDuration(s.timeouts.hardMs)} hard · ${formatDuration(s.timeouts.inactivityMs)} idle ` +
|
|
483
|
+
(s.timeouts.source === "project" ? `(project ${s.timeouts.projectPath})` : "(user-wide)"),
|
|
484
|
+
);
|
|
485
|
+
if (s.timeouts.projectCorrupt) {
|
|
486
|
+
lines.push(`warning: project config corrupt, user values used: ${s.timeouts.projectCorrupt}`);
|
|
487
|
+
}
|
|
481
488
|
lines.push(`store: ${s.store.runsDir}`);
|
|
482
489
|
if (app.getModeRuntime().persistenceDegraded) lines.push("warning: mode persistence is degraded");
|
|
483
490
|
if (!s.modeEnabled) {
|
|
@@ -600,10 +607,11 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
600
607
|
|
|
601
608
|
// ── Dashboard (§12.2) ───────────────────────────────────────────────────
|
|
602
609
|
|
|
603
|
-
const dashboardSnapshot = (): PanelSnapshot => {
|
|
604
|
-
const s = app.getStatus(pi.getActiveTools());
|
|
610
|
+
const dashboardSnapshot = (projectRoot?: string): PanelSnapshot => {
|
|
611
|
+
const s = app.getStatus(pi.getActiveTools(), projectRoot);
|
|
605
612
|
const active = s.activeRun;
|
|
606
613
|
const last = s.lastRun;
|
|
614
|
+
const t = s.timeouts;
|
|
607
615
|
return {
|
|
608
616
|
title: "Delegation",
|
|
609
617
|
summaryLines: [
|
|
@@ -612,6 +620,7 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
612
620
|
`Active run ${active ? `${active.runId.slice(0, 24)} (${active.role})` : "none"}`,
|
|
613
621
|
`Last run ${last ? `${last.role} · ${last.state}${last.durationMs != null ? ` · ${Math.round(last.durationMs / 1000)}s` : ""}` : "none"}`,
|
|
614
622
|
`Default role ${s.defaultRole}`,
|
|
623
|
+
`Base timeout ${formatDuration(t.hardMs)} hard · ${formatDuration(t.inactivityMs)} idle (${t.source === "project" ? "project" : "user-wide"})`,
|
|
615
624
|
],
|
|
616
625
|
sections: [
|
|
617
626
|
{
|
|
@@ -625,6 +634,38 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
625
634
|
{ key: "doctor", label: "Doctor", value: "", kind: "action" },
|
|
626
635
|
],
|
|
627
636
|
},
|
|
637
|
+
{
|
|
638
|
+
title: "Timeouts (base)",
|
|
639
|
+
rows: [
|
|
640
|
+
{
|
|
641
|
+
key: "timeout-user",
|
|
642
|
+
label: "Hard · user-wide",
|
|
643
|
+
value: formatDuration(t.userHardMs),
|
|
644
|
+
rawValue: formatDuration(t.userHardMs),
|
|
645
|
+
kind: "input",
|
|
646
|
+
inputHint: "e.g. 30m / 2h / 1d — saves ~/.pi/agent/delegate/config.json",
|
|
647
|
+
},
|
|
648
|
+
{
|
|
649
|
+
key: "timeout-project",
|
|
650
|
+
label: "Hard · project",
|
|
651
|
+
value: t.projectHardMs !== undefined ? formatDuration(t.projectHardMs) : "not set",
|
|
652
|
+
rawValue: t.projectHardMs !== undefined ? formatDuration(t.projectHardMs) : "",
|
|
653
|
+
kind: "input",
|
|
654
|
+
inputHint: `merges into ${t.projectPath ?? ".pi/delegate/config.json"} (this key only)`,
|
|
655
|
+
},
|
|
656
|
+
{
|
|
657
|
+
key: "idle-user",
|
|
658
|
+
label: "Idle · user-wide",
|
|
659
|
+
value: formatDuration(t.userInactivityMs),
|
|
660
|
+
rawValue: formatDuration(t.userInactivityMs),
|
|
661
|
+
kind: "input",
|
|
662
|
+
inputHint: "no-output watchdog; capped at ½ of the hard timeout",
|
|
663
|
+
},
|
|
664
|
+
...(t.projectCorrupt
|
|
665
|
+
? [{ key: "project-corrupt", label: "Project config", value: "corrupt — user values used", kind: "info" as const, valueStyle: "warning" as const }]
|
|
666
|
+
: []),
|
|
667
|
+
],
|
|
668
|
+
},
|
|
628
669
|
],
|
|
629
670
|
detailLines: active ? [`elapsed updates refresh every 1s while a run is active`] : undefined,
|
|
630
671
|
};
|
|
@@ -642,8 +683,19 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
642
683
|
theme,
|
|
643
684
|
keybindings,
|
|
644
685
|
initialKey,
|
|
645
|
-
snapshot: dashboardSnapshot,
|
|
646
|
-
apply: () =>
|
|
686
|
+
snapshot: () => dashboardSnapshot(ctx.cwd ?? process.cwd()),
|
|
687
|
+
apply: (key: string, raw: string): string | null => {
|
|
688
|
+
switch (key) {
|
|
689
|
+
case "timeout-user":
|
|
690
|
+
return app.patchConfig("hardTimeoutMs", raw);
|
|
691
|
+
case "idle-user":
|
|
692
|
+
return app.patchConfig("inactivityTimeoutMs", raw);
|
|
693
|
+
case "timeout-project":
|
|
694
|
+
return app.patchProjectConfig(ctx.cwd ?? process.cwd(), "hardTimeoutMs", raw);
|
|
695
|
+
default:
|
|
696
|
+
return `Unknown setting '${key}'.`;
|
|
697
|
+
}
|
|
698
|
+
},
|
|
647
699
|
activate: (key): PanelActionResult => ({ kind: "close", action: key }),
|
|
648
700
|
requestRender: () => tui.requestRender(),
|
|
649
701
|
done,
|
package/package.json
CHANGED
package/run-store.ts
CHANGED
|
@@ -11,6 +11,7 @@
|
|
|
11
11
|
import * as fs from "node:fs";
|
|
12
12
|
import * as path from "node:path";
|
|
13
13
|
import * as crypto from "node:crypto";
|
|
14
|
+
import * as childProcess from "node:child_process";
|
|
14
15
|
import type {
|
|
15
16
|
DelegatePaths,
|
|
16
17
|
DelegateRequest,
|
|
@@ -258,22 +259,107 @@ export function listRuns(agentDir: string, limit = 50): RunSummary[] {
|
|
|
258
259
|
}
|
|
259
260
|
|
|
260
261
|
/**
|
|
261
|
-
*
|
|
262
|
-
*
|
|
263
|
-
*
|
|
262
|
+
* Signal-0 liveness probe: `process.kill(pid, 0)` sends no signal. EPERM
|
|
263
|
+
* means the pid exists (owned by another user) — treat as alive; ESRCH and
|
|
264
|
+
* any other error mean the pid is gone.
|
|
265
|
+
*/
|
|
266
|
+
export function isPidAlive(pid: number): boolean {
|
|
267
|
+
if (!Number.isInteger(pid) || pid <= 1) return false;
|
|
268
|
+
try {
|
|
269
|
+
process.kill(pid, 0);
|
|
270
|
+
return true;
|
|
271
|
+
} catch (error) {
|
|
272
|
+
return (error as NodeJS.ErrnoException).code === "EPERM";
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/**
|
|
277
|
+
* Best-effort read of another process's command line:
|
|
278
|
+
* - Linux: /proc/<pid>/cmdline (NUL-separated args);
|
|
279
|
+
* - elsewhere (macOS): `ps -o args= -p <pid>` (single line, no header).
|
|
280
|
+
* Returns null when the pid is dead or the cmdline cannot be read.
|
|
281
|
+
*/
|
|
282
|
+
export function pidCommandLine(pid: number): string | null {
|
|
283
|
+
if (!isPidAlive(pid)) return null;
|
|
284
|
+
if (process.platform === "linux") {
|
|
285
|
+
try {
|
|
286
|
+
const text = fs.readFileSync(`/proc/${pid}/cmdline`, "utf8")
|
|
287
|
+
.replace(/\0+/g, " ")
|
|
288
|
+
.trim();
|
|
289
|
+
return text.length > 0 ? text : null;
|
|
290
|
+
} catch {
|
|
291
|
+
return null;
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
try {
|
|
295
|
+
const out = childProcess.spawnSync("ps", ["-o", "args=", "-p", String(pid)], {
|
|
296
|
+
encoding: "utf8",
|
|
297
|
+
timeout: 2_000,
|
|
298
|
+
});
|
|
299
|
+
if (out.error || out.status !== 0) return null;
|
|
300
|
+
const text = (out.stdout ?? "").trim();
|
|
301
|
+
return text.length > 0 ? text : null;
|
|
302
|
+
} catch {
|
|
303
|
+
return null;
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
/**
|
|
308
|
+
* True when the command line belongs to a Pi process (a delegate child, or
|
|
309
|
+
* a concurrent pi parent owning a run): any whitespace-split token whose
|
|
310
|
+
* path basename is exactly `pi` (covers `pi --mode rpc ...`,
|
|
311
|
+
* `/opt/homebrew/bin/pi ...`, `node /opt/homebrew/bin/pi ...`), or a path
|
|
312
|
+
* under the pi-coding-agent package (covers
|
|
313
|
+
* `node .../pi-coding-agent/dist/bundle/cli.js ...`).
|
|
314
|
+
*/
|
|
315
|
+
export function commandLineIsPi(cmdline: string): boolean {
|
|
316
|
+
for (const token of cmdline.trim().split(/\s+/)) {
|
|
317
|
+
if (token && path.basename(token) === "pi") return true;
|
|
318
|
+
}
|
|
319
|
+
return cmdline.includes("pi-coding-agent");
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
/**
|
|
323
|
+
* Startup orphan recovery (§10.6): nonterminal metadata whose owned process
|
|
324
|
+
* is gone becomes `crashed` with E_ORPHANED_RUN. This process NEVER kills a
|
|
325
|
+
* PID found in stale metadata.
|
|
326
|
+
*
|
|
327
|
+
* P1: a live pi process owns its runs — concurrent multi-session pi (the
|
|
328
|
+
* pattern documented in AGENTS.md) must never clobber a run that another
|
|
329
|
+
* live pi process is actively running or finalizing. Decision table per
|
|
330
|
+
* nonterminal run:
|
|
331
|
+
* - no stored pid, or pid dead → mark crashed (unchanged);
|
|
332
|
+
* - pid alive, cmdline is pi → SKIP (live delegate owner);
|
|
333
|
+
* - pid alive, cmdline known, not pi → mark crashed (recycled PID);
|
|
334
|
+
* - pid alive, cmdline unreadable → SKIP (fail-safe: never clobber on doubt).
|
|
335
|
+
* Returns the touched run IDs.
|
|
264
336
|
*/
|
|
265
337
|
export function markOrphanedRuns(agentDir: string): string[] {
|
|
266
338
|
const touched: string[] = [];
|
|
267
339
|
for (const summary of listRuns(agentDir)) {
|
|
268
340
|
if (isTerminalRunState(summary.state)) continue;
|
|
269
341
|
try {
|
|
270
|
-
const
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
342
|
+
const storedPid = readRunMetadata(agentDir, summary.runId)?.pid;
|
|
343
|
+
if (typeof storedPid === "number" && isPidAlive(storedPid)) {
|
|
344
|
+
const cmdline = pidCommandLine(storedPid);
|
|
345
|
+
if (cmdline === null) continue; // fail-safe: alive but unreadable
|
|
346
|
+
if (commandLineIsPi(cmdline)) continue; // live pi owner
|
|
347
|
+
const next = updateRunMetadata(agentDir, summary.runId, (current) => ({
|
|
348
|
+
state: "crashed",
|
|
349
|
+
errorCode: "E_ORPHANED_RUN",
|
|
350
|
+
errorMessage: `Run store started with this run nonterminal; stored pid ${storedPid} is alive but not a pi process (recycled pid), so the run has no owner.`,
|
|
351
|
+
finishedAt: current.finishedAt ?? new Date().toISOString(),
|
|
352
|
+
}));
|
|
353
|
+
if (next.state === "crashed") touched.push(summary.runId);
|
|
354
|
+
} else {
|
|
355
|
+
const next = updateRunMetadata(agentDir, summary.runId, (current) => ({
|
|
356
|
+
state: "crashed",
|
|
357
|
+
errorCode: "E_ORPHANED_RUN",
|
|
358
|
+
errorMessage: "Run store started with this run nonterminal and no owned child process.",
|
|
359
|
+
finishedAt: current.finishedAt ?? new Date().toISOString(),
|
|
360
|
+
}));
|
|
361
|
+
if (next.state === "crashed") touched.push(summary.runId);
|
|
362
|
+
}
|
|
277
363
|
} catch {
|
|
278
364
|
// skip
|
|
279
365
|
}
|
package/runner.ts
CHANGED
|
@@ -25,6 +25,7 @@ import type {
|
|
|
25
25
|
import { EMPTY_USAGE } from "./types.ts";
|
|
26
26
|
import { classifyRpcRecord, RpcJsonlParser, type RpcRecord } from "./rpc-jsonl.ts";
|
|
27
27
|
import { appendTranscriptRecord, updateRunMetadata, type OpenedRun } from "./run-store.ts";
|
|
28
|
+
import { formatDuration } from "./config.ts";
|
|
28
29
|
|
|
29
30
|
export interface RunnerConfig {
|
|
30
31
|
maxResultBytes: number;
|
|
@@ -603,7 +604,13 @@ export class DelegateRunner {
|
|
|
603
604
|
this.finalizing = true;
|
|
604
605
|
const finishedAt = new Date().toISOString();
|
|
605
606
|
const durationMs = this.startedAtMs ? Date.now() - this.startedAtMs : 0;
|
|
606
|
-
|
|
607
|
+
// P3: timeout/cancel terminal states are reached without an explicit
|
|
608
|
+
// error (timers and user cancels funnel through finish() bare).
|
|
609
|
+
// Synthesize a specific payload so the tool text never degrades to
|
|
610
|
+
// "unknown failure" — the header shows the state; the error line must
|
|
611
|
+
// agree. Flows into both the metadata and the reported outcome.
|
|
612
|
+
const effectiveError = error ?? this.synthesizedTerminalError(state);
|
|
613
|
+
this.finalError = effectiveError ?? this.finalError;
|
|
607
614
|
const usage = { ...(extra?.usage ?? this.usage), turns: this.turns };
|
|
608
615
|
const metadataPatch: Record<string, unknown> = {
|
|
609
616
|
state,
|
|
@@ -617,9 +624,9 @@ export class DelegateRunner {
|
|
|
617
624
|
metadataPatch.outputBytes = Buffer.byteLength(extra.handoff, "utf8");
|
|
618
625
|
}
|
|
619
626
|
if (extra?.stopReason) metadataPatch.stopReason = extra.stopReason;
|
|
620
|
-
if (
|
|
621
|
-
metadataPatch.errorCode =
|
|
622
|
-
metadataPatch.errorMessage =
|
|
627
|
+
if (effectiveError) {
|
|
628
|
+
metadataPatch.errorCode = effectiveError.code;
|
|
629
|
+
metadataPatch.errorMessage = effectiveError.message;
|
|
623
630
|
}
|
|
624
631
|
if (this.diagnosticNotes.length > 0) {
|
|
625
632
|
metadataPatch.errorMessage = metadataPatch.errorMessage
|
|
@@ -643,12 +650,39 @@ export class DelegateRunner {
|
|
|
643
650
|
this.reapChild();
|
|
644
651
|
this.cleanup();
|
|
645
652
|
|
|
646
|
-
const outcome = this.outcome(state, extra,
|
|
653
|
+
const outcome = this.outcome(state, extra, effectiveError);
|
|
647
654
|
const resolver = this.settledResolver;
|
|
648
655
|
this.settledResolver = null;
|
|
649
656
|
resolver?.(outcome);
|
|
650
657
|
}
|
|
651
658
|
|
|
659
|
+
/**
|
|
660
|
+
* P3: specific error payloads for the terminal states reached without an
|
|
661
|
+
* explicit error. `succeeded`/`failed` already carry their error at the
|
|
662
|
+
* call site (or legitimately have none) and are unaffected.
|
|
663
|
+
*/
|
|
664
|
+
private synthesizedTerminalError(state: RunTerminalState): DelegateError | undefined {
|
|
665
|
+
switch (state) {
|
|
666
|
+
case "timed_out_idle":
|
|
667
|
+
return {
|
|
668
|
+
code: "E_TIMEOUT_IDLE",
|
|
669
|
+
message: `no child activity for ${formatDuration(this.cfg.inactivityTimeoutMs)} (inactivity watchdog)`,
|
|
670
|
+
};
|
|
671
|
+
case "timed_out_hard":
|
|
672
|
+
return {
|
|
673
|
+
code: "E_TIMEOUT_HARD",
|
|
674
|
+
message: `hard timeout of ${formatDuration(this.cfg.hardTimeoutMs)} reached (wall-clock cap)`,
|
|
675
|
+
};
|
|
676
|
+
case "cancelled":
|
|
677
|
+
return {
|
|
678
|
+
code: "E_CANCELLED",
|
|
679
|
+
message: this.cancelledByUser ? "cancelled by user" : "aborted (parent session abort)",
|
|
680
|
+
};
|
|
681
|
+
default:
|
|
682
|
+
return undefined;
|
|
683
|
+
}
|
|
684
|
+
}
|
|
685
|
+
|
|
652
686
|
private outcome(
|
|
653
687
|
state: RunTerminalState,
|
|
654
688
|
extra?: { handoff?: string; truncated?: boolean; stopReason?: string; usage?: DelegateUsage },
|
package/types.ts
CHANGED
|
@@ -195,6 +195,8 @@ export interface RunMetadataV1 {
|
|
|
195
195
|
finalHandoff?: string;
|
|
196
196
|
transcriptPath: string;
|
|
197
197
|
stderrPath: string;
|
|
198
|
+
/** Present only on manually curated receipts (one-time data repair). */
|
|
199
|
+
curationNote?: string;
|
|
198
200
|
}
|
|
199
201
|
|
|
200
202
|
export interface TranscriptRecordV1 {
|
|
@@ -303,6 +305,23 @@ export interface DelegateStatus {
|
|
|
303
305
|
durationMs?: number;
|
|
304
306
|
} | null;
|
|
305
307
|
defaultRole: RoleName;
|
|
308
|
+
/** Effective timeout view for the current project (cascade resolved). */
|
|
309
|
+
timeouts: {
|
|
310
|
+
/** Effective hard/inactivity used for runs in this project. */
|
|
311
|
+
hardMs: number;
|
|
312
|
+
inactivityMs: number;
|
|
313
|
+
/** Where the effective hard timeout comes from. */
|
|
314
|
+
source: "user" | "project";
|
|
315
|
+
userHardMs: number;
|
|
316
|
+
userInactivityMs: number;
|
|
317
|
+
/** Present when the project file overrides the hard timeout. */
|
|
318
|
+
projectHardMs?: number;
|
|
319
|
+
projectPath?: string;
|
|
320
|
+
/** Config keys overridden by the project file. */
|
|
321
|
+
projectOverrides?: string[];
|
|
322
|
+
/** Set when a corrupt project file was ignored (user values used). */
|
|
323
|
+
projectCorrupt?: string;
|
|
324
|
+
};
|
|
306
325
|
store: DelegatePaths;
|
|
307
326
|
}
|
|
308
327
|
|
|
@@ -376,7 +395,8 @@ export interface DelegateApplication {
|
|
|
376
395
|
cancel(runId?: string): Promise<CancelResult>;
|
|
377
396
|
inspect(runId?: string, includeTranscript?: boolean): RunInspection;
|
|
378
397
|
doctor(): DoctorReport;
|
|
379
|
-
getStatus(activeTools: string[] | "degraded"): DelegateStatus;
|
|
398
|
+
getStatus(activeTools: string[] | "degraded", projectRoot?: string): DelegateStatus;
|
|
380
399
|
patchConfig(key: string, rawValue: string): string | null;
|
|
400
|
+
patchProjectConfig(projectRoot: string, key: string, rawValue: string): string | null;
|
|
381
401
|
paths(): DelegatePaths;
|
|
382
402
|
}
|