@maheidem/pi-delegate 0.3.1 → 0.6.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.
@@ -17,6 +17,8 @@
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
19
  import { formatDuration, formatTokens, shortModel } from "./format.ts";
20
+ import { frameHeight, padToFrame } from "./panel-frame.ts";
21
+ import type { PanelSnapshot } from "./settings-panel.ts";
20
22
 
21
23
  export interface RunningViewState {
22
24
  runId: string;
@@ -43,10 +45,34 @@ export interface RunningViewHost {
43
45
  done(result: { cancelled?: boolean }): void;
44
46
  }
45
47
 
46
- /** Constant panel height (top + header + progress + in-flight + FEED + footer + bottom). */
47
- const PANEL_ROWS = 9;
48
- /** Feed rows inside the fixed frame; the rest are the fixed scaffold. */
49
- const FEED_ROWS = PANEL_ROWS - 5;
48
+ /**
49
+ * Feed rows inside the fixed frame; the rest are the fixed scaffold. The
50
+ * feed is a windowed content block — newest last, blank-padded on top,
51
+ * ALWAYS exactly FEED_ROWS tall (panel-frame rule: the builder windows the
52
+ * content; the frame never grows).
53
+ */
54
+ const FEED_ROWS = 4;
55
+
56
+ /**
57
+ * Grammar slots the canonical panel-frame has that this composer-inline
58
+ * panel does not render: the navigation line and the bottom border
59
+ * (constructed, then clipped — the composer owns the row below).
60
+ */
61
+ const CLIPPED_GRAMMAR_ROWS = 2;
62
+
63
+ /**
64
+ * Constant panel height, DERIVED from the canonical panel-frame grammar
65
+ * (top + summary ×3 + feed window + message/footer + nav + bottom) minus
66
+ * the clipped slots. Must evaluate to 9: the composer-region component has
67
+ * to render a fixed height every frame (see RENDER CONTRACT above).
68
+ */
69
+ const PANEL_ROWS =
70
+ frameHeight({
71
+ title: "",
72
+ sections: [],
73
+ summaryLines: ["", "", ""],
74
+ detailLines: Array.from({ length: FEED_ROWS }, () => ""),
75
+ }) - CLIPPED_GRAMMAR_ROWS;
50
76
 
51
77
  export class RunningView implements Component {
52
78
  private readonly host: RunningViewHost;
@@ -129,18 +155,37 @@ export class RunningView implements Component {
129
155
  // failed (see skills/pi-extension-builder OPERATIONAL-EXTENSIONS.md).
130
156
  const inFlightColor: ThemeColor | undefined = openTools.length > 0 ? "dim" : undefined;
131
157
 
132
- // Assemble a fixed-height body: header, progress, in-flight, feed block, footer.
133
- const body: Array<[string, ThemeColor?]> = [
158
+ // Fixed scaffold summary rows — always exactly 3 (header, progress,
159
+ // in-flight), the canonical frame's summaryLines slots.
160
+ const summary: Array<[string, ThemeColor?]> = [
134
161
  [head],
135
162
  [progress, "accent"],
136
163
  [inFlight, inFlightColor],
137
- ...feedRows.map((l): [string, ThemeColor?] => [l, l ? "text" : undefined]),
138
- [footer, this.cancelArmed ? "error" : "dim"],
139
164
  ];
140
165
 
141
- const lines: string[] = [top, ...body.map(([t, c]) => pad(t, c)), bottom];
166
+ // Frame arithmetic through the canonical helper: the feed window is
167
+ // the grammar's detail block, the footer its message line. padToFrame
168
+ // is a no-op while the builder invariant holds (window exactly
169
+ // FEED_ROWS) and is the tripwire the moment any slot count drifts.
170
+ const snapshot: PanelSnapshot = {
171
+ title,
172
+ sections: [],
173
+ summaryLines: summary.map(([t]) => t),
174
+ detailLines: feedRows,
175
+ };
176
+ const windowRows = padToFrame(snapshot, PANEL_ROWS + CLIPPED_GRAMMAR_ROWS).detailLines ?? [];
177
+
178
+ // Assemble a fixed-height body: header, progress, in-flight, feed block, footer.
179
+ const lines: string[] = [
180
+ top,
181
+ ...summary.map(([t, c]) => pad(t, c)),
182
+ ...windowRows.map((l) => pad(l, l ? "text" : undefined)),
183
+ pad(footer, this.cancelArmed ? "error" : "dim"),
184
+ bottom,
185
+ ];
142
186
 
143
- // Belt-and-braces: hard-clip to the exact height and width.
187
+ // Belt-and-braces: hard-clip to the exact height and width. The bottom
188
+ // border is deliberately clipped away (PANEL_ROWS counts it out).
144
189
  const clipped = lines.slice(0, PANEL_ROWS);
145
190
  while (clipped.length < PANEL_ROWS) clipped.splice(clipped.length - 1, 0, pad(""));
146
191
  return clipped.map((l) => (visibleWidth(l) > w ? truncateToWidth(l, w) : l));
@@ -0,0 +1,129 @@
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 ADDED
@@ -0,0 +1,69 @@
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
+ }
package/version.ts CHANGED
@@ -5,24 +5,20 @@
5
5
  * newer npm-store installs only apply after /reload. Every result header
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
+ *
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.
8
13
  */
9
14
 
10
- import * as fs from "node:fs";
11
15
  import * as path from "node:path";
12
16
  import { fileURLToPath } from "node:url";
13
17
 
14
- let cached: string | null = null;
18
+ import { extensionVersion } from "./ui/version.ts";
15
19
 
16
20
  export function delegateVersion(): string {
17
- if (cached) return cached;
18
- try {
19
- const here = path.dirname(fileURLToPath(import.meta.url));
20
- const pkg = JSON.parse(fs.readFileSync(path.join(here, "package.json"), "utf8")) as {
21
- version?: string;
22
- };
23
- cached = pkg.version ?? "unknown";
24
- } catch {
25
- cached = "unknown";
26
- }
27
- return cached;
21
+ return extensionVersion({
22
+ packageJsonPath: path.join(path.dirname(fileURLToPath(import.meta.url)), "package.json"),
23
+ });
28
24
  }