@maheidem/pi-delegate 0.7.2 → 0.8.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.
package/CHANGELOG.md ADDED
@@ -0,0 +1,11 @@
1
+ # Changelog
2
+
3
+ ## [0.8.0]
4
+
5
+ - Move the runtime code to `extensions/`. The pi entry is `./extensions/index.ts`.
6
+ - Import the shared UI parts from `@maheidem/pi-panel-kit`. The local copies are gone.
7
+ - Export `CONFIG_PATH` from `extensions/config.ts`. `/delegate paths` prints it.
8
+ - Use the canonical test runner and tarball test of the kit.
9
+ - Export `COMMAND_NAME` from `extensions/metadata.ts`. The command name stays `delegate`.
10
+ - Align `package.json` with the standard: every peer is `*`, the dev host packages match pi 1.6.1, `engines.node` is `>=18`.
11
+ - Stop tracking `.planning/`. The files stay on disk, ignored.
package/README.md CHANGED
@@ -10,17 +10,14 @@ structured metadata, full transcript on disk), and can put the parent session
10
10
  into a **strict coordinator mode** where the parent may only delegate — the
11
11
  gate is an allowlist and exceptions fail closed.
12
12
 
13
- ## Install (source of truth: this workspace)
13
+ ## Install
14
14
 
15
15
  ```bash
16
- # development: run from a pi session in this repo
17
- pi # /delegate is auto-discovered from .pi/extensions or ~/.pi/agent/extensions
16
+ pi install npm:@maheidem/pi-delegate@<x.y.z>
18
17
  ```
19
18
 
20
- Register globally by copying/symlinking `custom-extensions/delegate` into
21
- `~/.pi/agent/extensions/delegate` and adding it to
22
- `~/.pi/agent/settings.json → packages`, then `/reload`. No automated install
23
- is performed by this package.
19
+ Use the exact version. Then run `/reload` in each open pi session.
20
+ To try a local checkout without an install, run `pi -e ./extensions/index.ts` in this repo.
24
21
 
25
22
  ## Usage
26
23
 
@@ -48,8 +45,8 @@ Any unrecognized first word is shorthand for `run general …`.
48
45
 
49
46
  ### Terminal UI (v0.3.0)
50
47
 
51
- One centralized experience built on the vendored canonical `SettingsPanel`
52
- (never a bespoke panel). Everything reachable from the panel is also reachable
48
+ One centralized experience built on the `SettingsPanel` of
49
+ `@maheidem/pi-panel-kit` (never a bespoke panel). Everything reachable from the panel is also reachable
53
50
  as a nested command and from headless stdout — the same application method.
54
51
 
55
52
  - **Home dashboard** (`/delegate`, TUI) — health summary (version · mode,
@@ -75,8 +72,7 @@ as a nested command and from headless stdout — the same application method.
75
72
  - **Destructive actions** (cancel, strict on/off) require confirmation.
76
73
 
77
74
  Headless (`pi -p` / child mode) prints the same status/doctor/paths text, so
78
- panel ≡ command ≡ headless. Screens with pixel evidence live in
79
- `.planning/ui-redesign-2026-09-04/evidence/` (see `manifest.json`).
75
+ panel ≡ command ≡ headless. The screen captures of the UI work are not in this repo.
80
76
 
81
77
  ### Timeouts
82
78
 
@@ -284,6 +280,14 @@ never free text we hope has the right shape:
284
280
  apply after `/reload` in that session — the version line makes a stale
285
281
  copy self-evident instead of indistinguishable from a regression.
286
282
 
283
+ ## Configuration
284
+
285
+ - The user config file is `<agent dir>/delegate/config.json`. The agent dir comes from `getAgentDir()` (normally `~/.pi/agent`). The code exports the path as `CONFIG_PATH` from `extensions/config.ts`.
286
+ - A project file `<project>/.pi/delegate/config.json` overlays the user config key by key (see "Timeouts").
287
+ - The run store is `<agent dir>/delegate/runs/`. It keeps the newest `maxRuns` terminal receipts (default 50).
288
+ - `/delegate paths` prints the config file, the run store and the agent dir.
289
+ - The dashboard edits the same keys. A corrupt file is kept as evidence and the defaults load.
290
+
287
291
  ## Safety model (selected invariants)
288
292
 
289
293
  - The delegated task travels over child **RPC stdin**, never argv.
@@ -311,7 +315,7 @@ never free text we hope has the right shape:
311
315
  repairs are recorded on the receipt in a `curationNote` field (one-time
312
316
  2026-09-03 repair: receipts clobbered by pre-0.1.5 orphan recovery and
313
317
  later removed by retention were reconstructed from the parent sessions'
314
- delegate tool results — see `.planning/`, excluded from the npm tarball).
318
+ delegate tool results; the evidence is not in this repo).
315
319
  - Strict mode is session-scoped, replayed per branch (tree/resume/fork safe),
316
320
  persisted via session custom entries; persistence failures degrade loudly
317
321
  but never silently disable the gate.
@@ -321,22 +325,29 @@ never free text we hope has the right shape:
321
325
  ## Development
322
326
 
