@maheidem/pi-delegate 0.1.2 → 0.1.4

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 CHANGED
@@ -42,6 +42,31 @@ is performed by this package.
42
42
 
43
43
  Any unrecognized first word is shorthand for `run general …`.
44
44
 
45
+ ### Timeouts
46
+
47
+ Three levels, highest priority first:
48
+
49
+ 1. **Per-invocation flag** — `--timeout <90s|10m|2h|1d|ms>` anywhere in the
50
+ task (e.g. `/delegate run general long migration --timeout 2h`). The
51
+ `delegate` tool exposes the same as its optional `timeout` parameter, so
52
+ the parent model can extend the budget when it expects a long subtask.
53
+ Clamped to the configured `hardTimeoutMs` bounds; the inactivity timeout
54
+ scales to at most half of it.
55
+ 2. **Project-wide** — `<project>/.pi/delegate/config.json` overlays the user
56
+ config field-by-field (only listed keys override; e.g.
57
+ `{ "hardTimeoutMs": 7200000 }`). A missing or corrupt project file never
58
+ breaks delegations — user values win and corruption is diagnosed.
59
+ 3. **User-wide** — `~/.pi/agent/delegate/config.json`
60
+ (`hardTimeoutMs` default 30 min, `inactivityTimeoutMs` default 5 min).
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
+
45
70
  Tool (`delegate`) is available to models: same semantics, JSON result with
46
71
  `ok`/`handoff`/`details` (usage, paths, state) or structured `error`.
47
72
 
package/application.ts CHANGED
@@ -33,7 +33,7 @@ import type {
33
33
  SessionEntryLike,
34
34
  } from "./types.ts";
35
35
  import { decodeTranscriptRecord } from "./types.ts";
36
- import { normalizeConfig, saveConfig, type DelegateConfigV1 } from "./config.ts";
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
38
  import { isRoleName, resolveRole, rolePromptExists, DELEGATE_ROLES } from "./roles.ts";
