@maheidem/pi-delegate 0.7.3 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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 or unref'd. The task travels over RPC
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: NodeJS.ProcessEnv = {
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
- this.handoffEnforceTimer.unref();
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()) {
@@ -7,8 +7,8 @@
7
7
 
8
8
  import { truncateToWidth, visibleWidth, matchesKey, type Component } from "@earendil-works/pi-tui";
9
9
  import type { Theme, KeybindingsManager, ThemeColor } from "@earendil-works/pi-coding-agent";
10
- import { frameHeight, padToFrame } from "./panel-frame.ts";
11
- import type { PanelSnapshot } from "./settings-panel.ts";
10
+ import { frameHeight, padToFrame } from "@maheidem/pi-panel-kit";
11
+ import type { PanelSnapshot } from "@maheidem/pi-panel-kit";
12
12
 
13
13
  export interface PeekViewState {
14
14
  /** Header: run id + state/model. */
@@ -16,9 +16,9 @@
16
16
 
17
17
  import { truncateToWidth, visibleWidth, matchesKey, type Component } from "@earendil-works/pi-tui";
18
18
  import type { Theme, KeybindingsManager, ThemeColor } from "@earendil-works/pi-coding-agent";
19
- import { formatDuration, formatTokens, shortModel } from "./format.ts";
20
- import { frameHeight, padToFrame } from "./panel-frame.ts";
21
- import type { PanelSnapshot } from "./settings-panel.ts";
19
+ import { formatDuration, formatTokens, shortModel } from "@maheidem/pi-panel-kit";
20
+ import { frameHeight, padToFrame } from "@maheidem/pi-panel-kit";
21
+ import type { PanelSnapshot } from "@maheidem/pi-panel-kit";
22
22
 
23
23
  export interface RunningViewState {
24
24
  runId: string;
@@ -6,19 +6,18 @@
6
6
  * and /delegate status therefore carries the version actually executing,
7
7
  * so "stale copy in this process" is self-evident instead of mysterious.
8
8
  *
9
- * Thin wrapper (S2) over the canonical helper vendored at `ui/version.ts`
10
- * (kit source: `skills/pi-extension-builder/assets/control-panel/…`); the
11
- * public name and return string are unchanged — the package.json path is
12
- * resolved from THIS module's URL, as before.
9
+ * Thin wrapper over `extensionVersion` of @maheidem/pi-panel-kit. The
10
+ * public name and the return string do not change. The package.json path
11
+ * is resolved from THIS module's URL, one level above extensions/.
13
12
  */
14
13
 
15
14
  import * as path from "node:path";
16
15
  import { fileURLToPath } from "node:url";
17
16
 
18
- import { extensionVersion } from "./ui/version.ts";
17
+ import { extensionVersion } from "@maheidem/pi-panel-kit";
19
18
 
20
19
  export function delegateVersion(): string {
21
20
  return extensionVersion({
22
- packageJsonPath: path.join(path.dirname(fileURLToPath(import.meta.url)), "package.json"),
21
+ packageJsonPath: path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "package.json"),
23
22
  });
24
23
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@maheidem/pi-delegate",
3
- "version": "0.7.3",
3
+ "version": "0.9.0",
4
4
  "type": "module",
5
5
  "description": "Foreground isolated delegation and strict coordinator mode for the Pi coding agent.",
6
6
  "license": "MIT",
@@ -26,24 +26,10 @@
26
26
  "access": "public"
27
27
  },
28
28
  "files": [
29
- "index.ts",
30
- "application.ts",
31
- "background.ts",
32
- "ask.ts",
33
- "commands.ts",
34
- "config.ts",
35
- "mode.ts",
36
- "roles.ts",
37
- "runner.ts",
38
- "rpc-jsonl.ts",
39
- "run-store.ts",
40
- "types.ts",
41
- "version.ts",
42
- "handoff.ts",
43
- "transcript-feed.ts",
29
+ "extensions/",
44
30
  "roles/",
45
- "ui/",
46
31
  "README.md",
32
+ "CHANGELOG.md",
47
33
  "LICENSE"
48
34
  ],
49
35
  "scripts": {
@@ -53,21 +39,27 @@
53
39
  "test:e2e": "node tests/e2e.mjs",
54
40
  "prepack": "npm run typecheck && npm test"
55
41
  },
42
+ "dependencies": {
43
+ "@maheidem/pi-panel-kit": "^0.1.0"
44
+ },
56
45
  "peerDependencies": {
57
- "@earendil-works/pi-coding-agent": ">=0.84.4",
46
+ "@earendil-works/pi-coding-agent": "*",
58
47
  "@earendil-works/pi-tui": "*",
59
48
  "typebox": "*"
60
49
  },
61
50
  "devDependencies": {
62
- "@earendil-works/pi-coding-agent": "^0.84.4",
63
- "@earendil-works/pi-tui": "^0.84.4",
51
+ "@earendil-works/pi-coding-agent": "1.6.1",
52
+ "@earendil-works/pi-tui": "1.6.1",
64
53
  "@types/node": "^22.0.0",
65
- "typebox": "^1.0.17",
54
+ "typebox": "1.3.27",
66
55
  "typescript": "^5.9.3"
67
56
  },
68
57
  "pi": {
69
58
  "extensions": [
70
- "./index.ts"
59
+ "./extensions/index.ts"
71
60
  ]
61
+ },
62
+ "engines": {
63
+ "node": ">=18"
72
64
  }
73
65
  }
package/ui/format.ts DELETED
@@ -1,122 +0,0 @@
1
- /**
2
- * canonical kit formatting primitive (v1) — vendored byte-identical;
3
- * consumers: extensions/ui/format.ts; guard: scripts/check-vendored.mjs
4
- *
5
- * ONE module all views import so tokens/durations/sizes/model render
6
- * identically across home, live strip, inline tool card, and peek.
7
- *
8
- * This kit copy is deliberately SELF-CONTAINED (zero imports): the canonical
9
- * `formatDuration` is inlined verbatim from the delegate `config.ts` so a
10
- * generated panel can vendor the whole primitive without importing
11
- * `../config.ts`. Consumers re-export it (`export { formatDuration }`) to
12
- * keep the historical public surface of `ui/format.ts` unchanged. The
13
- * delegate keeps its own `formatDuration` in `config.ts` for existing
14
- * importers; both copies descend from the same code and must stay
15
- * behaviorally identical — locked by
16
- * `custom-extensions/delegate/tests/format.test.ts`.
17
- *
18
- * Registered vendored target: `custom-extensions/delegate/ui/format.ts`
19
- * (`required: true`). Never hand-edit a vendored copy: edit this canonical
20
- * source, then `node scripts/check-vendored.mjs --fix`.
21
- */
22
-
23
- /** Human-readable duration for TUI display and prefilled inputs. */
24
- function formatDuration(ms: number): string {
25
- if (!Number.isFinite(ms) || ms < 0) return "?";
26
- if (ms < 1_000) return `${Math.round(ms)}ms`;
27
- const totalSec = Math.round(ms / 1_000);
28
- if (totalSec < 60) return `${totalSec}s`;
29
- const m = Math.floor(totalSec / 60);
30
- const s = totalSec % 60;
31
- if (m < 60) return s ? `${m}m ${s}s` : `${m}m`;
32
- const h = Math.floor(m / 60);
33
- const remM = m % 60;
34
- if (h < 24) return remM ? `${h}h ${remM}m` : `${h}h`;
35
- const d = Math.floor(h / 24);
36
- const remH = h % 24;
37
- return remH ? `${d}d ${remH}h` : `${d}d`;
38
- }
39
-
40
- /** Token count: 0 if falsy; raw <1000; else `X.Yk`; else `X.YM`. */
41
- export function formatTokens(n: number | undefined): string {
42
- if (!n || n < 0) return "0";
43
- if (n < 1000) return String(n);
44
- if (n < 1_000_000) return `${Math.round(n / 100) / 10}k`;
45
- return `${Math.round(n / 100_000) / 10}M`;
46
- }
47
-
48
- /**
49
- * Project-layer config cell for dashboard rows. The project FILE is the
50
- * source of truth for presence: a value equal to the user layer renders as
51
- * `2h (= user)` instead of reading as unset, and "not set" appears ONLY when
52
- * the key is absent from the file. `undefined` means absent.
53
- */
54
- export function projectValueCell(value: number | undefined, userValue: number | undefined): string {
55
- if (value === undefined || !Number.isFinite(value)) return "not set";
56
- const text = formatDuration(value);
57
- if (userValue !== undefined && Number.isFinite(userValue) && value === userValue) return `${text} (= user)`;
58
- return text;
59
- }
60
-
61
- /** Cost as `$X.YZ` (2 dp) or `$0.00`. Never emoji. */
62
- export function formatCost(cost: number | undefined): string {
63
- return `$${(cost ?? 0).toFixed(2)}`;
64
- }
65
-
66
- /** Bytes → binary size, 0–1 decimal ("51200"→"50 KB"). */
67
- export function formatSize(bytes: number | undefined): string {
68
- const b = bytes ?? 0;
69
- if (b < 1024) return `${b} B`;
70
- const kb = b / 1024;
71
- if (kb < 1024) return `${kb < 10 ? Math.round(kb * 10) / 10 : Math.round(kb)} KB`;
72
- const mb = kb / 1024;
73
- if (mb < 1024) return `${mb < 10 ? Math.round(mb * 10) / 10 : Math.round(mb)} MB`;
74
- const gb = mb / 1024;
75
- return `${gb < 10 ? Math.round(gb * 10) / 10 : Math.round(gb)} GB`;
76
- }
77
-
78
- /** "zai/glm-5.3" → "glm-5.3" for compact rows; full id for peek headers. */
79
- export function shortModel(model: string | undefined): string {
80
- if (!model) return "";
81
- const slash = model.lastIndexOf("/");
82
- return slash >= 0 ? model.slice(slash + 1) : model;
83
- }
84
-
85
- /**
86
- * State glyph + word (never color-alone, FIELDS §3.6). Returns the glyph and
87
- * the word separately so the caller colors them together.
88
- */
89
- export function stateGlyph(state: string): { glyph: string; word: string; color: "success" | "warning" | "error" | "muted" } {
90
- switch (state) {
91
- case "created":
92
- case "starting":
93
- return { glyph: "◐", word: "starting", color: "muted" };
94
- case "running":
95
- return { glyph: "●", word: "running", color: "success" };
96
- case "succeeded":
97
- return { glyph: "✓", word: "done", color: "success" };
98
- case "cancelled":
99
- return { glyph: "⊘", word: "cancelled", color: "muted" };
100
- case "timed_out_idle":
101
- return { glyph: "⏱", word: "timeout · idle", color: "warning" };
102
- case "timed_out_hard":
103
- return { glyph: "⏱", word: "timeout · hard", color: "warning" };
104
- case "queued":
105
- return { glyph: "○", word: "queued", color: "muted" };
106
- case "spawned":
107
- return { glyph: "↗", word: "spawned", color: "muted" };
108
- default:
109
- return { glyph: "✗", word: state || "unknown", color: "error" };
110
- }
111
- }
112
-
113
- /** Progress bar: `filled(█) + empty(░)` + "NN%" text (never shape-alone). */
114
- export function progressBar(frac: number, width: number): string {
115
- const f = Math.max(0, Math.min(1, frac));
116
- const w = Math.max(4, Math.floor(width));
117
- const filled = Math.round(f * w);
118
- return `${"█".repeat(filled)}${"░".repeat(Math.max(0, w - filled))} ${Math.round(f * 100)}%`;
119
- }
120
-
121
- /** Canonical duration (ms → "41s"/"30m 22s"/"2h"). */
122
- export { formatDuration };
package/ui/panel-frame.ts DELETED
@@ -1,126 +0,0 @@
1
- /**
2
- * ui/panel-frame.ts — one fixed-height frame grammar for every secondary
3
- * panel screen (slice 1b, `.planning/ui-alignment-2026-09-08` §5/§7).
4
- *
5
- * WHY THIS EXISTS
6
- * `ui/settings-panel.ts` is the canonical vendored panel and must stay
7
- * byte-identical (guard: `node skills/pi-extension-builder/scripts/check-vendored.mjs`),
8
- * and it never pads: what it renders is exactly the SUM of the blocks it is
9
- * handed. The OPERATIONAL §1 rule ("fixed frame, growing content *window*")
10
- * therefore has to be enforced by the code that BUILDS snapshots — and it has
11
- * to be enforced in one place, otherwise every screen re-invents the arithmetic
12
- * and the frames drift (the exact failure this migration is about).
13
- *
14
- * FRAME GRAMMAR (mirrors `SettingsPanel.render()`, same order):
15
- * 1 top border
16
- * N summaryLines
17
- * Σ per section: 1 header + rows.length
18
- * N detailLines ← blank padding lives here, INSIDE the border
19
- * 1 messageLine (always rendered by the panel)
20
- * 0|1 shortcutLine (iff shortcuts.length)
21
- * 1 navigationLine (always rendered by the panel)
22
- * 1 bottom border
23
- */
24
-
25
- import type { PanelRow, PanelSnapshot, PanelShortcut } from "./settings-panel.ts";
26
-
27
- /** Rendered height of a snapshot under the vendored panel's frame grammar. */
28
- export function frameHeight(snapshot: PanelSnapshot): number {
29
- const rows = snapshot.sections.reduce((total, section) => total + 1 + section.rows.length, 0);
30
- return (
31
- 1 +
32
- (snapshot.summaryLines?.length ?? 0) +
33
- rows +
34
- (snapshot.detailLines?.length ?? 0) +
35
- 1 +
36
- (snapshot.shortcuts?.length ? 1 : 0) +
37
- 1 +
38
- 1
39
- );
40
- }
41
-
42
- /**
43
- * Blank-pad a snapshot inside the border until it renders exactly `rows` tall.
44
- * Padding is additive only: content that does not FIT must be windowed by the
45
- * builder (`paginateRows`), never smuggled in by growing the frame.
46
- */
47
- export function padToFrame<T extends PanelSnapshot>(snapshot: T, rows: number): T {
48
- const pad = Math.max(0, rows - frameHeight(snapshot));
49
- return {
50
- ...snapshot,
51
- detailLines: [...(snapshot.detailLines ?? []), ...Array.from({ length: pad }, () => "")],
52
- };
53
- }
54
-
55
- /** Row keys of the pagination controls. Stable, inventory-visible, no magic. */
56
- export const PAGE_PREV_KEY = "page:prev";
57
- export const PAGE_NEXT_KEY = "page:next";
58
-
59
- export interface RowPage {
60
- /** The rows that fit this page (controls included when paging is active). */
61
- rows: PanelRow[];
62
- /** 0-based page index actually rendered. */
63
- page: number;
64
- /** Total pages (1 when everything fits). */
65
- pages: number;
66
- /** Rows hidden behind the current page's `next` control. */
67
- hidden: number;
68
- }
69
-
70
- /**
71
- * Window rows into a fixed slot count. When the list overflows, two slots are
72
- * spent on `‹ prev` / `next ›` action rows so the window is always reachable
73
- * with the panel's own navigation — the frame never grows and the footer is
74
- * never cut. The two control slots are reserved on EVERY page (including the
75
- * first and last) so the frame height is identical across pages.
76
- */
77
- export function paginateRows(rows: readonly PanelRow[], budget: number): RowPage {
78
- if (budget <= 0) return { rows: [], page: 0, pages: 1, hidden: rows.length };
79
- if (rows.length <= budget) return { rows: rows.map((row) => ({ ...row })), page: 0, pages: 1, hidden: 0 };
80
-
81
- const pageSize = Math.max(1, budget - 2);
82
- const pages = Math.max(1, Math.ceil(rows.length / pageSize));
83
- return { rows: [], page: 0, pages, hidden: Math.max(0, rows.length - pageSize) };
84
- }
85
-
86
- /**
87
- * Rows for one page of a windowed section, including the pagination controls.
88
- * `page` is clamped, so a stale index (after a delete) can never blank the
89
- * frame: the window always renders the same number of slots.
90
- */
91
- export function pageRows(rows: readonly PanelRow[], budget: number, page: number): RowPage {
92
- const sizing = paginateRows(rows, budget);
93
- if (sizing.pages === 1) return sizing;
94
- const pageSize = Math.max(1, budget - 2);
95
- const safe = Math.min(Math.max(0, page), sizing.pages - 1);
96
- const start = safe * pageSize;
97
- const items = rows.slice(start, start + pageSize).map((row) => ({ ...row }));
98
- const out: PanelRow[] = [];
99
- if (safe > 0) {
100
- out.push({
101
- key: PAGE_PREV_KEY,
102
- label: "‹ previous page",
103
- value: `${safe + 1}/${sizing.pages}`,
104
- kind: "action",
105
- valueStyle: "muted",
106
- });
107
- }
108
- out.push(...items);
109
- const next = safe + 1 < sizing.pages;
110
- while (out.length < budget) out.push({ key: `info:pad:${out.length}`, label: "", value: "", kind: "info", valueStyle: "muted" });
111
- if (next) {
112
- out[budget - 1] = {
113
- key: PAGE_NEXT_KEY,
114
- label: "next page ›",
115
- value: `${safe + 2}/${sizing.pages}`,
116
- kind: "action",
117
- valueStyle: "muted",
118
- };
119
- }
120
- return { rows: out.slice(0, budget), page: safe, pages: sizing.pages, hidden: Math.max(0, rows.length - (start + pageSize)) };
121
- }
122
-
123
- /** Footer shortcuts, rendered by the panel as one unwrapped dim line. */
124
- export function shortcuts(list: readonly [string, string, string][]): PanelShortcut[] {
125
- return list.map(([key, label, action]) => ({ key: key as PanelShortcut["key"], label, action }));
126
- }