@maheidem/pi-delegate 0.3.2 → 0.6.1

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/mode.ts CHANGED
@@ -17,8 +17,8 @@ import type {
17
17
  } from "./types.ts";
18
18
  import { DELEGATE_MODE_CUSTOM_TYPE } from "./types.ts";
19
19
 
20
- export const STRICT_ALLOWED_TOOLS = new Set(["delegate"]);
21
- export const STRICT_ACTIVE_TOOLS = ["delegate"];
20
+ export const STRICT_ALLOWED_TOOLS = new Set(["delegate", "delegate_status", "delegate_send", "delegate_answer"]);
21
+ export const STRICT_ACTIVE_TOOLS = ["delegate", "delegate_status", "delegate_send", "delegate_answer"];
22
22
 
23
23
  export const STRICT_OVERLAY = [
24
24
  "[DELEGATION-MODE OVERLAY — enforced by the delegate extension]",
package/package.json CHANGED
@@ -1,71 +1,73 @@
1
1
  {
2
- "name": "@maheidem/pi-delegate",
3
- "version": "0.3.2",
4
- "type": "module",
5
- "description": "Foreground isolated delegation and strict coordinator mode for the Pi coding agent.",
6
- "license": "MIT",
7
- "author": "maheidem",
8
- "keywords": [
9
- "pi",
10
- "pi-coding-agent",
11
- "pi-extension",
12
- "delegate",
13
- "subagent",
14
- "orchestration",
15
- "coordinator"
16
- ],
17
- "repository": {
18
- "type": "git",
19
- "url": "git+https://github.com/Maheidem/pi-delegate.git"
20
- },
21
- "bugs": {
22
- "url": "https://github.com/Maheidem/pi-delegate/issues"
23
- },
24
- "homepage": "https://github.com/Maheidem/pi-delegate#readme",
25
- "publishConfig": {
26
- "access": "public"
27
- },
28
- "files": [
29
- "index.ts",
30
- "application.ts",
31
- "commands.ts",
32
- "config.ts",
33
- "mode.ts",
34
- "roles.ts",
35
- "runner.ts",
36
- "rpc-jsonl.ts",
37
- "run-store.ts",
38
- "types.ts",
39
- "version.ts",
40
- "handoff.ts",
41
- "transcript-feed.ts",
42
- "roles/",
43
- "ui/",
44
- "README.md",
45
- "LICENSE"
46
- ],
47
- "scripts": {
48
- "typecheck": "tsc -p tsconfig.json",
49
- "test": "node tests/run.mjs",
50
- "test:unit": "node tests/run.mjs",
51
- "test:e2e": "node tests/e2e.mjs",
52
- "prepack": "npm run typecheck && npm test"
53
- },
54
- "peerDependencies": {
55
- "@earendil-works/pi-coding-agent": ">=0.84.4",
56
- "@earendil-works/pi-tui": "*",
57
- "typebox": "*"
58
- },
59
- "devDependencies": {
60
- "@earendil-works/pi-coding-agent": "^0.84.4",
61
- "@earendil-works/pi-tui": "^0.84.4",
62
- "@types/node": "^22.0.0",
63
- "typebox": "^1.0.17",
64
- "typescript": "^5.9.3"
65
- },
66
- "pi": {
67
- "extensions": [
68
- "./index.ts"
69
- ]
70
- }
71
- }
2
+ "name": "@maheidem/pi-delegate",
3
+ "version": "0.6.1",
4
+ "type": "module",
5
+ "description": "Foreground isolated delegation and strict coordinator mode for the Pi coding agent.",
6
+ "license": "MIT",
7
+ "author": "maheidem",
8
+ "keywords": [
9
+ "pi",
10
+ "pi-coding-agent",
11
+ "pi-extension",
12
+ "delegate",
13
+ "subagent",
14
+ "orchestration",
15
+ "coordinator"
16
+ ],
17
+ "repository": {
18
+ "type": "git",
19
+ "url": "git+https://github.com/Maheidem/pi-delegate.git"
20
+ },
21
+ "bugs": {
22
+ "url": "https://github.com/Maheidem/pi-delegate/issues"
23
+ },
24
+ "homepage": "https://github.com/Maheidem/pi-delegate#readme",
25
+ "publishConfig": {
26
+ "access": "public"
27
+ },
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",
44
+ "roles/",
45
+ "ui/",
46
+ "README.md",
47
+ "LICENSE"
48
+ ],
49
+ "scripts": {
50
+ "typecheck": "tsc -p tsconfig.json",
51
+ "test": "node tests/run.mjs",
52
+ "test:unit": "node tests/run.mjs",
53
+ "test:e2e": "node tests/e2e.mjs",
54
+ "prepack": "npm run typecheck && npm test"
55
+ },
56
+ "peerDependencies": {
57
+ "@earendil-works/pi-coding-agent": ">=0.84.4",
58
+ "@earendil-works/pi-tui": "*",
59
+ "typebox": "*"
60
+ },
61
+ "devDependencies": {
62
+ "@earendil-works/pi-coding-agent": "^0.84.4",
63
+ "@earendil-works/pi-tui": "^0.84.4",
64
+ "@types/node": "^22.0.0",
65
+ "typebox": "^1.0.17",
66
+ "typescript": "^5.9.3"
67
+ },
68
+ "pi": {
69
+ "extensions": [
70
+ "./index.ts"
71
+ ]
72
+ }
73
+ }
package/run-store.ts CHANGED
@@ -98,6 +98,8 @@ export function openRun(agentDir: string, request: DelegateRequest): OpenedRun {
98
98
  usage: { ...EMPTY_USAGE },
99
99
  transcriptPath: paths.transcriptPath,
100
100
  stderrPath: paths.stderrPath,
101
+ ...(request.background ? { background: true } : {}),
102
+ ...(request.description ? { description: request.description } : {}),
101
103
  };
