pi-arsenal 0.1.4 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/extensions/startup-splash.ts +11 -9
- package/extensions/task-panel.ts +41 -0
- package/extensions/workspace-drawer.ts +866 -510
- package/package.json +1 -1
|
@@ -1,510 +1,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 } 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
|
|
14
|
-
const
|
|
15
|
-
const
|
|
16
|
-
const
|
|
17
|
-
const
|
|
18
|
-
const
|
|
19
|
-
const
|
|
20
|
-
const HIDDEN_NAMES = new Set([".git", "node_modules", ".venv", "__pycache__"]);
|
|
21
|
-
const LIST_PAGE_SIZE = 16;
|
|
22
|
-
const DIAGRAM_PAGE_SIZE = 8;
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
type
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
type
|
|
34
|
-
type
|
|
35
|
-
type
|
|
36
|
-
type
|
|
37
|
-
type
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
};
|
|
43
|
-
|
|
44
|
-
type
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
return
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
}
|
|
86
|
-
return
|
|
87
|
-
}
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
}
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
}
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
return
|
|
123
|
-
}
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
}
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
}
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
}
|
|
146
|
-
|
|
147
|
-
function
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
}
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
const
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
}
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
function
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
const
|
|
241
|
-
if (existsSync(
|
|
242
|
-
|
|
243
|
-
return
|
|
244
|
-
}
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
{
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
this.
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
if (
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
if (
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
}
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
if (!
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
const
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
if (
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
}
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
const next =
|
|
500
|
-
if (next
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
}
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
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
|
+
}
|