39
39
  import {
@@ -114,8 +114,8 @@ export class DelegateApplicationImpl implements DelegateApplication {
114
114
  patchConfig(key: string, rawValue: string): string | null {
115
115
  const current = this.liveConfig as unknown as Record<string, unknown>;
116
116
  if (!(key in current)) return `Unknown setting '${key}'.`;
117
- const num = Number(rawValue);
118
- if (!Number.isFinite(num)) return "Value must be a number.";
117
+ const num = parseSettingValue(rawValue);
118
+ if (num === null) return settingParseError(rawValue);
119
119
  try {
120
120
  const { config } = normalizeConfig({ ...current, [key]: num });
121
121
  saveConfig(this.ports.agentDir, config);
@@ -126,6 +126,25 @@ export class DelegateApplicationImpl implements DelegateApplication {
126
126
  }
127
127
  }
128
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
+
129
148
  // ── Mode ───────────────────────────────────────────────────────────────
130
149
 
131
150
  isStrict(): boolean {
@@ -182,8 +201,31 @@ export class DelegateApplicationImpl implements DelegateApplication {
182
201
  };
183
202
  }
184
203
 
185
- const cfg = this.liveConfig;
186
204
  const agentDir = this.ports.agentDir;
205
+ // Config cascade: project .pi/delegate/config.json overlays the
206
+ // user-wide (live) config per run; missing file = live config.
207
+ let baseCfg: DelegateConfigV1 = this.liveConfig;
208
+ if (request.projectRoot) {
209
+ // Strip the overlay's diagnostic keys so only real config fields
210
+ // reach the runner (a spurious key would survive into metadata).
211
+ const overlay = applyProjectOverlay(this.liveConfig, request.projectRoot);
212
+ const { projectOverrides, projectCorrupt, ...rest } = overlay as unknown as DelegateConfigV1 & {
213
+ projectOverrides: string[];
214
+ projectCorrupt?: string;
215
+ };
216
+ baseCfg = { ...(rest as unknown as DelegateConfigV1) } as DelegateConfigV1;
217
+ }
218
+
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
+ };
187
229
 
188
230
  // 2. Validate task (line endings, blank, byte limit).
189
231
  const taskResult = validateTask(request.task, cfg.maxTaskBytes);
@@ -316,17 +358,45 @@ export class DelegateApplicationImpl implements DelegateApplication {
316
358
 
317
359
  // ── Status ─────────────────────────────────────────────────────────────
318
360
 
319
- getStatus(activeTools: string[] | "degraded"): DelegateStatus {
361
+ getStatus(activeTools: string[] | "degraded", projectRoot?: string): DelegateStatus {
320
362
  const cfg = this.liveConfig;
321
363
  const runs = listRuns(this.ports.agentDir, 10);
322
364
  const active = this.activeRun;
323
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
+ }
324
393
  return {
325
394
  modeEnabled: this.isStrict(),
326
395
  activeTools: this.isStrict() ? ["delegate"] : activeTools,
327
396
  activeRun: active ? { runId: active.id, role: active.role, startedAt: active.startedAt } : null,
328
397
  lastRun: last ? { runId: last.runId, role: last.role, state: last.state, finishedAt: last.finishedAt, durationMs: last.durationMs } : null,
329
398
  defaultRole: cfg.defaultRole,
399
+ timeouts,
330
400
  store: pathsForAgentDir(this.ports.agentDir),
331
401
  };
332
402
  }
@@ -458,6 +528,30 @@ export class DelegateApplicationImpl implements DelegateApplication {
458
528
  }
459
529
  }
460
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
+
461
555
  function isTerminal(state: string): boolean {
462
556
  return ["succeeded", "failed", "cancelled", "timed_out_idle", "timed_out_hard", "crashed"].includes(state);
463
557
  }
package/commands.ts CHANGED
@@ -7,6 +7,7 @@
7
7
 
8
8
  import type { RoleName } from "./types.ts";
9
9
  import { ROLE_NAMES } from "./types.ts";
10
+ import { parseDuration } from "./config.ts";
10
11
 
11
12
  export type DelegateIntent =
12
13
  | { kind: "dashboard" }
@@ -18,11 +19,11 @@ export type DelegateIntent =
18
19
  | { kind: "help" }
19
20
  | { kind: "cancel"; runId?: string }
20
21
  | { kind: "inspect"; runId?: string }
21
- | { kind: "run"; role: RoleName; task: string; explicit: boolean }
22
+ | { kind: "run"; role: RoleName; task: string; explicit: boolean; timeoutMs?: number }
22
23
  | { kind: "invalid"; token: string; usage: string };
23
24
 
24
25
  export const DELEGATE_USAGE = [
25
- "/delegate dashboard (TUI) or status (headless)",
26
+ "/delegate dashboard (TUI: edit base timeouts) or status (headless)",
26
27
  "/delegate on enable strict delegation mode",
27
28
  "/delegate off disable strict delegation mode",
28
29
  "/delegate status mode, active run, last run",
@@ -33,6 +34,8 @@ export const DELEGATE_USAGE = [
33
34
  "/delegate run <general|research> <task...> run with an explicit role",
34
35
  "/delegate research <task...> research-role shorthand",
35
36
  "/delegate <task...> general-role shorthand",
37
+ "flags (run/research/<task>): --timeout <90s|10m|2h|1d|ms>",
38
+ "timeout priority: per-invocation > project .pi/delegate/config.json > user ~/.pi/agent/delegate/config.json",
36
39
  "/delegate help this help",
37
40
  ].join("\n");
38
41
 
@@ -62,7 +65,9 @@ export function parseDelegateCommand(input: string, options: ParseOptions = {}):
62
65
  if (!RESERVED_FIRST_TOKENS.has(first)) {
63
66
  // General-role shorthand. `research` is reserved, so a general task
64
67
  // that starts with that word must use `run general ...`.
65
- return { kind: "run", role: "general", task: trimmed, explicit: false };
68
+ const { task, timeoutMs } = extractFlags(trimmed);
69
+ if (!task) return invalid(first);
70
+ return { kind: "run", role: "general", task, explicit: false, timeoutMs };
66
71
  }
67
72
 
68
73
  switch (first) {
@@ -88,21 +93,24 @@ export function parseDelegateCommand(input: string, options: ParseOptions = {}):
88
93
  }
89
94
  case "run": {
90
95
  const rest = trimmed.slice("run".length).trim();
91
- const parts = rest.split(/\s+/);
92
96
  if (!rest) return invalid("run");
97
+ const { task, timeoutMs } = extractFlags(rest);
98
+ const parts = task.split(/\s+/);
93
99
  const roleToken = parts[0]!;
94
100
  if (roleToken === "general" || roleToken === "research") {
95
- const task = parts.slice(1).join(" ").trim();
96
- if (!task) return invalid("run");
97
- return { kind: "run", role: roleToken, task, explicit: true };
101
+ const body = parts.slice(1).join(" ").trim();
102
+ if (!body) return invalid("run");
103
+ return { kind: "run", role: roleToken, task: body, explicit: true, timeoutMs };
98
104
  }
99
105
  // `run <task...>` — role defaults to general.
100
- return { kind: "run", role: "general", task: rest, explicit: true };
106
+ return { kind: "run", role: "general", task, explicit: true, timeoutMs };
101
107
  }
102
108
  case "research": {
103
- const task = trimmed.slice("research".length).trim();
109
+ const rest = trimmed.slice("research".length).trim();
110
+ if (!rest) return invalid("research");
111
+ const { task, timeoutMs } = extractFlags(rest);
104
112
  if (!task) return invalid("research");
105
- return { kind: "run", role: "research", task, explicit: true };
113
+ return { kind: "run", role: "research", task, explicit: true, timeoutMs };
106
114
  }
107
115
  }
108
116
  return invalid(first);
@@ -140,6 +148,35 @@ export function delegateCompletions(prefix: string, recentRunIds: string[] = [])
140
148
  return [...new Set(matches)].slice(0, 10);
141
149
  }
142
150
 
151
+ /**
152
+ * Pull `--timeout <duration>` flags out of a task string (any position).
153
+ * Unknown flags are kept in the task text; a malformed duration yields a
154
+ * stable error message.
155
+ */
156
+ export function extractFlags(input: string): { task: string; timeoutMs?: number; error?: string } {
157
+ const tokens = input.split(/\s+/).filter(Boolean);
158
+ const kept: string[] = [];
159
+ let timeoutMs: number | undefined;
160
+ for (let i = 0; i < tokens.length; i++) {
161
+ const t = tokens[i]!;
162
+ if (t === "--timeout") {
163
+ const value = tokens[i + 1];
164
+ if (!value) return { task: "", error: "--timeout needs a value (e.g. --timeout 30m)" };
165
+ try {
166
+ const parsed = parseDuration(value);
167
+ if (parsed === undefined) return { task: "", error: "--timeout needs a value (e.g. --timeout 30m)" };
168
+ timeoutMs = parsed;
169
+ i += 1;
170
+ } catch (e) {
171
+ return { task: "", error: (e as Error).message };
172
+ }
173
+ continue;
174
+ }
175
+ kept.push(t);
176
+ }
177
+ return { task: kept.join(" "), timeoutMs };
178
+ }
179
+
143
180
  /**
144
181
  * Validate a raw task: normalize line endings, reject blank input,
145
182
  * enforce the UTF-8 byte limit. Returns the normalized task or a stable
package/config.ts CHANGED
@@ -176,6 +176,203 @@ export function loadConfig(agentDir: string, configPath?: string): ConfigLoadRes
176
176
  }
177
177
  }
178
178
 
179
+ /** Clamp a per-invocation timeout into the configured hard-timeout bounds. */
180
+ export function clampTimeoutMs(value: number): number {
181
+ const min = MIN_VALUES.hardTimeoutMs ?? 1_000;
182
+ const max = MAX_VALUES.hardTimeoutMs ?? 604_800_000;
183
+ return Math.min(max, Math.max(min, Math.trunc(value)));
184
+ }
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
+
265
+ /**
266
+ * Parse a human duration into milliseconds: "90s", "10m", "2h", "1d",
267
+ * or a bare number (already ms). Returns undefined for empty input;
268
+ * throws for malformed values (callers surface a stable error).
269
+ */
270
+ export function parseDuration(input: string): number | undefined {
271
+ const text = (input ?? "").trim().toLowerCase();
272
+ if (!text) return undefined;
273
+ const m = /^(\d+(?:\.\d+)?)\s*(ms|s|m|h|d)$/.exec(text);
274
+ if (m) {
275
+ const value = Number(m[1]);
276
+ const unit = m[2];
277
+ const factor = unit === "ms" ? 1 : unit === "s" ? 1_000 : unit === "m" ? 60_000 : unit === "h" ? 3_600_000 : 86_400_000;
278
+ return Math.round(value * factor);
279
+ }
280
+ if (/^\d+$/.test(text)) return Number(text);
281
+ throw new Error(`invalid duration '${input}' (use e.g. 90s, 10m, 2h, 1d, or bare ms)`);
282
+ }
283
+
284
+ /**
285
+ * Project-wide config path for a project root: `<root>/.pi/delegate/config.json`.
286
+ * The project file is an OPTIONAL overlay: only fields present in it override
287
+ * the user-wide config; it is never required to be schema-complete.
288
+ */
289
+ export function projectConfigPath(projectRoot: string): string {
290
+ return path.join(projectRoot, ".pi", "delegate", "config.json");
291
+ }
292
+
293
+ /**
294
+ * Overlay a project-wide config file onto a base config (the user-wide
295
+ * config in production; the app's live config for injected-config tests).
296
+ * Project file semantics:
297
+ * - missing file → base unchanged (the normal case);
298
+ * - corrupt file → diagnosed via `projectCorrupt`, base still wins
299
+ * (a broken project file must never break delegations);
300
+ * - only keys PRESENT in the project file override (no default backfill);
301
+ * - values are clamped by the same min/max bounds as the user config.
302
+ * Returns a NEW config object; the base is never mutated.
303
+ */
304
+ export function applyProjectOverlay(
305
+ base: DelegateConfigV1,
306
+ projectRoot: string,
307
+ ): DelegateConfigV1 & { projectOverrides: string[]; projectCorrupt?: string } {
308
+ const result: DelegateConfigV1 & { projectOverrides: string[]; projectCorrupt?: string } = {
309
+ ...base,
310
+ projectOverrides: [],
311
+ };
312
+ const pPath = projectConfigPath(projectRoot);
313
+ let raw: unknown;
314
+ try {
315
+ raw = JSON.parse(fs.readFileSync(pPath, "utf8"));
316
+ } catch (error) {
317
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") {
318
+ result.projectCorrupt = pPath;
319
+ }
320
+ return result;
321
+ }
322
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return result;
323
+ const record = raw as Record<string, unknown>;
324
+ const known = new Set<string>(Object.keys(DEFAULT_DELEGATE_CONFIG));
325
+ const overrides: string[] = [];
326
+ for (const key of Object.keys(record)) {
327
+ if (key === "schemaVersion") continue;
328
+ if (!knownKey(key)) continue; // unknown keys in project overlay ignored
329
+ try {
330
+ const probe: DelegateConfigV1 = { ...DEFAULT_DELEGATE_CONFIG };
331
+ applyKnownField(probe, key, record[key]);
332
+ const next = probe[key as keyof DelegateConfigV1] as number;
333
+ if (next !== (base[key as keyof DelegateConfigV1] as number)) {
334
+ result[key as keyof DelegateConfigV1] = next as never;
335
+ overrides.push(key);
336
+ }
337
+ } catch {
338
+ // invalid value for one key: skip it, keep base value
339
+ }
340
+ }
341
+ result.projectOverrides = overrides;
342
+ return result;
343
+ }
344
+
345
+ function knownKey(key: string): boolean {
346
+ return (Object.keys(DEFAULT_DELEGATE_CONFIG) as string[]).includes(key);
347
+ }
348
+
349
+ /**
350
+ * Load the user-wide config, then overlay project-wide values on top.
351
+ * Convenience wrapper over loadConfig + applyProjectOverlay.
352
+ */
353
+ export function loadConfigCascade(
354
+ agentDir: string,
355
+ projectRoot?: string,
356
+ configPath?: string,
357
+ ): ConfigLoadResult & { projectOverrides: string[]; projectCorrupt?: string } {
358
+ const base = loadConfig(agentDir, configPath);
359
+ if (!projectRoot) {
360
+ return { ...base, projectOverrides: [] };
361
+ }
362
+ const overlay = applyProjectOverlay(base.config, projectRoot);
363
+ const { projectOverrides, projectCorrupt, ...rest } = overlay as unknown as DelegateConfigV1 & {
364
+ projectOverrides: string[];
365
+ projectCorrupt?: string;
366
+ };
367
+ const config: DelegateConfigV1 = { ...(rest as unknown as DelegateConfigV1) };
368
+ return {
369
+ ...base,
370
+ config,
371
+ projectOverrides: overlay.projectOverrides,
372
+ projectCorrupt: overlay.projectCorrupt,
373
+ };
374
+ }
375
+
179
376
  /**
180
377
  * Persist config: temp file + fsync + close + rename inside the same
181
378
  * directory, mode 0600. Unknown future keys carried in `extraKeys` are
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, 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";
@@ -162,7 +162,13 @@ export default function delegateExtension(pi: ExtensionAPI) {
162
162
  }
163
163
  };
164
164
 
165
- const buildRequest = (task: string, role: "general" | "research", source: "tool" | "command", ctx: ExtensionContext): DelegateRequest => ({
165
+ const buildRequest = (
166
+ task: string,
167
+ role: "general" | "research",
168
+ source: "tool" | "command",
169
+ ctx: ExtensionContext,
170
+ timeoutMs?: number,
171
+ ): DelegateRequest => ({
166
172
  task,
167
173
  role,
168
174
  source,
@@ -170,6 +176,8 @@ export default function delegateExtension(pi: ExtensionAPI) {
170
176
  parentModel: modelString(ctx),
171
177
  thinkingLevel: thinkingOf(ctx),
172
178
  projectTrusted: ctx.isProjectTrusted(),
179
+ projectRoot: ctx.cwd ?? process.cwd(),
180
+ ...(timeoutMs !== undefined ? { timeoutMs } : {}),
173
181
  });
174
182
 
175
183
  const refreshDoctor = (ctx: ExtensionContext) => {
@@ -257,6 +265,11 @@ export default function delegateExtension(pi: ExtensionAPI) {
257
265
  const DelegateParams = Type.Object({
258
266
  task: Type.String({ minLength: 1 }),
259
267
  role: Type.Optional(Type.Union([Type.Literal("general"), Type.Literal("research")])),
268
+ timeout: Type.Optional(Type.String({
269
+ description:
270
+ "Optional per-run hard timeout, e.g. '90s', '10m', '2h', '1d' or bare ms. " +
271
+ "Use it when the subtask is expected to run longer than the configured default; it overrides the project/user config base.",
272
+ })),
260
273
  });
261
274
 
262
275
  pi.registerTool({
@@ -276,7 +289,19 @@ export default function delegateExtension(pi: ExtensionAPI) {
276
289
  parameters: DelegateParams,
277
290
  async execute(_toolCallId, params, signal, onUpdate, ctx) {
278
291
  // Strict mode invariant also holds here: only delegate runs anyway.
279
- const request = buildRequest(params.task, params.role ?? config.defaultRole, "tool", ctx);
292
+ let timeoutMs: number | undefined;
293
+ if (typeof params.timeout === "string" && params.timeout.trim()) {
294
+ try {
295
+ timeoutMs = parseDuration(params.timeout);
296
+ } catch (error) {
297
+ return {
298
+ content: [{ type: "text" as const, text: (error as Error).message }],
299
+ details: {} satisfies Record<string, unknown>,
300
+ isError: true,
301
+ };
302
+ }
303
+ }
304
+ const request = buildRequest(params.task, params.role ?? config.defaultRole, "tool", ctx, timeoutMs);
280
305
  refreshDoctor(ctx);
281
306
  const hooks = {
282
307
  abortSignal: signal ?? undefined,
@@ -368,8 +393,8 @@ export default function delegateExtension(pi: ExtensionAPI) {
368
393
  }
369
394
  };
370
395
 
371
- const runCommandForeground = async (task: string, role: "general" | "research", ctx: ExtensionCommandContext): Promise<void> => {
372
- const request = buildRequest(task, role, "command", ctx);
396
+ const runCommandForeground = async (task: string, role: "general" | "research", ctx: ExtensionCommandContext, timeoutMs?: number): Promise<void> => {
397
+ const request = buildRequest(task, role, "command", ctx, timeoutMs);
373
398
  refreshDoctor(ctx);
374
399
  let lastText = `[delegate] starting ${role} run…`;
375
400
  const hooks = {
@@ -442,7 +467,7 @@ export default function delegateExtension(pi: ExtensionAPI) {
442
467
  };
443
468
 
444
469
  const statusText = (ctx: ExtensionContext): string => {
445
- const s = app.getStatus(pi.getActiveTools());
470
+ const s = app.getStatus(pi.getActiveTools(), ctx.cwd ?? process.cwd());
446
471
  const lines = ["[delegate]", `mode: ${s.modeEnabled ? "strict" : "normal"}`];
447
472
  lines.push(`parent tools: ${s.modeEnabled ? "delegate only" : "normal active set"}`);
448
473
  lines.push(`active run: ${s.activeRun ? `${s.activeRun.runId} (${s.activeRun.role})` : "none"}`);
@@ -453,6 +478,13 @@ export default function delegateExtension(pi: ExtensionAPI) {
453
478
  lines.push("last run: none");
454
479
  }
455
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
+ }
456
488
  lines.push(`store: ${s.store.runsDir}`);
457
489
  if (app.getModeRuntime().persistenceDegraded) lines.push("warning: mode persistence is degraded");
458
490
  if (!s.modeEnabled) {
@@ -556,7 +588,7 @@ export default function delegateExtension(pi: ExtensionAPI) {
556
588
  say(ctx, `[delegate] invalid role '${intent.role}'. Use general or research.`, "error");
557
589
  return;
558
590
  }
559
- await runCommandForeground(intent.task, intent.role, ctx);
591
+ await runCommandForeground(intent.task, intent.role, ctx, intent.timeoutMs);
560
592
  return;
561
593
  case "invalid":
562
594
  say(ctx, `[delegate] unrecognized '${intent.token}'.\n${intent.usage}\n${helpText()}`, "error");
@@ -575,10 +607,11 @@ export default function delegateExtension(pi: ExtensionAPI) {
575
607
 
576
608
  // ── Dashboard (§12.2) ───────────────────────────────────────────────────
577
609
 
578
- const dashboardSnapshot = (): PanelSnapshot => {
579
- const s = app.getStatus(pi.getActiveTools());
610
+ const dashboardSnapshot = (projectRoot?: string): PanelSnapshot => {
611
+ const s = app.getStatus(pi.getActiveTools(), projectRoot);
580
612
  const active = s.activeRun;
581
613
  const last = s.lastRun;
614
+ const t = s.timeouts;
582
615
  return {
583
616
  title: "Delegation",
584
617
  summaryLines: [
@@ -587,6 +620,7 @@ export default function delegateExtension(pi: ExtensionAPI) {
587
620
  `Active run ${active ? `${active.runId.slice(0, 24)} (${active.role})` : "none"}`,
588
621
  `Last run ${last ? `${last.role} · ${last.state}${last.durationMs != null ? ` · ${Math.round(last.durationMs / 1000)}s` : ""}` : "none"}`,
589
622
  `Default role ${s.defaultRole}`,
623
+ `Base timeout ${formatDuration(t.hardMs)} hard · ${formatDuration(t.inactivityMs)} idle (${t.source === "project" ? "project" : "user-wide"})`,
590
624
  ],
591
625
  sections: [
592
626
  {
@@ -600,6 +634,38 @@ export default function delegateExtension(pi: ExtensionAPI) {
600
634
  { key: "doctor", label: "Doctor", value: "", kind: "action" },
601
635
  ],
602
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
+ },
603
669
  ],
604
670
  detailLines: active ? [`elapsed updates refresh every 1s while a run is active`] : undefined,
605
671
  };
@@ -617,8 +683,19 @@ export default function delegateExtension(pi: ExtensionAPI) {
617
683
  theme,
618
684
  keybindings,
619
685
  initialKey,
620
- snapshot: dashboardSnapshot,
621
- apply: () => null,
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
+ },
622
699
  activate: (key): PanelActionResult => ({ kind: "close", action: key }),
623
700
  requestRender: () => tui.requestRender(),
624
701
  done,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@maheidem/pi-delegate",
3
- "version": "0.1.2",
3
+ "version": "0.1.4",
4
4
  "type": "module",
5
5
  "description": "Foreground isolated delegation and strict coordinator mode for the Pi coding agent.",
6
6
  "license": "MIT",
package/types.ts CHANGED
@@ -94,6 +94,9 @@ export const EMPTY_USAGE: DelegateUsage = {
94
94
 
95
95
  export type RunSource = "tool" | "command";
96
96
 
97
+ /** Project-wide config path: `<projectRoot>/.pi/delegate/config.json`. */
98
+ export const PROJECT_DELEGATE_CONFIG_REL = ".pi/delegate/config.json";
99
+
97
100
  export interface DelegateRequest {
98
101
  task: string;
99
102
  role: RoleName;
@@ -105,6 +108,10 @@ export interface DelegateRequest {
105
108
  /** Parent thinking level, when available. */
106
109
  thinkingLevel?: string;
107
110
  projectTrusted: boolean;
111
+ /** Per-invocation hard timeout (ms); overrides the config cascade. */
112
+ timeoutMs?: number;
113
+ /** Project root for the project-wide config overlay (optional). */
114
+ projectRoot?: string;
108
115
  }
109
116
 
110
117
  /** Bounded, parent-visible tool result details (schema v1). */
@@ -296,6 +303,23 @@ export interface DelegateStatus {
296
303
  durationMs?: number;
297
304
  } | null;
298
305
  defaultRole: RoleName;
306
+ /** Effective timeout view for the current project (cascade resolved). */
307
+ timeouts: {
308
+ /** Effective hard/inactivity used for runs in this project. */
309
+ hardMs: number;
310
+ inactivityMs: number;
311
+ /** Where the effective hard timeout comes from. */
312
+ source: "user" | "project";
313
+ userHardMs: number;
314
+ userInactivityMs: number;
315
+ /** Present when the project file overrides the hard timeout. */
316
+ projectHardMs?: number;
317
+ projectPath?: string;
318
+ /** Config keys overridden by the project file. */
319
+ projectOverrides?: string[];
320
+ /** Set when a corrupt project file was ignored (user values used). */
321
+ projectCorrupt?: string;
322
+ };
299
323
  store: DelegatePaths;
300
324
  }
301
325
 
@@ -369,7 +393,8 @@ export interface DelegateApplication {
369
393
  cancel(runId?: string): Promise<CancelResult>;
370
394
  inspect(runId?: string, includeTranscript?: boolean): RunInspection;
371
395
  doctor(): DoctorReport;
372
- getStatus(activeTools: string[] | "degraded"): DelegateStatus;
396
+ getStatus(activeTools: string[] | "degraded", projectRoot?: string): DelegateStatus;
373
397
  patchConfig(key: string, rawValue: string): string | null;
398
+ patchProjectConfig(projectRoot: string, key: string, rawValue: string): string | null;
374
399
  paths(): DelegatePaths;
375
400
  }