102
104
  atomicWriteJson(paths.metadataPath, metadata);
103
105
 
@@ -209,6 +211,9 @@ export interface RunSummary {
209
211
  finishedAt?: string;
210
212
  durationMs?: number;
211
213
  mtimeMs: number;
214
+ /** R14: background-run marker + description (absent on foreground runs). */
215
+ background?: boolean;
216
+ description?: string;
212
217
  }
213
218
 
214
219
  /** List runs newest-first (by metadata mtime, falling back to createdAt). */
@@ -249,6 +254,8 @@ export function listRuns(agentDir: string, limit = 50): RunSummary[] {
249
254
  ? Date.parse(meta.finishedAt) - Date.parse(meta.startedAt)
250
255
  : undefined,
251
256
  mtimeMs,
257
+ ...(meta.background ? { background: true } : {}),
258
+ ...(meta.description ? { description: meta.description } : {}),
252
259
  });
253
260
  } catch {
254
261
  // unreadable metadata: leave alone; retention will not touch it
package/runner.ts CHANGED
@@ -27,6 +27,7 @@ import { classifyRpcRecord, RpcJsonlParser, type RpcRecord } from "./rpc-jsonl.t
27
27
  import { appendTranscriptRecord, updateRunMetadata, type OpenedRun } from "./run-store.ts";
28
28
  import { formatDuration } from "./config.ts";
29
29
  import { renderHandoff, validateHandoffSubmission, type HandoffSubmission } from "./handoff.ts";
30
+ import { writeAskAnswerFile } from "./ask.ts";
30
31
  import type { FeedEvent } from "./transcript-feed.ts";
31
32
 
32
33
  export interface RunnerConfig {
@@ -89,6 +90,13 @@ export interface RunnerSpawnRequest {
89
90
  sessionPath?: string;
90
91
  /** R3: directory the child's session file is persisted to (new runs). */
91
92
  sessionDir?: string;
93
+ /** R8: this is a background run (ask_parent channel + markers in env). */
94
+ background?: boolean;
95
+ /** R17: answers directory for ask_parent questions ($PI_DELEGATE_ASK_DIR). */
96
+ askDir?: string;
97
+ /** R17: ask budget (env to the child; 0/undefined disables ask_parent). */
98
+ askTimeoutMs?: number;
99
+ askMaxQuestions?: number;
92
100
  }
93
101
 
94
102
  export function buildChildArgs(
@@ -96,8 +104,10 @@ export function buildChildArgs(
96
104
  role: DelegateRole,
97
105
  ): { args: string[]; env: NodeJS.ProcessEnv; promptId: string } {
98
106
  // The mandatory structured-handoff tool is always in the child's
99
- // ceiling; the delegate extension registers it in child mode.
100
- const toolList = [...role.tools, "handoff"].join(",");
107
+ // ceiling; the delegate extension registers it in child mode. Background
108
+ // children (R17/R18) also get ask_parent when the ask channel is enabled.
109
+ const askEnabled = Boolean(req.background && req.askDir && req.askTimeoutMs && req.askTimeoutMs > 0);
110
+ const toolList = [...role.tools, "handoff", ...(askEnabled ? ["ask_parent"] : [])].join(",");
101
111
  // R3: the child's session is DURABLE. New runs persist it under the run
102
112
  // store (--session-dir); resumed runs re-enter the prior session file
103
113
  // directly (--session <file>) so a killed run can be continued in the
@@ -120,17 +130,32 @@ export function buildChildArgs(
120
130
  PI_DELEGATE_CHILD: "1",
121
131
  PI_DELEGATE_RUN_ID: req.runId,
122
132
  PI_DELEGATE_PARENT_PID: String(process.pid),
133
+ ...(askEnabled
134
+ ? {
135
+ PI_DELEGATE_BACKGROUND: "1",
136
+ PI_DELEGATE_ASK_DIR: req.askDir,
137
+ PI_DELEGATE_ASK_TIMEOUT_MS: String(req.askTimeoutMs),
138
+ PI_DELEGATE_ASK_MAX: String(req.askMaxQuestions ?? 5),
139
+ }
140
+ : {}),
123
141
  };
124
142
  return { args, env, promptId: `delegate:${req.runId}:prompt` };
125
143
  }
126
144
 
127
- function buildPromptMessage(runId: string, role: string, task: string, resumeOf?: string): string {
145
+ function buildPromptMessage(runId: string, role: string, task: string, resumeOf?: string, background?: boolean): string {
128
146
  const resumeNote = resumeOf
129
147
  ? `You are RESUMING the child session of run ${resumeOf} (its earlier turns are in your context). Continue from where that run left off.\n`
130
148
  : "";
149
+ const askContract = background
150
+ ? `You have an ask_parent channel to the parent agent:\n` +
151
+ `- ask_parent(kind="question") BLOCKS until the parent answers (or the budget expires — then proceed with your best judgment and state the assumption in your handoff).\n` +
152
+ `- ask_parent(kind="note") files a non-blocking note (risks, observations, concerns) and never stalls your run.\n` +
153
+ `- Ask ONLY when you are genuinely blocked or a wrong guess is expensive; for cheap decisions proceed with a stated assumption.\n\n`
154
+ : "";
131
155
  return (
132
156
  `[delegated child run · id=${runId} · role=${role}]\n` +
133
157
  resumeNote +
158
+ askContract +
134
159
  `This task came from a parent Pi session. Work only on this task.\n` +
135
160
  `Do not delegate or attempt to contact the parent during execution.\n` +
136
161
  `Follow the role output contract exactly.\n\n` +
@@ -243,6 +268,8 @@ export class DelegateRunner {
243
268
  private lastAssistant: AssistantFinal | null = null;
244
269
  /** R1: toolCallIds with a start but no matching end yet. */
245
270
  private openToolCalls = new Set<string>();
271
+ /** R17: open ask_parent questions (watchdog-suspended while non-empty). */
272
+ private askOpenIds = new Set<string>();
246
273
  /** Feed: toolCallId → start ms (for end-event durations). */
247
274
  private toolStartedAt = new Map<string, number>();
248
275
  /** Feed: toolCallId → tool name. */
@@ -279,6 +306,8 @@ export class DelegateRunner {
279
306
  private readonly listeners: Array<{ remove: () => void }> = [];
280
307
  private transcriptSeq = 0;
281
308
  private readonly promptId: string;
309
+ /** R16: steering sequence (follow_up record ids). */
310
+ private steerSeq = 0;
282
311
 
283
312
  constructor(opened: OpenedRun, req: RunnerSpawnRequest, cfg: RunnerConfig, hooks: RunHooks = {}, resolveInvocation?: PiInvocationResolver) {
284
313
  this.opened = opened;
@@ -408,7 +437,7 @@ export class DelegateRunner {
408
437
  child.stdin?.on("error", () => {});
409
438
 
410
439
  // Send the single prompt over RPC stdin.
411
- const promptMessage = buildPromptMessage(this.runId, role.name, this.req.task, this.req.resumeOf);
440
+ const promptMessage = buildPromptMessage(this.runId, role.name, this.req.task, this.req.resumeOf, this.req.background);
412
441
  const promptRecord = JSON.stringify({ id: this.promptId, type: "prompt", message: promptMessage });
413
442
  try {
414
443
  child.stdin?.write(`${promptRecord}\n`);
@@ -450,6 +479,14 @@ export class DelegateRunner {
450
479
  * still hits the normal inactivity budget. */
451
480
  private armInactivity(): void {
452
481
  if (this.finalizing || !this.child) return;
482
+ // R17: an open ask_parent question suspends the idle/stuck watchdogs —
483
+ // the child is legitimately blocked on the parent; only the hard cap
484
+ // still applies (armInactivity simply doesn't re-arm).
485
+ if (this.askOpenIds.size > 0) {
486
+ if (this.inactivityTimer) clearTimeout(this.inactivityTimer);
487
+ this.inactivityTimer = null;
488
+ return;
489
+ }
453
490
  if (this.inactivityTimer) clearTimeout(this.inactivityTimer);
454
491
  const budget = this.openToolCalls.size > 0
455
492
  ? this.cfg.stuckToolTimeoutMs ?? this.cfg.hardTimeoutMs
@@ -542,6 +579,27 @@ export class DelegateRunner {
542
579
  this.toolNames.delete(cls.id);
543
580
  this.toolDetails.delete(cls.id);
544
581
  }
582
+ // R17: ask_parent channel — fire the hook and (for questions)
583
+ // suspend the watchdogs while the child waits for the parent.
584
+ if (cls.toolName === "ask_parent") {
585
+ if (cls.phase === "start") {
586
+ const kind = cls.args?.kind === "note" ? "note" : "question";
587
+ if (kind === "question") this.askOpenIds.add(cls.id);
588
+ this.hooks.onAsk?.({
589
+ runId: this.runId,
590
+ phase: "start",
591
+ kind,
592
+ topic: typeof cls.args?.topic === "string" ? cls.args.topic : "",
593
+ text: typeof (cls.args?.text ?? cls.args?.question ?? cls.args?.note) === "string"
594
+ ? String(cls.args?.text ?? cls.args?.question ?? cls.args?.note)
595
+ : "",
596
+ toolCallId: cls.id,
597
+ });
598
+ } else if (cls.phase === "end") {
599
+ const wasOpen = this.askOpenIds.delete(cls.id);
600
+ this.hooks.onAsk?.({ runId: this.runId, phase: "end", kind: wasOpen ? "question" : "note", topic: "", text: "", toolCallId: cls.id });
601
+ }
602
+ }
545
603
  // a tool event resets the watchdog to the right budget
546
604
  this.armInactivity();
547
605
  }
@@ -650,6 +708,41 @@ export class DelegateRunner {
650
708
  * A user/parent `cancelled` keeps the OLD fast path (2 s → SIGTERM):
651
709
  * the caller asked to stop, not to negotiate.
652
710
  */
711
+ /**
712
+ * R16: write ONE steering message to the live child as an RPC
713
+ * `follow_up` record (pi steering semantics: queued before the next
714
+ * model call, never interrupts). Only valid while the run is live;
715
+ * terminal runs point at resumeFrom. Steering re-arms the idle
716
+ * watchdog (a steer that lands between turns must not read as a stall).
717
+ */
718
+ steer(message: string): { ok: true } | { ok: false; error: string } {
719
+ if (this.finalizing || this.cancelRequested || this.settled) {
720
+ return { ok: false, error: `run ${this.runId} is no longer live (finished or finishing); continue it with delegate({ resumeFrom: "${this.runId}", … }) instead.` };
721
+ }
722
+ const child = this.child;
723
+ if (!child || child.killed || child.exitCode !== null) {
724
+ return { ok: false, error: `run ${this.runId} has no live child process.` };
725
+ }
726
+ try {
727
+ this.steerSeq += 1;
728
+ const record = JSON.stringify({ id: `delegate:${this.runId}:steer:${this.steerSeq}`, type: "follow_up", message });
729
+ child.stdin?.write(`${record}\n`);
730
+ this.noteActivity();
731
+ return { ok: true };
732
+ } catch (error) {
733
+ return { ok: false, error: `could not write steering message: ${(error as Error).message}` };
734
+ }
735
+ }
736
+
737
+ /**
738
+ * R17: write the parent's answer for a pending ask_parent question. The
739
+ * blocked child's execute() resolves the moment this file appears.
740
+ */
741
+ writeAskAnswer(toolCallId: string, payload: { answeredBy: "model" | "user"; answeredAt: string; answer: string }): void {
742
+ if (!this.req.askDir) throw new Error(`run ${this.runId} has no ask directory.`);
743
+ writeAskAnswerFile(this.req.askDir, toolCallId, payload);
744
+ }
745
+
653
746
  cancel(state: RunTerminalState): void {
654
747
  if (this.finalizing) return;
655
748
  // §9.7 — the FIRST cancellation wins; later cancels are no-ops.
package/types.ts CHANGED
@@ -47,6 +47,7 @@ export const DELEGATE_ERROR_CODES = [
47
47
  "E_TIMEOUT_HARD",
48
48
  "E_MODE_PERSIST",
49
49
  "E_TOOL_RESTORE",
50
+ "E_BACKGROUND_FULL",
50
51
  "E_ORPHANED_RUN",
51
52
  ] as const;
52
53
  export type DelegateErrorCode = (typeof DELEGATE_ERROR_CODES)[number];
@@ -81,8 +82,8 @@ export interface DelegateUsage {
81
82
  output: number;
82
83
  cacheRead: number;
83
84
  cacheWrite: number;
85
+ contextTokens?: number;
84
86
  cost: number;
85
- contextTokens: number;
86
87
  turns: number;
87
88
  }
88
89
 
@@ -120,6 +121,10 @@ export interface DelegateRequest {
120
121
  projectRoot?: string;
121
122
  /** R3: resume a prior run's child session (its session file is re-entered). */
122
123
  resumeFrom?: string;
124
+ /** R8: run as a background delegation (non-blocking tool call). */
125
+ background?: boolean;
126
+ /** R8: 3–6-word purpose summary, required when background. */
127
+ description?: string;
123
128
  }
124
129
 
125
130
  /** Bounded, parent-visible tool result details (schema v1). */
@@ -229,6 +234,10 @@ export interface RunMetadataV1 {
229
234
  stderrPath: string;
230
235
  /** Present only on manually curated receipts (one-time data repair). */
231
236
  curationNote?: string;
237
+ /** R8: this run was spawned as a background delegation. */
238
+ background?: boolean;
239
+ /** R8: validated 3–6-word purpose summary (background runs). */
240
+ description?: string;
232
241
  }
233
242
 
234
243
  export interface TranscriptRecordV1 {
@@ -278,6 +287,49 @@ export interface SessionEntryLike {
278
287
  type?: unknown;
279
288
  customType?: unknown;
280
289
  data?: unknown;
290
+ /** Custom messages carry their delivery details (R12 dedup scans). */
291
+ details?: unknown;
292
+ }
293
+
294
+ /** R11: `delegate.background` ledger entries (schema v1, session JSONL). */
295
+ export interface BackgroundCreatedEntry {
296
+ v: 1;
297
+ type: "created";
298
+ runId: string;
299
+ role: RoleName;
300
+ description: string;
301
+ createdAt: string;
302
+ }
303
+
304
+ export interface BackgroundFinishedEntry {
305
+ v: 1;
306
+ type: "finished";
307
+ runId: string;
308
+ state: RunTerminalState;
309
+ finishedAt: string;
310
+ }
311
+
312
+ export type BackgroundLedgerEntry = BackgroundCreatedEntry | BackgroundFinishedEntry;
313
+
314
+ /** R8: projected background-run state on the current branch. */
315
+ export interface BackgroundRunRecord {
316
+ created: BackgroundCreatedEntry;
317
+ finished?: BackgroundFinishedEntry;
318
+ }
319
+
320
+ /** R8: live handle for a background run spawned by this session. */
321
+ export interface BackgroundRunHandle {
322
+ runId: string;
323
+ role: RoleName;
324
+ description: string;
325
+ /** Cancels the child (R13 shutdown / user cancel). */
326
+ cancel: (reason?: string) => void;
327
+ /** R16: steering to the live child (background runs only). */
328
+ steer?: (message: string) => { ok: true } | { ok: false; error: string };
329
+ /** R17: write an answer file for a pending ask_parent question. */
330
+ writeAnswer?: (toolCallId: string, payload: { answeredBy: "model" | "user"; answeredAt: string; answer: string }) => void;
331
+ /** Resolves with the terminal DelegateRunResult (never rejects). */
332
+ completion: Promise<DelegateRunResult>;
281
333
  }
282
334
 
283
335
  export interface ModeReplayResult {
@@ -389,6 +441,8 @@ export type RunHooks = {
389
441
  onUpdate?: (update: RunStreamUpdate) => void;
390
442
  /** Live feed events for the running panel and peek views (every event, unthrottled). */
391
443
  onEvent?: (event: FeedEvent) => void;
444
+ /** R17/R18: ask_parent channel events from the child stream. */
445
+ onAsk?: (ask: { runId: string; phase: "start" | "end"; kind: "question" | "note"; topic: string; text: string; toolCallId: string }) => void;
392
446
  abortSignal?: AbortSignal;
393
447
  };
394
448
 
@@ -432,6 +486,10 @@ export interface DelegateApplication {
432
486
  enableStrict(ctx: ModeTransitionContext): Promise<ModeResult>;
433
487
  disableStrict(ctx: ModeTransitionContext): Promise<ModeResult>;
434
488
  run(request: DelegateRequest, hooks?: RunHooks): Promise<RunAttemptResult>;
489
+ /** R8: spawn a background run (no slot reservation, no queue). Returns a
490
+ * validation error result, or a live handle whose completion resolves at
491
+ * the terminal state. */
492
+ runBackground(request: DelegateRequest): { error: DelegateRunResult } | { handle: BackgroundRunHandle };
435
493
  cancel(runId?: string): Promise<CancelResult>;
436
494
  inspect(runId?: string, includeTranscript?: boolean): RunInspection;
437
495
  doctor(): DoctorReport;
package/ui/format.ts CHANGED
@@ -1,16 +1,41 @@
1
1
  /**
2
- * delegate — shared formatting (reuse mandate, FIELDS.md §2).
2
+ * canonical kit formatting primitive (v1) — vendored byte-identical;
3
+ * consumers: extensions/ui/format.ts; guard: scripts/check-vendored.mjs
3
4
  *
4
5
  * ONE module all views import so tokens/durations/sizes/model render
5
- * identically across home, live strip, inline tool card, and peek. Wraps the
6
- * canonical `formatDuration` (config.ts) rather than re-rolling it. Replaces
7
- * the duplicate `fmtDuration`/`fmtTokens` that used to live in running-view.
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`.
8
21
  */
9
22
 
10
- import { formatDuration } from "../config.ts";
11
-
12
- /** Canonical duration (ms → "41s"/"30m 22s"/"2h"). */
13
- export { formatDuration };
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
+ }
14
39
 
15
40
  /** Token count: 0 if falsy; raw <1000; else `X.Yk`; else `X.YM`. */
16
41
  export function formatTokens(n: number | undefined): string {
@@ -90,3 +115,6 @@ export function progressBar(frac: number, width: number): string {
90
115
  const filled = Math.round(f * w);
91
116
  return `${"█".repeat(filled)}${"░".repeat(Math.max(0, w - filled))} ${Math.round(f * 100)}%`;
92
117
  }
118
+
119
+ /** Canonical duration (ms → "41s"/"30m 22s"/"2h"). */
120
+ export { formatDuration };
@@ -0,0 +1,126 @@
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
+ }