@maheidem/pi-delegate 0.1.3 → 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
@@ -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
 
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, clampTimeoutMs, 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
-
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 = Number(rawValue);
120
- if (!Number.isFinite(num)) return "Value must be a number.";
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
- // Per-invocation timeout overrides the config-cascade value, clamped
203
- // to the configured bounds; inactivity scales to match. A per-run
204
- // copy is used so the override never leaks into later runs.
205
- const cfg: DelegateConfigV1 = request.timeoutMs !== undefined
206
- ? {
207
- ...baseCfg,
208
- hardTimeoutMs: clampTimeoutMs(request.timeoutMs),
209
- inactivityTimeoutMs: Math.min(
210
- baseCfg.inactivityTimeoutMs,
211
- Math.max(MIN_INACTIVITY, Math.floor(clampTimeoutMs(request.timeoutMs) / 2)),
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: () => 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
+ },
647
699
  activate: (key): PanelActionResult => ({ kind: "close", action: key }),
648
700
  requestRender: () => tui.requestRender(),
649
701
  done,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@maheidem/pi-delegate",
3
- "version": "0.1.3",
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
@@ -303,6 +303,23 @@ export interface DelegateStatus {
303
303
  durationMs?: number;
304
304
  } | null;
305
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
+ };
306
323
  store: DelegatePaths;
307
324
  }
308
325
 
@@ -376,7 +393,8 @@ export interface DelegateApplication {
376
393
  cancel(runId?: string): Promise<CancelResult>;
377
394
  inspect(runId?: string, includeTranscript?: boolean): RunInspection;
378
395
  doctor(): DoctorReport;
379
- getStatus(activeTools: string[] | "degraded"): DelegateStatus;
396
+ getStatus(activeTools: string[] | "degraded", projectRoot?: string): DelegateStatus;
380
397
  patchConfig(key: string, rawValue: string): string | null;
398
+ patchProjectConfig(projectRoot: string, key: string, rawValue: string): string | null;
381
399
  paths(): DelegatePaths;
382
400
  }