@luxass/pi-resources 0.0.0-stage → 0.0.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026-PRESENT Lucas Nørgård
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,46 @@
1
- # Temporary Holding Version
1
+ # @luxass/pi-resources
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Browse the resources that [Pi](https://pi.dev) loaded, registered tools, and loader diagnostics in a tabbed dialog.
4
+
5
+ ## Install
6
+
7
+ ```sh
8
+ pi install npm:@luxass/pi-resources
9
+ ```
10
+
11
+ This command previously shipped in `@luxass/pi-personal`. Install this package separately after updating `pi-personal`.
12
+
13
+ To try the extension from this checkout:
14
+
15
+ ```sh
16
+ pi -e ./packages/pi-resources
17
+ ```
18
+
19
+ ## Use
20
+
21
+ Run `/resources` in Pi’s terminal interface. The dialog opens on Tools and has five tabs:
22
+
23
+ - Tools shows compact names, active status, and registered exposure. Press `e` to show descriptions and exposure explanations for all tools. Exposure controls how Pi can reach a tool. Inactive codemode and deferred tools remain callable from other tools. Per-request changes that hide tool declarations are not shown.
24
+ - Context lists loaded instruction files and system-prompt sources in Pi’s loading order.
25
+ - Skills lists loaded skill names. Names stay complete, with columns when space allows.
26
+ - Extensions groups loaded entries into Local, Packages, and Built-in sections. It includes event-only extensions and omits hidden entries, like Pi’s startup display.
27
+ - Diagnostics lists loader errors, warnings, and name collisions for extensions, skills, prompts, and themes.
28
+
29
+ Press `e` in Tools or Extensions to expand or collapse details. Each tab keeps its own expansion state while the dialog stays open. In Extensions, details include full paths and package entries. Packages share one row, with a count for multiple entries. Matching labels retain source details that distinguish them. Home-directory paths use `~`.
30
+
31
+ | Controls | Action |
32
+ | --------------------------------------- | --------------------------------------------------- |
33
+ | Left, Right, Tab, Shift+Tab | Switch tabs. |
34
+ | `e` | Expand or collapse Tools or Extensions. |
35
+ | `1`–`5` | Jump to a tab. |
36
+ | Up, Down, Page Up, Page Down, Home, End | Scroll. |
37
+ | Confirm, cancel, or `q` | Close. Confirm and cancel default to Enter and Esc. |
38
+ | Click a tab or use the mouse wheel | Switch tabs or scroll in fullscreen mode. |
39
+
40
+ On small screens, the tab bar uses shorter labels without counts. The title shows the selected tab’s full name and count. Short summaries leave more room for content.
41
+
42
+ The close and scroll controls follow your Pi keybindings. Their hints show the primary configured keys. Other configured alternatives also work.
43
+
44
+ The extension reads Pi’s active resource loader, not a directory scan or an inferred list. Each command invocation reads the current loaded state. An unsupported hook temporarily intercepts `DefaultResourceLoader.getExtensions()` to capture that loader. It restores the original method after capture or on session shutdown. Capture must start when the extension loads, before Pi builds its extension runtime.
45
+
46
+ Pi updates can break this hook. If capture fails, `/resources` reports an error instead of guessing which resources loaded.
package/package.json CHANGED
@@ -1,6 +1,43 @@
1
1
  {
2
2
  "name": "@luxass/pi-resources",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.0.0",
4
+ "description": "Browse Pi's loaded resources, registered tools, and loader diagnostics.",
5
+ "keywords": [
6
+ "pi",
7
+ "pi-extension",
8
+ "pi-package",
9
+ "resources"
10
+ ],
11
+ "license": "MIT",
12
+ "repository": {
13
+ "type": "git",
14
+ "url": "https://github.com/luxass/agent-extensions",
15
+ "directory": "packages/pi-resources"
16
+ },
17
+ "files": [
18
+ "src",
19
+ "README.md",
20
+ "LICENSE"
21
+ ],
22
+ "type": "module",
23
+ "publishConfig": {
24
+ "access": "public"
25
+ },
26
+ "peerDependencies": {
27
+ "@earendil-works/pi-coding-agent": "*",
28
+ "@earendil-works/pi-tui": "*"
29
+ },
30
+ "pi": {
31
+ "image": "https://raw.githubusercontent.com/luxass/agent-extensions/main/packages/pi-resources/docs/cover.png",
32
+ "extensions": [
33
+ "./src/index.ts"
34
+ ]
35
+ },
36
+ "scripts": {
37
+ "lint": "oxlint .",
38
+ "lint:fix": "oxlint --fix .",
39
+ "fmt": "oxfmt .",
40
+ "fmt:check": "oxfmt --check .",
41
+ "typecheck": "tsc -p tsconfig.json"
42
+ }
6
43
  }
@@ -0,0 +1,35 @@
1
+ import type { Theme } from "@earendil-works/pi-coding-agent";
2
+ import { wrapTextWithAnsi } from "@earendil-works/pi-tui";
3
+
4
+ import type { LoaderDiagnostic } from "./resources.ts";
5
+
6
+ export function renderDiagnostics(
7
+ diagnostics: LoaderDiagnostic[],
8
+ theme: Theme,
9
+ width: number,
10
+ ): string[] {
11
+ if (diagnostics.length === 0) return [theme.fg("muted", "No loader errors or warnings.")];
12
+
13
+ const lines: string[] = [];
14
+ const row = (text: string, color: "text" | "dim" | "warning" | "error", indent = 0) => {
15
+ for (const line of wrapTextWithAnsi(text, Math.max(1, width - indent))) {
16
+ lines.push(" ".repeat(indent) + theme.fg(color, line));
17
+ }
18
+ };
19
+ for (const [index, diagnostic] of diagnostics.entries()) {
20
+ // One blank line between entries, never after the last.
21
+ if (index > 0) lines.push("");
22
+ row(
23
+ diagnostic.resource + " · " + diagnostic.type,
24
+ diagnostic.type === "error" ? "error" : "warning",
25
+ );
26
+ row(diagnostic.message, "text", 2);
27
+ if (diagnostic.path !== undefined) row(diagnostic.path, "dim", 2);
28
+ if (diagnostic.collision !== undefined) {
29
+ row("Name: " + diagnostic.collision.name, "dim", 2);
30
+ row("Used: " + diagnostic.collision.winnerPath, "dim", 2);
31
+ row("Ignored: " + diagnostic.collision.loserPath, "dim", 2);
32
+ }
33
+ }
34
+ return lines;
35
+ }
package/src/dialog.ts ADDED
@@ -0,0 +1,385 @@
1
+ import type { Theme } from "@earendil-works/pi-coding-agent";
2
+ import {
3
+ isKeyRelease,
4
+ Key,
5
+ matchesKey,
6
+ ScrollView,
7
+ truncateToWidth,
8
+ visibleWidth,
9
+ wrapTextWithAnsi,
10
+ type Component,
11
+ type KeybindingsManager,
12
+ type TUI,
13
+ type TuiMouseEvent,
14
+ type TuiMouseEventResult,
15
+ } from "@earendil-works/pi-tui";
16
+
17
+ import { renderDiagnostics } from "./diagnostics.ts";
18
+ import { renderExtensions } from "./extensions.ts";
19
+ import type { ResourceSnapshot } from "./resources.ts";
20
+ import {
21
+ EXPANDABLE,
22
+ RESOURCE_TABS,
23
+ type ResourceTab,
24
+ TAB_LABELS,
25
+ tabCount,
26
+ tabSummary,
27
+ tabUnit,
28
+ } from "./tabs.ts";
29
+ import { renderTools } from "./tools.ts";
30
+
31
+ const MAX_DIALOG_ROWS = 28;
32
+ const DIALOG_HEIGHT_RATIO = 0.8;
33
+ const DIALOG_HEIGHT_RESERVED = 4;
34
+ const CHROME_ROWS = 5; // top border, two nav rows, hints, bottom border
35
+ const MIN_DIALOG_WIDTH = 24;
36
+ const MIN_DIALOG_HEIGHT = 8;
37
+ const COMPACT_WIDTH = 76; // compact when the inner width is below this
38
+ const COMPACT_HEIGHT = 16;
39
+ const MIN_PAGE_ROWS = 4; // never request fewer rows than this
40
+
41
+ const KEY_LABELS: Record<string, string> = {
42
+ escape: "Esc",
43
+ enter: "Enter",
44
+ tab: "Tab",
45
+ up: "↑",
46
+ down: "↓",
47
+ left: "←",
48
+ right: "→",
49
+ pageUp: "PgUp",
50
+ pageDown: "PgDn",
51
+ home: "Home",
52
+ end: "End",
53
+ ctrl: "Ctrl",
54
+ shift: "Shift",
55
+ alt: process.platform === "darwin" ? "Option" : "Alt",
56
+ };
57
+
58
+ function keyLabels(keys: readonly string[]): string {
59
+ return [...new Set(keys)]
60
+ .map((key) =>
61
+ key
62
+ .split("+")
63
+ .map((part) => KEY_LABELS[part] ?? part)
64
+ .join("+"),
65
+ )
66
+ .join("/");
67
+ }
68
+
69
+ function fit(text: string, width: number): string {
70
+ const clipped = truncateToWidth(text, width, "…");
71
+ return clipped + " ".repeat(Math.max(0, width - visibleWidth(clipped)));
72
+ }
73
+
74
+ interface TabTarget {
75
+ tab: ResourceTab;
76
+ start: number;
77
+ end: number;
78
+ }
79
+
80
+ interface ResourcesDialogOptions {
81
+ tui: TUI;
82
+ theme: Theme;
83
+ keybindings: KeybindingsManager;
84
+ resources: ResourceSnapshot;
85
+ done: () => void;
86
+ }
87
+
88
+ export class ResourcesDialog implements Component {
89
+ private readonly tui: TUI;
90
+ private readonly theme: Theme;
91
+ private readonly keybindings: KeybindingsManager;
92
+ private readonly resources: ResourceSnapshot;
93
+ private readonly done: () => void;
94
+ private readonly closeKeys: string;
95
+ private readonly scrollKeys: string;
96
+ private readonly pageKeys: string;
97
+ private readonly scroll: ScrollView;
98
+
99
+ private tab: ResourceTab = RESOURCE_TABS[0];
100
+ private page = 1;
101
+ private mouseWidth = 0;
102
+ private targets: TabTarget[] = [];
103
+ private readonly expanded = new Set<ResourceTab>();
104
+
105
+ constructor({ tui, theme, keybindings, resources, done }: ResourcesDialogOptions) {
106
+ this.tui = tui;
107
+ this.theme = theme;
108
+ this.keybindings = keybindings;
109
+ this.resources = resources;
110
+ this.done = done;
111
+
112
+ const first = (action: Parameters<KeybindingsManager["getKeys"]>[0]) =>
113
+ keybindings.getKeys(action).slice(0, 1);
114
+ this.closeKeys = keyLabels([
115
+ ...first("tui.select.cancel"),
116
+ ...first("tui.select.confirm"),
117
+ "q",
118
+ ]);
119
+ this.scrollKeys = keyLabels([...first("tui.select.up"), ...first("tui.select.down")]);
120
+ this.pageKeys = keyLabels([...first("tui.select.pageUp"), ...first("tui.select.pageDown")]);
121
+
122
+ this.scroll = new ScrollView(
123
+ {
124
+ render: (width) => this.body(width),
125
+ invalidate() {},
126
+ },
127
+ { scrollbar: "hidden" },
128
+ );
129
+ }
130
+
131
+ private switchTab(tab: ResourceTab): void {
132
+ this.tab = tab;
133
+ this.scroll.scrollToStart();
134
+ this.tui.requestRender();
135
+ }
136
+
137
+ private stepTab(delta: number): void {
138
+ const index = RESOURCE_TABS.indexOf(this.tab);
139
+ this.switchTab(RESOURCE_TABS[(index + delta + RESOURCE_TABS.length) % RESOURCE_TABS.length]!);
140
+ }
141
+
142
+ private toggleExpanded(): void {
143
+ if (this.expanded.has(this.tab)) this.expanded.delete(this.tab);
144
+ else this.expanded.add(this.tab);
145
+ }
146
+
147
+ private navigation(width: number): { rows: string[]; targets: TabTarget[] } {
148
+ const targets: TabTarget[] = [];
149
+ const available = width - (RESOURCE_TABS.length - 1);
150
+ const size = Math.floor(available / RESOURCE_TABS.length);
151
+ const remainder = available % RESOURCE_TABS.length;
152
+ // Pick one label set for the whole bar. Never show half a tab name.
153
+ const labelSets = [
154
+ RESOURCE_TABS.map((label) => `${label} ${tabCount(this.resources, label)}`),
155
+ ...TAB_LABELS,
156
+ ];
157
+ const labels = labelSets.find((set) => set.every((label) => visibleWidth(label) <= size))!;
158
+ let column = 2;
159
+ const cells = RESOURCE_TABS.map((tab, index) => {
160
+ const label = labels[index] ?? tab;
161
+ const cellWidth = size + (index < remainder ? 1 : 0);
162
+ const padding = cellWidth - visibleWidth(label);
163
+ const centered =
164
+ " ".repeat(Math.floor(padding / 2)) + label + " ".repeat(Math.ceil(padding / 2));
165
+ targets.push({ tab, start: column, end: column + cellWidth });
166
+ column += cellWidth + 1;
167
+ const active = tab === this.tab;
168
+ return {
169
+ title: active
170
+ ? this.theme.bold(this.theme.fg("accent", centered))
171
+ : this.theme.fg("muted", centered),
172
+ rail: this.theme.fg(
173
+ active ? "accent" : "borderMuted",
174
+ (active ? "━" : "─").repeat(cellWidth),
175
+ ),
176
+ };
177
+ });
178
+ return {
179
+ rows: [
180
+ cells.map((cell) => cell.title).join(" "),
181
+ cells.map((cell) => cell.rail).join(this.theme.fg("borderMuted", "─")),
182
+ ],
183
+ targets,
184
+ };
185
+ }
186
+
187
+ private heading(
188
+ width: number,
189
+ current: ResourceTab,
190
+ compact: boolean,
191
+ expanded: boolean,
192
+ ): string[] {
193
+ const wrapped = wrapTextWithAnsi(tabSummary(this.resources, current, compact, expanded), width);
194
+ const rows = compact ? 1 : 2;
195
+ return wrapped
196
+ .slice(0, rows)
197
+ .map((text, index) =>
198
+ this.theme.fg(
199
+ "muted",
200
+ index === rows - 1 && wrapped.length > rows
201
+ ? truncateToWidth(text, width - 1, "") + "…"
202
+ : text,
203
+ ),
204
+ );
205
+ }
206
+
207
+ private hints(width: number, expandable: boolean, expanded: boolean): string {
208
+ const help: [string, string][] = [[this.closeKeys, "close"]];
209
+ if (expandable) help.push(["e", expanded ? "collapse" : "expand"]);
210
+ help.push(
211
+ ["←→/Tab", "tabs"],
212
+ [this.scrollKeys, "scroll"],
213
+ [`1–${RESOURCE_TABS.length}`, "jump"],
214
+ [this.pageKeys, "page"],
215
+ );
216
+ let line = "";
217
+ for (const [key, label] of help) {
218
+ const hint = this.theme.fg("accent", key) + this.theme.fg("dim", ` ${label}`);
219
+ const candidate = line ? `${line}${this.theme.fg("borderMuted", " · ")}${hint}` : hint;
220
+ if (visibleWidth(candidate) <= width) line = candidate;
221
+ }
222
+ return line;
223
+ }
224
+
225
+ private body(width: number): string[] {
226
+ const expanded = this.expanded.has(this.tab);
227
+ if (this.tab === "Tools") return renderTools(this.resources.tools, this.theme, width, expanded);
228
+ if (this.tab === "Extensions")
229
+ return renderExtensions(this.resources.extensions, this.theme, width, expanded);
230
+ if (this.tab === "Diagnostics")
231
+ return renderDiagnostics(this.resources.diagnostics, this.theme, width);
232
+ const items = this.tab === "Context" ? this.resources.context : this.resources.skills;
233
+ return this.sourceList(items, width, this.tab === "Skills");
234
+ }
235
+
236
+ private sourceList(items: string[], width: number, columns: boolean): string[] {
237
+ if (items.length === 0) return [this.theme.fg("muted", "None loaded.")];
238
+
239
+ const lines: string[] = [];
240
+ for (const entry of items) {
241
+ for (const line of wrapTextWithAnsi(entry, Math.max(1, width))) {
242
+ lines.push(this.theme.fg("text", line));
243
+ }
244
+ }
245
+ if (!columns || items.length === 1) return lines;
246
+
247
+ // Read down each column, like a directory listing. Keep every name intact.
248
+ const gap = 3;
249
+ const longest = Math.max(...items.map(visibleWidth));
250
+ const count = Math.max(1, Math.min(3, Math.floor((width + gap) / (longest + gap))));
251
+ if (count === 1) return lines;
252
+
253
+ lines.length = 0;
254
+ const cellWidth = Math.floor((width - gap * (count - 1)) / count);
255
+ const rows = Math.ceil(items.length / count);
256
+ for (let row = 0; row < rows; row++) {
257
+ const cells: string[] = [];
258
+ for (let column = 0; column < count; column++) {
259
+ cells.push(fit(this.theme.fg("text", items[column * rows + row] ?? ""), cellWidth));
260
+ }
261
+ lines.push(cells.join(" ".repeat(gap)));
262
+ }
263
+ return lines;
264
+ }
265
+
266
+ render(width: number): string[] {
267
+ this.mouseWidth = width;
268
+ const height = Math.min(
269
+ MAX_DIALOG_ROWS,
270
+ Math.floor(this.tui.terminal.rows * DIALOG_HEIGHT_RATIO),
271
+ this.tui.terminal.rows - DIALOG_HEIGHT_RESERVED,
272
+ );
273
+ if (width < MIN_DIALOG_WIDTH || height < MIN_DIALOG_HEIGHT) {
274
+ this.targets = [];
275
+ return [fit(`Resize to browse · ${this.closeKeys} close`, Math.max(0, width))];
276
+ }
277
+
278
+ const inner = width - 4;
279
+ const border = (text: string) => this.theme.fg("borderAccent", text);
280
+ const row = (text = "") => border("│ ") + fit(text, inner) + border(" │");
281
+ const current = this.tab;
282
+ const count = tabCount(this.resources, current);
283
+ const compact = inner < COMPACT_WIDTH || height < COMPACT_HEIGHT;
284
+ const expanded = this.expanded.has(current);
285
+ const expandable = EXPANDABLE.has(current);
286
+
287
+ const nav = this.navigation(inner);
288
+ this.targets = nav.targets;
289
+ const headingLines = this.heading(inner, current, compact, expanded);
290
+ const body = this.scroll.render(inner);
291
+ const spacer = compact ? [] : [row()];
292
+ // Borders, navigation, hints, and headings stay outside the scrollable body.
293
+ this.page = Math.max(
294
+ 1,
295
+ Math.min(
296
+ height - CHROME_ROWS - headingLines.length - spacer.length,
297
+ Math.max(MIN_PAGE_ROWS, body.length),
298
+ ),
299
+ );
300
+ this.scroll.updateLayout(body.length, this.page, () => this.tui.requestRender());
301
+ const visible = body.slice(this.scroll.scrollTop, this.scroll.scrollTop + this.page);
302
+ while (visible.length < this.page) visible.push("");
303
+
304
+ const position =
305
+ body.length > this.page
306
+ ? `Rows ${this.scroll.scrollTop + 1}–${Math.min(body.length, this.scroll.scrollTop + this.page)} / ${body.length}`
307
+ : `${count} ${tabUnit(current)}`;
308
+ const footer = this.theme.fg("dim", truncateToWidth(` ${position} `, inner, "…"));
309
+ const title = this.theme.bold(
310
+ this.theme.fg(
311
+ "accent",
312
+ truncateToWidth(
313
+ ` ${compact ? `${current} ${count}` : `Resources · ${current} ${count}`} `,
314
+ inner,
315
+ "…",
316
+ ),
317
+ ),
318
+ );
319
+
320
+ return [
321
+ border("╭─") + title + border("─".repeat(inner - visibleWidth(title)) + "─╮"),
322
+ ...nav.rows.map(row),
323
+ ...headingLines.map(row),
324
+ ...spacer,
325
+ ...visible.map(row),
326
+ row(this.hints(inner, expandable, expanded)),
327
+ border("╰─") + footer + border("─".repeat(Math.max(0, inner - visibleWidth(footer))) + "─╯"),
328
+ ];
329
+ }
330
+
331
+ handleMouse(event: TuiMouseEvent): TuiMouseEventResult | undefined {
332
+ if (event.width !== this.mouseWidth) return undefined;
333
+ if (event.type === "wheel") {
334
+ this.scroll.scrollBy(event.wheelDelta ?? 0);
335
+ this.tui.requestRender();
336
+ // Contain the event even at an edge so the transcript does not scroll.
337
+ return { handled: true, focus: true };
338
+ }
339
+ if (
340
+ event.button !== "left" ||
341
+ event.shift ||
342
+ event.alt ||
343
+ event.ctrl ||
344
+ (event.type !== "press" && event.type !== "click") ||
345
+ (event.y !== 1 && event.y !== 2)
346
+ )
347
+ return undefined;
348
+ const target = this.targets.find((item) => event.x >= item.start && event.x < item.end);
349
+ if (!target) return undefined;
350
+ if (event.type === "click") this.switchTab(target.tab);
351
+ return { handled: true, focus: true };
352
+ }
353
+
354
+ handleInput(data: string): void {
355
+ if (isKeyRelease(data)) return;
356
+ if (
357
+ this.keybindings.matches(data, "tui.select.cancel") ||
358
+ this.keybindings.matches(data, "tui.select.confirm") ||
359
+ data === "q"
360
+ ) {
361
+ this.done();
362
+ return;
363
+ }
364
+ const current = this.tab;
365
+ if (EXPANDABLE.has(current) && data === "e") {
366
+ this.toggleExpanded();
367
+ this.scroll.scrollToStart();
368
+ } else if (matchesKey(data, Key.tab) || matchesKey(data, Key.right)) this.stepTab(1);
369
+ else if (matchesKey(data, Key.shift(Key.tab)) || matchesKey(data, Key.left)) this.stepTab(-1);
370
+ else if (/^[1-9]$/.test(data)) {
371
+ const target = RESOURCE_TABS[Number(data) - 1];
372
+ if (target) this.switchTab(target);
373
+ } else if (this.keybindings.matches(data, "tui.select.up")) this.scroll.scrollBy(-1);
374
+ else if (this.keybindings.matches(data, "tui.select.down")) this.scroll.scrollBy(1);
375
+ else if (this.keybindings.matches(data, "tui.select.pageUp")) this.scroll.scrollBy(-this.page);
376
+ else if (this.keybindings.matches(data, "tui.select.pageDown")) this.scroll.scrollBy(this.page);
377
+ else if (matchesKey(data, Key.home)) this.scroll.scrollToStart();
378
+ else if (matchesKey(data, Key.end)) this.scroll.scrollToEnd();
379
+ this.tui.requestRender();
380
+ }
381
+
382
+ invalidate(): void {
383
+ this.scroll.invalidate();
384
+ }
385
+ }
@@ -0,0 +1,100 @@
1
+ import { homedir } from "node:os";
2
+ import { basename, relative, sep } from "node:path";
3
+
4
+ import type { SourceInfo, Theme } from "@earendil-works/pi-coding-agent";
5
+ import { wrapTextWithAnsi } from "@earendil-works/pi-tui";
6
+
7
+ function entryPath(source: SourceInfo): string {
8
+ return source.baseDir === undefined ? source.path : relative(source.baseDir, source.path);
9
+ }
10
+
11
+ function shortPath(path: string): string {
12
+ const home = homedir();
13
+ return path.startsWith(home + sep) ? "~" + path.slice(home.length) : path;
14
+ }
15
+
16
+ function packageLabel(source: string): string {
17
+ if (source.startsWith("npm:")) return source.slice(4);
18
+ if (source.startsWith("git:")) return source.slice(4);
19
+ return basename(source);
20
+ }
21
+
22
+ export function renderExtensions(
23
+ sources: SourceInfo[],
24
+ theme: Theme,
25
+ width: number,
26
+ expanded: boolean,
27
+ ): string[] {
28
+ const lines: string[] = [];
29
+ const local: SourceInfo[] = [];
30
+ const builtin: SourceInfo[] = [];
31
+ const packages = new Map<string, { source: SourceInfo; entries: SourceInfo[] }>();
32
+
33
+ for (const source of sources) {
34
+ if (source.source === "builtin") {
35
+ builtin.push(source);
36
+ } else if (source.origin === "package") {
37
+ const key = JSON.stringify([source.source, source.scope, source.baseDir]);
38
+ const group = packages.get(key);
39
+ if (group) group.entries.push(source);
40
+ else packages.set(key, { source, entries: [source] });
41
+ } else {
42
+ local.push(source);
43
+ }
44
+ }
45
+
46
+ const heading = (label: string) => {
47
+ if (lines.length > 0) lines.push("");
48
+ lines.push(theme.bold(theme.fg("muted", label)));
49
+ };
50
+ const row = (text: string, indent: number, color: "text" | "dim") => {
51
+ const prefix = " ".repeat(indent);
52
+ for (const line of wrapTextWithAnsi(text, Math.max(1, width - indent))) {
53
+ lines.push(prefix + theme.fg(color, line));
54
+ }
55
+ };
56
+
57
+ if (local.length > 0) {
58
+ heading("Local");
59
+ for (const source of local) {
60
+ const label = entryPath(source);
61
+ const sharedLabel = local.some((other) => other !== source && entryPath(other) === label);
62
+ row("• " + (sharedLabel ? shortPath(source.path) + " · " + source.scope : label), 2, "text");
63
+ if (expanded && !sharedLabel) row(shortPath(source.path) + " · " + source.scope, 4, "dim");
64
+ }
65
+ }
66
+ if (packages.size > 0) {
67
+ heading("Packages");
68
+ const sorted = [...packages.values()].toSorted((a, b) =>
69
+ packageLabel(a.source.source).localeCompare(packageLabel(b.source.source)),
70
+ );
71
+ for (const group of sorted) {
72
+ const { source, entries } = group;
73
+ const label = packageLabel(source.source);
74
+ // Shorten only the display label. Group identity always uses full source metadata.
75
+ const sharedLabel = sorted.some(
76
+ (other) => other !== group && packageLabel(other.source.source) === label,
77
+ );
78
+ const display = sharedLabel ? shortPath(source.source) + " · " + source.scope : label;
79
+ const count = entries.length > 1 ? " · " + entries.length + " extensions" : "";
80
+ row((expanded ? "▾ " : "▸ ") + display + count, 2, "text");
81
+ if (expanded && !sharedLabel) row(shortPath(source.source) + " · " + source.scope, 4, "dim");
82
+ if (
83
+ (expanded || sharedLabel) &&
84
+ source.baseDir !== undefined &&
85
+ source.baseDir !== source.source
86
+ ) {
87
+ row(shortPath(source.baseDir), 4, "dim");
88
+ }
89
+ if (expanded) {
90
+ for (const entry of entries) row(entryPath(entry), 4, "dim");
91
+ }
92
+ }
93
+ }
94
+ if (builtin.length > 0) {
95
+ heading("Built-in");
96
+ for (const source of builtin) row("• " + source.path.replace(/^builtin:/, ""), 2, "text");
97
+ }
98
+ if (lines.length === 0) row("No visible extensions loaded.", 0, "dim");
99
+ return lines;
100
+ }
package/src/index.ts ADDED
@@ -0,0 +1,45 @@
1
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+
3
+ import { ResourcesDialog } from "./dialog.ts";
4
+ import { captureResourceLoader } from "./loader-hook.ts";
5
+ import { collectResources } from "./resources.ts";
6
+
7
+ export default function (pi: ExtensionAPI) {
8
+ const capture = captureResourceLoader("resources");
9
+ pi.on("session_shutdown", () => capture.dispose());
10
+
11
+ pi.registerCommand("resources", {
12
+ description: "Browse resources and registered tools in a tabbed dialog",
13
+ handler: async (_args, ctx) => {
14
+ if (ctx.mode !== "tui") return;
15
+ const resourceLoader = capture.read();
16
+ if (!resourceLoader) {
17
+ ctx.ui.notify(
18
+ "Could not capture Pi's resource loader. Reload Pi before using /resources.",
19
+ "error",
20
+ );
21
+ return;
22
+ }
23
+ const resources = collectResources({
24
+ pi,
25
+ loader: resourceLoader,
26
+ cwd: ctx.cwd,
27
+ });
28
+
29
+ await ctx.ui.custom<void>(
30
+ (tui, theme, keybindings, done) =>
31
+ new ResourcesDialog({ tui, theme, keybindings, resources, done }),
32
+ {
33
+ overlay: true,
34
+ overlayOptions: {
35
+ anchor: "center",
36
+ width: 100,
37
+ minWidth: 46,
38
+ maxHeight: "80%",
39
+ margin: 2,
40
+ },
41
+ },
42
+ );
43
+ },
44
+ });
45
+ }
@@ -0,0 +1,32 @@
1
+ import type { LoadExtensionsResult, ResourceLoader } from "@earendil-works/pi-coding-agent";
2
+ import { DefaultResourceLoader } from "@earendil-works/pi-coding-agent";
3
+
4
+ export function captureResourceLoader(command: string) {
5
+ let loader: ResourceLoader | undefined;
6
+ const prototype = DefaultResourceLoader.prototype;
7
+ // oxlint-disable-next-line typescript/unbound-method -- The interceptor supplies the original receiver with call(this).
8
+ const original = prototype.getExtensions;
9
+
10
+ function restore() {
11
+ if (prototype.getExtensions === intercept) prototype.getExtensions = original;
12
+ }
13
+
14
+ function intercept(this: DefaultResourceLoader): LoadExtensionsResult {
15
+ const result = original.call(this);
16
+ if (result.extensions.some((extension) => extension.commands.has(command))) {
17
+ // oxlint-disable-next-line typescript/no-this-alias -- Capture the actual loader receiver for later resource reads.
18
+ loader = this;
19
+ restore();
20
+ }
21
+ return result;
22
+ }
23
+
24
+ // Unsupported bridge: Pi reads this list after loading extensions to build its runtime.
25
+ // Capture that loader once, then leave the shared prototype unchanged.
26
+ prototype.getExtensions = intercept;
27
+
28
+ return {
29
+ read: () => loader,
30
+ dispose: restore,
31
+ };
32
+ }
@@ -0,0 +1,85 @@
1
+ import { relative } from "node:path";
2
+
3
+ import type {
4
+ ExtensionAPI,
5
+ ResourceDiagnostic,
6
+ ResourceLoader,
7
+ SourceInfo,
8
+ ToolInfo,
9
+ } from "@earendil-works/pi-coding-agent";
10
+
11
+ export type LoaderDiagnostic = ResourceDiagnostic & {
12
+ resource: "Extensions" | "Skills" | "Prompts" | "Themes";
13
+ };
14
+
15
+ export type ResourceTool = Pick<ToolInfo, "name" | "description" | "exposure"> & {
16
+ active: boolean;
17
+ };
18
+
19
+ export type ResourceSnapshot = {
20
+ context: string[];
21
+ skills: string[];
22
+ extensions: SourceInfo[];
23
+ tools: ResourceTool[];
24
+ diagnostics: LoaderDiagnostic[];
25
+ };
26
+
27
+ function diagnosticsFor(
28
+ resource: LoaderDiagnostic["resource"],
29
+ diagnostics: ResourceDiagnostic[],
30
+ ): LoaderDiagnostic[] {
31
+ return diagnostics.map((diagnostic) => ({ ...diagnostic, resource }));
32
+ }
33
+
34
+ interface CollectResourceOptions {
35
+ pi: ExtensionAPI;
36
+ loader: ResourceLoader;
37
+ cwd: string;
38
+ }
39
+
40
+ export function collectResources({ pi, loader, cwd }: CollectResourceOptions): ResourceSnapshot {
41
+ const activeTools = new Set(pi.getActiveTools());
42
+ const loadedExtensions = loader.getExtensions();
43
+ const loadedSkills = loader.getSkills();
44
+ const systemPrompt = loader.getSystemPromptSource();
45
+ const contextSources = [
46
+ ...(systemPrompt ? [systemPrompt] : []),
47
+ ...loader.getAppendSystemPromptSources(),
48
+ ...loader.getAgentsFiles().agentsFiles,
49
+ ];
50
+
51
+ const tools = pi
52
+ .getAllTools()
53
+ .map(({ name, description, exposure }) => ({
54
+ name,
55
+ description,
56
+ exposure,
57
+ active: activeTools.has(name),
58
+ }))
59
+ .toSorted((a, b) => a.name.localeCompare(b.name));
60
+ const context = contextSources.map(({ path }) => relative(cwd, path));
61
+ const skills = loadedSkills.skills.map((skill) => skill.name).toSorted();
62
+ const extensions = loadedExtensions.extensions
63
+ .filter((extension) => !extension.hidden)
64
+ .map((extension) => extension.sourceInfo)
65
+ .toSorted((a, b) => a.path.localeCompare(b.path));
66
+ const diagnostics = [
67
+ ...loadedExtensions.errors.map(({ path, error }): LoaderDiagnostic => ({
68
+ resource: "Extensions",
69
+ type: "error",
70
+ message: error,
71
+ path,
72
+ })),
73
+ ...(loadedExtensions.warnings ?? []).map(({ path, warning }): LoaderDiagnostic => ({
74
+ resource: "Extensions",
75
+ type: "warning",
76
+ message: warning,
77
+ path,
78
+ })),
79
+ ...diagnosticsFor("Skills", loadedSkills.diagnostics),
80
+ ...diagnosticsFor("Prompts", loader.getPrompts().diagnostics),
81
+ ...diagnosticsFor("Themes", loader.getThemes().diagnostics),
82
+ ];
83
+
84
+ return { tools, context, skills, extensions, diagnostics };
85
+ }
package/src/tabs.ts ADDED
@@ -0,0 +1,60 @@
1
+ import type { ResourceSnapshot } from "./resources.ts";
2
+
3
+ export const RESOURCE_TABS = ["Tools", "Context", "Skills", "Extensions", "Diagnostics"] as const;
4
+ export type ResourceTab = (typeof RESOURCE_TABS)[number];
5
+
6
+ // Narrower label sets, tried in order when the full bar does not fit.
7
+ export const TAB_LABELS = [
8
+ ["Tools", "Ctx", "Skills", "Ext", "Diag"],
9
+ ["T", "C", "S", "E", "D"],
10
+ ];
11
+
12
+ export const EXPANDABLE = new Set<ResourceTab>(["Tools", "Extensions"]);
13
+
14
+ const UNIT: Record<ResourceTab, string> = {
15
+ Tools: "registered",
16
+ Context: "loaded",
17
+ Skills: "loaded",
18
+ Extensions: "loaded",
19
+ Diagnostics: "issues",
20
+ };
21
+
22
+ const SUMMARY: Record<"Context" | "Skills" | "Diagnostics", string> = {
23
+ Context: "Loaded instruction files and system-prompt sources, in Pi’s loading order.",
24
+ Skills: "Run a skill with /skill:<name>.",
25
+ Diagnostics:
26
+ "Loader errors, warnings, and name collisions across extensions, skills, prompts, and themes.",
27
+ };
28
+
29
+ export function tabCount(resources: ResourceSnapshot, tab: ResourceTab): number {
30
+ if (tab === "Tools") return resources.tools.length;
31
+ if (tab === "Context") return resources.context.length;
32
+ if (tab === "Skills") return resources.skills.length;
33
+ if (tab === "Extensions") return resources.extensions.length;
34
+ return resources.diagnostics.length;
35
+ }
36
+
37
+ export function tabUnit(tab: ResourceTab): string {
38
+ return UNIT[tab];
39
+ }
40
+
41
+ export function tabSummary(
42
+ resources: ResourceSnapshot,
43
+ tab: ResourceTab,
44
+ compact: boolean,
45
+ expanded: boolean,
46
+ ): string {
47
+ if (tab === "Tools") {
48
+ const active = resources.tools.filter((tool) => tool.active).length;
49
+ const counts = `${active} active · ${resources.tools.length - active} inactive`;
50
+ return compact
51
+ ? counts
52
+ : `${counts} · Registered exposure is shown. Per-request tool hiding is not.`;
53
+ }
54
+ if (tab === "Extensions") {
55
+ return compact
56
+ ? "Loaded extensions by source."
57
+ : `Loaded extensions by source. Press e to ${expanded ? "hide" : "show"} full paths and package entries.`;
58
+ }
59
+ return SUMMARY[tab];
60
+ }
package/src/tools.ts ADDED
@@ -0,0 +1,47 @@
1
+ import type { Theme, ToolExposure } from "@earendil-works/pi-coding-agent";
2
+ import { visibleWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui";
3
+
4
+ import type { ResourceSnapshot } from "./resources.ts";
5
+
6
+ const EXPOSURE_HELP: Record<ToolExposure, string> = {
7
+ direct: "Declared to the model and callable from other tools while active.",
8
+ "model-only": "Declared to the model while active. Never callable from other tools.",
9
+ codemode: "Callable from other tools even when inactive. Not normally declared to the model.",
10
+ deferred: "Callable from other tools even when inactive. Tool search can find and activate it.",
11
+ hidden: "Registered but unreachable.",
12
+ };
13
+
14
+ export function renderTools(
15
+ tools: ResourceSnapshot["tools"],
16
+ theme: Theme,
17
+ width: number,
18
+ expanded: boolean,
19
+ ): string[] {
20
+ if (tools.length === 0) return [theme.fg("muted", "No tools registered.")];
21
+
22
+ const lines: string[] = [];
23
+ const row = (text: string, color: "muted" | "dim") => {
24
+ for (const line of wrapTextWithAnsi(text, Math.max(1, width - 2))) {
25
+ lines.push(" " + theme.fg(color, line));
26
+ }
27
+ };
28
+ for (const tool of tools) {
29
+ const status = tool.active ? theme.fg("success", "● active") : theme.fg("dim", "○ inactive");
30
+ const title =
31
+ theme.fg("accent", expanded ? "▾ " : "▸ ") + theme.bold(theme.fg("text", tool.name));
32
+ const exposure = theme.fg("accent", "[" + tool.exposure + "]");
33
+ const metadata = status + " " + exposure;
34
+ const heading = title + " " + metadata;
35
+ if (visibleWidth(heading) <= width) lines.push(heading);
36
+ else {
37
+ lines.push(...wrapTextWithAnsi(title, Math.max(1, width)));
38
+ row(metadata, "dim");
39
+ }
40
+ if (expanded) {
41
+ row(tool.description.trim(), "muted");
42
+ row(EXPOSURE_HELP[tool.exposure], "dim");
43
+ lines.push("");
44
+ }
45
+ }
46
+ return lines;
47
+ }