323
327
  ```bash
328
+ npm install
324
329
  npm run typecheck # strict tsc, no emit
325
- npm test # unit + runner (real RPC children) + application + UI + load
330
+ npm test # tests/run.mjs: each tests/*.test.ts file with an isolated HOME
326
331
  npm run test:e2e # real pi session E2E (needs a working default model)
327
332
  # E2E_SCENARIOS=D,F runs a targeted subset
333
+ npm pack --dry-run # the packed file list
328
334
  ```
329
335
 
330
- Design: `types.ts`/`config.ts`/`mode.ts`/`run-store.ts`/`rpc-jsonl.ts`/
331
- `runner.ts`/`application.ts` are Pi-free domain modules; `index.ts` is the
332
- sole Pi adapter (loads through jiti exactly as pi loads extensions; registers
333
- only `/delegate`, the `delegate` tool, and the `delegate-handoff` renderer).
336
+ `npm test` never starts a live pi. `@maheidem/pi-panel-kit` supplies the generic UI parts and the test runner.
337
+
338
+ Design: the runtime code is in `extensions/`. `types.ts`/`config.ts`/`mode.ts`/`run-store.ts`/`rpc-jsonl.ts`/
339
+ `runner.ts`/`application.ts` are Pi-free domain modules; `extensions/index.ts` is the
340
+ sole Pi adapter (loads through jiti exactly as pi loads extensions). The role prompts are in `roles/`.
334
341
 
335
342
  ## Provenance / attribution
336
343
 
337
344
  Built against `@earendil-works/pi-coding-agent` 0.84.4 and its official
338
- `subagent` and `plan-mode` extension examples (MIT). `ui/settings-panel.ts`
339
- is vendored from the local `/loop` extension's control panel (same author,
340
- same workspace; pi-extension-builder v0.1.0 template). RPC protocol shapes
345
+ `subagent` and `plan-mode` extension examples (MIT). The `SettingsPanel` came
346
+ from the `/loop` extension's control panel (same author). It is now part of
347
+ `@maheidem/pi-panel-kit`. RPC protocol shapes
341
348
  follow the installed pi RPC documentation (`docs/rpc.md`) in
342
349
  `@earendil-works/pi-coding-agent`.
350
+
351
+ ## License
352
+
353
+ MIT
@@ -116,6 +116,14 @@ export function registerAskParentTool(pi: ExtensionAPI, env: AskEnv): void {
116
116
  "Ask the delegating parent agent a question (you block until it answers or the budget expires) or file a non-blocking note. " +
117
117
  "Ask only when you are genuinely blocked or a wrong guess is expensive; for cheap decisions proceed with a stated assumption instead. " +
118
118
  "Prefer notes for risks and observations — they never stall your run.",
119
+ // Pi >= 1.0 lists an extension tool in the system prompt's <tools> section
120
+ // only when it has a promptSnippet. Without one, small models read that
121
+ // list, say "I don't have an ask_parent tool" and never call it, even
122
+ // though the tool is declared to the provider.
123
+ promptSnippet: "Ask the delegating parent agent a question (blocks until it answers) or file a non-blocking note",
124
+ promptGuidelines: [
125
+ "ask_parent is a real tool in this session. When the user or task tells you to ask the parent, call ask_parent; do not say it is unavailable.",
126
+ ],
119
127
  parameters: AskParentParams,
120
128
  async execute(toolCallId: string, params): Promise<AskToolResult> {
121
129
  const validation = validateAskSubmission(params);
@@ -5,6 +5,7 @@
5
5
 
6
6
  import * as fs from "node:fs";
7
7
  import * as path from "node:path";
8
+ import { getAgentDir } from "@earendil-works/pi-coding-agent";
8
9
  import type { RoleName } from "./types.ts";
9
10
  import { ROLE_NAMES } from "./types.ts";
10
11
 
@@ -213,6 +214,9 @@ function applyKnownField(config: DelegateConfigV1, key: string, value: unknown):
213
214
  ) as never;
214
215
  }
215
216
 
