pi-arsenal 0.2.1 → 0.3.2

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.
@@ -1,866 +1,1121 @@
1
- import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, writeFileSync } from "node:fs";
2
- import { createServer, type Server } from "node:http";
3
- import { basename, dirname, extname, join, parse, relative, resolve, sep } from "node:path";
4
- import { spawn } from "node:child_process";
5
- import type { AssistantMessage } from "@earendil-works/pi-ai";
6
- import type { ExtensionAPI, ExtensionCommandContext, ExtensionContext, SessionEntry, Theme } from "@earendil-works/pi-coding-agent";
7
- import { openSessionLibrary, listSessions, sessionTitle, relativeTime } from "../lib/session-library.ts";
8
- import { Key, matchesKey, truncateToWidth, visibleWidth, type Focusable } from "@earendil-works/pi-tui";
9
-
10
- const STATE_TYPE = "terra-workspace-v1";
11
- const ROOT = process.env.USERPROFILE || process.env.HOME || ".";
12
- const WORKSPACES_FILE = join(ROOT, ".pi", "agent", "workspaces.json");
13
- const DIAGRAMS_DIR = join(".pi", "diagrams");
14
- const DIAGRAMS_MANIFEST = "gallery.json";
15
- const SKILLS_DIR = join(ROOT, ".agents", "skills");
16
- const DISABLED_SKILLS_DIR = join(ROOT, ".agents", "disabled-skills");
17
- const MCP_CACHE_FILE = join(ROOT, ".pi", "agent", "mcp-cache.json");
18
- const RESOURCE_METADATA_FILE = join(ROOT, ".pi", "agent", "resource-library.json");
19
- const EXTENSIONS_DIR = join(ROOT, ".pi", "agent", "extensions");
20
- const HIDDEN_NAMES = new Set([".git", "node_modules", ".venv", "__pycache__"]);
21
- const LIST_PAGE_SIZE = 16;
22
- const DIAGRAM_PAGE_SIZE = 8;
23
- const NOTES_FILENAME = ".pi/workspace-notes.md";
24
- const NOTES_CTX_FILE = join(ROOT, ".pi", "agent", "workspace-notes-context.json");
25
- const APPROVAL_LOG_FILE = join(ROOT, ".pi", "agent", "destructive-operation-guard.jsonl");
26
- const DIAGRAM_STARTER = "Draw a system architecture diagram for this project.";
27
-
28
- type Workspace = { name: string; path: string };
29
- // "files" view removed — read-only listing with no actionable operations had no UX value.
30
- // "skill-confirm" view removed — replaced with ctx.ui.confirm() for consistent interaction.
31
- // Global letter shortcuts (p/f/b/c/d/l/m) removed — undiscoverable with no on-screen hint.
32
- // Added: "notes" (Workspace Notes), "env-check" (Environment Check) views.
33
- type View = "home" | "projects" | "browser" | "usage" | "diagrams" | "skills" | "skill-list" | "skill-detail" | "mcp" | "mcp-detail" | "notes" | "env-check";
34
- type FileItem = { name: string; directory: boolean };
35
- type UsageTotals = { input: number; output: number; cacheRead: number };
36
- type Diagram = { id: string; title: string; file: string; type?: string; createdAt?: string; summary?: string };
37
- type Skill = { name: string; description: string; path: string; enabled: boolean };
38
- type SkillEntry = { type: "folder"; name: string; relative: string } | { type: "skill"; skill: Skill };
39
- type McpTool = { name: string; description?: string };
40
- type McpServer = { name: string; tools: McpTool[]; cachedAt?: number };
41
- type ResourceLabels = { displayName?: string; note?: string };
42
- type ResourceMetadata = { skills?: Record<string, ResourceLabels>; mcp?: Record<string, ResourceLabels> };
43
- type TranslationStudioBridge = { version: 1; open(ctx: ExtensionCommandContext): Promise<void> };
44
- type EnvItem = { label: string; status: "ok" | "warn" | "info"; detail: string };
45
- type ApprovalEntry = { timestamp: string; operation: string; tool: string; approval: string; approved: boolean };
46
- type Result =
47
- | { type: "close" }
48
- | { type: "workspace"; workspace: Workspace }
49
- | { type: "view-diagram"; diagram: Diagram }
50
- | { type: "diagram-starter" }
51
- | { type: "sessions" | "translation" | "search-sessions" | "clean-sessions" | "approval-log" | "toggle-notes-context" }
52
- | { type: "edit-label"; kind: "skills" | "mcp"; key: string; fallback: string; field: "displayName" | "note" }
53
- | { type: "use-skill"; canonicalName: string }
54
- | { type: "organize-skills" }
55
- | { type: "toggle-skill-folder"; enabled: boolean; relative: string }
56
- | { type: "confirm-skill-toggle"; skill: Skill }
57
- | { type: "edit-notes"; workspacePath: string };
58
-
59
- const TRANSLATION_BRIDGE_KEY = Symbol.for("pi-translation-studio.bridge.v1");
60
- const CHOICES_BRIDGE_KEY = Symbol.for("pi-choices.bridge.v1");
61
- const translationBridge = (): TranslationStudioBridge | undefined => {
62
- const bridge = (globalThis as Record<symbol, unknown>)[TRANSLATION_BRIDGE_KEY] as TranslationStudioBridge | undefined;
63
- return bridge?.version === 1 ? bridge : undefined;
64
- };
65
- const hasChoicesBridge = (): boolean => !!(globalThis as Record<symbol, unknown>)[CHOICES_BRIDGE_KEY];
66
-
67
- type MermaidViewer = { server: Server; source: string; title: string; url: string };
68
- let mermaidViewer: MermaidViewer | undefined;
69
-
70
- function configuredWorkspaces(fallback: string): Workspace[] {
71
- try {
72
- const data = JSON.parse(readFileSync(WORKSPACES_FILE, "utf8")) as { workspaces?: Workspace[] };
73
- const found = (data.workspaces || []).filter((item) => typeof item.name === "string" && typeof item.path === "string" && existsSync(item.path));
74
- if (found.length) return found;
75
- } catch { /* Current Pi cwd is a safe fallback. */ }
76
- return [{ name: basename(fallback) || fallback, path: fallback }];
77
- }
78
-
79
- function restoredWorkspace(entries: readonly SessionEntry[], fallback: string): Workspace {
80
- for (let i = entries.length - 1; i >= 0; i--) {
81
- const entry = entries[i];
82
- if (entry?.type !== "custom" || entry.customType !== STATE_TYPE) continue;
83
- const item = entry.data as Workspace | undefined;
84
- if (item && typeof item.name === "string" && typeof item.path === "string" && existsSync(item.path)) return item;
85
- }
86
- return configuredWorkspaces(fallback)[0]!;
87
- }
88
-
89
- function browserEntries(path: string): FileItem[] {
90
- try {
91
- return readdirSync(path, { withFileTypes: true })
92
- .filter((entry) => !HIDDEN_NAMES.has(entry.name) && entry.isDirectory())
93
- .sort((a, b) => a.name.localeCompare(b.name))
94
- .slice(0, 120)
95
- .map((entry) => ({ name: entry.name, directory: true }));
96
- } catch { return []; }
97
- }
98
-
99
- function sessionUsage(ctx: ExtensionContext): UsageTotals {
100
- const totals: UsageTotals = { input: 0, output: 0, cacheRead: 0 };
101
- for (const entry of ctx.sessionManager.getBranch()) {
102
- if (entry.type !== "message" || entry.message.role !== "assistant") continue;
103
- const usage = (entry.message as AssistantMessage).usage;
104
- if (!usage) continue;
105
- totals.input += usage.input || 0;
106
- totals.output += usage.output || 0;
107
- totals.cacheRead += usage.cacheRead || 0;
108
- }
109
- return totals;
110
- }
111
-
112
- const formatTokens = (value: number) => value < 1000 ? String(value) : `${(value / 1000).toFixed(1)}k`;
113
-
114
- function diagrams(root: string): Diagram[] {
115
- try {
116
- const data = JSON.parse(readFileSync(join(root, DIAGRAMS_DIR, DIAGRAMS_MANIFEST), "utf8")) as { diagrams?: Diagram[] };
117
- return (data.diagrams || []).filter((item) => typeof item.id === "string" && typeof item.title === "string" && typeof item.file === "string");
118
- } catch { return []; }
119
- }
120
-
121
- function resourceMetadata(): ResourceMetadata {
122
- try { return JSON.parse(readFileSync(RESOURCE_METADATA_FILE, "utf8")) as ResourceMetadata; } catch { return {}; }
123
- }
124
-
125
- function saveResourceMetadata(data: ResourceMetadata): void {
126
- mkdirSync(dirname(RESOURCE_METADATA_FILE), { recursive: true });
127
- writeFileSync(RESOURCE_METADATA_FILE, `${JSON.stringify(data, null, 2)}\n`, "utf8");
128
- }
129
-
130
- function workspaceNotes(workspacePath: string): string {
131
- try { return readFileSync(join(workspacePath, NOTES_FILENAME), "utf8"); } catch { return ""; }
132
- }
133
-
134
- function saveWorkspaceNotes(workspacePath: string, text: string): void {
135
- const file = join(workspacePath, NOTES_FILENAME);
136
- mkdirSync(dirname(file), { recursive: true });
137
- writeFileSync(file, text, "utf8");
138
- }
139
-
140
- function notesContextEnabled(workspacePath: string): boolean {
141
- try {
142
- const data = JSON.parse(readFileSync(NOTES_CTX_FILE, "utf8")) as Record<string, boolean>;
143
- return data[workspacePath] === true;
144
- } catch { return false; }
145
- }
146
-
147
- function saveNotesContext(workspacePath: string, enabled: boolean): void {
148
- let data: Record<string, boolean> = {};
149
- try { data = JSON.parse(readFileSync(NOTES_CTX_FILE, "utf8")) as Record<string, boolean>; } catch { /* First write. */ }
150
- if (enabled) data[workspacePath] = true; else delete data[workspacePath];
151
- mkdirSync(dirname(NOTES_CTX_FILE), { recursive: true });
152
- writeFileSync(NOTES_CTX_FILE, `${JSON.stringify(data, null, 2)}\n`, "utf8");
153
- }
154
-
155
- function readApprovalLog(): ApprovalEntry[] {
156
- try {
157
- return readFileSync(APPROVAL_LOG_FILE, "utf8").trim().split("\n").filter(Boolean).map((line) => JSON.parse(line) as ApprovalEntry).reverse();
158
- } catch { return []; }
159
- }
160
-
161
- function buildEnvItems(ctx: ExtensionCommandContext, hasTranslation: boolean, hasChoices: boolean): EnvItem[] {
162
- const items: EnvItem[] = [];
163
- // Local extensions
164
- const extFiles: string[] = [];
165
- try {
166
- for (const item of readdirSync(EXTENSIONS_DIR, { withFileTypes: true })) {
167
- if (item.isFile() && (item.name.endsWith(".ts") || item.name.endsWith(".js")) && !item.name.endsWith(".disabled")) extFiles.push(item.name.replace(/\.[^.]+$/, ""));
168
- }
169
- } catch { /* Directory may not exist. */ }
170
- items.push({ label: "Local extensions", status: extFiles.length > 0 ? "ok" : "info", detail: extFiles.length > 0 ? extFiles.join(", ") : "None found" });
171
- // pi-choices
172
- items.push({ label: "pi-choices", status: hasChoices ? "ok" : "warn", detail: hasChoices ? "Available — Task Plan protection active" : "Not loaded — install pi-arsenal to enable plan protection" });
173
- // Translation Studio
174
- items.push({ label: "Translation Studio", status: hasTranslation ? "ok" : "info", detail: hasTranslation ? "pi-translation-studio bridge active" : "Not installed (optional)" });
175
- // Workspace
176
- items.push({ label: "Workspace path", status: existsSync(ctx.cwd) ? "ok" : "warn", detail: existsSync(ctx.cwd) ? ctx.cwd : `Missing: ${ctx.cwd}` });
177
- // MCP cache
178
- try {
179
- const raw = JSON.parse(readFileSync(MCP_CACHE_FILE, "utf8")) as { servers?: Record<string, { cachedAt?: number }> };
180
- const servers = Object.keys(raw.servers || {});
181
- const timestamps = Object.values(raw.servers || {}).map((s) => s.cachedAt || 0).filter(Boolean);
182
- const latest = timestamps.length ? new Date(Math.max(...timestamps)) : null;
183
- items.push({ label: "MCP cache", status: servers.length ? "ok" : "info", detail: servers.length ? `${servers.length} server${servers.length === 1 ? "" : "s"} · updated ${latest ? latest.toLocaleDateString() : "unknown"}` : "No cached servers" });
184
- } catch { items.push({ label: "MCP cache", status: "info", detail: "No cache file found" }); }
185
- // Skills
186
- try {
187
- let count = 0; const walk = (dir: string) => { for (const item of readdirSync(dir, { withFileTypes: true })) { if (item.isDirectory() && existsSync(join(dir, item.name, "SKILL.md"))) count++; else if (item.isDirectory()) walk(join(dir, item.name)); } }; walk(SKILLS_DIR);
188
- items.push({ label: "Active skills", status: count > 0 ? "ok" : "info", detail: `${count} skill${count === 1 ? "" : "s"} in enabled library` });
189
- } catch { items.push({ label: "Active skills", status: "info", detail: "Skills directory not found" }); }
190
- // Model
191
- const model = ctx.model?.id;
192
- items.push({ label: "Model", status: model ? "ok" : "warn", detail: model || "Unknown — check Pi model configuration" });
193
- return items;
194
- }
195
-
196
- function skillRoot(skill: Skill): string { return skill.enabled ? SKILLS_DIR : DISABLED_SKILLS_DIR; }
197
- function skillKey(skill: Skill): string { return relative(skillRoot(skill), skill.path).replaceAll("\\", "/"); }
198
- function moveSkill(skill: Skill, targetRoot: string, targetRelative: string): Skill {
199
- const target = join(targetRoot, targetRelative);
200
- if (existsSync(target)) throw new Error("A skill already exists at the destination.");
201
- mkdirSync(dirname(target), { recursive: true });
202
- renameSync(skill.path, target);
203
- const data = resourceMetadata(), oldKey = skillKey(skill), next: Skill = { ...skill, path: target, enabled: targetRoot === SKILLS_DIR }, newKey = skillKey(next);
204
- if (oldKey !== newKey && data.skills?.[oldKey]) { data.skills[newKey] = data.skills[oldKey]; delete data.skills[oldKey]; saveResourceMetadata(data); }
205
- return next;
206
- }
207
- function categoryOf(skill: Skill): string { const dir = dirname(skillKey(skill)); return dir === "." ? "Uncategorized" : dir; }
208
- const CATEGORY_COLORS = ["accent", "success", "warning", "error", "mdLink", "mdCode", "syntaxFunction", "syntaxType", "syntaxString"] as const;
209
- function categoryColor(category: string): typeof CATEGORY_COLORS[number] {
210
- let hash = 0; for (const char of category) hash = (hash * 31 + char.charCodeAt(0)) >>> 0;
211
- return CATEGORY_COLORS[hash % CATEGORY_COLORS.length]!;
212
- }
213
- function validCategory(value: string): string | undefined {
214
- const category = value.trim().replaceAll("\\", "/").replace(/^\/+|\/+$/g, "");
215
- return category && !category.split("/").some((part) => !part || part === "." || part === "..") ? category : undefined;
216
- }
217
- function skillCategories(): string[] {
218
- const collect = (root: string): string[] => { const found: string[] = []; const walk = (dir: string) => { for (const item of readdirSync(dir, { withFileTypes: true })) { if (!item.isDirectory()) continue; const path = join(dir, item.name); if (existsSync(join(path, "SKILL.md"))) continue; found.push(relative(root, path).replaceAll("\\", "/")); walk(path); } }; try { walk(root); } catch { /* Empty or unavailable library. */ } return found; };
219
- return [...new Set([...collect(SKILLS_DIR), ...collect(DISABLED_SKILLS_DIR)])].sort();
220
- }
221
- function labelsFor(kind: "skills" | "mcp", key: string): ResourceLabels { return resourceMetadata()[kind]?.[key] || {}; }
222
- function displayName(kind: "skills" | "mcp", key: string, fallback: string): string { return labelsFor(kind, key).displayName?.trim() || fallback; }
223
-
224
- function skills(): Skill[] {
225
- const read = (root: string, enabled: boolean): Skill[] => {
226
- const found: Skill[] = [], walk = (dir: string) => { try { for (const item of readdirSync(dir, { withFileTypes: true })) { if (!item.isDirectory()) continue; const path = join(dir, item.name), file = join(path, "SKILL.md"); if (existsSync(file)) { const source = readFileSync(file, "utf8"); found.push({ name: /^name:\s*(.+)$/m.exec(source)?.[1]?.trim() || item.name, description: /^description:\s*(.+)$/m.exec(source)?.[1]?.trim() || "No description declared.", path, enabled }); } else walk(path); } } catch { /* An unreadable folder does not block the library. */ } };
227
- walk(root); return found;
228
- };
229
- return [...read(SKILLS_DIR, true), ...read(DISABLED_SKILLS_DIR, false)].sort((a, b) => Number(b.enabled) - Number(a.enabled) || categoryOf(a).localeCompare(categoryOf(b)) || a.name.localeCompare(b.name));
230
- }
231
-
232
- function skillCount(folder: string): number {
233
- try { let count = 0; const walk = (dir: string) => { for (const item of readdirSync(dir, { withFileTypes: true })) { if (!item.isDirectory()) continue; const path = join(dir, item.name); if (existsSync(join(path, "SKILL.md"))) count++; else walk(path); } }; walk(folder); return count; } catch { return 0; }
234
- }
235
-
236
- function skillEntries(enabled: boolean, directory = ""): SkillEntry[] {
237
- const root = enabled ? SKILLS_DIR : DISABLED_SKILLS_DIR, folder = resolve(root, directory);
238
- if (!isInside(root, folder)) return [];
239
- try { return readdirSync(folder, { withFileTypes: true }).filter((item) => item.isDirectory()).flatMap((item): SkillEntry[] => {
240
- const path = join(folder, item.name), file = join(path, "SKILL.md"), relativePath = relative(root, path).replaceAll("\\", "/");
241
- if (!existsSync(file)) return skillCount(path) ? [{ type: "folder", name: item.name, relative: relativePath }] : [];
242
- const source = readFileSync(file, "utf8"); return [{ type: "skill", skill: { name: /^name:\s*(.+)$/m.exec(source)?.[1]?.trim() || item.name, description: /^description:\s*(.+)$/m.exec(source)?.[1]?.trim() || "No description declared.", path, enabled } }];
243
- }).sort((a, b) => Number(b.type === "folder") - Number(a.type === "folder") || (a.type === "folder" ? a.name : a.skill.name).localeCompare(b.type === "folder" ? b.name : b.skill.name)); } catch { return []; }
244
- }
245
-
246
- function moveSkillFolder(enabled: boolean, folderRelative: string): number {
247
- const sourceRoot = enabled ? SKILLS_DIR : DISABLED_SKILLS_DIR, targetRoot = enabled ? DISABLED_SKILLS_DIR : SKILLS_DIR;
248
- const source = resolve(sourceRoot, folderRelative), target = resolve(targetRoot, folderRelative);
249
- if (!isInside(sourceRoot, source) || !isInside(targetRoot, target) || !existsSync(source)) throw new Error("Invalid skill folder.");
250
- const contained = skills().filter((skill) => skill.enabled === enabled && (skillKey(skill) === folderRelative || skillKey(skill).startsWith(`${folderRelative}/`)));
251
- if (!contained.length) throw new Error("This folder has no skills to move.");
252
- for (const skill of contained) moveSkill(skill, targetRoot, skillKey(skill));
253
- return contained.length;
254
- }
255
-
256
- function cachedMcpServers(): McpServer[] {
257
- try {
258
- const data = JSON.parse(readFileSync(MCP_CACHE_FILE, "utf8")) as { servers?: Record<string, { tools?: McpTool[]; cachedAt?: number }> };
259
- return Object.entries(data.servers || {}).map(([name, server]) => ({ name, tools: (server.tools || []).filter((tool) => typeof tool.name === "string").map(({ name, description }) => ({ name, description: typeof description === "string" ? description : undefined })), cachedAt: server.cachedAt }));
260
- } catch { return []; }
261
- }
262
-
263
- async function organizeSkillFolders(ctx: ExtensionCommandContext): Promise<void> {
264
- while (true) {
265
- const action = await ctx.ui.select("Organize Skill Folders", ["Create shared category folder", "Move a skill", "Back"]);
266
- if (!action || action === "Back") return;
267
- if (action === "Create shared category folder") {
268
- const value = await ctx.ui.input("New shared category", "");
269
- const category = value ? validCategory(value) : undefined;
270
- if (!category) { ctx.ui.notify("Enter a relative folder name without . or ...", "warning"); continue; }
271
- mkdirSync(join(SKILLS_DIR, category), { recursive: true }); mkdirSync(join(DISABLED_SKILLS_DIR, category), { recursive: true });
272
- ctx.ui.notify(`Created category in both libraries: ${category}`, "info"); continue;
273
- }
274
- const library = await ctx.ui.select("Choose skill library", ["✨ Enabled skills", "💤 Disabled skills", "Cancel"]);
275
- if (!library || library === "Cancel") continue;
276
- const enabled = library.startsWith("✨"), list = skills().filter((skill) => skill.enabled === enabled);
277
- if (!list.length) { ctx.ui.notify("No skills in this library.", "info"); continue; }
278
- const choices = list.map((skill) => `${displayName("skills", skillKey(skill), skill.name)} · ${categoryOf(skill)}`);
279
- const selected = await ctx.ui.select("Move a skill", [...choices, "Cancel"]);
280
- if (!selected || selected === "Cancel") continue;
281
- const skill = list[choices.indexOf(selected)]; if (!skill) continue;
282
- const categories = skillCategories();
283
- const destination = await ctx.ui.select("Move to category", ["Library root (Uncategorized)", ...categories, "Create new category…", "Cancel"]);
284
- if (!destination || destination === "Cancel") continue;
285
- let category = destination === "Library root (Uncategorized)" ? "" : destination;
286
- if (destination === "Create new category…") { const value = await ctx.ui.input("New shared category", ""); category = value ? validCategory(value) || "" : ""; if (!category) { ctx.ui.notify("Enter a relative folder name without . or ...", "warning"); continue; } mkdirSync(join(SKILLS_DIR, category), { recursive: true }); mkdirSync(join(DISABLED_SKILLS_DIR, category), { recursive: true }); }
287
- try { moveSkill(skill, skillRoot(skill), category ? join(category, basename(skill.path)) : basename(skill.path)); ctx.ui.notify("Skill moved. Run /reload before relying on a changed active skill path.", "info"); }
288
- catch (error) { ctx.ui.notify(error instanceof Error ? error.message : "Could not move skill.", "error"); }
289
- }
290
- }
291
-
292
- async function searchAndOpenSession(pi: ExtensionAPI, ctx: ExtensionCommandContext): Promise<void> {
293
- if (ctx.mode !== "tui") return;
294
- const query = await ctx.ui.input("Search sessions", "");
295
- if (!query?.trim()) return;
296
- const term = query.trim().toLowerCase();
297
- const all = await listSessions();
298
- const matched = all.filter((session) => {
299
- const title = sessionTitle(session).toLowerCase();
300
- const first = session.firstMessage.toLowerCase();
301
- return title.includes(term) || first.includes(term);
302
- });
303
- if (!matched.length) { ctx.ui.notify(`No sessions matching "${query}".`, "info"); return; }
304
- const currentPath = ctx.sessionManager.getSessionFile();
305
- const options = matched.map((session) => `${sessionTitle(session)} — ${relativeTime(session.modified)} · ${session.messageCount} messages${session.path === currentPath ? " ● current" : ""}`);
306
- const choice = await ctx.ui.select(`Sessions matching "${query}"`, [...options, "Cancel"]);
307
- if (!choice || choice === "Cancel") return;
308
- const session = matched[options.indexOf(choice)];
309
- if (!session || session.path === currentPath) return;
310
- await ctx.waitForIdle();
311
- await ctx.switchSession(session.path, { withSession: async (replacement) => replacement.ui.notify(`Reloaded: ${sessionTitle(session)}`, "info") });
312
- }
313
-
314
- function isInside(parent: string, child: string): boolean {
315
- return child === parent || child.startsWith(parent.endsWith(sep) ? parent : `${parent}${sep}`);
316
- }
317
-
318
- function registeredMermaidSource(root: string, diagram: Diagram): string | undefined {
319
- const base = resolve(root, DIAGRAMS_DIR);
320
- const file = resolve(base, diagram.file);
321
- if (diagram.type && diagram.type !== "mermaid") return undefined;
322
- if (extname(file).toLowerCase() !== ".mmd" || !isInside(base, file) || !existsSync(file)) return undefined;
323
- try { return readFileSync(file, "utf8"); } catch { return undefined; }
324
- }
325
-
326
- function viewerHtml(title: string, source: string): string {
327
- return `<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${title.replace(/[<&]/g, "")}</title><style>body{margin:0;background:#1a1b26;color:#c0caf5;font:16px system-ui,sans-serif}header{padding:14px 20px;border-bottom:1px solid #414868;font-weight:600}main{padding:24px;overflow:auto;min-height:calc(100vh - 68px)}.mermaid{background:#24283b;border:1px solid #414868;border-radius:10px;padding:24px;display:inline-block;min-width:calc(100% - 50px);white-space:pre-wrap}.error{color:#f7768e;white-space:pre-wrap;margin-bottom:16px}</style><header>${title.replace(/[<&]/g, "")}</header><main><div class="error" hidden></div><pre class="mermaid"></pre></main><script type="module">const source=${JSON.stringify(source)};const target=document.querySelector('.mermaid');const errorBox=document.querySelector('.error');target.textContent=source;async function loadMermaid(){let lastError;for(const url of ['https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.esm.min.mjs','https://unpkg.com/mermaid@11/dist/mermaid.esm.min.mjs']){try{return (await import(url)).default}catch(error){lastError=error}}throw lastError}try{const mermaid=await loadMermaid();mermaid.initialize({startOnLoad:false,theme:'dark'});await mermaid.run({nodes:[target]})}catch(error){errorBox.hidden=false;errorBox.textContent='Mermaid renderer could not be loaded. Showing source instead.\\n'+error}</script></html>`;
328
- }
329
-
330
- async function openMermaidViewer(root: string, diagram: Diagram): Promise<string | undefined> {
331
- const source = registeredMermaidSource(root, diagram);
332
- if (!source) return undefined;
333
- if (!mermaidViewer) {
334
- const server = createServer((request, response) => {
335
- if (!mermaidViewer || request.url !== "/") { response.writeHead(404).end(); return; }
336
- response.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store" });
337
- response.end(viewerHtml(mermaidViewer.title, mermaidViewer.source));
338
- });
339
- await new Promise<void>((resolveListen, rejectListen) => { server.once("error", rejectListen); server.listen(0, "127.0.0.1", () => { server.off("error", rejectListen); resolveListen(); }); });
340
- const address = server.address();
341
- if (!address || typeof address === "string") { server.close(); return undefined; }
342
- mermaidViewer = { server, source, title: diagram.title, url: `http://127.0.0.1:${address.port}/` };
343
- } else { mermaidViewer.source = source; mermaidViewer.title = diagram.title; }
344
- spawn("cmd.exe", ["/c", "start", "", mermaidViewer.url], { detached: true, stdio: "ignore" }).unref();
345
- return mermaidViewer.url;
346
- }
347
-
348
- function driveRoots(): string[] {
349
- const roots: string[] = [];
350
- for (let code = 67; code <= 90; code++) {
351
- const root = `${String.fromCharCode(code)}:\\`;
352
- if (existsSync(root)) roots.push(root);
353
- }
354
- return roots;
355
- }
356
-
357
- class WorkspaceDrawer implements Focusable {
358
- readonly width = 52;
359
- focused = false;
360
- private view: View = "home";
361
- private selected = 0;
362
- private browserPath: string | undefined;
363
- private browserItems: FileItem[] = [];
364
- private diagramItems: Diagram[] | undefined;
365
- private skillItems: Skill[] | undefined;
366
- private skillEntryItems: SkillEntry[] = [];
367
- private skillDirectory = "";
368
- private skillEnabled = true;
369
- private selectedSkill: Skill | undefined;
370
- private mcpItems: McpServer[] | undefined;
371
- private selectedMcp: McpServer | undefined;
372
- private envItems: EnvItem[] | undefined;
373
-
374
- constructor(
375
- private readonly ctx: ExtensionCommandContext,
376
- private readonly workspace: Workspace,
377
- private readonly workspaces: Workspace[],
378
- private readonly theme: Theme,
379
- private readonly done: (result: Result) => void,
380
- private readonly tui: { requestRender(): void },
381
- private readonly hasTranslationStudio: boolean,
382
- private readonly hasPiChoices: boolean,
383
- ) {}
384
-
385
- private homeItems(): Array<{ label: string; view?: View; result?: Result["type"] }> {
386
- const hasNotes = workspaceNotes(this.workspace.path).trim().length > 0;
387
- const notesInCtx = notesContextEnabled(this.workspace.path);
388
- return [
389
- { label: "📁 Projects", view: "projects" },
390
- { label: "🖥️ Browse computer…", view: "browser" },
391
- { label: "📊 Session Tokens", view: "usage" },
392
- { label: "🗺️ Diagram Gallery", view: "diagrams" },
393
- { label: "🕘 Session Library", result: "sessions" },
394
- { label: "🔎 Search sessions…", result: "search-sessions" },
395
- { label: "🧹 Clean up sessions…", result: "clean-sessions" },
396
- ...(this.hasTranslationStudio ? [{ label: "🌐 Translation Studio", result: "translation" as const }] : []),
397
- { label: `📌 Workspace Notes${hasNotes ? " ·" : ""}`, view: "notes" as View },
398
- { label: `${notesInCtx ? "📌" : "○"} Include notes in context`, result: "toggle-notes-context" as Result["type"] },
399
- { label: "✨ Skill Library", view: "skills" },
400
- { label: "🔌 MCP Servers", view: "mcp" },
401
- { label: "🛡 Approval Log", result: "approval-log" as Result["type"] },
402
- { label: "🔍 Environment Check", view: "env-check" as View },
403
- ];
404
- }
405
-
406
- private open(view: View): void {
407
- this.view = view;
408
- this.selected = 0;
409
- if (view === "browser") this.openBrowser(this.browserPath);
410
- if (view === "diagrams") this.diagramItems = diagrams(this.workspace.path);
411
- if (view === "skills") this.skillItems = skills();
412
- if (view === "skill-list") this.skillEntryItems = skillEntries(this.skillEnabled, this.skillDirectory);
413
- if (view === "mcp") this.mcpItems = cachedMcpServers();
414
- if (view === "env-check") this.envItems = buildEnvItems(this.ctx, this.hasTranslationStudio, this.hasPiChoices);
415
- }
416
-
417
- private openBrowser(path: string | undefined): void {
418
- this.browserPath = path;
419
- this.selected = 0;
420
- this.browserItems = path ? browserEntries(path) : driveRoots().map((root) => ({ name: root, directory: true }));
421
- }
422
-
423
- private backBrowser(): void {
424
- if (!this.browserPath) { this.open("projects"); return; }
425
- const parent = dirname(this.browserPath);
426
- this.openBrowser(parent === this.browserPath ? undefined : parent);
427
- }
428
-
429
- handleInput(data: string): void {
430
- if (matchesKey(data, Key.escape) || matchesKey(data, Key.left)) {
431
- if (this.view === "home") { this.done({ type: "close" }); return; }
432
- if (this.view === "browser") { this.backBrowser(); return; }
433
- if (this.view === "skill-list") {
434
- if (this.skillDirectory) { this.skillDirectory = dirname(this.skillDirectory); if (this.skillDirectory === ".") this.skillDirectory = ""; this.open("skill-list"); }
435
- else this.open("skills");
436
- return;
437
- }
438
- if (this.view === "skill-detail") { this.open("skill-list"); return; }
439
- if (this.view === "mcp-detail") { this.open("mcp"); return; }
440
- this.view = "home"; this.selected = 0; return;
441
- }
442
- // MCP detail label shortcuts — shown in footer so discoverable
443
- if (matchesKey(data, "n") && this.view === "mcp-detail" && this.selectedMcp) { this.done({ type: "edit-label", kind: "mcp", key: this.selectedMcp.name, fallback: this.selectedMcp.name, field: "displayName" }); return; }
444
- if (matchesKey(data, "o") && this.view === "mcp-detail" && this.selectedMcp) { this.done({ type: "edit-label", kind: "mcp", key: this.selectedMcp.name, fallback: this.selectedMcp.name, field: "note" }); return; }
445
- // Browser workspace-select shortcut
446
- if (matchesKey(data, "s") && this.view === "browser" && this.browserPath) { this.done({ type: "workspace", workspace: { name: basename(parse(this.browserPath).root === this.browserPath ? this.browserPath : this.browserPath) || this.browserPath, path: this.browserPath } }); return; }
447
- if (matchesKey(data, Key.up) || matchesKey(data, "k")) { this.selected = Math.max(0, this.selected - 1); return; }
448
- if (matchesKey(data, Key.down) || matchesKey(data, "j")) {
449
- const last =
450
- this.view === "projects" ? this.workspaces.length :
451
- this.view === "browser" ? Math.max(0, this.browserItems.length - 1) :
452
- this.view === "diagrams" ? Math.max(0, (this.diagramItems?.length ?? 0) > 0 ? (this.diagramItems!.length - 1) : 0) :
453
- this.view === "skills" ? 1 :
454
- this.view === "skill-list" ? this.skillEntryItems.length + (this.skillDirectory ? 1 : 0) :
455
- this.view === "skill-detail" ? (this.selectedSkill?.enabled ? 3 : 2) :
456
- this.view === "mcp" ? Math.max(0, (this.mcpItems?.length || 1) - 1) :
457
- this.view === "mcp-detail" ? Math.max(0, (this.selectedMcp?.tools.length || 1) - 1) :
458
- this.view === "usage" || this.view === "notes" || this.view === "env-check" ? 0 :
459
- this.homeItems().length - 1;
460
- this.selected = Math.min(last, this.selected + 1); return;
461
- }
462
- if (!matchesKey(data, Key.enter) && !matchesKey(data, Key.right)) return;
463
- // notes: Enter opens editor outside the custom UI
464
- if (this.view === "notes") { this.done({ type: "edit-notes", workspacePath: this.workspace.path }); return; }
465
- if (this.view === "mcp-detail" || this.view === "usage" || this.view === "env-check") return;
466
- // diagrams: empty state has a starter prompt at index 0
467
- if (this.view === "diagrams") {
468
- const gallery = this.diagramItems || [];
469
- if (gallery.length === 0 && this.selected === 0) { this.done({ type: "diagram-starter" }); return; }
470
- const diagram = gallery[this.selected]; if (diagram) this.done({ type: "view-diagram", diagram }); return;
471
- }
472
- if (this.view === "home") {
473
- const item = this.homeItems()[this.selected];
474
- if (item?.result) this.done({ type: item.result as Result["type"] } as Result);
475
- else if (item?.view) this.open(item.view);
476
- return;
477
- }
478
- if (this.view === "skills") { this.skillEnabled = this.selected === 0; this.skillDirectory = ""; this.open("skill-list"); return; }
479
- if (this.view === "skill-list") {
480
- const entry = this.skillEntryItems[this.selected];
481
- if (entry?.type === "skill") { this.selectedSkill = entry.skill; this.open("skill-detail"); }
482
- else if (entry?.type === "folder") { this.skillDirectory = entry.relative; this.open("skill-list"); }
483
- else if (this.skillDirectory && this.selected === this.skillEntryItems.length) this.done({ type: "toggle-skill-folder", enabled: this.skillEnabled, relative: this.skillDirectory });
484
- else this.done({ type: "organize-skills" });
485
- return;
486
- }
487
- if (this.view === "skill-detail") {
488
- if (!this.selectedSkill) return;
489
- const offset = this.selectedSkill.enabled ? 1 : 0;
490
- if (this.selectedSkill.enabled && this.selected === 0) this.done({ type: "use-skill", canonicalName: this.selectedSkill.name });
491
- else if (this.selected === offset) this.done({ type: "edit-label", kind: "skills", key: skillKey(this.selectedSkill), fallback: this.selectedSkill.name, field: "displayName" });
492
- else if (this.selected === offset + 1) this.done({ type: "edit-label", kind: "skills", key: skillKey(this.selectedSkill), fallback: this.selectedSkill.name, field: "note" });
493
- else this.done({ type: "confirm-skill-toggle", skill: this.selectedSkill });
494
- return;
495
- }
496
- if (this.view === "mcp") { const server = this.mcpItems?.[this.selected]; if (server) { this.selectedMcp = server; this.open("mcp-detail"); } return; }
497
- if (this.view === "projects") {
498
- if (this.selected === this.workspaces.length) { this.open("browser"); return; }
499
- const next = this.workspaces[this.selected];
500
- if (next) this.done({ type: "workspace", workspace: next });
501
- return;
502
- }
503
- if (this.view === "browser") {
504
- const next = this.browserItems[this.selected];
505
- if (next) this.openBrowser(this.browserPath ? join(this.browserPath, next.name) : next.name);
506
- }
507
- }
508
-
509
- render(_width: number): string[] {
510
- const th = this.theme;
511
- const inner = this.width - 2;
512
- const row = (text: string) => th.fg("border", "│") + truncateToWidth(text, inner) + " ".repeat(Math.max(0, inner - visibleWidth(text))) + th.fg("border", "│");
513
- const marker = (index: number) => index === this.selected ? th.fg("accent", "›") : " ";
514
-
515
- const viewTitle: Record<View, string> = {
516
- home: "Terra Workspace",
517
- projects: "Projects",
518
- browser: "Browse computer",
519
- usage: "Session Tokens",
520
- diagrams: "Diagram Gallery",
521
- skills: "Skill Library",
522
- "skill-list": this.skillEnabled ? "Enabled Skills" : "Disabled Skills",
523
- "skill-detail": "Skill Details",
524
- mcp: "MCP Servers",
525
- "mcp-detail": "MCP Server Details",
526
- notes: "Workspace Notes",
527
- "env-check": "Environment Check",
528
- };
529
- const lines = [th.fg("borderAccent", `╭─ ${viewTitle[this.view]} ${"─".repeat(Math.max(0, inner - visibleWidth(viewTitle[this.view]) - 3))}╮`)];
530
-
531
- if (this.view === "home") {
532
- const hasNotes = workspaceNotes(this.workspace.path).trim().length > 0;
533
- const notesInCtx = notesContextEnabled(this.workspace.path);
534
- lines.push(row(` ${th.fg("accent", "◈")} ${th.bold(this.workspace.name)}${hasNotes ? ` ${th.fg("warning", "📌")}` : ""}${notesInCtx ? ` ${th.fg("success", "→ctx")}` : ""}`));
535
- lines.push(row(` ${th.fg("dim", this.workspace.path)}`));
536
- lines.push(row(""));
537
- for (const [i, item] of this.homeItems().entries()) lines.push(row(` ${marker(i)} ${th.fg("text", item.label)}`));
538
- lines.push(row(""));
539
- lines.push(row(th.fg("dim", "↑ ↓ select · Enter / → open · Esc close")));
540
-
541
- } else if (this.view === "projects") {
542
- lines.push(row(th.fg("muted", "Saved project roots for this session")));
543
- lines.push(row(""));
544
- for (let i = 0; i < this.workspaces.length; i++) {
545
- const item = this.workspaces[i]!;
546
- lines.push(row(` ${marker(i)} ${th.fg(i === this.selected ? "text" : "muted", item.name)}`));
547
- lines.push(row(` ${th.fg("dim", item.path)}`));
548
- }
549
- lines.push(row(` ${marker(this.workspaces.length)} ${th.fg("accent", "Browse computer…")}`));
550
- lines.push(row(""));
551
- lines.push(row(th.fg("dim", "Enter / → apply · Esc / ← back")));
552
-
553
- } else if (this.view === "usage") {
554
- const totals = sessionUsage(this.ctx), context = this.ctx.getContextUsage();
555
- lines.push(row(th.fg("muted", "Current session token usage")));
556
- lines.push(row(""));
557
- lines.push(row(`Model ${th.fg("text", this.ctx.model?.id || "—")}`));
558
- lines.push(row(""));
559
- lines.push(row(`Input ${th.fg("accent", formatTokens(totals.input))} tokens`));
560
- lines.push(row(`Output ${th.fg("accent", formatTokens(totals.output))} tokens`));
561
- lines.push(row(`Cache read ${th.fg("accent", formatTokens(totals.cacheRead))} tokens`));
562
- lines.push(row(`Total ${th.fg("accent", formatTokens(totals.input + totals.output + totals.cacheRead))} tokens`));
563
- lines.push(row(""));
564
- lines.push(row(`Context ${th.fg("accent", String(context?.tokens ?? "—"))} / ${th.fg("dim", String(context?.contextWindow ?? "—"))}`));
565
- lines.push(row(""));
566
- lines.push(row(th.fg("dim", "Session only · Esc / ← back")));
567
-
568
- } else if (this.view === "diagrams") {
569
- const gallery = this.diagramItems || [];
570
- lines.push(row(th.fg("muted", "Mermaid diagrams registered for this workspace")));
571
- lines.push(row(""));
572
- if (gallery.length) {
573
- const start = Math.floor(this.selected / DIAGRAM_PAGE_SIZE) * DIAGRAM_PAGE_SIZE;
574
- for (let i = start; i < Math.min(start + DIAGRAM_PAGE_SIZE, gallery.length); i++) {
575
- const diagram = gallery[i]!;
576
- lines.push(row(` ${marker(i)} ${th.fg(i === this.selected ? "accent" : "text", diagram.title)}`));
577
- lines.push(row(` ${th.fg("dim", `${diagram.type || "mermaid"}${diagram.createdAt ? ` · ${diagram.createdAt}` : ""}`)}`));
578
- }
579
- if (gallery.length > DIAGRAM_PAGE_SIZE) lines.push(row(th.fg("dim", `Page ${Math.floor(start / DIAGRAM_PAGE_SIZE) + 1} / ${Math.ceil(gallery.length / DIAGRAM_PAGE_SIZE)} · ↑ ↓ to browse`)));
580
- lines.push(row(""));
581
- lines.push(row(th.fg("dim", "Enter / → open in browser · Esc / ← back")));
582
- } else {
583
- lines.push(row(th.fg("dim", "No Mermaid diagrams yet.")));
584
- lines.push(row(""));
585
- lines.push(row(th.fg("muted", "Try asking Pi:")));
586
- lines.push(row(` ${marker(0)} ${th.fg("accent", `"${DIAGRAM_STARTER}"`)}`));
587
- lines.push(row(""));
588
- lines.push(row(th.fg("dim", "Enter sends prompt to editor · Esc / ← back")));
589
- }
590
-
591
- } else if (this.view === "notes") {
592
- const content = workspaceNotes(this.workspace.path);
593
- lines.push(row(th.fg("muted", `📌 ${this.workspace.name}`)));
594
- lines.push(row(""));
595
- if (content.trim()) {
596
- for (const line of content.split("\n").slice(0, 18)) lines.push(row(` ${th.fg("text", line)}`));
597
- if (content.split("\n").length > 18) lines.push(row(th.fg("dim", ` … ${content.split("\n").length - 18} more lines`)));
598
- } else {
599
- lines.push(row(th.fg("dim", "No notes yet.")));
600
- lines.push(row(th.fg("dim", "Personal reminders about this project.")));
601
- lines.push(row(th.fg("dim", "Not sent to the model.")));
602
- }
603
- lines.push(row(""));
604
- lines.push(row(th.fg("dim", "Enter edit · Esc / ← back")));
605
-
606
- } else if (this.view === "env-check") {
607
- const items = this.envItems || [];
608
- lines.push(row(th.fg("muted", "Arsenal extension and environment status")));
609
- lines.push(row(""));
610
- for (const item of items) {
611
- const icon = item.status === "ok" ? th.fg("success", "✓") : item.status === "warn" ? th.fg("error", "!") : th.fg("dim", "·");
612
- lines.push(row(` ${icon} ${th.fg(item.status === "warn" ? "error" : "text", item.label)}`));
613
- lines.push(row(` ${th.fg("dim", item.detail)}`));
614
- }
615
- lines.push(row(""));
616
- lines.push(row(th.fg("dim", "Esc / ← back")));
617
-
618
- } else if (this.view === "skills") {
619
- const allSkills = this.skillItems || [];
620
- const activeCount = allSkills.filter((skill) => skill.enabled).length;
621
- const disabledCount = allSkills.length - activeCount;
622
- lines.push(row(th.fg("muted", "Choose a library to browse or manage skills")));
623
- lines.push(row(""));
624
- lines.push(row(` ${marker(0)} ${th.fg("accent", `✨ Enabled skills · ${activeCount}`)}`));
625
- lines.push(row(` ${marker(1)} ${th.fg("muted", `💤 Disabled skills · ${disabledCount}`)}`));
626
- lines.push(row(""));
627
- lines.push(row(th.fg("dim", "Enter / → open · Esc / ← back")));
628
-
629
- } else if (this.view === "skill-list") {
630
- const list = this.skillEntryItems, location = this.skillDirectory || "Library root";
631
- lines.push(row(th.fg("muted", `${this.skillEnabled ? "Enabled" : "Disabled"} · 📂 ${location}`)));
632
- lines.push(row(""));
633
- if (!list.length) lines.push(row(th.fg("dim", "This folder is empty.")));
634
- else for (let i = 0; i < list.length; i++) {
635
- const entry = list[i]!;
636
- if (entry.type === "folder") {
637
- const color = categoryColor(entry.relative), count = skillCount(join(this.skillEnabled ? SKILLS_DIR : DISABLED_SKILLS_DIR, entry.relative));
638
- lines.push(row(` ${marker(i)} ${th.fg(color, `📂 ${entry.name}`)} ${th.fg("dim", `· ${count} skill${count === 1 ? "" : "s"}`)}`));
639
- } else {
640
- const skill = entry.skill, category = categoryOf(skill), custom = displayName("skills", skillKey(skill), skill.name);
641
- lines.push(row(` ${marker(i)} ${th.fg(categoryColor(category), `${this.skillEnabled ? "✨" : "💤"} ${custom}`)}`));
642
- lines.push(row(` ${th.fg("dim", labelsFor("skills", skillKey(skill)).note || skill.description)}`));
643
- }
644
- }
645
- const actionIndex = list.length;
646
- if (this.skillDirectory) lines.push(row(` ${marker(actionIndex)} ${th.fg("warning", `${this.skillEnabled ? "💤 Disable" : "✨ Enable"} this folder`)}`));
647
- lines.push(row(` ${marker(actionIndex + (this.skillDirectory ? 1 : 0))} ${th.fg("accent", "📂 Organize folders…")}`));
648
- lines.push(row(""));
649
- lines.push(row(th.fg("dim", "Enter / → open/action · Esc / ← up")));
650
-
651
- } else if (this.view === "skill-detail") {
652
- const skill = this.selectedSkill;
653
- if (skill) {
654
- const labels = labelsFor("skills", skillKey(skill)), category = categoryOf(skill), color = categoryColor(category);
655
- lines.push(row(`${th.fg(color, skill.enabled ? "✨ Enabled" : "💤 Disabled")} · ${th.fg(color, displayName("skills", skillKey(skill), skill.name))}`));
656
- lines.push(row(th.fg(color, `📂 ${category}`)));
657
- lines.push(row(""));
658
- if (labels.note) { lines.push(row(th.fg("muted", labels.note))); lines.push(row("")); }
659
- lines.push(row(th.fg("dim", `Original: ${skill.name}`)));
660
- lines.push(row(th.fg("dim", skill.description)));
661
- lines.push(row(""));
662
- const actions = skill.enabled
663
- ? ["Use this skill now", "Edit display name", "Edit personal note", "Disable this skill"]
664
- : ["Edit display name", "Edit personal note", "Enable this skill"];
665
- for (const [i, action] of actions.entries()) lines.push(row(` ${marker(i)} ${th.fg(i === this.selected ? "accent" : "text", action)}`));
666
- }
667
- lines.push(row(""));
668
- lines.push(row(th.fg("dim", "↑ ↓ select · Enter / → confirm · Esc / ← back")));
669
-
670
- } else if (this.view === "mcp") {
671
- const list = this.mcpItems || [];
672
- lines.push(row(th.fg("muted", "Cached MCP servers · secrets are never shown")));
673
- lines.push(row(""));
674
- if (!list.length) {
675
- lines.push(row(th.fg("dim", "No cached MCP servers.")));
676
- lines.push(row(th.fg("dim", "Use the MCP plugin to discover and cache servers.")));
677
- } else {
678
- for (let i = 0; i < list.length; i++) {
679
- const server = list[i]!;
680
- const labels = labelsFor("mcp", server.name);
681
- lines.push(row(` ${marker(i)} ${th.fg(i === this.selected ? "accent" : "text", `🔌 ${displayName("mcp", server.name, server.name)}`)}`));
682
- lines.push(row(` ${th.fg("dim", labels.note || `${server.tools.length} cached tool${server.tools.length === 1 ? "" : "s"}`)}`));
683
- }
684
- }
685
- lines.push(row(""));
686
- lines.push(row(th.fg("dim", "Enter / → details · Esc / ← back")));
687
-
688
- } else if (this.view === "mcp-detail") {
689
- const server = this.selectedMcp;
690
- if (server) {
691
- const labels = labelsFor("mcp", server.name);
692
- lines.push(row(th.fg("accent", `🔌 ${displayName("mcp", server.name, server.name)}`)));
693
- if (labels.note) lines.push(row(th.fg("muted", labels.note)));
694
- lines.push(row(th.fg("dim", `Original: ${server.name}`)));
695
- lines.push(row(th.fg("muted", `${server.tools.length} tool${server.tools.length === 1 ? "" : "s"} cached · secrets never shown`)));
696
- lines.push(row(""));
697
- if (server.tools.length) {
698
- const start = Math.floor(this.selected / LIST_PAGE_SIZE) * LIST_PAGE_SIZE;
699
- for (let i = start; i < Math.min(start + LIST_PAGE_SIZE, server.tools.length); i++) {
700
- const tool = server.tools[i]!;
701
- lines.push(row(` ${marker(i)} ${th.fg("text", tool.name)}`));
702
- if (tool.description) lines.push(row(` ${th.fg("dim", tool.description)}`));
703
- }
704
- if (server.tools.length > LIST_PAGE_SIZE) lines.push(row(th.fg("dim", `Page ${Math.floor(start / LIST_PAGE_SIZE) + 1} / ${Math.ceil(server.tools.length / LIST_PAGE_SIZE)} · ↑ ↓`)));
705
- } else { lines.push(row(th.fg("dim", "No cached tools."))); }
706
- lines.push(row(""));
707
- lines.push(row(th.fg("dim", "N edit display name · O edit note · Esc / ← back")));
708
- }
709
-
710
- } else {
711
- // browser view
712
- lines.push(row(th.fg("muted", this.browserPath || "Choose a drive")));
713
- if (this.browserPath) lines.push(row(` ${th.fg("accent", "S")} set this folder as Workspace`));
714
- lines.push(row(""));
715
- if (!this.browserItems.length) { lines.push(row(th.fg("dim", " No sub-folders here."))); }
716
- else {
717
- const start = Math.floor(this.selected / LIST_PAGE_SIZE) * LIST_PAGE_SIZE;
718
- const end = Math.min(start + LIST_PAGE_SIZE, this.browserItems.length);
719
- for (let i = start; i < end; i++) {
720
- const item = this.browserItems[i]!;
721
- lines.push(row(` ${marker(i)} ${this.theme.fg(i === this.selected ? "text" : "muted", `${item.name}/`)}`));
722
- }
723
- if (this.browserItems.length > LIST_PAGE_SIZE) lines.push(row(this.theme.fg("dim", `Page ${Math.floor(start / LIST_PAGE_SIZE) + 1} / ${Math.ceil(this.browserItems.length / LIST_PAGE_SIZE)} · ↑ ↓`)));
724
- }
725
- lines.push(row(""));
726
- lines.push(row(th.fg("dim", this.browserPath ? "Enter / → folder · S select · Esc / ← up" : "Enter / → drive · Esc / ← back")));
727
- }
728
-
729
- lines.push(th.fg("borderAccent", `╰${"─".repeat(inner)}╯`));
730
- return lines;
731
- }
732
-
733
- invalidate(): void {}
734
- }
735
-
736
- export default function workspaceDrawer(pi: ExtensionAPI) {
737
- let workspace: Workspace | undefined;
738
- const active = (ctx: ExtensionContext): Workspace => workspace || restoredWorkspace(ctx.sessionManager.getBranch(), ctx.cwd);
739
- const restore = (ctx: ExtensionContext) => { workspace = restoredWorkspace(ctx.sessionManager.getBranch(), ctx.cwd); };
740
- pi.on("session_start", async (_event, ctx) => restore(ctx));
741
- pi.on("session_tree", async (_event, ctx) => restore(ctx));
742
- pi.on("before_agent_start", async (event, ctx) => {
743
- const root = active(ctx);
744
- const notes = notesContextEnabled(root.path) ? workspaceNotes(root.path).trim() : "";
745
- const notesSection = notes ? `\n\nWorkspace Notes (personal reminders from the user — read-only context, do not modify):\n${notes}` : "";
746
- return {
747
- systemPrompt: `${event.systemPrompt}\n\nActive Workspace: ${root.path}\nInterpret relative file paths, project files, and project commands as referring to this workspace by default. Use paths under it for native file tools and run project shell commands from it. An explicit user-provided absolute path overrides this default.\n\nDiagram Gallery contract: Do not create or register diagrams unless the user explicitly asks you to generate a diagram, chart, architecture view, flowchart, or node graph. For such a request, create Mermaid flowchart/graph source under <Active Workspace>/.pi/diagrams/<stable-id>.mmd and create or update <Active Workspace>/.pi/diagrams/gallery.json in this exact shape: {"diagrams":[{"id":"stable-id","title":"Human title","file":"stable-id.mmd","type":"mermaid","createdAt":"ISO-8601 timestamp","summary":"short description"}]}. The TUI Gallery only displays manifest entries and previews .mmd Mermaid sources; never infer or auto-register existing files.${notesSection}\n`,
748
- };
749
- });
750
- const open = async (ctx: ExtensionCommandContext): Promise<void> => {
751
- if (ctx.mode !== "tui") return;
752
- const current = active(ctx);
753
- const result = await ctx.ui.custom<Result>(
754
- (tui, theme, _keybindings, done) => new WorkspaceDrawer(ctx, current, configuredWorkspaces(ctx.cwd), theme, done, tui, Boolean(translationBridge()), hasChoicesBridge()),
755
- { overlay: true, overlayOptions: { anchor: "right-center", width: 54, maxHeight: "100%", margin: { top: 1, right: 1, bottom: 1 } } },
756
- );
757
- if (!result) return;
758
- if (result.type === "workspace") { workspace = result.workspace; pi.appendEntry(STATE_TYPE, workspace); ctx.ui.notify(`Workspace: ${workspace.name}`, "info"); }
759
- else if (result.type === "sessions") await openSessionLibrary(pi, ctx);
760
- else if (result.type === "search-sessions") await searchAndOpenSession(pi, ctx);
761
- else if (result.type === "translation") {
762
- const bridge = translationBridge();
763
- if (bridge) await bridge.open(ctx);
764
- else ctx.ui.notify("Install pi-translation-studio to enable Translation Studio.", "info");
765
- }
766
- else if (result.type === "diagram-starter") {
767
- ctx.ui.setEditorText(DIAGRAM_STARTER);
768
- ctx.ui.notify("Prompt placed in editor — add details and submit when ready.", "info");
769
- }
770
- else if (result.type === "edit-notes") {
771
- const existing = workspaceNotes(result.workspacePath);
772
- const next = await ctx.ui.editor("Workspace Notes", existing);
773
- if (next !== undefined) {
774
- saveWorkspaceNotes(result.workspacePath, next.trim() ? `${next.trim()}\n` : "");
775
- ctx.ui.notify(next.trim() ? "Notes saved." : "Notes cleared.", "info");
776
- }
777
- }
778
- else if (result.type === "clean-sessions") {
779
- const currentPath = ctx.sessionManager.getSessionFile();
780
- const all = await listSessions();
781
- const nonCurrent = all.filter((s) => s.path !== currentPath);
782
- if (!nonCurrent.length) { ctx.ui.notify("No other sessions to clean up.", "info"); return; }
783
- const strategy = await ctx.ui.select(
784
- `Clean up sessions (${nonCurrent.length} available, current is protected)`,
785
- ["Keep newest 10, delete the rest", "Keep newest 20, delete the rest", "Delete sessions older than 7 days", "Delete sessions older than 30 days", "Cancel"],
786
- );
787
- if (!strategy || strategy === "Cancel") return;
788
- const now = Date.now();
789
- const toDelete = strategy.startsWith("Keep newest")
790
- ? nonCurrent.slice(Number(strategy.includes("10") ? 10 : 20))
791
- : nonCurrent.filter((s) => (now - s.modified.getTime()) > (strategy.includes("7") ? 7 : 30) * 86400000);
792
- if (!toDelete.length) { ctx.ui.notify("No sessions match the criteria.", "info"); return; }
793
- const preview = toDelete.slice(0, 5).map((s) => `• ${sessionTitle(s)} (${relativeTime(s.modified)})`).join("\n");
794
- const more = toDelete.length > 5 ? `\n… and ${toDelete.length - 5} more` : "";
795
- const confirmed = await ctx.ui.confirm(`Delete ${toDelete.length} session${toDelete.length === 1 ? "" : "s"}?`, `${preview}${more}\n\nThis cannot be undone.`);
796
- if (!confirmed) return;
797
- let deleted = 0;
798
- for (const s of toDelete) { try { const { rmSync } = await import("node:fs"); rmSync(s.path); deleted++; } catch { /* Skip undeletable sessions. */ } }
799
- ctx.ui.notify(`Deleted ${deleted} session${deleted === 1 ? "" : "s"}.`, "info");
800
- }
801
- else if (result.type === "toggle-notes-context") {
802
- const enabled = notesContextEnabled(current.path);
803
- const next = !enabled;
804
- saveNotesContext(current.path, next);
805
- ctx.ui.notify(next ? "📌 Notes will be included in context from the next message." : "Notes removed from context.", "info");
806
- }
807
- else if (result.type === "approval-log") {
808
- const entries = readApprovalLog();
809
- if (!entries.length) { ctx.ui.notify("No approval log entries yet.", "info"); return; }
810
- const today = new Date().toDateString();
811
- const todayEntries = entries.filter((e) => new Date(e.timestamp).toDateString() === today);
812
- const rows = (todayEntries.length ? todayEntries : entries.slice(0, 20)).map((e) => {
813
- const time = new Date(e.timestamp).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
814
- const verdict = e.approved ? (e.approval === "deny" ? "deny" : "allow") : "deny";
815
- return `${time} ${verdict.padEnd(5)} ${e.operation} (${e.tool})`;
816
- });
817
- const header = todayEntries.length ? `Today's approvals (${todayEntries.length})` : `Recent approvals (${rows.length})`;
818
- await ctx.ui.select(header + "\n\nTime Verdict Operation (tool)\n" + rows.join("\n"), ["Close"]);
819
- }
820
- else if (result.type === "organize-skills") { await organizeSkillFolders(ctx); await open(ctx); }
821
- else if (result.type === "use-skill") {
822
- ctx.ui.setEditorText(`/skill:${result.canonicalName} `);
823
- ctx.ui.notify("Skill command is ready in the editor. Add details, then submit.", "info");
824
- }
825
- else if (result.type === "toggle-skill-folder") {
826
- const action = result.enabled ? "Disable" : "Enable";
827
- const approved = await ctx.ui.confirm(`${action} skill folder?`, `${action} every skill in "${result.relative}"? Nothing is deleted; the complete skill folders move to the other library.`);
828
- if (approved) {
829
- try { const count = moveSkillFolder(result.enabled, result.relative); ctx.ui.notify(`${action}d ${count} skill${count === 1 ? "" : "s"}. Run /reload to apply discovery changes.`, "info"); }
830
- catch (error) { ctx.ui.notify(error instanceof Error ? error.message : "Could not move skill folder.", "error"); }
831
- }
832
- await open(ctx);
833
- }
834
- else if (result.type === "confirm-skill-toggle") {
835
- const skill = result.skill;
836
- const action = skill.enabled ? "Disable" : "Enable";
837
- const approved = await ctx.ui.confirm(`${action} skill?`, `${action} "${skill.name}"? The skill folder moves to the ${skill.enabled ? "disabled" : "active"} library. Nothing is deleted. Run /reload to apply changes.`);
838
- if (approved) {
839
- try {
840
- moveSkill(skill, skill.enabled ? DISABLED_SKILLS_DIR : SKILLS_DIR, skillKey(skill));
841
- ctx.ui.notify(`${action}d "${skill.name}". Run /reload to apply discovery changes.`, "info");
842
- } catch (error) { ctx.ui.notify(error instanceof Error ? error.message : "Could not move skill.", "error"); }
843
- }
844
- }
845
- else if (result.type === "edit-label") {
846
- const existing = labelsFor(result.kind, result.key)[result.field] || "";
847
- const next = result.field === "displayName"
848
- ? await ctx.ui.input(`Personal ${result.kind === "mcp" ? "MCP" : "skill"} display name`, existing || result.fallback)
849
- : await ctx.ui.editor(`Personal note for ${result.fallback}`, existing);
850
- if (next !== undefined) {
851
- const data = resourceMetadata(), collection = data[result.kind] || {};
852
- const labels = { ...collection[result.key], [result.field]: next.trim() };
853
- if (!labels.displayName && !labels.note) delete collection[result.key]; else collection[result.key] = labels;
854
- data[result.kind] = collection;
855
- saveResourceMetadata(data);
856
- ctx.ui.notify("Personal label saved. It is not sent to the model.", "info");
857
- }
858
- }
859
- else if (result.type === "view-diagram") {
860
- const url = await openMermaidViewer(current.path, result.diagram);
861
- ctx.ui.notify(url ? `Opened Mermaid Viewer: ${result.diagram.title}` : "This entry does not have a readable registered .mmd Mermaid source.", url ? "info" : "error");
862
- }
863
- };
864
- pi.registerCommand("workspace", { description: "Open Terra Workspace Drawer", handler: async (_args, ctx) => await open(ctx) });
865
- pi.registerShortcut(Key.alt("w"), { description: "Open Terra Workspace Drawer", handler: async (ctx) => await open(ctx as ExtensionCommandContext) });
866
- }
1
+ import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, writeFileSync } from "node:fs";
2
+ import { createServer, type Server } from "node:http";
3
+ import { basename, dirname, extname, join, parse, relative, resolve, sep } from "node:path";
4
+ import { spawn } from "node:child_process";
5
+ import type { AssistantMessage } from "@earendil-works/pi-ai";
6
+ import type { ExtensionAPI, ExtensionCommandContext, ExtensionContext, SessionEntry, Theme } from "@earendil-works/pi-coding-agent";
7
+ import { openSessionLibrary, listSessions, sessionTitle, relativeTime, manageSession } from "../lib/session-library.ts";
8
+ import { Key, matchesKey, truncateToWidth, visibleWidth, type Focusable } from "@earendil-works/pi-tui";
9
+
10
+ // ─── Constants ────────────────────────────────────────────────────────────────
11
+
12
+ const STATE_TYPE = "terra-workspace-v1";
13
+ const ROOT = process.env.USERPROFILE || process.env.HOME || ".";
14
+ const WORKSPACES_FILE = join(ROOT, ".pi", "agent", "workspaces.json");
15
+ const DIAGRAMS_DIR = join(".pi", "diagrams");
16
+ const DIAGRAMS_MANIFEST = "gallery.json";
17
+ const SKILLS_DIR = join(ROOT, ".agents", "skills");
18
+ const DISABLED_SKILLS_DIR = join(ROOT, ".agents", "disabled-skills");
19
+ const MCP_CACHE_FILE = join(ROOT, ".pi", "agent", "mcp-cache.json");
20
+ const RESOURCE_METADATA_FILE = join(ROOT, ".pi", "agent", "resource-library.json");
21
+ const EXTENSIONS_DIR = join(ROOT, ".pi", "agent", "extensions");
22
+ const NOTES_FILENAME = ".pi/workspace-notes.md";
23
+ const NOTES_CTX_FILE = join(ROOT, ".pi", "agent", "workspace-notes-context.json");
24
+ const APPROVAL_LOG_FILE = join(ROOT, ".pi", "agent", "destructive-operation-guard.jsonl");
25
+ const DIAGRAM_STARTER = "Draw a system architecture diagram for this project.";
26
+ const HIDDEN_NAMES = new Set([".git", "node_modules", ".venv", "__pycache__"]);
27
+ const LIST_PAGE_SIZE = 16;
28
+ const DIAGRAM_PAGE_SIZE = 8;
29
+ const DRAWER_WIDTH = 54;
30
+ const INNER = DRAWER_WIDTH - 2;
31
+
32
+ // ─── Types ────────────────────────────────────────────────────────────────────
33
+
34
+ type Workspace = { name: string; path: string };
35
+ type View =
36
+ | "home" | "projects" | "browser"
37
+ | "usage" | "diagrams" | "notes" | "env-check" | "approval-log"
38
+ | "skills" | "skill-list" | "skill-detail" | "skill-readme"
39
+ | "mcp" | "mcp-detail";
40
+ type FileItem = { name: string; directory: boolean };
41
+ type UsageTotals = { input: number; output: number; cacheRead: number };
42
+ type Diagram = { id: string; title: string; file: string; type?: string; createdAt?: string; summary?: string };
43
+ type Skill = { name: string; description: string; path: string; enabled: boolean };
44
+ type SkillEntry = { type: "folder"; name: string; relative: string } | { type: "skill"; skill: Skill };
45
+ type McpTool = { name: string; description?: string };
46
+ type McpServer = { name: string; tools: McpTool[]; cachedAt?: number };
47
+ type ResourceLabels = { displayName?: string; note?: string };
48
+ type ResourceMetadata = { skills?: Record<string, ResourceLabels>; mcp?: Record<string, ResourceLabels> };
49
+ type TranslationStudioBridge = { version: 1; open(ctx: ExtensionCommandContext): Promise<void> };
50
+ type EnvItem = { label: string; status: "ok" | "warn" | "info"; detail: string };
51
+ type ApprovalEntry = { timestamp: string; operation: string; tool: string; approval: string; approved: boolean };
52
+
53
+ // Home items can be selectable entries or section dividers.
54
+ type HomeEntry =
55
+ | { kind: "section"; label: string }
56
+ | { kind: "item"; label: string; badge?: string; view?: View; result?: Result["type"] };
57
+
58
+ type Result =
59
+ | { type: "close" }
60
+ | { type: "workspace"; workspace: Workspace }
61
+ | { type: "view-diagram"; diagram: Diagram }
62
+ | { type: "diagram-starter" }
63
+ | { type: "sessions" | "translation" | "search-sessions" }
64
+ | { type: "notes-action"; action: "edit" | "toggle-context" }
65
+ | { type: "edit-label"; kind: "skills" | "mcp"; key: string; fallback: string; field: "displayName" | "note" }
66
+ | { type: "use-skill"; canonicalName: string }
67
+ | { type: "organize-skills" }
68
+ | { type: "toggle-skill-folder"; enabled: boolean; relative: string }
69
+ | { type: "confirm-skill-toggle"; skill: Skill };
70
+
71
+ // ─── Bridges ──────────────────────────────────────────────────────────────────
72
+
73
+ const TRANSLATION_BRIDGE_KEY = Symbol.for("pi-translation-studio.bridge.v1");
74
+ const CHOICES_BRIDGE_KEY = Symbol.for("pi-choices.bridge.v1");
75
+ const translationBridge = (): TranslationStudioBridge | undefined => {
76
+ const b = (globalThis as Record<symbol, unknown>)[TRANSLATION_BRIDGE_KEY] as TranslationStudioBridge | undefined;
77
+ return b?.version === 1 ? b : undefined;
78
+ };
79
+ const hasChoicesBridge = (): boolean => !!(globalThis as Record<symbol, unknown>)[CHOICES_BRIDGE_KEY];
80
+
81
+ // ─── Mermaid viewer ───────────────────────────────────────────────────────────
82
+
83
+ type MermaidViewer = { server: Server; source: string; title: string; url: string };
84
+ let mermaidViewer: MermaidViewer | undefined;
85
+
86
+ function viewerHtml(title: string, source: string): string {
87
+ return `<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${title.replace(/[<&]/g, "")}</title><style>body{margin:0;background:#1a1b26;color:#c0caf5;font:16px system-ui,sans-serif}header{padding:14px 20px;border-bottom:1px solid #414868;font-weight:600}main{padding:24px;overflow:auto;min-height:calc(100vh - 68px)}.mermaid{background:#24283b;border:1px solid #414868;border-radius:10px;padding:24px;display:inline-block;min-width:calc(100% - 50px);white-space:pre-wrap}.error{color:#f7768e;white-space:pre-wrap;margin-bottom:16px}</style><header>${title.replace(/[<&]/g, "")}</header><main><div class="error" hidden></div><pre class="mermaid"></pre></main><script type="module">const source=${JSON.stringify(source)};const target=document.querySelector('.mermaid');const errorBox=document.querySelector('.error');target.textContent=source;async function loadMermaid(){let lastError;for(const url of ['https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.esm.min.mjs','https://unpkg.com/mermaid@11/dist/mermaid.esm.min.mjs']){try{return (await import(url)).default}catch(error){lastError=error}}throw lastError}try{const mermaid=await loadMermaid();mermaid.initialize({startOnLoad:false,theme:'dark'});await mermaid.run({nodes:[target]})}catch(error){errorBox.hidden=false;errorBox.textContent='Mermaid renderer could not be loaded. Showing source instead.\\n'+error}</script></html>`;
88
+ }
89
+
90
+ async function openMermaidViewer(root: string, diagram: Diagram): Promise<string | undefined> {
91
+ const source = registeredMermaidSource(root, diagram);
92
+ if (!source) return undefined;
93
+ if (!mermaidViewer) {
94
+ const server = createServer((req, res) => {
95
+ if (!mermaidViewer || req.url !== "/") { res.writeHead(404).end(); return; }
96
+ res.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store" });
97
+ res.end(viewerHtml(mermaidViewer.title, mermaidViewer.source));
98
+ });
99
+ await new Promise<void>((ok, fail) => { server.once("error", fail); server.listen(0, "127.0.0.1", () => { server.off("error", fail); ok(); }); });
100
+ const addr = server.address();
101
+ if (!addr || typeof addr === "string") { server.close(); return undefined; }
102
+ mermaidViewer = { server, source, title: diagram.title, url: `http://127.0.0.1:${addr.port}/` };
103
+ } else { mermaidViewer.source = source; mermaidViewer.title = diagram.title; }
104
+ spawn("cmd.exe", ["/c", "start", "", mermaidViewer.url], { detached: true, stdio: "ignore" }).unref();
105
+ return mermaidViewer.url;
106
+ }
107
+
108
+ // ─── Data helpers ─────────────────────────────────────────────────────────────
109
+
110
+ function configuredWorkspaces(fallback: string): Workspace[] {
111
+ try {
112
+ const data = JSON.parse(readFileSync(WORKSPACES_FILE, "utf8")) as { workspaces?: Workspace[] };
113
+ const found = (data.workspaces || []).filter((w) => typeof w.name === "string" && typeof w.path === "string" && existsSync(w.path));
114
+ if (found.length) return found;
115
+ } catch { /* fallback below */ }
116
+ return [{ name: basename(fallback) || fallback, path: fallback }];
117
+ }
118
+
119
+ function restoredWorkspace(entries: readonly SessionEntry[], fallback: string): Workspace {
120
+ for (let i = entries.length - 1; i >= 0; i--) {
121
+ const e = entries[i];
122
+ if (e?.type !== "custom" || e.customType !== STATE_TYPE) continue;
123
+ const w = e.data as Workspace | undefined;
124
+ if (w && typeof w.name === "string" && typeof w.path === "string" && existsSync(w.path)) return w;
125
+ }
126
+ return configuredWorkspaces(fallback)[0]!;
127
+ }
128
+
129
+ function browserEntries(path: string): FileItem[] {
130
+ try {
131
+ return readdirSync(path, { withFileTypes: true })
132
+ .filter((e) => !HIDDEN_NAMES.has(e.name) && e.isDirectory())
133
+ .sort((a, b) => a.name.localeCompare(b.name))
134
+ .slice(0, 120)
135
+ .map((e) => ({ name: e.name, directory: true }));
136
+ } catch { return []; }
137
+ }
138
+
139
+ function sessionUsage(ctx: ExtensionContext): UsageTotals {
140
+ const t: UsageTotals = { input: 0, output: 0, cacheRead: 0 };
141
+ for (const e of ctx.sessionManager.getBranch()) {
142
+ if (e.type !== "message" || e.message.role !== "assistant") continue;
143
+ const u = (e.message as AssistantMessage).usage;
144
+ if (!u) continue;
145
+ t.input += u.input || 0; t.output += u.output || 0; t.cacheRead += u.cacheRead || 0;
146
+ }
147
+ return t;
148
+ }
149
+
150
+ const fmtTokens = (n: number) => n < 1000 ? String(n) : `${(n / 1000).toFixed(1)}k`;
151
+
152
+ function diagrams(root: string): Diagram[] {
153
+ try {
154
+ const d = JSON.parse(readFileSync(join(root, DIAGRAMS_DIR, DIAGRAMS_MANIFEST), "utf8")) as { diagrams?: Diagram[] };
155
+ return (d.diagrams || []).filter((x) => typeof x.id === "string" && typeof x.title === "string" && typeof x.file === "string");
156
+ } catch { return []; }
157
+ }
158
+
159
+ function resourceMetadata(): ResourceMetadata {
160
+ try { return JSON.parse(readFileSync(RESOURCE_METADATA_FILE, "utf8")) as ResourceMetadata; } catch { return {}; }
161
+ }
162
+
163
+ function saveResourceMetadata(data: ResourceMetadata): void {
164
+ mkdirSync(dirname(RESOURCE_METADATA_FILE), { recursive: true });
165
+ writeFileSync(RESOURCE_METADATA_FILE, `${JSON.stringify(data, null, 2)}\n`, "utf8");
166
+ }
167
+
168
+ function workspaceNotes(workspacePath: string): string {
169
+ try { return readFileSync(join(workspacePath, NOTES_FILENAME), "utf8"); } catch { return ""; }
170
+ }
171
+
172
+ function saveWorkspaceNotes(workspacePath: string, text: string): void {
173
+ const f = join(workspacePath, NOTES_FILENAME);
174
+ mkdirSync(dirname(f), { recursive: true });
175
+ writeFileSync(f, text, "utf8");
176
+ }
177
+
178
+ function notesContextEnabled(workspacePath: string): boolean {
179
+ try { return (JSON.parse(readFileSync(NOTES_CTX_FILE, "utf8")) as Record<string, boolean>)[workspacePath] === true; }
180
+ catch { return false; }
181
+ }
182
+
183
+ function saveNotesContext(workspacePath: string, enabled: boolean): void {
184
+ let data: Record<string, boolean> = {};
185
+ try { data = JSON.parse(readFileSync(NOTES_CTX_FILE, "utf8")) as Record<string, boolean>; } catch { /* first write */ }
186
+ if (enabled) data[workspacePath] = true; else delete data[workspacePath];
187
+ mkdirSync(dirname(NOTES_CTX_FILE), { recursive: true });
188
+ writeFileSync(NOTES_CTX_FILE, `${JSON.stringify(data, null, 2)}\n`, "utf8");
189
+ }
190
+
191
+ function readApprovalLog(): ApprovalEntry[] {
192
+ try {
193
+ return readFileSync(APPROVAL_LOG_FILE, "utf8").trim().split("\n").filter(Boolean)
194
+ .map((l) => JSON.parse(l) as ApprovalEntry).reverse();
195
+ } catch { return []; }
196
+ }
197
+
198
+ function buildEnvItems(ctx: ExtensionCommandContext, hasTranslation: boolean, hasChoices: boolean): EnvItem[] {
199
+ const items: EnvItem[] = [];
200
+ const extFiles: string[] = [];
201
+ try { for (const e of readdirSync(EXTENSIONS_DIR, { withFileTypes: true })) { if (e.isFile() && (e.name.endsWith(".ts") || e.name.endsWith(".js")) && !e.name.endsWith(".disabled")) extFiles.push(e.name.replace(/\.[^.]+$/, "")); } } catch { /* ok */ }
202
+ items.push({ label: "Local extensions", status: extFiles.length > 0 ? "ok" : "info", detail: extFiles.length > 0 ? extFiles.join(", ") : "None found" });
203
+ items.push({ label: "pi-choices", status: hasChoices ? "ok" : "warn", detail: hasChoices ? "Available — Task Plan protection active" : "Not loaded — install pi-arsenal" });
204
+ items.push({ label: "Translation Studio", status: hasTranslation ? "ok" : "info", detail: hasTranslation ? "Bridge active" : "Not installed (optional)" });
205
+ items.push({ label: "Workspace path", status: existsSync(ctx.cwd) ? "ok" : "warn", detail: existsSync(ctx.cwd) ? ctx.cwd : `Missing: ${ctx.cwd}` });
206
+ try {
207
+ const raw = JSON.parse(readFileSync(MCP_CACHE_FILE, "utf8")) as { servers?: Record<string, { cachedAt?: number }> };
208
+ const servers = Object.keys(raw.servers || {});
209
+ const ts = Object.values(raw.servers || {}).map((s) => s.cachedAt || 0).filter(Boolean);
210
+ const latest = ts.length ? new Date(Math.max(...ts)) : null;
211
+ items.push({ label: "MCP cache", status: servers.length ? "ok" : "info", detail: servers.length ? `${servers.length} server${servers.length === 1 ? "" : "s"} · ${latest ? latest.toLocaleDateString() : "unknown"}` : "No cached servers" });
212
+ } catch { items.push({ label: "MCP cache", status: "info", detail: "No cache file" }); }
213
+ try {
214
+ let count = 0;
215
+ const walk = (dir: string) => { for (const e of readdirSync(dir, { withFileTypes: true })) { if (!e.isDirectory()) continue; const p = join(dir, e.name); if (existsSync(join(p, "SKILL.md"))) count++; else walk(p); } };
216
+ walk(SKILLS_DIR);
217
+ items.push({ label: "Active skills", status: count > 0 ? "ok" : "info", detail: `${count} skill${count === 1 ? "" : "s"}` });
218
+ } catch { items.push({ label: "Active skills", status: "info", detail: "Skills dir not found" }); }
219
+ const model = ctx.model?.id;
220
+ items.push({ label: "Model", status: model ? "ok" : "warn", detail: model || "Unknown" });
221
+ return items;
222
+ }
223
+
224
+ // ─── Skill helpers ────────────────────────────────────────────────────────────
225
+
226
+ function isInside(parent: string, child: string): boolean {
227
+ return child === parent || child.startsWith(parent.endsWith(sep) ? parent : `${parent}${sep}`);
228
+ }
229
+
230
+ function registeredMermaidSource(root: string, diagram: Diagram): string | undefined {
231
+ const base = resolve(root, DIAGRAMS_DIR);
232
+ const file = resolve(base, diagram.file);
233
+ if (diagram.type && diagram.type !== "mermaid") return undefined;
234
+ if (extname(file).toLowerCase() !== ".mmd" || !isInside(base, file) || !existsSync(file)) return undefined;
235
+ try { return readFileSync(file, "utf8"); } catch { return undefined; }
236
+ }
237
+
238
+ function skillRoot(skill: Skill): string { return skill.enabled ? SKILLS_DIR : DISABLED_SKILLS_DIR; }
239
+ function skillKey(skill: Skill): string { return relative(skillRoot(skill), skill.path).replaceAll("\\", "/"); }
240
+ function categoryOf(skill: Skill): string { const d = dirname(skillKey(skill)); return d === "." ? "Uncategorized" : d; }
241
+
242
+ const CATEGORY_COLORS = ["accent", "success", "warning", "error", "mdLink", "mdCode", "syntaxFunction", "syntaxType", "syntaxString"] as const;
243
+ function categoryColor(cat: string): typeof CATEGORY_COLORS[number] {
244
+ let h = 0; for (const c of cat) h = (h * 31 + c.charCodeAt(0)) >>> 0;
245
+ return CATEGORY_COLORS[h % CATEGORY_COLORS.length]!;
246
+ }
247
+
248
+ function validCategory(v: string): string | undefined {
249
+ const c = v.trim().replaceAll("\\", "/").replace(/^\/+|\/+$/g, "");
250
+ return c && !c.split("/").some((p) => !p || p === "." || p === "..") ? c : undefined;
251
+ }
252
+
253
+ function skillCategories(): string[] {
254
+ const collect = (root: string): string[] => {
255
+ const found: string[] = [];
256
+ const walk = (dir: string) => { for (const e of readdirSync(dir, { withFileTypes: true })) { if (!e.isDirectory()) continue; const p = join(dir, e.name); if (!existsSync(join(p, "SKILL.md"))) { found.push(relative(root, p).replaceAll("\\", "/")); walk(p); } } };
257
+ try { walk(root); } catch { /* ok */ }
258
+ return found;
259
+ };
260
+ return [...new Set([...collect(SKILLS_DIR), ...collect(DISABLED_SKILLS_DIR)])].sort();
261
+ }
262
+
263
+ function labelsFor(kind: "skills" | "mcp", key: string): ResourceLabels { return resourceMetadata()[kind]?.[key] || {}; }
264
+ function displayName(kind: "skills" | "mcp", key: string, fallback: string): string { return labelsFor(kind, key).displayName?.trim() || fallback; }
265
+
266
+ function skillCount(folder: string): number {
267
+ try {
268
+ let n = 0;
269
+ const walk = (d: string) => { for (const e of readdirSync(d, { withFileTypes: true })) { if (!e.isDirectory()) continue; const p = join(d, e.name); if (existsSync(join(p, "SKILL.md"))) n++; else walk(p); } };
270
+ walk(folder); return n;
271
+ } catch { return 0; }
272
+ }
273
+
274
+ function skillEntries(enabled: boolean, directory = ""): SkillEntry[] {
275
+ const root = enabled ? SKILLS_DIR : DISABLED_SKILLS_DIR, folder = resolve(root, directory);
276
+ if (!isInside(root, folder)) return [];
277
+ try {
278
+ return readdirSync(folder, { withFileTypes: true }).filter((e) => e.isDirectory()).flatMap((e): SkillEntry[] => {
279
+ const p = join(folder, e.name), file = join(p, "SKILL.md"), rel = relative(root, p).replaceAll("\\", "/");
280
+ if (!existsSync(file)) return skillCount(p) ? [{ type: "folder", name: e.name, relative: rel }] : [];
281
+ const src = readFileSync(file, "utf8");
282
+ return [{ type: "skill", skill: { name: /^name:\s*(.+)$/m.exec(src)?.[1]?.trim() || e.name, description: /^description:\s*(.+)$/m.exec(src)?.[1]?.trim() || "No description declared.", path: p, enabled } }];
283
+ }).sort((a, b) => Number(b.type === "folder") - Number(a.type === "folder") || (a.type === "folder" ? a.name : a.skill.name).localeCompare(b.type === "folder" ? b.name : b.skill.name));
284
+ } catch { return []; }
285
+ }
286
+
287
+ function moveSkill(skill: Skill, targetRoot: string, targetRelative: string): Skill {
288
+ const target = join(targetRoot, targetRelative);
289
+ if (existsSync(target)) throw new Error("A skill already exists at the destination.");
290
+ mkdirSync(dirname(target), { recursive: true });
291
+ renameSync(skill.path, target);
292
+ const data = resourceMetadata(), oldKey = skillKey(skill), next: Skill = { ...skill, path: target, enabled: targetRoot === SKILLS_DIR }, newKey = skillKey(next);
293
+ if (oldKey !== newKey && data.skills?.[oldKey]) { data.skills[newKey] = data.skills[oldKey]; delete data.skills[oldKey]; saveResourceMetadata(data); }
294
+ return next;
295
+ }
296
+
297
+ function moveSkillFolder(enabled: boolean, folderRelative: string): number {
298
+ const src = enabled ? SKILLS_DIR : DISABLED_SKILLS_DIR, dst = enabled ? DISABLED_SKILLS_DIR : SKILLS_DIR;
299
+ const source = resolve(src, folderRelative), target = resolve(dst, folderRelative);
300
+ if (!isInside(src, source) || !isInside(dst, target) || !existsSync(source)) throw new Error("Invalid skill folder.");
301
+ const list = skills().filter((s) => s.enabled === enabled && (skillKey(s) === folderRelative || skillKey(s).startsWith(`${folderRelative}/`)));
302
+ if (!list.length) throw new Error("This folder has no skills to move.");
303
+ for (const s of list) moveSkill(s, dst, skillKey(s));
304
+ return list.length;
305
+ }
306
+
307
+ function skills(): Skill[] {
308
+ const read = (root: string, enabled: boolean): Skill[] => {
309
+ const found: Skill[] = [];
310
+ const walk = (dir: string) => {
311
+ try {
312
+ for (const e of readdirSync(dir, { withFileTypes: true })) {
313
+ if (!e.isDirectory()) continue;
314
+ const p = join(dir, e.name), f = join(p, "SKILL.md");
315
+ if (existsSync(f)) { const src = readFileSync(f, "utf8"); found.push({ name: /^name:\s*(.+)$/m.exec(src)?.[1]?.trim() || e.name, description: /^description:\s*(.+)$/m.exec(src)?.[1]?.trim() || "No description declared.", path: p, enabled }); }
316
+ else walk(p);
317
+ }
318
+ } catch { /* ok */ }
319
+ };
320
+ walk(root); return found;
321
+ };
322
+ return [...read(SKILLS_DIR, true), ...read(DISABLED_SKILLS_DIR, false)].sort((a, b) => Number(b.enabled) - Number(a.enabled) || categoryOf(a).localeCompare(categoryOf(b)) || a.name.localeCompare(b.name));
323
+ }
324
+
325
+ function cachedMcpServers(): McpServer[] {
326
+ try {
327
+ const d = JSON.parse(readFileSync(MCP_CACHE_FILE, "utf8")) as { servers?: Record<string, { tools?: McpTool[]; cachedAt?: number }> };
328
+ return Object.entries(d.servers || {}).map(([name, s]) => ({ name, tools: (s.tools || []).filter((t) => typeof t.name === "string").map(({ name: n, description }) => ({ name: n, description: typeof description === "string" ? description : undefined })), cachedAt: s.cachedAt }));
329
+ } catch { return []; }
330
+ }
331
+
332
+ function driveRoots(): string[] {
333
+ const roots: string[] = [];
334
+ for (let c = 67; c <= 90; c++) { const r = `${String.fromCharCode(c)}:\\`; if (existsSync(r)) roots.push(r); }
335
+ return roots;
336
+ }
337
+
338
+ async function organizeSkillFolders(ctx: ExtensionCommandContext): Promise<void> {
339
+ while (true) {
340
+ const action = await ctx.ui.select("Organize Skill Folders", ["Create shared category folder", "Move a skill", "Back"]);
341
+ if (!action || action === "Back") return;
342
+ if (action === "Create shared category folder") {
343
+ const v = await ctx.ui.input("New shared category", "");
344
+ const cat = v ? validCategory(v) : undefined;
345
+ if (!cat) { ctx.ui.notify("Enter a relative folder name without . or ..", "warning"); continue; }
346
+ mkdirSync(join(SKILLS_DIR, cat), { recursive: true }); mkdirSync(join(DISABLED_SKILLS_DIR, cat), { recursive: true });
347
+ ctx.ui.notify(`Created: ${cat}`, "info"); continue;
348
+ }
349
+ const lib = await ctx.ui.select("Choose library", ["✨ Enabled skills", "💤 Disabled skills", "Cancel"]);
350
+ if (!lib || lib === "Cancel") continue;
351
+ const enabled = lib.startsWith("✨"), list = skills().filter((s) => s.enabled === enabled);
352
+ if (!list.length) { ctx.ui.notify("No skills in this library.", "info"); continue; }
353
+ const choices = list.map((s) => `${displayName("skills", skillKey(s), s.name)} · ${categoryOf(s)}`);
354
+ const sel = await ctx.ui.select("Move a skill", [...choices, "Cancel"]);
355
+ if (!sel || sel === "Cancel") continue;
356
+ const skill = list[choices.indexOf(sel)]; if (!skill) continue;
357
+ const categories = skillCategories();
358
+ const dest = await ctx.ui.select("Move to category", ["Library root (Uncategorized)", ...categories, "Create new category…", "Cancel"]);
359
+ if (!dest || dest === "Cancel") continue;
360
+ let cat = dest === "Library root (Uncategorized)" ? "" : dest;
361
+ if (dest === "Create new category…") {
362
+ const v = await ctx.ui.input("New shared category", ""); cat = v ? validCategory(v) || "" : "";
363
+ if (!cat) { ctx.ui.notify("Enter a relative folder name without . or ..", "warning"); continue; }
364
+ mkdirSync(join(SKILLS_DIR, cat), { recursive: true }); mkdirSync(join(DISABLED_SKILLS_DIR, cat), { recursive: true });
365
+ }
366
+ try { moveSkill(skill, skillRoot(skill), cat ? join(cat, basename(skill.path)) : basename(skill.path)); ctx.ui.notify("Skill moved. Run /reload to apply.", "info"); }
367
+ catch (e) { ctx.ui.notify(e instanceof Error ? e.message : "Could not move skill.", "error"); }
368
+ }
369
+ }
370
+
371
+ async function searchAndOpenSession(pi: ExtensionAPI, ctx: ExtensionCommandContext): Promise<void> {
372
+ if (ctx.mode !== "tui") return;
373
+ const query = await ctx.ui.input("Search sessions", "");
374
+ if (!query?.trim()) return;
375
+ const term = query.trim().toLowerCase();
376
+ const all = await listSessions();
377
+ const matched = all.filter((s) => sessionTitle(s).toLowerCase().includes(term) || s.firstMessage.toLowerCase().includes(term));
378
+ if (!matched.length) { ctx.ui.notify(`No sessions matching "${query}".`, "info"); return; }
379
+ const currentPath = ctx.sessionManager.getSessionFile();
380
+ const opts = matched.map((s) => `${sessionTitle(s)} — ${relativeTime(s.modified)} · ${s.messageCount} messages${s.path === currentPath ? " ● current" : ""}`);
381
+ const choice = await ctx.ui.select(`${matched.length} result${matched.length === 1 ? "" : "s"} for "${query}"`, [...opts, "Cancel"]);
382
+ if (!choice || choice === "Cancel") return;
383
+ const session = matched[opts.indexOf(choice)];
384
+ if (!session) return;
385
+ // Hand off to manageSession for full detail view (rename / delete / reload).
386
+ await manageSession(pi, ctx, session, currentPath);
387
+ }
388
+
389
+ // ─── Render helpers ───────────────────────────────────────────────────────────
390
+
391
+ /** Single row padded to INNER width, with optional accent highlight for selected rows. */
392
+ function makeRow(theme: Theme) {
393
+ return (text: string, selected = false): string => {
394
+ const pad = " ".repeat(Math.max(0, INNER - visibleWidth(text)));
395
+ const inner = selected
396
+ ? theme.fg("accent", theme.bold(text)) + pad
397
+ : text + pad;
398
+ return theme.fg("border", "│") + inner + theme.fg("border", "│");
399
+ };
400
+ }
401
+
402
+ /** Section divider line, e.g. ── Workspace ──────────────── */
403
+ function makeDivider(theme: Theme) {
404
+ return (label: string): string => {
405
+ const prefix = "── ";
406
+ const suffix = " " + "─".repeat(Math.max(0, INNER - 4 - visibleWidth(label)));
407
+ return theme.fg("border", "│") + theme.fg("dim", prefix + label + suffix) + theme.fg("border", "│");
408
+ };
409
+ }
410
+
411
+ /** Horizontal bar graph using block characters. e.g. ████████░░ 8.0k / 32k */
412
+ function tokenBar(used: number, total: number, width: number): string {
413
+ if (!total) return "—";
414
+ const ratio = Math.min(1, used / total);
415
+ const filled = Math.round(ratio * width);
416
+ const bar = "█".repeat(filled) + "░".repeat(width - filled);
417
+ return `${bar} ${fmtTokens(used)} / ${fmtTokens(total)}`;
418
+ }
419
+
420
+ /** Breadcrumb: show last two path components, prefixed with … */
421
+ function breadcrumb(path: string): string {
422
+ const parts = path.replace(/[/\\]+$/, "").split(/[/\\]/);
423
+ if (parts.length <= 2) return path;
424
+ return `… › ${parts.at(-2)} › ${parts.at(-1)}`;
425
+ }
426
+
427
+ // ─── WorkspaceDrawer class ────────────────────────────────────────────────────
428
+
429
+ class WorkspaceDrawer implements Focusable {
430
+ readonly width = DRAWER_WIDTH;
431
+ focused = false;
432
+
433
+ // View state
434
+ private view: View = "home";
435
+ private selected = 0;
436
+
437
+ // Per-view data (loaded once on enter, never re-read during render)
438
+ private homeEntries: HomeEntry[] = [];
439
+ private homeSelectables: number[] = []; // indices of selectable HomeEntry rows
440
+ private browserPath: string | undefined;
441
+ private browserItems: FileItem[] = [];
442
+ private diagramItems: Diagram[] = [];
443
+ private skillItems: Skill[] = [];
444
+ private skillEntryItems: SkillEntry[] = [];
445
+ private skillDirectory = "";
446
+ private skillEnabled = true;
447
+ private selectedSkill: Skill | undefined;
448
+ private skillReadmeLines: string[] = []; // SKILL.md lines for preview
449
+ private mcpItems: McpServer[] = [];
450
+ private selectedMcp: McpServer | undefined;
451
+ private envItems: EnvItem[] = [];
452
+ private approvalEntries: ApprovalEntry[] = [];
453
+ private approvalPage = 0;
454
+
455
+ // Cached data loaded at Drawer open (not per-frame)
456
+ private readonly notesContent: string;
457
+ private notesInCtx: boolean;
458
+ private readonly resourceMeta: ResourceMetadata;
459
+
460
+ constructor(
461
+ private readonly ctx: ExtensionCommandContext,
462
+ private readonly workspace: Workspace,
463
+ private readonly workspaces: Workspace[],
464
+ private readonly theme: Theme,
465
+ private readonly done: (result: Result) => void,
466
+ private readonly tui: { requestRender(): void },
467
+ private readonly hasTranslationStudio: boolean,
468
+ private readonly hasPiChoices: boolean,
469
+ ) {
470
+ // Load all disk state once at construction; render() never touches disk.
471
+ this.notesContent = workspaceNotes(workspace.path);
472
+ this.notesInCtx = notesContextEnabled(workspace.path);
473
+ this.resourceMeta = resourceMetadata();
474
+ this.buildHomeEntries();
475
+ this.open("home");
476
+ }
477
+
478
+ // ── Home entry builder ───────────────────────────────────────────────────
479
+
480
+ private buildHomeEntries(): void {
481
+ const hasNotes = this.notesContent.trim().length > 0;
482
+ const inCtx = this.notesInCtx;
483
+ const entries: HomeEntry[] = [
484
+ { kind: "section", label: "Workspace" },
485
+ { kind: "item", label: "📁 Projects", view: "projects" },
486
+ { kind: "item", label: "🗺 Diagram Gallery", view: "diagrams" },
487
+ { kind: "item", label: `📌 Notes${hasNotes ? " ·" : ""}`, badge: inCtx ? "→ctx" : undefined, view: "notes" },
488
+ { kind: "item", label: "📊 Session Tokens", view: "usage" },
489
+ { kind: "item", label: "🖥️ Browse computer…", view: "browser" },
490
+ { kind: "section", label: "Sessions" },
491
+ { kind: "item", label: "🕘 Session Library", result: "sessions" },
492
+ { kind: "item", label: "🔎 Search sessions…", result: "search-sessions" },
493
+ { kind: "item", label: "🛡 Approval Log", view: "approval-log" },
494
+ { kind: "section", label: "Resources" },
495
+ { kind: "item", label: "✨ Skill Library", view: "skills" },
496
+ { kind: "item", label: "🔌 MCP Servers", view: "mcp" },
497
+ ...(this.hasTranslationStudio ? [{ kind: "item" as const, label: "🌐 Translation Studio", result: "translation" as Result["type"] }] : []),
498
+ { kind: "item", label: "🔍 Environment Check", view: "env-check" },
499
+ ];
500
+ this.homeEntries = entries;
501
+ this.homeSelectables = entries.flatMap((e, i) => e.kind === "item" ? [i] : []);
502
+ }
503
+
504
+ // ── View open ────────────────────────────────────────────────────────────
505
+
506
+ private open(view: View): void {
507
+ this.view = view;
508
+ this.selected = 0;
509
+ if (view === "browser") this.openBrowser(this.browserPath);
510
+ if (view === "diagrams") this.diagramItems = diagrams(this.workspace.path);
511
+ if (view === "skills") this.skillItems = skills();
512
+ if (view === "skill-list") this.skillEntryItems = skillEntries(this.skillEnabled, this.skillDirectory);
513
+ if (view === "mcp") this.mcpItems = cachedMcpServers();
514
+ if (view === "env-check") this.envItems = buildEnvItems(this.ctx, this.hasTranslationStudio, this.hasPiChoices);
515
+ if (view === "approval-log") {
516
+ this.approvalEntries = readApprovalLog();
517
+ this.approvalPage = 0;
518
+ }
519
+ if (view === "skill-readme" && this.selectedSkill) {
520
+ try {
521
+ const raw = readFileSync(join(this.selectedSkill.path, "SKILL.md"), "utf8");
522
+ this.skillReadmeLines = raw.split("\n");
523
+ } catch { this.skillReadmeLines = ["(SKILL.md could not be read)"]; }
524
+ }
525
+ }
526
+
527
+ private openBrowser(path: string | undefined): void {
528
+ this.browserPath = path;
529
+ this.selected = 0;
530
+ this.browserItems = path ? browserEntries(path) : driveRoots().map((r) => ({ name: r, directory: true }));
531
+ }
532
+
533
+ private backBrowser(): void {
534
+ if (!this.browserPath) { this.open("projects"); return; }
535
+ const parent = dirname(this.browserPath);
536
+ this.openBrowser(parent === this.browserPath ? undefined : parent);
537
+ }
538
+
539
+ // ── Input ────────────────────────────────────────────────────────────────
540
+
541
+ handleInput(data: string): void {
542
+ if (matchesKey(data, Key.escape) || matchesKey(data, Key.left)) {
543
+ if (this.view === "home") { this.done({ type: "close" }); return; }
544
+ if (this.view === "browser") { this.backBrowser(); return; }
545
+ if (this.view === "skill-readme") { this.open("skill-detail"); return; }
546
+ if (this.view === "skill-list") {
547
+ if (this.skillDirectory) {
548
+ this.skillDirectory = dirname(this.skillDirectory);
549
+ if (this.skillDirectory === ".") this.skillDirectory = "";
550
+ this.open("skill-list");
551
+ } else this.open("skills");
552
+ return;
553
+ }
554
+ if (this.view === "skill-detail") { this.open("skill-list"); return; }
555
+ if (this.view === "mcp-detail") { this.open("mcp"); return; }
556
+ this.open("home"); return;
557
+ }
558
+
559
+ // Context-specific shortcuts (shown in footer)
560
+ if (matchesKey(data, "n") && this.view === "mcp-detail" && this.selectedMcp) {
561
+ this.done({ type: "edit-label", kind: "mcp", key: this.selectedMcp.name, fallback: this.selectedMcp.name, field: "displayName" }); return;
562
+ }
563
+ if (matchesKey(data, "o") && this.view === "mcp-detail" && this.selectedMcp) {
564
+ this.done({ type: "edit-label", kind: "mcp", key: this.selectedMcp.name, fallback: this.selectedMcp.name, field: "note" }); return;
565
+ }
566
+ if (matchesKey(data, "s") && this.view === "browser" && this.browserPath) {
567
+ this.done({ type: "workspace", workspace: { name: basename(this.browserPath) || this.browserPath, path: this.browserPath } }); return;
568
+ }
569
+ // approval-log: [ / ] to page
570
+ if (this.view === "approval-log") {
571
+ const pageSize = 12;
572
+ const maxPage = Math.max(0, Math.ceil(this.approvalEntries.length / pageSize) - 1);
573
+ if ((matchesKey(data, Key.right) || matchesKey(data, "]")) && this.approvalPage < maxPage) { this.approvalPage++; return; }
574
+ if ((matchesKey(data, Key.left) || matchesKey(data, "[")) && this.approvalPage > 0) { this.approvalPage--; return; }
575
+ }
576
+ // skill-readme: Esc / ← back to detail
577
+ if (this.view === "skill-readme") { this.open("skill-detail"); return; }
578
+
579
+ if (matchesKey(data, Key.up) || matchesKey(data, "k")) { this.moveSelection(-1); return; }
580
+ if (matchesKey(data, Key.down) || matchesKey(data, "j")) { this.moveSelection(1); return; }
581
+ if (!matchesKey(data, Key.enter) && !matchesKey(data, Key.right)) return;
582
+ this.activate();
583
+ }
584
+
585
+ private moveSelection(delta: number): void {
586
+ if (this.view === "home") {
587
+ // Skip over section dividers.
588
+ const idx = this.homeSelectables.indexOf(this.selected);
589
+ const next = this.homeSelectables[Math.max(0, Math.min(this.homeSelectables.length - 1, idx + delta))];
590
+ if (next !== undefined) this.selected = next;
591
+ return;
592
+ }
593
+ const max = this.selectionMax();
594
+ this.selected = Math.max(0, Math.min(max, this.selected + delta));
595
+ }
596
+
597
+ private selectionMax(): number {
598
+ switch (this.view) {
599
+ case "projects": return this.workspaces.length;
600
+ case "browser": return Math.max(0, this.browserItems.length - 1);
601
+ case "diagrams": return Math.max(0, (this.diagramItems.length > 0 ? this.diagramItems.length - 1 : 0));
602
+ case "skills": return 1;
603
+ case "skill-list": return this.skillEntryItems.length + (this.skillDirectory ? 1 : 0);
604
+ case "skill-detail": return this.selectedSkill?.enabled ? 4 : 3;
605
+ case "mcp": return Math.max(0, this.mcpItems.length - 1);
606
+ case "mcp-detail": return 0; // tools are non-interactive; N/O via letter keys
607
+ case "notes": return 1; // 0 = edit, 1 = toggle context
608
+ case "approval-log": return 1; // prev/next page arrows
609
+ default: return 0;
610
+ }
611
+ }
612
+
613
+ private activate(): void {
614
+ if (this.view === "mcp-detail" || this.view === "usage" || this.view === "env-check" || this.view === "approval-log" || this.view === "skill-readme") return;
615
+
616
+ // Notes: two explicit actions instead of direct-to-editor
617
+ if (this.view === "notes") {
618
+ if (this.selected === 0) this.done({ type: "notes-action", action: "edit" });
619
+ else this.done({ type: "notes-action", action: "toggle-context" });
620
+ return;
621
+ }
622
+
623
+ if (this.view === "diagrams") {
624
+ if (!this.diagramItems.length && this.selected === 0) { this.done({ type: "diagram-starter" }); return; }
625
+ const d = this.diagramItems[this.selected]; if (d) this.done({ type: "view-diagram", diagram: d }); return;
626
+ }
627
+ if (this.view === "home") {
628
+ const entry = this.homeEntries[this.selected];
629
+ if (!entry || entry.kind !== "item") return;
630
+ if (entry.result) { this.done({ type: entry.result } as Result); return; }
631
+ if (entry.view) { this.open(entry.view); return; }
632
+ }
633
+ if (this.view === "skills") { this.skillEnabled = this.selected === 0; this.skillDirectory = ""; this.open("skill-list"); return; }
634
+ if (this.view === "skill-list") {
635
+ const entry = this.skillEntryItems[this.selected];
636
+ if (entry?.type === "skill") { this.selectedSkill = entry.skill; this.open("skill-detail"); }
637
+ else if (entry?.type === "folder") { this.skillDirectory = entry.relative; this.open("skill-list"); }
638
+ else if (this.skillDirectory && this.selected === this.skillEntryItems.length) this.done({ type: "toggle-skill-folder", enabled: this.skillEnabled, relative: this.skillDirectory });
639
+ else this.done({ type: "organize-skills" });
640
+ return;
641
+ }
642
+ if (this.view === "skill-detail") {
643
+ if (!this.selectedSkill) return;
644
+ const off = this.selectedSkill.enabled ? 1 : 0;
645
+ if (this.selected === 0) this.open("skill-readme"); // first action is always "Read SKILL.md"
646
+ else if (this.selectedSkill.enabled && this.selected === 1) this.done({ type: "use-skill", canonicalName: this.selectedSkill.name });
647
+ else if (this.selected === off + 1) this.done({ type: "edit-label", kind: "skills", key: skillKey(this.selectedSkill), fallback: this.selectedSkill.name, field: "displayName" });
648
+ else if (this.selected === off + 2) this.done({ type: "edit-label", kind: "skills", key: skillKey(this.selectedSkill), fallback: this.selectedSkill.name, field: "note" });
649
+ else this.done({ type: "confirm-skill-toggle", skill: this.selectedSkill });
650
+ return;
651
+ }
652
+ if (this.view === "mcp") { const s = this.mcpItems[this.selected]; if (s) { this.selectedMcp = s; this.open("mcp-detail"); } return; }
653
+ if (this.view === "projects") {
654
+ if (this.selected === this.workspaces.length) { this.open("browser"); return; }
655
+ const w = this.workspaces[this.selected]; if (w) this.done({ type: "workspace", workspace: w }); return;
656
+ }
657
+ if (this.view === "browser") {
658
+ const item = this.browserItems[this.selected];
659
+ if (item) this.openBrowser(this.browserPath ? join(this.browserPath, item.name) : item.name);
660
+ }
661
+ }
662
+
663
+ // ── Render ───────────────────────────────────────────────────────────────
664
+
665
+ render(_width: number): string[] {
666
+ const th = this.theme;
667
+ const row = makeRow(th);
668
+ const divider = makeDivider(th);
669
+ const sel = (i: number) => i === this.selected;
670
+
671
+ const viewTitle: Record<View, string> = {
672
+ home: "Pi Arsenal",
673
+ projects: "Projects",
674
+ browser: "Browse",
675
+ usage: "Session Tokens",
676
+ diagrams: "Diagram Gallery",
677
+ skills: "Skill Library",
678
+ "skill-list": this.skillEnabled ? "Enabled Skills" : "Disabled Skills",
679
+ "skill-detail": "Skill Details",
680
+ "skill-readme": "SKILL.md",
681
+ mcp: "MCP Servers",
682
+ "mcp-detail": "MCP Details",
683
+ notes: "Workspace Notes",
684
+ "env-check": "Environment",
685
+ "approval-log": "Approval Log",
686
+ };
687
+
688
+ const title = viewTitle[this.view];
689
+ const lines: string[] = [
690
+ th.fg("borderAccent", `╭─ ${th.bold(title)} ${"─".repeat(Math.max(0, INNER - visibleWidth(title) - 3))}╮`),
691
+ ];
692
+
693
+ // ── Home ──────────────────────────────────────────────────────────────
694
+ if (this.view === "home") {
695
+ const inCtx = this.notesInCtx;
696
+ lines.push(row(""));
697
+ lines.push(row(` ${th.fg("accent", "◈")} ${th.bold(this.workspace.name)}${inCtx ? ` ${th.fg("success", "→ctx")}` : ""}`));
698
+ lines.push(row(` ${th.fg("dim", this.workspace.path)}`));
699
+ lines.push(row(""));
700
+ for (let i = 0; i < this.homeEntries.length; i++) {
701
+ const entry = this.homeEntries[i]!;
702
+ if (entry.kind === "section") {
703
+ lines.push(divider(entry.label));
704
+ } else {
705
+ const isSelected = i === this.selected;
706
+ const badge = entry.badge ? ` ${th.fg("success", entry.badge)}` : "";
707
+ const label = entry.label + (isSelected ? "" : badge);
708
+ lines.push(row(` ${label}${badge && !isSelected ? "" : (entry.badge && isSelected ? ` ${entry.badge}` : "")}`, isSelected));
709
+ }
710
+ }
711
+ lines.push(row(""));
712
+ lines.push(row(th.fg("dim", "↑ ↓ Enter / → Esc close")));
713
+
714
+ // ── Projects ─────────────────────────────────────────────────────────
715
+ } else if (this.view === "projects") {
716
+ lines.push(row(th.fg("muted", " Saved project roots")));
717
+ lines.push(row(""));
718
+ for (let i = 0; i < this.workspaces.length; i++) {
719
+ const w = this.workspaces[i]!;
720
+ lines.push(row(` ${th.fg(sel(i) ? "accent" : "text", w.name)}`, sel(i)));
721
+ lines.push(row(` ${th.fg("dim", w.path)}`));
722
+ }
723
+ lines.push(row(` ${th.fg("accent", "Browse computer…")}`, sel(this.workspaces.length)));
724
+ lines.push(row(""));
725
+ lines.push(row(th.fg("dim", "Enter / → apply · Esc / ← back")));
726
+
727
+ // ── Browser ───────────────────────────────────────────────────────────
728
+ } else if (this.view === "browser") {
729
+ const crumb = this.browserPath ? breadcrumb(this.browserPath) : "Choose a drive";
730
+ lines.push(row(` ${th.fg("muted", crumb)}`));
731
+ if (this.browserPath) lines.push(row(` ${th.fg("accent", "S")} ${th.fg("dim", "set as workspace")}`));
732
+ lines.push(row(""));
733
+ if (!this.browserItems.length) {
734
+ lines.push(row(th.fg("dim", " No sub-folders here.")));
735
+ } else {
736
+ const start = Math.floor(this.selected / LIST_PAGE_SIZE) * LIST_PAGE_SIZE;
737
+ for (let i = start; i < Math.min(start + LIST_PAGE_SIZE, this.browserItems.length); i++) {
738
+ lines.push(row(` ${this.browserItems[i]!.name}/`, sel(i)));
739
+ }
740
+ if (this.browserItems.length > LIST_PAGE_SIZE) lines.push(row(th.fg("dim", ` Page ${Math.floor(start / LIST_PAGE_SIZE) + 1} / ${Math.ceil(this.browserItems.length / LIST_PAGE_SIZE)}`)));
741
+ }
742
+ lines.push(row(""));
743
+ lines.push(row(th.fg("dim", this.browserPath ? "Enter / → open · S select · Esc / ← up" : "Enter / → drive · Esc / ← back")));
744
+
745
+ // ── Session Tokens ────────────────────────────────────────────────────
746
+ } else if (this.view === "usage") {
747
+ const t = sessionUsage(this.ctx), ctx = this.ctx.getContextUsage();
748
+ const total = t.input + t.output + t.cacheRead;
749
+ const ctxUsed = ctx?.tokens ?? 0, ctxMax = ctx?.contextWindow ?? 0;
750
+ lines.push(row(""));
751
+ lines.push(row(` ${th.fg("muted", this.ctx.model?.id || "—")}`));
752
+ lines.push(row(""));
753
+ lines.push(row(` Input ${th.fg("accent", fmtTokens(t.input))}`));
754
+ lines.push(row(` Output ${th.fg("accent", fmtTokens(t.output))}`));
755
+ lines.push(row(` Cache read ${th.fg("accent", fmtTokens(t.cacheRead))}`));
756
+ lines.push(row(` Total ${th.fg("accent", fmtTokens(total))}`));
757
+ lines.push(row(""));
758
+ if (ctxMax) {
759
+ const barWidth = Math.max(10, INNER - 22);
760
+ const bar = tokenBar(ctxUsed, ctxMax, barWidth);
761
+ const pct = `${((ctxUsed / ctxMax) * 100).toFixed(0)}%`;
762
+ const color = ctxUsed / ctxMax > 0.85 ? "error" : ctxUsed / ctxMax > 0.6 ? "warning" : "success";
763
+ lines.push(row(` Context ${th.fg(color, pct)}`));
764
+ lines.push(row(` ${th.fg(color, bar)}`));
765
+ } else {
766
+ lines.push(row(` Context ${th.fg("dim", "—")}`));
767
+ }
768
+ lines.push(row(""));
769
+ lines.push(row(th.fg("dim", "Session only · Esc / ← back")));
770
+
771
+ // ── Diagram Gallery ───────────────────────────────────────────────────
772
+ } else if (this.view === "diagrams") {
773
+ lines.push(row(th.fg("muted", " Registered Mermaid diagrams")));
774
+ lines.push(row(""));
775
+ if (this.diagramItems.length) {
776
+ const start = Math.floor(this.selected / DIAGRAM_PAGE_SIZE) * DIAGRAM_PAGE_SIZE;
777
+ for (let i = start; i < Math.min(start + DIAGRAM_PAGE_SIZE, this.diagramItems.length); i++) {
778
+ const d = this.diagramItems[i]!;
779
+ lines.push(row(` ${th.fg(sel(i) ? "accent" : "text", d.title)}`, sel(i)));
780
+ lines.push(row(` ${th.fg("dim", `${d.type || "mermaid"}${d.createdAt ? ` · ${d.createdAt}` : ""}`)}`));
781
+ }
782
+ if (this.diagramItems.length > DIAGRAM_PAGE_SIZE) lines.push(row(th.fg("dim", ` Page ${Math.floor(start / DIAGRAM_PAGE_SIZE) + 1} / ${Math.ceil(this.diagramItems.length / DIAGRAM_PAGE_SIZE)}`)));
783
+ lines.push(row(""));
784
+ lines.push(row(th.fg("dim", "Enter / → open in browser · Esc / ← back")));
785
+ } else {
786
+ lines.push(row(th.fg("dim", " No diagrams yet.")));
787
+ lines.push(row(""));
788
+ lines.push(row(th.fg("muted", " Try asking Pi:")));
789
+ lines.push(row(` ${th.fg("accent", `"${DIAGRAM_STARTER}"`)}`));
790
+ lines.push(row(""));
791
+ lines.push(row(th.fg("dim", "Enter sends prompt · Esc / ← back")));
792
+ }
793
+
794
+ // ── Workspace Notes ───────────────────────────────────────────────────
795
+ } else if (this.view === "notes") {
796
+ const inCtx = this.notesInCtx;
797
+ lines.push(row(` ${th.fg("muted", this.workspace.name)} ${inCtx ? th.fg("success", "→ included in context") : th.fg("dim", "not in context")}`));
798
+ lines.push(row(""));
799
+ if (this.notesContent.trim()) {
800
+ for (const line of this.notesContent.split("\n").slice(0, 14)) lines.push(row(` ${th.fg("text", line)}`));
801
+ const extra = this.notesContent.split("\n").length - 14;
802
+ if (extra > 0) lines.push(row(th.fg("dim", ` … ${extra} more lines`)));
803
+ } else {
804
+ lines.push(row(th.fg("dim", " No notes yet.")));
805
+ lines.push(row(th.fg("dim", " Personal reminders — not sent to model by default.")));
806
+ }
807
+ lines.push(row(""));
808
+ lines.push(row(` ${th.fg("text", "✏️ Edit notes")}`, sel(0)));
809
+ lines.push(row(` ${th.fg(inCtx ? "success" : "muted", inCtx ? "■ Remove from context" : "□ Include in context")}`, sel(1)));
810
+ lines.push(row(""));
811
+ lines.push(row(th.fg("dim", "↑ ↓ Enter confirm · Esc / ← back")));
812
+
813
+ // ── Environment Check ─────────────────────────────────────────────────
814
+ } else if (this.view === "env-check") {
815
+ lines.push(row(th.fg("muted", " Extension and environment status")));
816
+ lines.push(row(""));
817
+ for (const item of this.envItems) {
818
+ const icon = item.status === "ok" ? th.fg("success", "✓") : item.status === "warn" ? th.fg("error", "!") : th.fg("dim", "·");
819
+ lines.push(row(` ${icon} ${th.fg(item.status === "warn" ? "error" : "text", item.label)}`));
820
+ lines.push(row(` ${th.fg("dim", item.detail)}`));
821
+ }
822
+ lines.push(row(""));
823
+ lines.push(row(th.fg("dim", "Esc / ← back")));
824
+
825
+ // ── Skill Library ─────────────────────────────────────────────────────
826
+ } else if (this.view === "skills") {
827
+ const active = this.skillItems.filter((s) => s.enabled).length;
828
+ const disabled = this.skillItems.length - active;
829
+ lines.push(row(th.fg("muted", " Choose a library")));
830
+ lines.push(row(""));
831
+ lines.push(row(` ✨ Enabled skills · ${th.fg("accent", String(active))}`, sel(0)));
832
+ lines.push(row(` 💤 Disabled skills · ${th.fg("muted", String(disabled))}`, sel(1)));
833
+ lines.push(row(""));
834
+ lines.push(row(th.fg("dim", "Enter / → open · Esc / ← back")));
835
+
836
+ // ── Skill List ────────────────────────────────────────────────────────
837
+ } else if (this.view === "skill-list") {
838
+ const loc = this.skillDirectory || "Library root";
839
+ lines.push(row(` ${th.fg("muted", `${this.skillEnabled ? "✨" : "💤"} ${loc}`)}`));
840
+ lines.push(row(""));
841
+ if (!this.skillEntryItems.length) lines.push(row(th.fg("dim", " This folder is empty.")));
842
+ else {
843
+ for (let i = 0; i < this.skillEntryItems.length; i++) {
844
+ const entry = this.skillEntryItems[i]!;
845
+ if (entry.type === "folder") {
846
+ const color = categoryColor(entry.relative);
847
+ const count = skillCount(join(this.skillEnabled ? SKILLS_DIR : DISABLED_SKILLS_DIR, entry.relative));
848
+ lines.push(row(` ${th.fg(color, `📂 ${entry.name}`)} ${th.fg("dim", `· ${count}`)}`, sel(i)));
849
+ } else {
850
+ const s = entry.skill, cat = categoryOf(s), name = displayName("skills", skillKey(s), s.name);
851
+ const note = this.resourceMeta.skills?.[skillKey(s)]?.note || s.description;
852
+ lines.push(row(` ${th.fg(categoryColor(cat), `${this.skillEnabled ? "✨" : "💤"} ${name}`)}`, sel(i)));
853
+ lines.push(row(` ${th.fg("dim", note)}`));
854
+ }
855
+ }
856
+ }
857
+ const actionBase = this.skillEntryItems.length;
858
+ if (this.skillDirectory) lines.push(row(` ${th.fg("warning", `${this.skillEnabled ? "💤 Disable" : "✨ Enable"} this folder`)}`, sel(actionBase)));
859
+ lines.push(row(` ${th.fg("accent", "📂 Organize folders…")}`, sel(actionBase + (this.skillDirectory ? 1 : 0))));
860
+ lines.push(row(""));
861
+ lines.push(row(th.fg("dim", "Enter / → open · Esc / ← up")));
862
+
863
+ // ── Skill Detail ──────────────────────────────────────────────────────
864
+ } else if (this.view === "skill-detail") {
865
+ const s = this.selectedSkill;
866
+ if (s) {
867
+ const labels = this.resourceMeta.skills?.[skillKey(s)] || {}, cat = categoryOf(s), color = categoryColor(cat);
868
+ lines.push(row(` ${th.fg(color, s.enabled ? "✨ Enabled" : "💤 Disabled")} · ${th.fg(color, displayName("skills", skillKey(s), s.name))}`));
869
+ lines.push(row(` ${th.fg(color, `📂 ${cat}`)}`));
870
+ lines.push(row(""));
871
+ if (labels.note) { lines.push(row(` ${th.fg("muted", labels.note)}`)); lines.push(row("")); }
872
+ lines.push(row(` ${th.fg("dim", s.description)}`));
873
+ lines.push(row(""));
874
+ const actions = s.enabled
875
+ ? ["Read SKILL.md", "Use this skill now", "Edit display name", "Edit personal note", "Disable this skill"]
876
+ : ["Read SKILL.md", "Edit display name", "Edit personal note", "Enable this skill"];
877
+ for (const [i, action] of actions.entries()) lines.push(row(` ${th.fg(sel(i) ? "accent" : "text", action)}`, sel(i)));
878
+ }
879
+ lines.push(row(""));
880
+ lines.push(row(th.fg("dim", "↑ ↓ Enter / → confirm · Esc / ← back")));
881
+
882
+ // ── MCP List ──────────────────────────────────────────────────────────
883
+ } else if (this.view === "mcp") {
884
+ lines.push(row(th.fg("muted", " Cached MCP servers · no secrets shown")));
885
+ lines.push(row(""));
886
+ if (!this.mcpItems.length) {
887
+ lines.push(row(th.fg("dim", " No cached MCP servers.")));
888
+ } else {
889
+ for (let i = 0; i < this.mcpItems.length; i++) {
890
+ const server = this.mcpItems[i]!;
891
+ const labels = this.resourceMeta.mcp?.[server.name] || {};
892
+ const name = labels.displayName?.trim() || server.name;
893
+ lines.push(row(` 🔌 ${th.fg(sel(i) ? "accent" : "text", name)}`, sel(i)));
894
+ lines.push(row(` ${th.fg("dim", labels.note || `${server.tools.length} tool${server.tools.length === 1 ? "" : "s"}`)}`));
895
+ }
896
+ }
897
+ lines.push(row(""));
898
+ lines.push(row(th.fg("dim", "Enter / → details · Esc / ← back")));
899
+
900
+ // ── MCP Detail ────────────────────────────────────────────────────────
901
+ } else if (this.view === "mcp-detail") {
902
+ const server = this.selectedMcp;
903
+ if (server) {
904
+ const labels = this.resourceMeta.mcp?.[server.name] || {};
905
+ const name = labels.displayName?.trim() || server.name;
906
+ lines.push(row(` ${th.fg("accent", `🔌 ${name}`)}`));
907
+ if (labels.note) lines.push(row(` ${th.fg("muted", labels.note)}`));
908
+ lines.push(row(` ${th.fg("dim", `Original: ${server.name}`)}`));
909
+ lines.push(row(` ${th.fg("muted", `${server.tools.length} tool${server.tools.length === 1 ? "" : "s"} · no secrets shown`)}`));
910
+ lines.push(row(""));
911
+ if (server.tools.length) {
912
+ const start = Math.floor(this.selected / LIST_PAGE_SIZE) * LIST_PAGE_SIZE;
913
+ for (let i = start; i < Math.min(start + LIST_PAGE_SIZE, server.tools.length); i++) {
914
+ const tool = server.tools[i]!;
915
+ lines.push(row(` ${th.fg(sel(i) ? "accent" : "text", tool.name)}`, sel(i)));
916
+ if (tool.description) lines.push(row(` ${th.fg("dim", tool.description)}`));
917
+ }
918
+ if (server.tools.length > LIST_PAGE_SIZE) lines.push(row(th.fg("dim", ` Page ${Math.floor(start / LIST_PAGE_SIZE) + 1} / ${Math.ceil(server.tools.length / LIST_PAGE_SIZE)}`)));
919
+ } else lines.push(row(th.fg("dim", " No cached tools.")));
920
+ lines.push(row(""));
921
+ lines.push(row(th.fg("dim", "N display name · O note · Esc / ← back")));
922
+ }
923
+
924
+ // ── Skill README ─────────────────────────────────────────────────────
925
+ } else if (this.view === "skill-readme") {
926
+ const name = this.selectedSkill ? displayName("skills", skillKey(this.selectedSkill), this.selectedSkill.name) : "";
927
+ lines.push(row(` ${th.fg("muted", name)}`));
928
+ lines.push(row(""));
929
+ const maxLines = 24;
930
+ const readmeLines = this.skillReadmeLines;
931
+ const start = Math.floor(this.selected / maxLines) * maxLines;
932
+ for (let i = start; i < Math.min(start + maxLines, readmeLines.length); i++) {
933
+ // Strip markdown formatting for clean display
934
+ const raw = readmeLines[i]!.replace(/^#{1,6}\s+/, "").replace(/\*\*([^*]+)\*\*/g, "$1").replace(/`([^`]+)`/g, "$1");
935
+ const isHeader = /^#{1,6}\s/.test(readmeLines[i]!);
936
+ lines.push(row(` ${isHeader ? th.fg("accent", raw) : th.fg("text", raw)}`));
937
+ }
938
+ if (readmeLines.length > maxLines) {
939
+ const page = Math.floor(start / maxLines) + 1;
940
+ const total = Math.ceil(readmeLines.length / maxLines);
941
+ lines.push(row(th.fg("dim", ` Page ${page} / ${total}`)));
942
+ }
943
+ lines.push(row(""));
944
+ lines.push(row(th.fg("dim", "↑ ↓ scroll · Esc / ← back to detail")));
945
+
946
+ // ── Approval Log ─────────────────────────────────────────────────────
947
+ } else if (this.view === "approval-log") {
948
+ const entries = this.approvalEntries;
949
+ const pageSize = 12;
950
+ const today = new Date().toDateString();
951
+ const todayCount = entries.filter((e) => new Date(e.timestamp).toDateString() === today).length;
952
+ lines.push(row(` ${th.fg("muted", `${entries.length} total entries${todayCount ? ` · ${todayCount} today` : ""}`)}`));
953
+ lines.push(row(""));
954
+ if (!entries.length) {
955
+ lines.push(row(th.fg("dim", " No approval events yet.")));
956
+ lines.push(row(th.fg("dim", " Events are recorded when pi-op-approval intercepts a tool call.")));
957
+ } else {
958
+ const start = this.approvalPage * pageSize;
959
+ for (let i = start; i < Math.min(start + pageSize, entries.length); i++) {
960
+ const e = entries[i]!;
961
+ const time = new Date(e.timestamp).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
962
+ const isToday = new Date(e.timestamp).toDateString() === today;
963
+ const verdict = e.approved && e.approval !== "deny";
964
+ const verdictStr = verdict ? "allow" : "deny ";
965
+ const verdictColor = verdict ? "success" : "error";
966
+ const timeStr = isToday ? th.fg("text", time) : th.fg("dim", time);
967
+ lines.push(row(` ${timeStr} ${th.fg(verdictColor, verdictStr)} ${th.fg("text", e.operation)} ${th.fg("dim", `(${e.tool})`)}`));
968
+ }
969
+ const totalPages = Math.ceil(entries.length / pageSize);
970
+ if (totalPages > 1) {
971
+ lines.push(row(""));
972
+ const prev = this.approvalPage > 0 ? th.fg("accent", "[ prev") : th.fg("dim", "[ prev");
973
+ const next = this.approvalPage < totalPages - 1 ? th.fg("accent", "next ]") : th.fg("dim", "next ]");
974
+ lines.push(row(` ${prev} Page ${this.approvalPage + 1} / ${totalPages} ${next}`));
975
+ }
976
+ }
977
+ lines.push(row(""));
978
+ lines.push(row(th.fg("dim", "[ / ] page · Esc / ← back")));
979
+ }
980
+
981
+ lines.push(th.fg("borderAccent", `╰${"─".repeat(INNER)}╯`));
982
+ return lines;
983
+ }
984
+
985
+ invalidate(): void {}
986
+ }
987
+
988
+ // ─── Extension entry point ────────────────────────────────────────────────────
989
+
990
+ export default function workspaceDrawer(pi: ExtensionAPI) {
991
+ let workspace: Workspace | undefined;
992
+ const active = (ctx: ExtensionContext): Workspace => workspace || restoredWorkspace(ctx.sessionManager.getBranch(), ctx.cwd);
993
+ const restore = (ctx: ExtensionContext) => { workspace = restoredWorkspace(ctx.sessionManager.getBranch(), ctx.cwd); };
994
+
995
+ pi.on("session_start", async (_e, ctx) => restore(ctx));
996
+ pi.on("session_tree", async (_e, ctx) => restore(ctx));
997
+
998
+ pi.on("before_agent_start", async (event, ctx) => {
999
+ const root = active(ctx);
1000
+ const notes = notesContextEnabled(root.path) ? workspaceNotes(root.path).trim() : "";
1001
+ const notesSection = notes ? `\n\nWorkspace Notes (personal reminders from the user — read-only context, do not modify):\n${notes}` : "";
1002
+ return {
1003
+ systemPrompt: `${event.systemPrompt}\n\nActive Workspace: ${root.path}\nInterpret relative file paths, project files, and project commands as referring to this workspace by default. Use paths under it for native file tools and run project shell commands from it. An explicit user-provided absolute path overrides this default.\n\nDiagram Gallery contract: Do not create or register diagrams unless the user explicitly asks you to generate a diagram, chart, architecture view, flowchart, or node graph. For such a request, create Mermaid flowchart/graph source under <Active Workspace>/.pi/diagrams/<stable-id>.mmd and create or update <Active Workspace>/.pi/diagrams/gallery.json in this exact shape: {"diagrams":[{"id":"stable-id","title":"Human title","file":"stable-id.mmd","type":"mermaid","createdAt":"ISO-8601 timestamp","summary":"short description"}]}. The TUI Gallery only displays manifest entries and previews .mmd Mermaid sources; never infer or auto-register existing files.${notesSection}\n`,
1004
+ };
1005
+ });
1006
+
1007
+ const open = async (ctx: ExtensionCommandContext): Promise<void> => {
1008
+ if (ctx.mode !== "tui") return;
1009
+ const current = active(ctx);
1010
+
1011
+ const result = await ctx.ui.custom<Result>(
1012
+ (tui, theme, _kb, done) => new WorkspaceDrawer(ctx, current, configuredWorkspaces(ctx.cwd), theme, done, tui, Boolean(translationBridge()), hasChoicesBridge()),
1013
+ { overlay: true, overlayOptions: { anchor: "right-center", width: DRAWER_WIDTH + 2, maxHeight: "100%", margin: { top: 1, right: 1, bottom: 1 } } },
1014
+ );
1015
+ if (!result) return;
1016
+
1017
+ switch (result.type) {
1018
+ case "workspace":
1019
+ workspace = result.workspace;
1020
+ pi.appendEntry(STATE_TYPE, workspace);
1021
+ ctx.ui.notify(`Workspace: ${workspace.name}`, "info");
1022
+ break;
1023
+
1024
+ case "sessions":
1025
+ await openSessionLibrary(pi, ctx);
1026
+ break;
1027
+
1028
+ case "search-sessions":
1029
+ await searchAndOpenSession(pi, ctx);
1030
+ break;
1031
+
1032
+ case "translation": {
1033
+ const bridge = translationBridge();
1034
+ if (bridge) await bridge.open(ctx);
1035
+ else ctx.ui.notify("Install pi-translation-studio to enable Translation Studio.", "info");
1036
+ break;
1037
+ }
1038
+
1039
+ case "diagram-starter":
1040
+ ctx.ui.setEditorText(DIAGRAM_STARTER);
1041
+ ctx.ui.notify("Prompt placed in editor — add details and submit when ready.", "info");
1042
+ break;
1043
+
1044
+ case "notes-action": {
1045
+ if (result.action === "edit") {
1046
+ const existing = workspaceNotes(current.path);
1047
+ const next = await ctx.ui.editor("Workspace Notes", existing);
1048
+ if (next !== undefined) {
1049
+ saveWorkspaceNotes(current.path, next.trim() ? `${next.trim()}\n` : "");
1050
+ ctx.ui.notify(next.trim() ? "Notes saved." : "Notes cleared.", "info");
1051
+ }
1052
+ } else {
1053
+ const enabled = notesContextEnabled(current.path);
1054
+ saveNotesContext(current.path, !enabled);
1055
+ ctx.ui.notify(!enabled ? "📌 Notes will be included in context from the next message." : "Notes removed from context.", "info");
1056
+ }
1057
+ break;
1058
+ }
1059
+
1060
+ case "organize-skills":
1061
+ await organizeSkillFolders(ctx);
1062
+ await open(ctx);
1063
+ break;
1064
+
1065
+ case "use-skill":
1066
+ ctx.ui.setEditorText(`/skill:${result.canonicalName} `);
1067
+ ctx.ui.notify("Skill command ready — add details and submit.", "info");
1068
+ break;
1069
+
1070
+ case "toggle-skill-folder": {
1071
+ const action = result.enabled ? "Disable" : "Enable";
1072
+ const approved = await ctx.ui.confirm(`${action} skill folder?`, `${action} every skill in "${result.relative}"? Nothing is deleted; folders move to the other library.`);
1073
+ if (approved) {
1074
+ try { const count = moveSkillFolder(result.enabled, result.relative); ctx.ui.notify(`${action}d ${count} skill${count === 1 ? "" : "s"}. Run /reload to apply.`, "info"); }
1075
+ catch (e) { ctx.ui.notify(e instanceof Error ? e.message : "Could not move folder.", "error"); }
1076
+ }
1077
+ await open(ctx);
1078
+ break;
1079
+ }
1080
+
1081
+ case "confirm-skill-toggle": {
1082
+ const { skill } = result;
1083
+ const action = skill.enabled ? "Disable" : "Enable";
1084
+ const approved = await ctx.ui.confirm(`${action} skill?`, `${action} "${skill.name}"? The folder moves to the ${skill.enabled ? "disabled" : "active"} library. Nothing is deleted. Run /reload to apply.`);
1085
+ if (approved) {
1086
+ try {
1087
+ moveSkill(skill, skill.enabled ? DISABLED_SKILLS_DIR : SKILLS_DIR, skillKey(skill));
1088
+ ctx.ui.notify(`${action}d "${skill.name}". Run /reload to apply.`, "info");
1089
+ } catch (e) { ctx.ui.notify(e instanceof Error ? e.message : "Could not move skill.", "error"); }
1090
+ }
1091
+ break;
1092
+ }
1093
+
1094
+ case "edit-label": {
1095
+ const meta = resourceMetadata();
1096
+ const existing = (meta[result.kind] ?? {})[result.key]?.[result.field] ?? "";
1097
+ const next = result.field === "displayName"
1098
+ ? await ctx.ui.input(`${result.kind === "mcp" ? "MCP" : "Skill"} display name`, (existing as string) || result.fallback)
1099
+ : await ctx.ui.editor(`Note for ${result.fallback}`, existing as string);
1100
+ if (next !== undefined) {
1101
+ const data = resourceMetadata(), col = data[result.kind] || {};
1102
+ const labels = { ...col[result.key], [result.field]: next.trim() };
1103
+ if (!labels.displayName && !labels.note) delete col[result.key]; else col[result.key] = labels;
1104
+ data[result.kind] = col;
1105
+ saveResourceMetadata(data);
1106
+ ctx.ui.notify("Personal label saved — not sent to model.", "info");
1107
+ }
1108
+ break;
1109
+ }
1110
+
1111
+ case "view-diagram": {
1112
+ const url = await openMermaidViewer(current.path, result.diagram);
1113
+ ctx.ui.notify(url ? `Opened: ${result.diagram.title}` : "No readable .mmd source for this entry.", url ? "info" : "error");
1114
+ break;
1115
+ }
1116
+ }
1117
+ };
1118
+
1119
+ pi.registerCommand("workspace", { description: "Open Terra Workspace Drawer", handler: async (_a, ctx) => open(ctx) });
1120
+ pi.registerShortcut(Key.alt("w"), { description: "Open Terra Workspace Drawer", handler: async (ctx) => open(ctx as ExtensionCommandContext) });
1121
+ }