217
+ /** The config file of this extension: `<agent dir>/delegate/config.json`. */
218
+ export const CONFIG_PATH = path.join(getAgentDir(), "delegate", "config.json");
219
+
216
220
  export interface ConfigLoadResult {
217
221
  config: DelegateConfigV1;
218
222
  unknownKeys: string[];
@@ -21,7 +21,8 @@ import {
21
21
  } from "@earendil-works/pi-coding-agent";
22
22
  import { Text } from "@earendil-works/pi-tui";
23
23
 
24
- import { formatDuration, loadConfig, parseDuration, saveConfig } from "./config.ts";
24
+ import { CONFIG_PATH, formatDuration, loadConfig, parseDuration, saveConfig } from "./config.ts";
25
+ import { COMMAND_NAME } from "./metadata.ts";
25
26
  import * as fsSync from "node:fs";
26
27
  import { delegateVersion } from "./version.ts";
27
28
  import { HandoffToolParams, validateHandoffSubmission, type HandoffSubmission } from "./handoff.ts";
@@ -39,9 +40,9 @@ import type {
39
40
  RunStreamUpdate,
40
41
  SessionEntryLike,
41
42
  } from "./types.ts";
42
- import { SettingsPanel, type PanelSnapshot, type PanelActionResult, type PanelSection, type PanelRow } from "./ui/settings-panel.ts";
43
- import { shortModel, formatTokens, formatCost, stateGlyph, progressBar, projectValueCell } from "./ui/format.ts";
44
- import { renderToolCallCard, renderToolPlainCard, renderToolResultCard, type ToolCardLine } from "./ui/tool-card.ts";
43
+ import { SettingsPanel, type PanelSnapshot, type PanelActionResult, type PanelSection, type PanelRow } from "@maheidem/pi-panel-kit";
44
+ import { shortModel, formatTokens, formatCost, stateGlyph, progressBar, projectValueCell } from "@maheidem/pi-panel-kit";
45
+ import { renderToolCallCard, renderToolPlainCard, renderToolResultCard, type ToolCardLine } from "@maheidem/pi-panel-kit";
45
46
  import { RunningView, type RunningViewState } from "./ui/running-view.ts";
46
47
  import { PeekView } from "./ui/peek-view.ts";
47
48
  import { FeedRing, feedEventsFromTranscript, renderFeedEvents } from "./transcript-feed.ts";
@@ -150,6 +151,13 @@ function registerChildHandoffTool(pi: ExtensionAPI): void {
150
151
  "MANDATORY final report for this delegated run. Your run does not complete until this tool " +
151
152
  "has been called with a valid submission; free-text endings are rejected and you will be re-prompted. " +
152
153
  "When terminated mid-work, call it immediately with outcome=partial.",
154
+ // Pi >= 1.0 lists an extension tool in the system prompt's <tools> section
155
+ // only when it has a promptSnippet. Without one, small models read that
156
+ // list, say "I don't have a handoff tool" and end with free text instead.
157
+ promptSnippet: "Submit the mandatory structured final report for this delegated run",
158
+ promptGuidelines: [
159
+ "handoff is a real tool in this session. End the run by calling handoff; do not end with free text or say the tool is unavailable.",
160
+ ],
153
161
  parameters: HandoffToolParams,
154
162
  async execute(_toolCallId, params): Promise<{
155
163
  content: Array<{ type: "text"; text: string }>;
@@ -205,9 +213,12 @@ export default function delegateExtension(pi: ExtensionAPI) {
205
213
  }
206
214
  // 2. Construct state — no child, no timers at load time.
207
215
  // PI_DELEGATE_AGENT_DIR is a test override; production uses getAgentDir().
208
- const agentDir = process.env.PI_DELEGATE_AGENT_DIR || getAgentDir();
216
+ const agentDirOverride = process.env.PI_DELEGATE_AGENT_DIR;
217
+ const agentDir = agentDirOverride || getAgentDir();
209
218
  const { config, unknownKeys, recoveredFromCorrupt, corruptEvidencePath } = loadConfig(agentDir);
210
219
  const app = new DelegateApplicationImpl({ agentDir, config });
220
+ // The paths verb prints CONFIG_PATH. The test override moves the file below its own dir.
221
+ const configPath = agentDirOverride ? app.paths().configPath : CONFIG_PATH;
211
222
  // Startup orphan recovery (§10.6): receipts only; never kills PIDs.
212
223
  app.markOrphansOnStartup();
213
224
 
@@ -1171,7 +1182,7 @@ export default function delegateExtension(pi: ExtensionAPI) {
1171
1182
 
1172
1183
  // ── 4. /delegate command ───────────────────────────────────────────────
1173
1184
 
1174
- pi.registerCommand("delegate", {
1185
+ pi.registerCommand(COMMAND_NAME, {
1175
1186
  description: "Delegate tasks to isolated child Pi sessions; strict delegation mode gate.",
1176
1187
  getArgumentCompletions: (prefix: string) => {
1177
1188
  const items = delegateCompletions(prefix, app.recentRunIds(6)).map((v) => ({ value: v, label: v }));
@@ -1185,7 +1196,7 @@ export default function delegateExtension(pi: ExtensionAPI) {
1185
1196
  return;
1186
1197
  case "paths": {
1187
1198
  const p = app.paths();
1188
- say(ctx, ["[delegate paths]", `config: ${p.configPath}`, `runs: ${p.runsDir}`, `agent: ${p.agentDir}`].join("\n"));
1199
+ say(ctx, ["[delegate paths]", `config: ${configPath}`, `runs: ${p.runsDir}`, `agent: ${p.agentDir}`].join("\n"));
1189
1200
  return;
1190
1201
  }
1191
1202
  case "doctor":
@@ -1657,7 +1668,7 @@ export default function delegateExtension(pi: ExtensionAPI) {
1657
1668
  }
1658
1669
  if (action === "paths") {
1659
1670
  const p = app.paths();
1660
- say(ctx, [`[delegate paths]`, `config: ${p.configPath}`, `runs: ${p.runsDir}`].join("\n"));
1671
+ say(ctx, [`[delegate paths]`, `config: ${configPath}`, `runs: ${p.runsDir}`].join("\n"));
1661
1672
  continue;
1662
1673
  }
1663
1674
  if (action === "inspect-last") {
@@ -0,0 +1,2 @@
1
+ /** Names that pi sees. Keep them stable: users and scripts type them. */
2
+ export const COMMAND_NAME = "delegate";
@@ -12,7 +12,8 @@ import * as url from "node:url";
12
12
  import type { DelegateRole, RoleName } from "./types.ts";
13
13
  import { ROLE_NAMES } from "./types.ts";
14
14
 
15
- const HERE = path.dirname(url.fileURLToPath(import.meta.url));
15
+ // The roles/ folder is at the package root, one level above extensions/.
16
+ const HERE = path.dirname(path.dirname(url.fileURLToPath(import.meta.url)));
16
17
 
17
18
  const GENERAL_TOOLS = ["read", "bash", "edit", "write", "grep", "find", "ls"] as const;
18
19
  const RESEARCH_TOOLS = [
@@ -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.2",
3
+ "version": "0.8.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
- }
@@ -1,393 +0,0 @@
1
- /** pi-extension-builder SettingsPanel v0.1.0 — canonical source and vendored primitive. */
2
- import type { KeybindingsManager, Theme } from "@earendil-works/pi-coding-agent";
3
- import {
4
- Input,
5
- matchesKey,
6
- truncateToWidth,
7
- visibleWidth,
8
- type Component,
9
- type Focusable,
10
- type KeyId,
11
- } from "@earendil-works/pi-tui";
12
-
13
- export type PanelRowKind = "toggle" | "input" | "cycle" | "action" | "info";
14
- export type PanelValueStyle = "accent" | "success" | "warning" | "error" | "muted" | "text";
15
-
16
- export interface PanelRow {
17
- key: string;
18
- label: string;
19
- value: string;
20
- kind: PanelRowKind;
21
- rawValue?: string;
22
- choices?: string[];
23
- inputHint?: string;
24
- valueStyle?: PanelValueStyle;
25
- disabled?: boolean;
26
- }
27
-
28
- export interface PanelSection {
29
- title: string;
30
- rows: PanelRow[];
31
- }
32
-
33
- export interface PanelShortcut {
34
- key: KeyId;
35
- label: string;
36
- action: string;
37
- }
38
-
39
- export interface PanelSnapshot {
40
- title: string;
41
- summaryLines?: string[];
42
- sections: PanelSection[];
43
- detailLines?: string[];
44
- idleMessage?: string;
45
- shortcuts?: PanelShortcut[];
46
- }
47
-
48
- export type PanelActionResult =
49
- | { kind: "updated"; message?: string }
50
- | { kind: "close"; action: string }
51
- | { kind: "error"; message: string }
52
- | { kind: "none" };
53
-
54
- export interface PanelResult {
55
- action?: string;
56
- }
57
-
58
- export interface SettingsPanelHost {
59
- theme: Theme;
60
- keybindings: KeybindingsManager;
61
- initialKey?: string;
62
- snapshot(): PanelSnapshot;
63
- /** Apply a canonical setting value. Return an error string or null. */
64
- apply(key: string, rawValue: string): string | null;
65
- activate(key: string): PanelActionResult | void;
66
- requestRender(): void;
67
- done(result: PanelResult): void;
68
- }
69
-
70
- type FlashKind = "error" | "success" | "info";
71
- interface Flash {
72
- kind: FlashKind;
73
- text: string;
74
- }
75
-
76
- /**
77
- * Reusable, synchronous control panel.
78
- *
79
- * Business logic stays in the host. The panel owns only navigation, editing,
80
- * rendering, and transient feedback. Async or destructive actions should
81
- * close with an action result and be handled by the command adapter.
82
- */
83
- export class SettingsPanel implements Component, Focusable {
84
- private readonly host: SettingsPanelHost;
85
- private snapshotValue: PanelSnapshot;
86
- private cursor = 0;
87
- private editingKey: string | null = null;
88
- private input: Input | null = null;
89
- private flash: Flash | null = null;
90
- private _focused = false;
91
-
92
- constructor(host: SettingsPanelHost) {
93
- this.host = host;
94
- this.snapshotValue = host.snapshot();
95
- if (host.initialKey) this.focusRow(host.initialKey);
96
- this.clampCursor();
97
- }
98
-
99
- get focused(): boolean {
100
- return this._focused;
101
- }
102
-
103
- set focused(value: boolean) {
104
- this._focused = value;
105
- if (this.input) this.input.focused = value;
106
- }
107
-
108
- invalidate(): void {
109
- this.input?.invalidate();
110
- }
111
-
112
- handleInput(data: string): void {
113
- if (this.input) {
114
- this.input.handleInput(data);
115
- this.host.requestRender();
116
- return;
117
- }
118
-
119
- const kb = this.host.keybindings;
120
- if (kb.matches(data, "tui.select.cancel") || matchesKey(data, "q")) {
121
- this.host.done({});
122
- return;
123
- }
124
-
125
- if (kb.matches(data, "tui.select.up") || matchesKey(data, "k")) {
126
- this.move(-1);
127
- } else if (kb.matches(data, "tui.select.down") || matchesKey(data, "j")) {
128
- this.move(1);
129
- } else if (kb.matches(data, "tui.select.confirm") || matchesKey(data, "space")) {
130
- this.activateCurrent();
131
- } else {
132
- const shortcut = this.snapshotValue.shortcuts?.find((candidate) => matchesKey(data, candidate.key));
133
- if (!shortcut) return;
134
- this.runAction(shortcut.action, shortcut.label);
135
- }
136
-
137
- this.host.requestRender();
138
- }
139
-
140
- render(width: number): string[] {
141
- const t = this.host.theme;
142
- const lines: string[] = [this.topBorder(width, this.snapshotValue.title)];
143
-
144
- for (const line of this.snapshotValue.summaryLines ?? []) {
145
- lines.push(this.boxLine(t.fg("muted", ` ${line}`), width));
146
- }
147
-
148
- const selectedKey = this.selectableRows()[this.cursor]?.key;
149
- for (const section of this.snapshotValue.sections) {
150
- lines.push(this.boxLine(t.fg("accent", t.bold(` ${section.title}`)), width));
151
- for (const row of section.rows) {
152
- lines.push(this.renderRow(row, row.key === selectedKey, width));
153
- }
154
- }
155
-
156
- for (const line of this.snapshotValue.detailLines ?? []) {
157
- lines.push(this.boxLine(t.fg("dim", ` ${line}`), width));
158
- }
159
-
160
- lines.push(this.boxLine(this.renderMessageLine(), width));
161
- const shortcutLine = this.renderShortcutLine();
162
- if (shortcutLine) lines.push(this.boxLine(t.fg("dim", ` ${shortcutLine}`), width));
163
- lines.push(this.boxLine(t.fg("dim", ` ${this.renderNavigationLine()}`), width));
164
- lines.push(this.bottomBorder(width));
165
- return lines;
166
- }
167
-
168
- private allRows(): PanelRow[] {
169
- return this.snapshotValue.sections.flatMap((section) => section.rows);
170
- }
171
-
172
- private selectableRows(): PanelRow[] {
173
- return this.allRows().filter((row) => row.kind !== "info" && !row.disabled);
174
- }
175
-
176
- private focusRow(key: string): void {
177
- const index = this.selectableRows().findIndex((row) => row.key === key);
178
- if (index >= 0) this.cursor = index;
179
- }
180
-
181
- private clampCursor(): void {
182
- const rows = this.selectableRows();
183
- this.cursor = Math.max(0, Math.min(this.cursor, Math.max(0, rows.length - 1)));
184
- }
185
-
186
- /** Refresh derived rows while preserving the current selection when possible. */
187
- refresh(preferredKey?: string): void {
188
- const currentKey = preferredKey ?? this.selectableRows()[this.cursor]?.key;
189
- this.snapshotValue = this.host.snapshot();
190
- if (currentKey) this.focusRow(currentKey);
191
- this.clampCursor();
192
- }
193
-
194
- private move(delta: number): void {
195
- const rows = this.selectableRows();
196
- if (!rows.length) return;
197
- this.cursor = (this.cursor + delta + rows.length) % rows.length;
198
- this.flash = null;
199
- }
200
-
201
- private activateCurrent(): void {
202
- const row = this.selectableRows()[this.cursor];
203
- if (!row) return;
204
-
205
- if (row.kind === "input") {
206
- this.startEdit(row.key, row.rawValue ?? "");
207
- return;
208
- }
209
-
210
- if (row.kind === "toggle") {
211
- this.applyValue(row, row.rawValue === "true" ? "false" : "true");
212
- return;
213
- }
214
-
215
- if (row.kind === "cycle") {
216
- const choices = row.choices ?? [];
217
- if (!choices.length) return;
218
- const current = Math.max(0, choices.indexOf(row.rawValue ?? ""));
219
- this.applyValue(row, choices[(current + 1) % choices.length] ?? choices[0] ?? "");
220
- return;
221
- }
222
-
223
- if (row.kind === "action") this.runAction(row.key, row.label);
224
- }
225
-
226
- private applyValue(row: PanelRow, value: string): void {
227
- const error = this.host.apply(row.key, value);
228
- if (error) {
229
- this.flash = { kind: "error", text: error };
230
- return;
231
- }
232
-
233
- this.refresh(row.key);
234
- const fresh = this.allRows().find((candidate) => candidate.key === row.key);
235
- this.flash = { kind: "success", text: `${row.label}: ${fresh?.value ?? value}` };
236
- }
237
-
238
- private runAction(key: string, label: string): void {
239
- const result = this.host.activate(key) ?? { kind: "none" as const };
240
- if (result.kind === "close") {
241
- this.host.done({ action: result.action });
242
- return;
243
- }
244
- if (result.kind === "error") {
245
- this.flash = { kind: "error", text: result.message };
246
- return;
247
- }
248
- if (result.kind === "updated") {
249
- this.refresh(key);
250
- this.flash = { kind: "success", text: result.message ?? `${label} updated` };
251
- return;
252
- }
253
- this.flash = { kind: "info", text: label };
254
- }
255
-
256
- private startEdit(key: string, initialValue: string): void {
257
- this.editingKey = key;
258
- this.input = new Input();
259
- this.input.focused = this._focused;
260
- this.input.setValue(initialValue);
261
- // A fresh Input keeps its cursor at 0 after setValue(); move to End so a
262
- // prefilled setting edits naturally.
263
- this.input.handleInput("\x1b[F");
264
- this.flash = null;
265
-
266
- this.input.onSubmit = (value) => {
267
- const row = this.allRows().find((candidate) => candidate.key === key);
268
- if (!row) {
269
- this.cancelEdit();
270
- return;
271
- }
272
- const canonical = value.trim();
273
- const error = this.host.apply(key, canonical);
274
- if (error) {
275
- this.flash = { kind: "error", text: error };
276
- this.host.requestRender();
277
- return;
278
- }
279
- this.input = null;
280
- this.editingKey = null;
281
- this.refresh(key);
282
- const fresh = this.allRows().find((candidate) => candidate.key === key);
283
- this.flash = { kind: "success", text: `${row.label}: ${fresh?.value ?? canonical}` };
284
- this.host.requestRender();
285
- };
286
-
287
- this.input.onEscape = () => {
288
- this.cancelEdit();
289
- this.host.requestRender();
290
- };
291
- }
292
-
293
- private cancelEdit(): void {
294
- this.input = null;
295
- this.editingKey = null;
296
- this.flash = { kind: "info", text: "Edit cancelled" };
297
- }
298
-
299
- private renderRow(row: PanelRow, selected: boolean, width: number): string {
300
- const t = this.host.theme;
301
- const innerWidth = Math.max(1, width - 2);
302
- const selectable = row.kind !== "info" && !row.disabled;
303
- const prefix = selected ? t.fg("accent", " › ") : " ";
304
- const labelColor = row.disabled ? "dim" : selected ? "accent" : row.kind === "info" ? "muted" : "text";
305
- const label = t.fg(labelColor, row.label);
306
-
307
- if (this.editingKey === row.key && this.input) {
308
- const left = `${prefix}${label}: `;
309
- const available = Math.max(1, innerWidth - visibleWidth(left) - 1);
310
- this.input.focused = this._focused;
311
- const inputLine = this.input.render(available)[0] ?? "";
312
- return this.boxLine(`${left}${inputLine}`, width);
313
- }
314
-
315
- const value = t.fg(this.valueColor(row), row.value);
316
- const left = `${selectable ? prefix : " "}${label}`;
317
- const gap = Math.max(1, innerWidth - visibleWidth(left) - visibleWidth(value) - 2);
318
- return this.boxLine(`${left}${" ".repeat(gap)}${value} `, width);
319
- }
320
-
321
- private renderMessageLine(): string {
322
- const t = this.host.theme;
323
- if (this.flash) {
324
- const color = this.flash.kind === "error" ? "error" : this.flash.kind === "success" ? "success" : "muted";
325
- return t.fg(color, ` ${this.flash.text}`);
326
- }
327
- if (this.editingKey) {
328
- const row = this.allRows().find((candidate) => candidate.key === this.editingKey);
329
- return t.fg("muted", ` ${row?.inputHint ?? "Enter saves · Esc cancels"}`);
330
- }
331
- return t.fg("dim", ` ${this.snapshotValue.idleMessage ?? "Changes save immediately"}`);
332
- }
333
-
334
- private renderShortcutLine(): string | null {
335
- const shortcuts = this.snapshotValue.shortcuts ?? [];
336
- if (!shortcuts.length) return null;
337
- return shortcuts.map((shortcut) => `${shortcut.key} ${shortcut.label}`).join(" · ");
338
- }
339
-
340
- private renderNavigationLine(): string {
341
- const kb = this.host.keybindings;
342
- const up = this.bindingText(kb.getKeys("tui.select.up"), "↑");
343
- const down = this.bindingText(kb.getKeys("tui.select.down"), "↓");
344
- const confirm = this.bindingText(kb.getKeys("tui.select.confirm"), "enter");
345
- const cancel = this.bindingText(kb.getKeys("tui.select.cancel"), "esc");
346
- return `${up}/${down}/jk move · ${confirm} select · ${cancel}/q close`;
347
- }
348
-
349
- private bindingText(keys: readonly string[], fallback: string): string {
350
- const first = keys[0];
351
- if (!first) return fallback;
352
- return first
353
- .replace(/^up$/, "↑")
354
- .replace(/^down$/, "↓")
355
- .replace(/^left$/, "←")
356
- .replace(/^right$/, "→")
357
- .replace(/^escape$/, "esc")
358
- .replace(/^return$/, "enter");
359
- }
360
-
361
- private valueColor(row: PanelRow): Parameters<Theme["fg"]>[0] {
362
- if (row.valueStyle) return row.valueStyle;
363
- if (row.disabled) return "dim";
364
- if (row.kind === "toggle") return row.rawValue === "true" ? "success" : "muted";
365
- if (row.kind === "action") return "accent";
366
- return "text";
367
- }
368
-
369
- private boxLine(content: string, width: number): string {
370
- const t = this.host.theme;
371
- if (width <= 1) return truncateToWidth(content, Math.max(1, width), "", true);
372
- const innerWidth = Math.max(0, width - 2);
373
- const clipped = truncateToWidth(content, innerWidth, "…", true);
374
- const padded = clipped + " ".repeat(Math.max(0, innerWidth - visibleWidth(clipped)));
375
- return t.fg("border", "│") + padded + t.fg("border", "│");
376
- }
377
-
378
- private topBorder(width: number, title: string): string {
379
- const t = this.host.theme;
380
- if (width <= 1) return t.fg("borderAccent", "─".repeat(Math.max(1, width)));
381
- const innerWidth = Math.max(0, width - 2);
382
- const styledTitle = t.fg("accent", t.bold(` ${title} `));
383
- const clippedTitle = truncateToWidth(styledTitle, innerWidth, "", false);
384
- const tail = "─".repeat(Math.max(0, innerWidth - visibleWidth(clippedTitle)));
385
- return t.fg("border", "╭") + clippedTitle + t.fg("border", `${tail}╮`);
386
- }
387
-
388
- private bottomBorder(width: number): string {
389
- const t = this.host.theme;
390
- if (width <= 1) return t.fg("border", "─".repeat(Math.max(1, width)));
391
- return t.fg("border", `╰${"─".repeat(Math.max(0, width - 2))}╯`);
392
- }
393
- }
package/ui/tool-card.ts DELETED
@@ -1,129 +0,0 @@
1
- /**
2
- * canonical tool-result-card renderer (v1) — vendored byte-identical;
3
- * consumers: extensions/ui/tool-card.ts; guard: scripts/check-vendored.mjs
4
- *
5
- * The model-path card skeleton every tool shares (pi-panel-kit S1):
6
- *
7
- * call card `→ <title> · <subject><qualifier>` — one accent line
8
- * result card optional accent header · severity-styled state headline
9
- * (`<lead> <glyph> <word> <bits…>`) · plain summary lines ·
10
- * dim detail lines · trailing next-action line
11
- *
12
- * Severity comes ONLY from the explicit state key, never from content
13
- * (OPERATIONAL-EXTENSIONS §2.9), and follows the ladder literally (§2.10):
14
- * normal states stay neutral (success/muted), `warning` is reserved for
15
- * degraded outcomes (timeout, online-but-empty), `error` for failed ones.
16
- * The glyph+word pairing always survives the styling (never color-alone).
17
- *
18
- * Callers own the domain specifics — bit composition, truncation, and the
19
- * no-details fallback (`renderToolPlainCard`) — so behavior-neutral
20
- * adoption stays possible. This kit copy imports only `@earendil-works/
21
- * pi-tui` (peer, same pattern as settings-panel.ts) and the vendored
22
- * `./format.ts` primitive.
23
- */
24
- import { Text } from "@earendil-works/pi-tui";
25
-
26
- import { stateGlyph } from "./format.ts";
27
-
28
- /** Theme subset a tool card needs; `fg` is optional in headless/print modes. */
29
- export interface ToolCardTheme {
30
- fg?: (kind: string, text: string) => string;
31
- }
32
-
33
- /** Severity ladder values — also the `theme.fg` kinds used to style lines. */
34
- export type ToolCardSeverity = "success" | "warning" | "error" | "muted";
35
-
36
- /** Line kinds a card can style; detail lines default to muted (dim). */
37
- export type ToolCardLineKind = ToolCardSeverity | "accent";
38
-
39
- export interface ToolCardStateInfo {
40
- glyph: string;
41
- word: string;
42
- severity: ToolCardSeverity;
43
- }
44
-
45
- /**
46
- * Terminal card states that are not live-run states: `registered` is a
47
- * success with a domain word, `no-models` is degraded (online but empty
48
- * catalogue). Everything else — and the failed fallback for unknown keys —
49
- * comes from `format.ts` `stateGlyph` unchanged.
50
- */
51
- const TOOL_CARD_STATES: Record<string, ToolCardStateInfo> = {
52
- registered: { glyph: "✓", word: "registered", severity: "success" },
53
- "no-models": { glyph: "⊘", word: "online · no models", severity: "warning" },
54
- };
55
-
56
- /** Glyph + state word + severity for an explicit state key (never content). */
57
- export function toolCardState(state: string): ToolCardStateInfo {
58
- const own = TOOL_CARD_STATES[state];
59
- if (own) return own;
60
- const g = stateGlyph(state);
61
- return { glyph: g.glyph, word: g.word, severity: g.color };
62
- }
63
-
64
- /** `theme.fg` with identity fallback so headless modes render plain text. */
65
- export function themed(theme: ToolCardTheme | undefined, kind: string, text: string): string {
66
- return theme?.fg ? theme.fg(kind, text) : text;
67
- }
68
-
69
- export interface ToolCallCardSpec {
70
- /** Tool name shown after the arrow ("delegate", "discover"). */
71
- title: string;
72
- /** Primary subject (the role, the URL). */
73
- subject: string;
74
- /** Already-punctuated tail (` · model: task`, ` as "name"`); optional. */
75
- qualifier?: string;
76
- }
77
-
78
- /** One-line accent call card: `→ title · subject<qualifier>`. */
79
- export function renderToolCallCard(theme: ToolCardTheme | undefined, spec: ToolCallCardSpec): Text {
80
- const text = `→ ${spec.title} · ${spec.subject}${spec.qualifier ?? ""}`;
81
- return new Text(themed(theme, "accent", text), 0, 0);
82
- }
83
-
84
- /** A pre-composed detail line (indentation included); `kind` defaults muted. */
85
- export interface ToolCardLine {
86
- text: string;
87
- kind?: ToolCardLineKind;
88
- }
89
-
90
- export interface ToolResultCardSpec {
91
- /** Accent header line above the headline (e.g. `→ <run-id tail>`). */
92
- header?: string;
93
- /** Headline lead before the glyph ("discover", the run role). */
94
- lead: string;
95
- /** Explicit state key — severity comes from `toolCardState`, never content. */
96
- state: string;
97
- /** Info bits appended after the state word (duration, tokens, …). */
98
- stateBits?: string[];
99
- /** Joiner between headline segments; default `" "`. */
100
- bitJoiner?: string;
101
- /** Lines rendered verbatim (no styling) — canonical summaries. */
102
- plainLines?: string[];
103
- /** Dim detail lines (partial handoff, first error line, resume hint). */
104
- detailLines?: ToolCardLine[];
105
- /** Trailing next-action hint, always muted. */
106
- nextLine?: string;
107
- }
108
-
109
- /**
110
- * Result card skeleton: header · state headline · plain lines · dim details ·
111
- * next action. All glyph/word/severity styling derives from `spec.state`.
112
- */
113
- export function renderToolResultCard(theme: ToolCardTheme | undefined, spec: ToolResultCardSpec): Text {
114
- const s = toolCardState(spec.state);
115
- const joiner = spec.bitJoiner ?? " ";
116
- const headline = [`${spec.lead} ${s.glyph} ${s.word}`, ...(spec.stateBits ?? [])].join(joiner);
117
- const lines: string[] = [];
118
- if (spec.header !== undefined) lines.push(themed(theme, "accent", spec.header));
119
- lines.push(themed(theme, s.severity, headline));
120
- for (const line of spec.plainLines ?? []) lines.push(line);
121
- for (const line of spec.detailLines ?? []) lines.push(themed(theme, line.kind ?? "muted", line.text));
122
- if (spec.nextLine !== undefined) lines.push(themed(theme, "muted", spec.nextLine));
123
- return new Text(lines.join("\n"), 0, 0);
124
- }
125
-
126
- /** Fallback for results without structured details — plain text, never bare. */
127
- export function renderToolPlainCard(text: string): Text {
128
- return new Text(text || "(no output)", 0, 0);
129
- }
package/ui/version.ts DELETED
@@ -1,69 +0,0 @@
1
- /**
2
- * ui/version.ts — canonical loaded-version provenance (S2, pi-panel-kit
3
- * stage 1).
4
- *
5
- * WHY THIS EXISTS
6
- * A running Pi session keeps whatever extension code it loaded at startup;
7
- * newer installs (npm store or by-path) only apply after `/reload`. A stale
8
- * in-process copy is indistinguishable from a fresh one unless every status
9
- * line, panel summary, and tool card carries the version actually EXECUTING.
10
- * This helper reads that version from the extension's own `package.json` —
11
- * never hard-coded, never baked at build time.
12
- *
13
- * Vendored byte-identically into consumers (guard: `node
14
- * skills/pi-extension-builder/scripts/check-vendored.mjs`); each extension
15
- * keeps a thin wrapper (`version.ts` at its package root) that exports its
16
- * original function name and passes the `package.json` path resolved from
17
- * THE WRAPPER'S module URL — a vendored copy sits in `ui/` and cannot find
18
- * the package root by itself, which is exactly why the path is a parameter.
19
- *
20
- * Pi-free by design: node built-ins only, no imports from sibling modules.
21
- */
22
-
23
- import * as fs from "node:fs";
24
-
25
- export interface ExtensionVersionOptions {
26
- /**
27
- * Absolute path to the extension's `package.json`. Resolve it from the
28
- * wrapper's own module URL (`path.join(dirname(fileURLToPath(import.meta.url)), "package.json")`)
29
- * so the string is anchored to the code actually executing, not the cwd.
30
- */
31
- packageJsonPath: string;
32
- /**
33
- * Short extension name for composed headers. When set, the result is
34
- * `label vX.Y.Z` (the `[delegate v0.3.2 …]` pattern used in result
35
- * headers). Default: no label, bare version (status lines and panel
36
- * summaries render their own prefixes).
37
- */
38
- label?: string;
39
- /**
40
- * Verbatim suffix appended after the version, e.g.
41
- * `" (loaded at session start; /reload picks up newer installs)"`.
42
- * Default: none. Call sites that interpolate the suffix themselves keep
43
- * passing nothing — identical output either way.
44
- */
45
- suffix?: string;
46
- /** Returned when `package.json` is unreadable/unparsable or lacks `version`. Default `"unknown"`. */
47
- fallback?: string;
48
- }
49
-
50
- /** Raw versions keyed by resolved package.json path; read once per process. */
51
- const cache = new Map<string, string>();
52
-
53
- /** The `version` field of the extension's package.json (never a hardcoded string). */
54
- export function extensionVersion(options: ExtensionVersionOptions): string {
55
- const fallback = options.fallback ?? "unknown";
56
- let version = cache.get(options.packageJsonPath);
57
- if (version === undefined) {
58
- try {
59
- const pkg = JSON.parse(fs.readFileSync(options.packageJsonPath, "utf8")) as {
60
- version?: string;
61
- };
62
- version = pkg.version ?? fallback;
63
- } catch {
64
- version = fallback;
65
- }
66
- cache.set(options.packageJsonPath, version);
67
- }
68
- return `${options.label ? `${options.label} v` : ""}${version}${options.suffix ?? ""}`;
69
- }
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes