pi-arsenal 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +65 -0
- package/extensions/session-manager.ts +9 -0
- package/extensions/startup-splash.ts +159 -0
- package/extensions/task-panel.ts +99 -0
- package/extensions/workspace-drawer.ts +490 -0
- package/lib/session-library.ts +142 -0
- package/package.json +36 -0
- package/themes/tokyo-night-terra.json +86 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 SeiyunSky
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
# Pi Arsenal
|
|
2
|
+
|
|
3
|
+
<p align="center">
|
|
4
|
+
<img src="assets/pi-arsenal-banner.png" alt="Pi Arsenal red signal artwork" width="420">
|
|
5
|
+
</p>
|
|
6
|
+
|
|
7
|
+
> **LOADOUT READY.** A terminal control deck for [Pi](https://github.com/earendil-works/pi): organize the workspace, deploy skills, inspect sessions, and review MCP tools without leaving the TUI.
|
|
8
|
+
|
|
9
|
+
```text
|
|
10
|
+
╔══════════════════════════════════════════════╗
|
|
11
|
+
║ PI ARSENAL ║
|
|
12
|
+
║ WORKSPACE · SESSIONS · SKILLS · MCP ║
|
|
13
|
+
╚══════════════════════════════════════════════╝
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
## Modules
|
|
17
|
+
|
|
18
|
+
| Module | What it does |
|
|
19
|
+
|---|---|
|
|
20
|
+
| **Workspace Drawer** | Projects, files, computer browser, usage, Mermaid gallery, Session Library, Skill Library, and MCP Server browser. |
|
|
21
|
+
| **Session Library** | Inspect sessions, rename them, add private descriptions, reload in the current window, and delete non-current sessions. |
|
|
22
|
+
| **Skill Library** | Browse enabled/disabled skills by folder; add private labels; enable/disable skills or folders; organize folders; prepare `/skill:<name>` commands. |
|
|
23
|
+
| **MCP Server Browser** | Read cached MCP servers and tools without displaying secrets. |
|
|
24
|
+
| **Task Panel** | Persistent task panel extension. |
|
|
25
|
+
| **Startup Splash** | Red/black terminal startup header. |
|
|
26
|
+
| **Tokyo Night Terra** | Included Pi theme. |
|
|
27
|
+
|
|
28
|
+
## Deploy
|
|
29
|
+
|
|
30
|
+
```bash
|
|
31
|
+
pi install git:github.com/SeiyunSky/Pi-Arsenal
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
Then reload Pi:
|
|
35
|
+
|
|
36
|
+
```text
|
|
37
|
+
/reload
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
## Commands
|
|
41
|
+
|
|
42
|
+
| Command | Action |
|
|
43
|
+
|---|---|
|
|
44
|
+
| `Alt+W` | Open the Workspace Drawer |
|
|
45
|
+
| `/workspace` | Open the Workspace Drawer when the terminal does not deliver `Alt+W` |
|
|
46
|
+
| `/sessions` | Open Session Library directly |
|
|
47
|
+
| `/reload` | Apply changed skill discovery after enable/disable operations |
|
|
48
|
+
|
|
49
|
+
## Skill Loadout
|
|
50
|
+
|
|
51
|
+
Open the drawer, then:
|
|
52
|
+
|
|
53
|
+
```text
|
|
54
|
+
Skill Library → Enabled skills / Disabled skills → folder → skill
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
For enabled skills, select **Use this skill now**. Pi Arsenal prepares the canonical command in the editor:
|
|
58
|
+
|
|
59
|
+
```text
|
|
60
|
+
/skill:<canonical-name>
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
Add task details and submit when ready.
|
|
64
|
+
|
|
65
|
+
> Skill enable/disable moves complete skill folders between `~/.agents/skills` and `~/.agents/disabled-skills`. Nothing is deleted. Run `/reload` afterward.
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { openSessionLibrary } from "../lib/session-library.ts";
|
|
3
|
+
|
|
4
|
+
export default function sessionManagerExtension(pi: ExtensionAPI) {
|
|
5
|
+
pi.registerCommand("sessions", {
|
|
6
|
+
description: "Manage Pi sessions: inspect, rename, describe, reload, or delete",
|
|
7
|
+
handler: async (_args, ctx) => await openSessionLibrary(pi, ctx),
|
|
8
|
+
});
|
|
9
|
+
}
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
import type { ExtensionAPI, Theme } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
|
|
3
|
+
|
|
4
|
+
// Character content is loaded verbatim from the user-supplied ascii-art.txt.
|
|
5
|
+
const PORTRAIT: readonly string[] = [
|
|
6
|
+
"##########*###########################################################################+*############",
|
|
7
|
+
"############+#########################################################+=**+#########################",
|
|
8
|
+
"#############**######################*#######**#*++++++++*+*####*+=*#*****##########################",
|
|
9
|
+
"################*#*##########=++++**###*#===++**+++++++******##=++****#***#*#######*################",
|
|
10
|
+
"#############################=++**+++++++##=+****++*+****+++*****#*+******#*#########****###########",
|
|
11
|
+
"##################+*#*#====+*=++***++++**********#****+**********#*#**#***#*##+**###################",
|
|
12
|
+
"###################*+##=+++====**+*****++*++****++*#+*************####***###**#*####################",
|
|
13
|
+
"###############*######+++++=*+=++*****++++*+**++****++#+*********##*+**#*###+#******+*##############",
|
|
14
|
+
"####################==++++=+#++=*=++***+*****+****+*#**+#*******+++****#####+#*****##***+###########",
|
|
15
|
+
"################++++*+++*=+**#+++*=+++++***+*********+###*+*+++++*+****##**#+##******######+########",
|
|
16
|
+
"###*##########*+##*+++**==+*+*#+*+*=**++*+****++#*******#****+*******#****#####*#*****+#############",
|
|
17
|
+
"#############*##*=+==+*+=++*+**++*+****++**********#**#**+##+******#*****##**#*##*****+**###########",
|
|
18
|
+
"###########+####==++*++==++*+*###**#*****++***********#*#**#*#**##*****+#####**#**#*****+*##########",
|
|
19
|
+
"##########*####++++=++=++**+*##++#+**#+*******#*******#####**#*******###*####*#*#********+##########",
|
|
20
|
+
"##############+#+++*+++++**+**#+*+##+*+#+******#***********##***#####*#*###*#****#*******++##*######",
|
|
21
|
+
"#############+#++***#++++*+*#++**+++++**##*#*****###****#-+#++#*##**#*##*##*##****#*******+#########",
|
|
22
|
+
"#############+#+*+**##+*+*+***#+###++==*+++**++#**####***##+##+#****###*###*+#*******#****+#########",
|
|
23
|
+
"###############*+**####+**++**####====+++++++#++++#***+*#*#+++#+#*#*###**##**#*****#*#****+#########",
|
|
24
|
+
"################+**###***+*++*+*+#*=++++++*++++*+++#*#+***##++*+######***##*********#*#***+#########",
|
|
25
|
+
"################+**###*#**+=*+*+++++++++++++++++++#+#++++*++**+#######***#+**+#*******#***+#########",
|
|
26
|
+
"##########*##*###**###*####-*+*++--++++++++++++++++*+++#*#+*+#######*##**#+**+#+*******#****########",
|
|
27
|
+
"#################+*#####*-+++++=:#+++++++++++++++++*+++++++*###########**#****#+*******#*****#######",
|
|
28
|
+
"##################*##-++++++++++++++++++++++++++++++++++++#####*#####*#*#*****#*+******##**#########",
|
|
29
|
+
"#######################++++++++++++++++++++++++++++++#####*#**#######***#+****#*+*******#**##*######",
|
|
30
|
+
"##########################++++++++++++++++++++++++++#***++*#+#+###*###*##+**#*#********+#*######*###",
|
|
31
|
+
"##########################-+++++++++++++++++++++++++#+++++***+##*#####*#++****#**+*****+############",
|
|
32
|
+
"###########################+*+++++++++++++++++++++*++++++++*+#****###**#+*****#**********###########",
|
|
33
|
+
"############################-+++++++++++++++++++#+++++++++++**#*#####+#++*****#****#******##*#######",
|
|
34
|
+
"##############################-++++++++++++++++++++++++++++++*#*#####*++******#***********##*#######",
|
|
35
|
+
"##############################*++++++++++++++++++++++++++++++*#######*++******#*****#*****+#*#######",
|
|
36
|
+
"##########################*####-+++++++++++++*+++++++++++++++**#####*+++#+****#*************########",
|
|
37
|
+
"#########################*#####==++++*+++####++++++++++*******#######+*#++****#****#*#******#*######",
|
|
38
|
+
"###########################################**#--+++##**##########*##++#+*+****#*****#*##*****#######",
|
|
39
|
+
"###########################################=#+##*******####*****+#*#+*#**+***###*******#******######",
|
|
40
|
+
"########################################*#-##******##****#********#+#+#**+**####********#*****######",
|
|
41
|
+
"#########################################++#+**#*+********#*******+##*###++***##*****#**##****######",
|
|
42
|
+
"###################**###################++#+#+*#=*****#***********+##*###+++**###*****#**##****#####",
|
|
43
|
+
"################**######################+++#*#+#+**#*###***#******++######+++#*##*****#***##*#*#####",
|
|
44
|
+
"#############*+########################*++#+##=*****#*###****#******#**#####++####****#*#**##***##*#",
|
|
45
|
+
"###########+##########################+++*+#*##**********#**#*#*##**++*####*#**###****####**##**####",
|
|
46
|
+
"#########################*########*++*++++*#+##+**+*******#***==+*********#**##*###***####***##*####",
|
|
47
|
+
"################################*++*++*#+*##*#+***+****+#*+*+==+************#+#**##***####*#**######",
|
|
48
|
+
"###############################++##++#*+*##*=******+++*++#+===****************###++*+*#####****#####",
|
|
49
|
+
"############################+#*##++####++##+*****+-***+*++*==+************####+*####**#####*##**####",
|
|
50
|
+
"########################*###*###**####**=+#*********++#++***=*********#*###+####*###**#####*##**####",
|
|
51
|
+
"##########################*####**####**+#**+*****#*#+++++**********#*##**###########*######*###*####",
|
|
52
|
+
"##############################*#####=++**#**+#***#+++*+*#*******#*##+###############*######*###**###",
|
|
53
|
+
"#######################*######*####++*#*#*#******#**##++*#**########################*##########*####",
|
|
54
|
+
"######################*############+*=+##**++****#*##*+**#######**########################*####*####",
|
|
55
|
+
"##############################*####**+#*+++******##++########*+#####################################",
|
|
56
|
+
"#####################*#############++*+**+#******#########+++###*###################################",
|
|
57
|
+
"##############################*#++**#++++*++#**########+++########################*#################",
|
|
58
|
+
"#########################*##*=+++#+++++++*+###########*#############################################",
|
|
59
|
+
"######################*###*=+++#++++++++########*###################################################",
|
|
60
|
+
"#########################=****+++++**#######*#######################################################",
|
|
61
|
+
"###################*#*###+********###*##############################################################"
|
|
62
|
+
];
|
|
63
|
+
|
|
64
|
+
// Color zones sampled from the user-supplied reference image at the same 100 × 56 grid.
|
|
65
|
+
// D = dark gray, M = gray, r = dark red, R = red, H = highlight.
|
|
66
|
+
const ARSENAL_LOGO: readonly string[] = [
|
|
67
|
+
":@@@ *@@@@@",
|
|
68
|
+
" #@@@@@@@@ @@@@@ @@@",
|
|
69
|
+
" #@@ @@+ @@@@@* @@ @@: @@ @@@@@ @@@@@@* -@@@@@% #@*@@@@@ @@@@@@@. @@@",
|
|
70
|
+
" #@@ :@@ @@* @@+ #@@ @@@ @@# @@@ @@% %@@ #@@* #@@ .@@ @@@",
|
|
71
|
+
" #@@@@@@@ @@* -@@ @@# @@* @@@@@@ @@@@@@@@@ #@@ =@@ @@@@@@@ @@@",
|
|
72
|
+
" #@@ @@* @@@@@@@@@ @@* %@@ @@: #@@ =@@ +@@ @@ @@@",
|
|
73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DDDDMDDMrrrrMRRrrrrrDDDDDDDMDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD",
|
|
131
|
+
"DDDDDDDDDDDDDDDDDDDDDDDDrRrrrrrRRrrDDDDDDDMDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD",
|
|
132
|
+
"DDDDDDDDDDDDDDDDDDDrDrDDMrMrrrrrMDDMDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD"
|
|
133
|
+
];
|
|
134
|
+
|
|
135
|
+
function paint(line: string, colors: string, theme: Theme): string {
|
|
136
|
+
let result = "", buffer = "", current = "";
|
|
137
|
+
const colorOf = (mark: string): "dim" | "muted" | "error" | "text" => mark === "R" ? "error" : mark === "r" ? "muted" : mark === "H" ? "text" : mark === "M" ? "muted" : "dim";
|
|
138
|
+
const flush = () => { if (buffer) result += theme.fg(current as "dim" | "muted" | "error" | "text", buffer); buffer = ""; };
|
|
139
|
+
for (let i = 0; i < line.length; i++) { const next = colorOf(colors[i] || "D"); if (next !== current) { flush(); current = next; } buffer += line[i]!; }
|
|
140
|
+
flush(); return result;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
function splash(theme: Theme, width: number): string[] {
|
|
144
|
+
const label = `${theme.bold(theme.fg("error", "◆"))}${theme.fg("text", " ID: 沫路")} ${theme.fg("dim", "// PI ARSENAL")}`;
|
|
145
|
+
const artWidth = Math.max(...PORTRAIT.map(visibleWidth), visibleWidth(label));
|
|
146
|
+
if (width < artWidth) return [truncateToWidth(label, width)];
|
|
147
|
+
const center = (line: string) => " ".repeat(Math.max(0, Math.floor((width - artWidth) / 2))) + line;
|
|
148
|
+
const logoWidth = Math.max(...ARSENAL_LOGO.map(visibleWidth));
|
|
149
|
+
if (width < Math.max(artWidth, logoWidth)) return [truncateToWidth(label, width)];
|
|
150
|
+
const centerLogo = (line: string) => " ".repeat(Math.max(0, Math.floor((width - logoWidth) / 2))) + theme.fg("error", line);
|
|
151
|
+
return ["", ...PORTRAIT.map((line, index) => center(paint(line, COLOR_MASK[index] || "", theme))), "", ...ARSENAL_LOGO.map(centerLogo), center(label), ""];
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
export default function startupSplash(pi: ExtensionAPI) {
|
|
155
|
+
pi.on("session_start", async (_event, ctx) => {
|
|
156
|
+
if (ctx.mode !== "tui") return;
|
|
157
|
+
ctx.ui.setHeader((_tui, theme) => ({ invalidate() {}, render(width: number): string[] { return splash(theme, width); } }));
|
|
158
|
+
});
|
|
159
|
+
}
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import type { ExtensionAPI, ExtensionContext, SessionEntry } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { truncateToWidth } from "@earendil-works/pi-tui";
|
|
3
|
+
|
|
4
|
+
const WIDGET_ID = "sol-pi-task-panel";
|
|
5
|
+
const ONLINE_STATE_ENTRY = "sol-pi-online-context-state-v1";
|
|
6
|
+
const MAX_VISIBLE_STEPS = 10;
|
|
7
|
+
|
|
8
|
+
type PlanStatus = "pending" | "in_progress" | "completed";
|
|
9
|
+
|
|
10
|
+
type PlanStep = {
|
|
11
|
+
id: string;
|
|
12
|
+
goal: string;
|
|
13
|
+
status: PlanStatus;
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
function parseSteps(value: unknown): PlanStep[] | undefined {
|
|
17
|
+
if (!Array.isArray(value) || value.length === 0) return;
|
|
18
|
+
const steps: PlanStep[] = [];
|
|
19
|
+
for (const item of value) {
|
|
20
|
+
if (typeof item !== "object" || item === null || Array.isArray(item)) return;
|
|
21
|
+
const step = item as Record<string, unknown>;
|
|
22
|
+
if (
|
|
23
|
+
typeof step.id !== "string" ||
|
|
24
|
+
typeof step.goal !== "string" ||
|
|
25
|
+
!(["pending", "in_progress", "completed"] as const).includes(step.status as PlanStatus)
|
|
26
|
+
) {
|
|
27
|
+
return;
|
|
28
|
+
}
|
|
29
|
+
steps.push({ id: step.id, goal: step.goal, status: step.status as PlanStatus });
|
|
30
|
+
}
|
|
31
|
+
return steps;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function restoreSteps(entries: readonly SessionEntry[]): PlanStep[] {
|
|
35
|
+
for (let index = entries.length - 1; index >= 0; index--) {
|
|
36
|
+
const entry = entries[index];
|
|
37
|
+
if (entry?.type !== "custom" || entry.customType !== ONLINE_STATE_ENTRY) continue;
|
|
38
|
+
const data = entry.data as { plan?: unknown } | undefined;
|
|
39
|
+
return parseSteps(data?.plan) ?? [];
|
|
40
|
+
}
|
|
41
|
+
return [];
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export default function taskPanel(pi: ExtensionAPI) {
|
|
45
|
+
let steps: PlanStep[] = [];
|
|
46
|
+
|
|
47
|
+
function render(ctx: ExtensionContext): void {
|
|
48
|
+
if (ctx.mode !== "tui") return;
|
|
49
|
+
if (steps.length === 0) {
|
|
50
|
+
ctx.ui.setWidget(WIDGET_ID, undefined);
|
|
51
|
+
return;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
ctx.ui.setWidget(WIDGET_ID, (_tui, theme) => ({
|
|
55
|
+
invalidate() {},
|
|
56
|
+
render(width: number): string[] {
|
|
57
|
+
const completed = steps.filter((step) => step.status === "completed").length;
|
|
58
|
+
const lines = [
|
|
59
|
+
truncateToWidth(
|
|
60
|
+
theme.fg("accent", theme.bold("Tasks")) + theme.fg("dim", ` ${completed}/${steps.length} completed`),
|
|
61
|
+
width,
|
|
62
|
+
),
|
|
63
|
+
];
|
|
64
|
+
|
|
65
|
+
for (const step of steps.slice(0, MAX_VISIBLE_STEPS)) {
|
|
66
|
+
const marker =
|
|
67
|
+
step.status === "completed"
|
|
68
|
+
? theme.fg("success", "✓")
|
|
69
|
+
: step.status === "in_progress"
|
|
70
|
+
? theme.fg("warning", "●")
|
|
71
|
+
: theme.fg("dim", "○");
|
|
72
|
+
const goal = step.status === "completed" ? theme.fg("muted", step.goal) : theme.fg("text", step.goal);
|
|
73
|
+
lines.push(truncateToWidth(` ${marker} ${goal}`, width));
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
if (steps.length > MAX_VISIBLE_STEPS) {
|
|
77
|
+
lines.push(theme.fg("dim", ` … ${steps.length - MAX_VISIBLE_STEPS} more`));
|
|
78
|
+
}
|
|
79
|
+
return lines;
|
|
80
|
+
},
|
|
81
|
+
}));
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function restore(ctx: ExtensionContext): void {
|
|
85
|
+
steps = restoreSteps(ctx.sessionManager.getBranch());
|
|
86
|
+
render(ctx);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
pi.on("session_start", async (_event, ctx) => restore(ctx));
|
|
90
|
+
pi.on("session_tree", async (_event, ctx) => restore(ctx));
|
|
91
|
+
|
|
92
|
+
pi.on("tool_execution_start", async (event, ctx) => {
|
|
93
|
+
if (event.toolName !== "update_plan") return;
|
|
94
|
+
const next = parseSteps((event.args as { steps?: unknown } | undefined)?.steps);
|
|
95
|
+
if (!next) return;
|
|
96
|
+
steps = next;
|
|
97
|
+
render(ctx);
|
|
98
|
+
});
|
|
99
|
+
}
|
|
@@ -0,0 +1,490 @@
|
|
|
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 MODELS_FILE = join(ROOT, ".pi", "agent", "models.json");
|
|
14
|
+
const DIAGRAMS_DIR = join(".pi", "diagrams");
|
|
15
|
+
const DIAGRAMS_MANIFEST = "gallery.json";
|
|
16
|
+
const SKILLS_DIR = join(ROOT, ".agents", "skills");
|
|
17
|
+
const DISABLED_SKILLS_DIR = join(ROOT, ".agents", "disabled-skills");
|
|
18
|
+
const MCP_CACHE_FILE = join(ROOT, ".pi", "agent", "mcp-cache.json");
|
|
19
|
+
const RESOURCE_METADATA_FILE = join(ROOT, ".pi", "agent", "resource-library.json");
|
|
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
|
+
type Workspace = { name: string; path: string };
|
|
25
|
+
type View = "home" | "projects" | "files" | "browser" | "usage" | "diagrams" | "skills" | "skill-list" | "skill-detail" | "skill-confirm" | "mcp" | "mcp-detail";
|
|
26
|
+
type FileItem = { name: string; directory: boolean };
|
|
27
|
+
type Pricing = { input: number; output: number; cacheRead?: number };
|
|
28
|
+
type UsageTotals = { input: number; output: number; cacheRead: number };
|
|
29
|
+
type Diagram = { id: string; title: string; file: string; type?: string; createdAt?: string; summary?: string };
|
|
30
|
+
type Skill = { name: string; description: string; path: string; enabled: boolean };
|
|
31
|
+
type SkillEntry = { type: "folder"; name: string; relative: string } | { type: "skill"; skill: Skill };
|
|
32
|
+
type McpTool = { name: string; description?: string };
|
|
33
|
+
type McpServer = { name: string; tools: McpTool[]; cachedAt?: number };
|
|
34
|
+
type ResourceLabels = { displayName?: string; note?: string };
|
|
35
|
+
type ResourceMetadata = { skills?: Record<string, ResourceLabels>; mcp?: Record<string, ResourceLabels> };
|
|
36
|
+
type Result = { type: "close" } | { type: "workspace"; workspace: Workspace } | { type: "view-diagram"; diagram: Diagram } | { type: "sessions" } | { type: "edit-label"; kind: "skills" | "mcp"; key: string; fallback: string; field: "displayName" | "note" } | { type: "use-skill"; canonicalName: string } | { type: "organize-skills" } | { type: "toggle-skill-folder"; enabled: boolean; relative: string };
|
|
37
|
+
|
|
38
|
+
type MermaidViewer = { server: Server; source: string; title: string; url: string };
|
|
39
|
+
let mermaidViewer: MermaidViewer | undefined;
|
|
40
|
+
|
|
41
|
+
function configuredWorkspaces(fallback: string): Workspace[] {
|
|
42
|
+
try {
|
|
43
|
+
const data = JSON.parse(readFileSync(WORKSPACES_FILE, "utf8")) as { workspaces?: Workspace[] };
|
|
44
|
+
const found = (data.workspaces || []).filter((item) => typeof item.name === "string" && typeof item.path === "string" && existsSync(item.path));
|
|
45
|
+
if (found.length) return found;
|
|
46
|
+
} catch { /* Current Pi cwd is a safe fallback. */ }
|
|
47
|
+
return [{ name: basename(fallback) || fallback, path: fallback }];
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function restoredWorkspace(entries: readonly SessionEntry[], fallback: string): Workspace {
|
|
51
|
+
for (let i = entries.length - 1; i >= 0; i--) {
|
|
52
|
+
const entry = entries[i];
|
|
53
|
+
if (entry?.type !== "custom" || entry.customType !== STATE_TYPE) continue;
|
|
54
|
+
const item = entry.data as Workspace | undefined;
|
|
55
|
+
if (item && typeof item.name === "string" && typeof item.path === "string" && existsSync(item.path)) return item;
|
|
56
|
+
}
|
|
57
|
+
return configuredWorkspaces(fallback)[0]!;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function entries(path: string, directoriesOnly = false): FileItem[] {
|
|
61
|
+
try {
|
|
62
|
+
return readdirSync(path, { withFileTypes: true })
|
|
63
|
+
.filter((entry) => !HIDDEN_NAMES.has(entry.name) && (!directoriesOnly || entry.isDirectory()))
|
|
64
|
+
.sort((a, b) => Number(b.isDirectory()) - Number(a.isDirectory()) || a.name.localeCompare(b.name))
|
|
65
|
+
.slice(0, 120)
|
|
66
|
+
.map((entry) => ({ name: entry.name, directory: entry.isDirectory() }));
|
|
67
|
+
} catch { return []; }
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function sessionUsage(ctx: ExtensionContext): UsageTotals {
|
|
71
|
+
const totals: UsageTotals = { input: 0, output: 0, cacheRead: 0 };
|
|
72
|
+
for (const entry of ctx.sessionManager.getBranch()) {
|
|
73
|
+
if (entry.type !== "message" || entry.message.role !== "assistant") continue;
|
|
74
|
+
const usage = (entry.message as AssistantMessage).usage;
|
|
75
|
+
if (!usage) continue;
|
|
76
|
+
totals.input += usage.input || 0;
|
|
77
|
+
totals.output += usage.output || 0;
|
|
78
|
+
totals.cacheRead += usage.cacheRead || 0;
|
|
79
|
+
}
|
|
80
|
+
return totals;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
const formatTokens = (value: number) => value < 1000 ? String(value) : `${(value / 1000).toFixed(1)}k`;
|
|
84
|
+
|
|
85
|
+
function diagrams(root: string): Diagram[] {
|
|
86
|
+
try {
|
|
87
|
+
const data = JSON.parse(readFileSync(join(root, DIAGRAMS_DIR, DIAGRAMS_MANIFEST), "utf8")) as { diagrams?: Diagram[] };
|
|
88
|
+
return (data.diagrams || []).filter((item) => typeof item.id === "string" && typeof item.title === "string" && typeof item.file === "string");
|
|
89
|
+
} catch { return []; }
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function resourceMetadata(): ResourceMetadata {
|
|
93
|
+
try { return JSON.parse(readFileSync(RESOURCE_METADATA_FILE, "utf8")) as ResourceMetadata; } catch { return {}; }
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function saveResourceMetadata(data: ResourceMetadata): void {
|
|
97
|
+
mkdirSync(dirname(RESOURCE_METADATA_FILE), { recursive: true });
|
|
98
|
+
writeFileSync(RESOURCE_METADATA_FILE, `${JSON.stringify(data, null, 2)}\n`, "utf8");
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function skillRoot(skill: Skill): string { return skill.enabled ? SKILLS_DIR : DISABLED_SKILLS_DIR; }
|
|
102
|
+
function skillKey(skill: Skill): string { return relative(skillRoot(skill), skill.path).replaceAll("\\", "/"); }
|
|
103
|
+
function moveSkill(skill: Skill, targetRoot: string, targetRelative: string): Skill {
|
|
104
|
+
const target = join(targetRoot, targetRelative);
|
|
105
|
+
if (existsSync(target)) throw new Error("A skill already exists at the destination.");
|
|
106
|
+
mkdirSync(dirname(target), { recursive: true });
|
|
107
|
+
renameSync(skill.path, target);
|
|
108
|
+
const data = resourceMetadata(), oldKey = skillKey(skill), next: Skill = { ...skill, path: target, enabled: targetRoot === SKILLS_DIR }, newKey = skillKey(next);
|
|
109
|
+
if (oldKey !== newKey && data.skills?.[oldKey]) { data.skills[newKey] = data.skills[oldKey]; delete data.skills[oldKey]; saveResourceMetadata(data); }
|
|
110
|
+
return next;
|
|
111
|
+
}
|
|
112
|
+
function categoryOf(skill: Skill): string { const dir = dirname(skillKey(skill)); return dir === "." ? "Uncategorized" : dir; }
|
|
113
|
+
const CATEGORY_COLORS = ["accent", "success", "warning", "error", "mdLink", "mdCode", "syntaxFunction", "syntaxType", "syntaxString"] as const;
|
|
114
|
+
function categoryColor(category: string): typeof CATEGORY_COLORS[number] {
|
|
115
|
+
let hash = 0; for (const char of category) hash = (hash * 31 + char.charCodeAt(0)) >>> 0;
|
|
116
|
+
return CATEGORY_COLORS[hash % CATEGORY_COLORS.length]!;
|
|
117
|
+
}
|
|
118
|
+
function validCategory(value: string): string | undefined {
|
|
119
|
+
const category = value.trim().replaceAll("\\", "/").replace(/^\/+|\/+$/g, "");
|
|
120
|
+
return category && !category.split("/").some((part) => !part || part === "." || part === "..") ? category : undefined;
|
|
121
|
+
}
|
|
122
|
+
function skillCategories(): string[] {
|
|
123
|
+
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; };
|
|
124
|
+
return [...new Set([...collect(SKILLS_DIR), ...collect(DISABLED_SKILLS_DIR)])].sort();
|
|
125
|
+
}
|
|
126
|
+
function labelsFor(kind: "skills" | "mcp", key: string): ResourceLabels { return resourceMetadata()[kind]?.[key] || {}; }
|
|
127
|
+
function displayName(kind: "skills" | "mcp", key: string, fallback: string): string { return labelsFor(kind, key).displayName?.trim() || fallback; }
|
|
128
|
+
|
|
129
|
+
function skills(): Skill[] {
|
|
130
|
+
const read = (root: string, enabled: boolean): Skill[] => {
|
|
131
|
+
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. */ } };
|
|
132
|
+
walk(root); return found;
|
|
133
|
+
};
|
|
134
|
+
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));
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function skillCount(folder: string): number {
|
|
138
|
+
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; }
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function skillEntries(enabled: boolean, directory = ""): SkillEntry[] {
|
|
142
|
+
const root = enabled ? SKILLS_DIR : DISABLED_SKILLS_DIR, folder = resolve(root, directory);
|
|
143
|
+
if (!isInside(root, folder)) return [];
|
|
144
|
+
try { return readdirSync(folder, { withFileTypes: true }).filter((item) => item.isDirectory()).flatMap((item): SkillEntry[] => {
|
|
145
|
+
const path = join(folder, item.name), file = join(path, "SKILL.md"), relativePath = relative(root, path).replaceAll("\\", "/");
|
|
146
|
+
if (!existsSync(file)) return skillCount(path) ? [{ type: "folder", name: item.name, relative: relativePath }] : [];
|
|
147
|
+
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 } }];
|
|
148
|
+
}).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 []; }
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
function moveSkillFolder(enabled: boolean, folderRelative: string): number {
|
|
152
|
+
const sourceRoot = enabled ? SKILLS_DIR : DISABLED_SKILLS_DIR, targetRoot = enabled ? DISABLED_SKILLS_DIR : SKILLS_DIR;
|
|
153
|
+
const source = resolve(sourceRoot, folderRelative), target = resolve(targetRoot, folderRelative);
|
|
154
|
+
if (!isInside(sourceRoot, source) || !isInside(targetRoot, target) || !existsSync(source)) throw new Error("Invalid skill folder.");
|
|
155
|
+
const contained = skills().filter((skill) => skill.enabled === enabled && (skillKey(skill) === folderRelative || skillKey(skill).startsWith(`${folderRelative}/`)));
|
|
156
|
+
if (!contained.length) throw new Error("This folder has no skills to move.");
|
|
157
|
+
for (const skill of contained) moveSkill(skill, targetRoot, skillKey(skill));
|
|
158
|
+
return contained.length;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
function cachedMcpServers(): McpServer[] {
|
|
162
|
+
try {
|
|
163
|
+
const data = JSON.parse(readFileSync(MCP_CACHE_FILE, "utf8")) as { servers?: Record<string, { tools?: McpTool[]; cachedAt?: number }> };
|
|
164
|
+
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 }));
|
|
165
|
+
} catch { return []; }
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
async function organizeSkillFolders(ctx: ExtensionCommandContext): Promise<void> {
|
|
169
|
+
while (true) {
|
|
170
|
+
const action = await ctx.ui.select("Organize Skill Folders", ["Create shared category folder", "Move a skill", "Back"]);
|
|
171
|
+
if (!action || action === "Back") return;
|
|
172
|
+
if (action === "Create shared category folder") {
|
|
173
|
+
const value = await ctx.ui.input("New shared category", "");
|
|
174
|
+
const category = value ? validCategory(value) : undefined;
|
|
175
|
+
if (!category) { ctx.ui.notify("Enter a relative folder name without . or ...", "warning"); continue; }
|
|
176
|
+
mkdirSync(join(SKILLS_DIR, category), { recursive: true }); mkdirSync(join(DISABLED_SKILLS_DIR, category), { recursive: true });
|
|
177
|
+
ctx.ui.notify(`Created category in both libraries: ${category}`, "info"); continue;
|
|
178
|
+
}
|
|
179
|
+
const library = await ctx.ui.select("Choose skill library", ["✨ Enabled skills", "💤 Disabled skills", "Cancel"]);
|
|
180
|
+
if (!library || library === "Cancel") continue;
|
|
181
|
+
const enabled = library.startsWith("✨"), list = skills().filter((skill) => skill.enabled === enabled);
|
|
182
|
+
if (!list.length) { ctx.ui.notify("No skills in this library.", "info"); continue; }
|
|
183
|
+
const choices = list.map((skill) => `${displayName("skills", skillKey(skill), skill.name)} · ${categoryOf(skill)}`);
|
|
184
|
+
const selected = await ctx.ui.select("Move a skill", [...choices, "Cancel"]);
|
|
185
|
+
if (!selected || selected === "Cancel") continue;
|
|
186
|
+
const skill = list[choices.indexOf(selected)]; if (!skill) continue;
|
|
187
|
+
const categories = skillCategories();
|
|
188
|
+
const destination = await ctx.ui.select("Move to category", ["Library root (Uncategorized)", ...categories, "Create new category…", "Cancel"]);
|
|
189
|
+
if (!destination || destination === "Cancel") continue;
|
|
190
|
+
let category = destination === "Library root (Uncategorized)" ? "" : destination;
|
|
191
|
+
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 }); }
|
|
192
|
+
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"); }
|
|
193
|
+
catch (error) { ctx.ui.notify(error instanceof Error ? error.message : "Could not move skill.", "error"); }
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
function isInside(parent: string, child: string): boolean {
|
|
198
|
+
return child === parent || child.startsWith(parent.endsWith(sep) ? parent : `${parent}${sep}`);
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
function registeredMermaidSource(root: string, diagram: Diagram): string | undefined {
|
|
202
|
+
const base = resolve(root, DIAGRAMS_DIR);
|
|
203
|
+
const file = resolve(base, diagram.file);
|
|
204
|
+
if (diagram.type && diagram.type !== "mermaid") return undefined;
|
|
205
|
+
if (extname(file).toLowerCase() !== ".mmd" || !isInside(base, file) || !existsSync(file)) return undefined;
|
|
206
|
+
try { return readFileSync(file, "utf8"); } catch { return undefined; }
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
function viewerHtml(title: string, source: string): string {
|
|
210
|
+
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>`;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
async function openMermaidViewer(root: string, diagram: Diagram): Promise<string | undefined> {
|
|
214
|
+
const source = registeredMermaidSource(root, diagram);
|
|
215
|
+
if (!source) return undefined;
|
|
216
|
+
if (!mermaidViewer) {
|
|
217
|
+
const server = createServer((request, response) => {
|
|
218
|
+
if (!mermaidViewer || request.url !== "/") { response.writeHead(404).end(); return; }
|
|
219
|
+
response.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store" });
|
|
220
|
+
response.end(viewerHtml(mermaidViewer.title, mermaidViewer.source));
|
|
221
|
+
});
|
|
222
|
+
await new Promise<void>((resolveListen, rejectListen) => { server.once("error", rejectListen); server.listen(0, "127.0.0.1", () => { server.off("error", rejectListen); resolveListen(); }); });
|
|
223
|
+
const address = server.address();
|
|
224
|
+
if (!address || typeof address === "string") { server.close(); return undefined; }
|
|
225
|
+
mermaidViewer = { server, source, title: diagram.title, url: `http://127.0.0.1:${address.port}/` };
|
|
226
|
+
} else { mermaidViewer.source = source; mermaidViewer.title = diagram.title; }
|
|
227
|
+
spawn("cmd.exe", ["/c", "start", "", mermaidViewer.url], { detached: true, stdio: "ignore" }).unref();
|
|
228
|
+
return mermaidViewer.url;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
function driveRoots(): string[] {
|
|
232
|
+
const roots: string[] = [];
|
|
233
|
+
for (let code = 67; code <= 90; code++) {
|
|
234
|
+
const root = `${String.fromCharCode(code)}:\\`;
|
|
235
|
+
if (existsSync(root)) roots.push(root);
|
|
236
|
+
}
|
|
237
|
+
return roots;
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
class WorkspaceDrawer implements Focusable {
|
|
241
|
+
readonly width = 52;
|
|
242
|
+
focused = false;
|
|
243
|
+
private view: View = "home";
|
|
244
|
+
private selected = 0;
|
|
245
|
+
private files: FileItem[] | undefined;
|
|
246
|
+
private browserPath: string | undefined;
|
|
247
|
+
private browserEntries: FileItem[] = [];
|
|
248
|
+
private pricing: Pricing | undefined;
|
|
249
|
+
private pricingLoading = false;
|
|
250
|
+
private diagramItems: Diagram[] | undefined;
|
|
251
|
+
private skillItems: Skill[] | undefined;
|
|
252
|
+
private skillEntryItems: SkillEntry[] = [];
|
|
253
|
+
private skillDirectory = "";
|
|
254
|
+
private skillEnabled = true;
|
|
255
|
+
private selectedSkill: Skill | undefined;
|
|
256
|
+
private mcpItems: McpServer[] | undefined;
|
|
257
|
+
private selectedMcp: McpServer | undefined;
|
|
258
|
+
|
|
259
|
+
constructor(private readonly ctx: ExtensionCommandContext, private readonly workspace: Workspace, private readonly workspaces: Workspace[], private readonly theme: Theme, private readonly done: (result: Result) => void, private readonly tui: { requestRender(): void }) {}
|
|
260
|
+
|
|
261
|
+
private open(view: View): void {
|
|
262
|
+
this.view = view;
|
|
263
|
+
this.selected = 0;
|
|
264
|
+
if (view === "files" && !this.files) this.files = entries(this.workspace.path);
|
|
265
|
+
if (view === "browser") this.openBrowser(this.browserPath);
|
|
266
|
+
if (view === "usage") void this.loadPricing();
|
|
267
|
+
if (view === "diagrams") this.diagramItems = diagrams(this.workspace.path);
|
|
268
|
+
if (view === "skills") this.skillItems = skills();
|
|
269
|
+
if (view === "skill-list") this.skillEntryItems = skillEntries(this.skillEnabled, this.skillDirectory);
|
|
270
|
+
if (view === "mcp") this.mcpItems = cachedMcpServers();
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
private async loadPricing(): Promise<void> {
|
|
274
|
+
if (this.pricing || this.pricingLoading) return;
|
|
275
|
+
this.pricingLoading = true;
|
|
276
|
+
try {
|
|
277
|
+
const config = JSON.parse(readFileSync(MODELS_FILE, "utf8")).providers?.["litellm-openai"] as { baseUrl?: string; apiKey?: string } | undefined;
|
|
278
|
+
if (!config?.baseUrl || !config.apiKey || !this.ctx.model?.id) return;
|
|
279
|
+
const response = await fetch(`${config.baseUrl.replace(/\/v1\/?$/, "")}/model/info`, { headers: { Authorization: `Bearer ${config.apiKey}` }, signal: AbortSignal.timeout(5_000) });
|
|
280
|
+
if (!response.ok) return;
|
|
281
|
+
const data = await response.json() as { data?: Array<{ model_name?: string; model_info?: { input_cost_per_token?: number; output_cost_per_token?: number; cache_read_input_token_cost?: number } }> };
|
|
282
|
+
const info = data.data?.find((item) => item.model_name === this.ctx.model?.id)?.model_info;
|
|
283
|
+
if (info?.input_cost_per_token !== undefined && info.output_cost_per_token !== undefined) this.pricing = { input: info.input_cost_per_token, output: info.output_cost_per_token, cacheRead: info.cache_read_input_token_cost };
|
|
284
|
+
} catch { /* Usage remains available without price data. */ }
|
|
285
|
+
finally { this.pricingLoading = false; this.tui.requestRender(); }
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
private openBrowser(path: string | undefined): void {
|
|
289
|
+
this.browserPath = path;
|
|
290
|
+
this.selected = 0;
|
|
291
|
+
this.browserEntries = path ? entries(path, true) : driveRoots().map((root) => ({ name: root, directory: true }));
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
private backBrowser(): void {
|
|
295
|
+
if (!this.browserPath) { this.open("projects"); return; }
|
|
296
|
+
const parent = dirname(this.browserPath);
|
|
297
|
+
this.openBrowser(parent === this.browserPath ? undefined : parent);
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
handleInput(data: string): void {
|
|
301
|
+
if (matchesKey(data, Key.escape) || matchesKey(data, Key.left)) {
|
|
302
|
+
if (this.view === "home") this.done({ type: "close" });
|
|
303
|
+
else if (this.view === "browser") this.backBrowser();
|
|
304
|
+
else if (this.view === "skill-list") { if (this.skillDirectory) { this.skillDirectory = dirname(this.skillDirectory); if (this.skillDirectory === ".") this.skillDirectory = ""; this.open("skill-list"); } else this.open("skills"); }
|
|
305
|
+
else if (this.view === "skill-detail") this.open("skill-list");
|
|
306
|
+
else if (this.view === "skill-confirm") this.open("skill-detail");
|
|
307
|
+
else if (this.view === "mcp-detail") this.open("mcp");
|
|
308
|
+
else { this.view = "home"; this.selected = 0; }
|
|
309
|
+
return;
|
|
310
|
+
}
|
|
311
|
+
if (matchesKey(data, "p")) { this.open("projects"); return; }
|
|
312
|
+
if (matchesKey(data, "f")) { this.open("files"); return; }
|
|
313
|
+
if (matchesKey(data, "b")) { this.open("browser"); return; }
|
|
314
|
+
if (matchesKey(data, "c")) { this.open("usage"); return; }
|
|
315
|
+
if (matchesKey(data, "d")) { this.open("diagrams"); return; }
|
|
316
|
+
if (matchesKey(data, "l")) { this.open("skills"); return; }
|
|
317
|
+
if (matchesKey(data, "m")) { this.open("mcp"); return; }
|
|
318
|
+
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; }
|
|
319
|
+
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; }
|
|
320
|
+
if (matchesKey(data, "s") && this.view === "browser" && this.browserPath) { this.setCurrentDirectory(); return; }
|
|
321
|
+
if (matchesKey(data, Key.up) || matchesKey(data, "k")) { this.selected = Math.max(0, this.selected - 1); return; }
|
|
322
|
+
if (matchesKey(data, Key.down) || matchesKey(data, "j")) {
|
|
323
|
+
const last = this.view === "projects" ? this.workspaces.length : this.view === "files" ? Math.max(0, (this.files?.length || 1) - 1) : this.view === "browser" ? Math.max(0, this.browserEntries.length - 1) : this.view === "diagrams" ? Math.max(0, (this.diagramItems?.length || 1) - 1) : this.view === "skills" ? 1 : this.view === "skill-list" ? this.skillEntryItems.length + (this.skillDirectory ? 1 : 0) : this.view === "skill-detail" ? (this.selectedSkill?.enabled ? 3 : 2) : this.view === "mcp" ? Math.max(0, (this.mcpItems?.length || 1) - 1) : this.view === "mcp-detail" ? Math.max(0, (this.selectedMcp?.tools.length || 1) - 1) : this.view === "usage" ? 0 : 7;
|
|
324
|
+
this.selected = Math.min(last, this.selected + 1);
|
|
325
|
+
return;
|
|
326
|
+
}
|
|
327
|
+
if (!matchesKey(data, Key.enter) && !matchesKey(data, Key.right)) return;
|
|
328
|
+
if (this.view === "home") {
|
|
329
|
+
if (this.selected === 5) { this.done({ type: "sessions" }); return; }
|
|
330
|
+
this.open(["projects", "files", "browser", "usage", "diagrams", "sessions", "skills", "mcp"][this.selected] as View);
|
|
331
|
+
return;
|
|
332
|
+
}
|
|
333
|
+
if (this.view === "skills") { this.skillEnabled = this.selected === 0; this.skillDirectory = ""; this.open("skill-list"); return; }
|
|
334
|
+
if (this.view === "skill-list") { const entry = this.skillEntryItems[this.selected]; if (entry?.type === "skill") { this.selectedSkill = entry.skill; this.open("skill-detail"); } else if (entry?.type === "folder") { this.skillDirectory = entry.relative; this.open("skill-list"); } else if (this.skillDirectory && this.selected === this.skillEntryItems.length) this.done({ type: "toggle-skill-folder", enabled: this.skillEnabled, relative: this.skillDirectory }); else this.done({ type: "organize-skills" }); return; }
|
|
335
|
+
if (this.view === "skill-detail") {
|
|
336
|
+
if (!this.selectedSkill) return;
|
|
337
|
+
const offset = this.selectedSkill.enabled ? 1 : 0;
|
|
338
|
+
if (this.selectedSkill.enabled && this.selected === 0) this.done({ type: "use-skill", canonicalName: this.selectedSkill.name });
|
|
339
|
+
else if (this.selected === offset) this.done({ type: "edit-label", kind: "skills", key: skillKey(this.selectedSkill), fallback: this.selectedSkill.name, field: "displayName" });
|
|
340
|
+
else if (this.selected === offset + 1) this.done({ type: "edit-label", kind: "skills", key: skillKey(this.selectedSkill), fallback: this.selectedSkill.name, field: "note" });
|
|
341
|
+
else this.open("skill-confirm");
|
|
342
|
+
return;
|
|
343
|
+
}
|
|
344
|
+
if (this.view === "skill-confirm") { if (!this.selectedSkill) return; try { this.selectedSkill = moveSkill(this.selectedSkill, this.selectedSkill.enabled ? DISABLED_SKILLS_DIR : SKILLS_DIR, skillKey(this.selectedSkill)); this.skillEnabled = this.selectedSkill.enabled; this.skillDirectory = dirname(skillKey(this.selectedSkill)); if (this.skillDirectory === ".") this.skillDirectory = ""; this.open("skill-list"); } catch { /* Keep UI responsive; inability to move is visible on the unchanged list. */ } return; }
|
|
345
|
+
if (this.view === "mcp") { const server = this.mcpItems?.[this.selected]; if (server) { this.selectedMcp = server; this.open("mcp-detail"); } return; }
|
|
346
|
+
if (this.view === "mcp-detail") return;
|
|
347
|
+
if (this.view === "files" || this.view === "usage") return;
|
|
348
|
+
if (this.view === "diagrams") { const diagram = this.diagramItems?.[this.selected]; if (diagram) this.done({ type: "view-diagram", diagram }); return; }
|
|
349
|
+
if (this.view === "projects") {
|
|
350
|
+
if (this.selected === this.workspaces.length) { this.open("browser"); return; }
|
|
351
|
+
const next = this.workspaces[this.selected];
|
|
352
|
+
if (next) this.done({ type: "workspace", workspace: next });
|
|
353
|
+
return;
|
|
354
|
+
}
|
|
355
|
+
if (this.view === "browser") {
|
|
356
|
+
const next = this.browserEntries[this.selected];
|
|
357
|
+
if (next) this.openBrowser(this.browserPath ? join(this.browserPath, next.name) : next.name);
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
private setCurrentDirectory(): void {
|
|
362
|
+
if (this.browserPath) this.done({ type: "workspace", workspace: { name: basename(parse(this.browserPath).root === this.browserPath ? this.browserPath : this.browserPath) || this.browserPath, path: this.browserPath } });
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
render(_width: number): string[] {
|
|
366
|
+
const th = this.theme;
|
|
367
|
+
const inner = this.width - 2;
|
|
368
|
+
const row = (text: string) => th.fg("border", "│") + truncateToWidth(text, inner) + " ".repeat(Math.max(0, inner - visibleWidth(text))) + th.fg("border", "│");
|
|
369
|
+
const marker = (index: number) => index === this.selected ? th.fg("accent", "›") : " ";
|
|
370
|
+
const title = this.view === "home" ? "Terra Workspace" : this.view === "projects" ? "Projects" : this.view === "files" ? "Files" : this.view === "usage" ? "Usage & Cost" : this.view === "diagrams" ? "Diagram Gallery" : this.view === "skills" ? "Skill Library" : this.view === "skill-list" ? (this.skillEnabled ? "Enabled Skills" : "Disabled Skills") : this.view === "skill-detail" ? "Skill Details" : this.view === "skill-confirm" ? "Confirm Skill Change" : this.view === "mcp" ? "MCP Servers" : this.view === "mcp-detail" ? "MCP Server Details" : "Browse computer";
|
|
371
|
+
const lines = [th.fg("borderAccent", `╭─ ${title} ${"─".repeat(Math.max(0, inner - visibleWidth(title) - 3))}╮`)];
|
|
372
|
+
if (this.view === "home") {
|
|
373
|
+
lines.push(row(` ${th.fg("accent", "◈")} ${th.bold(this.workspace.name)}`));
|
|
374
|
+
lines.push(row(` ${th.fg("dim", this.workspace.path)}`));
|
|
375
|
+
lines.push(row(""));
|
|
376
|
+
for (const [i, label] of ["📁 Projects", "📄 Files", "🖥️ Browse computer…", "💰 Usage & Cost", "🗺️ Diagram Gallery", "🕘 Session Library", "✨ Skill Library", "🔌 MCP Servers"].entries()) lines.push(row(` ${marker(i)} ${th.fg("text", label)}`));
|
|
377
|
+
lines.push(row(""));
|
|
378
|
+
lines.push(row(th.fg("dim", "↑ ↓ select · Enter / → open · Esc / ← close")));
|
|
379
|
+
} else if (this.view === "projects") {
|
|
380
|
+
lines.push(row(th.fg("muted", "Saved project roots for this Session")));
|
|
381
|
+
lines.push(row(""));
|
|
382
|
+
for (let i = 0; i < this.workspaces.length; i++) { const item = this.workspaces[i]!; lines.push(row(` ${marker(i)} ${th.fg(i === this.selected ? "text" : "muted", item.name)}`)); lines.push(row(` ${th.fg("dim", item.path)}`)); }
|
|
383
|
+
lines.push(row(` ${marker(this.workspaces.length)} ${th.fg("accent", "Browse computer…")}`));
|
|
384
|
+
lines.push(row("")); lines.push(row(th.fg("dim", "Enter / → apply · Esc / ← back")));
|
|
385
|
+
} else if (this.view === "files") {
|
|
386
|
+
lines.push(row(th.fg("muted", "Current Workspace root · read-only"))); lines.push(row("")); this.renderItems(lines, row, marker, this.files || []); lines.push(row("")); lines.push(row(th.fg("dim", "Esc / ← back")));
|
|
387
|
+
} else if (this.view === "usage") {
|
|
388
|
+
const totals = sessionUsage(this.ctx), context = this.ctx.getContextUsage();
|
|
389
|
+
const estimated = this.pricing ? totals.input * this.pricing.input + totals.output * this.pricing.output + totals.cacheRead * (this.pricing.cacheRead ?? this.pricing.input) : undefined;
|
|
390
|
+
lines.push(row(th.fg("muted", "Current Session · local LiteLLM price estimate"))); lines.push(row(""));
|
|
391
|
+
for (const value of [`Model ${this.ctx.model?.id || "unknown"}`, `Input ${formatTokens(totals.input)} tokens`, `Output ${formatTokens(totals.output)} tokens`, `Cache read ${formatTokens(totals.cacheRead)} tokens`, `Context ${context?.tokens ?? "—"} / ${context?.contextWindow ?? "—"}`]) lines.push(row(value));
|
|
392
|
+
lines.push(row("")); lines.push(row(`${th.fg("accent", "Estimated")} ${estimated === undefined ? this.pricingLoading ? "loading local prices…" : "price unavailable" : `$${estimated.toFixed(4)}`}`)); lines.push(row(th.fg("dim", "Estimate only; not a provider invoice. Esc / ← back")));
|
|
393
|
+
} else if (this.view === "diagrams") {
|
|
394
|
+
const gallery = this.diagramItems || [];
|
|
395
|
+
lines.push(row(th.fg("muted", "Mermaid diagrams explicitly generated and registered by Pi"))); lines.push(row(""));
|
|
396
|
+
if (gallery.length) {
|
|
397
|
+
const start = Math.floor(this.selected / DIAGRAM_PAGE_SIZE) * DIAGRAM_PAGE_SIZE;
|
|
398
|
+
for (let i = start; i < Math.min(start + DIAGRAM_PAGE_SIZE, gallery.length); i++) { const diagram = gallery[i]!; lines.push(row(` ${marker(i)} ${th.fg(i === this.selected ? "accent" : "text", diagram.title)}`)); lines.push(row(` ${th.fg("dim", `${diagram.type || "mermaid"}${diagram.createdAt ? ` · ${diagram.createdAt}` : ""}`)}`)); }
|
|
399
|
+
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`)));
|
|
400
|
+
lines.push(row("")); lines.push(row(th.fg("dim", "Enter / → open in browser · Esc / ← back")));
|
|
401
|
+
} else { lines.push(row(th.fg("dim", "No Mermaid diagrams yet."))); lines.push(row(th.fg("dim", "Ask Pi to generate a Mermaid diagram; it will appear here."))); lines.push(row("")); lines.push(row(th.fg("dim", "Esc / ← back"))); }
|
|
402
|
+
} else if (this.view === "skills") {
|
|
403
|
+
const activeCount = (this.skillItems || []).filter((skill) => skill.enabled).length, disabledCount = (this.skillItems || []).length - activeCount;
|
|
404
|
+
lines.push(row(th.fg("muted", "Choose a library · disabled skills stay outside Pi discovery"))); lines.push(row(""));
|
|
405
|
+
lines.push(row(` ${marker(0)} ${th.fg("accent", `✨ Enabled skills · ${activeCount}`)}`));
|
|
406
|
+
lines.push(row(` ${marker(1)} ${th.fg("muted", `💤 Disabled skills · ${disabledCount}`)}`));
|
|
407
|
+
lines.push(row("")); lines.push(row(th.fg("dim", "Enter / → open · Esc / ← back")));
|
|
408
|
+
} else if (this.view === "skill-list") {
|
|
409
|
+
const list = this.skillEntryItems, location = this.skillDirectory || "Library root";
|
|
410
|
+
lines.push(row(th.fg("muted", `${this.skillEnabled ? "Enabled" : "Disabled"} · 📂 ${location}`))); lines.push(row(""));
|
|
411
|
+
if (!list.length) lines.push(row(th.fg("dim", "This folder is empty.")));
|
|
412
|
+
else for (let i = 0; i < list.length; i++) { const entry = list[i]!; if (entry.type === "folder") { const color = categoryColor(entry.relative), count = skillCount(join(this.skillEnabled ? SKILLS_DIR : DISABLED_SKILLS_DIR, entry.relative)); lines.push(row(` ${marker(i)} ${th.fg(color, `📂 ${entry.name}`)} ${th.fg("dim", `· ${count} skill${count === 1 ? "" : "s"}`)}`)); } else { const skill = entry.skill, category = categoryOf(skill), custom = displayName("skills", skillKey(skill), skill.name); lines.push(row(` ${marker(i)} ${th.fg(categoryColor(category), `${this.skillEnabled ? "✨" : "💤"} ${custom}`)}`)); lines.push(row(` ${th.fg("dim", labelsFor("skills", skillKey(skill)).note || skill.description)}`)); } }
|
|
413
|
+
const actionIndex = list.length;
|
|
414
|
+
if (this.skillDirectory) lines.push(row(` ${marker(actionIndex)} ${th.fg("warning", `${this.skillEnabled ? "💤 Disable" : "✨ Enable"} this folder`)}`));
|
|
415
|
+
lines.push(row(` ${marker(actionIndex + (this.skillDirectory ? 1 : 0))} ${th.fg("accent", "📂 Organize folders…")}`)); lines.push(row("")); lines.push(row(th.fg("dim", "Enter / → open/action · Esc / ← up")));
|
|
416
|
+
} else if (this.view === "skill-detail") {
|
|
417
|
+
const skill = this.selectedSkill;
|
|
418
|
+
if (skill) { const labels = labelsFor("skills", skillKey(skill)), category = categoryOf(skill), color = categoryColor(category); lines.push(row(`${th.fg(color, skill.enabled ? "✨ Enabled" : "💤 Disabled")} · ${th.fg(color, displayName("skills", skillKey(skill), skill.name))}`)); lines.push(row(th.fg(color, `📂 ${category}`))); lines.push(row("")); if (labels.note) { lines.push(row(th.fg("muted", labels.note))); lines.push(row("")); } lines.push(row(th.fg("dim", `Original: ${skill.name}`))); lines.push(row(th.fg("dim", skill.description))); lines.push(row("")); const actions = skill.enabled ? ["Use this skill now", "Edit display name", "Edit personal note", "Disable this skill"] : ["Edit display name", "Edit personal note", "Enable this skill"]; for (const [i, action] of actions.entries()) lines.push(row(` ${marker(i)} ${th.fg(i === this.selected ? "accent" : "text", action)}`)); }
|
|
419
|
+
lines.push(row("")); lines.push(row(th.fg("dim", "↑ ↓ select · Enter / → confirm · Esc / ← back")));
|
|
420
|
+
} else if (this.view === "skill-confirm") {
|
|
421
|
+
const skill = this.selectedSkill;
|
|
422
|
+
if (skill) { const action = skill.enabled ? "Disable" : "Enable"; lines.push(row(th.fg("accent", `⚠️ ${action} ${skill.name}?`))); lines.push(row("")); lines.push(row(th.fg("muted", skill.enabled ? "It will move to disabled-skills; nothing is deleted." : "It will move back to the active skills directory."))); lines.push(row(th.fg("muted", "Pi will apply the change after /reload."))); lines.push(row("")); lines.push(row(th.fg("accent", "Enter / → confirm · Esc / ← cancel"))); }
|
|
423
|
+
} else if (this.view === "mcp") {
|
|
424
|
+
const list = this.mcpItems || [];
|
|
425
|
+
lines.push(row(th.fg("muted", "🔌 Managed by the MCP plugin · cached discovered tools"))); lines.push(row(""));
|
|
426
|
+
if (!list.length) lines.push(row(th.fg("dim", "No cached MCP servers. Use the MCP plugin to discover them.")));
|
|
427
|
+
else for (let i = 0; i < list.length; i++) { const server = list[i]!; const labels = labelsFor("mcp", server.name); lines.push(row(` ${marker(i)} ${th.fg(i === this.selected ? "accent" : "text", `🔌 ${displayName("mcp", server.name, server.name)}`)}`)); lines.push(row(` ${th.fg("dim", labels.note || `${server.tools.length} cached tool${server.tools.length === 1 ? "" : "s"}`)}`)); }
|
|
428
|
+
lines.push(row("")); lines.push(row(th.fg("dim", "Enter / → tools · Esc / ← back")));
|
|
429
|
+
} else if (this.view === "mcp-detail") {
|
|
430
|
+
const server = this.selectedMcp;
|
|
431
|
+
if (server) { const labels = labelsFor("mcp", server.name); lines.push(row(th.fg("accent", `🔌 ${displayName("mcp", server.name, server.name)}`))); if (labels.note) lines.push(row(th.fg("muted", labels.note))); lines.push(row(th.fg("dim", `Original: ${server.name}`))); lines.push(row(th.fg("muted", `${server.tools.length} cached tool${server.tools.length === 1 ? "" : "s"} · secrets are never shown`))); lines.push(row("")); if (server.tools.length) { const start = Math.floor(this.selected / LIST_PAGE_SIZE) * LIST_PAGE_SIZE; for (let i = start; i < Math.min(start + LIST_PAGE_SIZE, server.tools.length); i++) { const tool = server.tools[i]!; lines.push(row(` ${marker(i)} ${th.fg("text", tool.name)}`)); if (tool.description) lines.push(row(` ${th.fg("dim", tool.description)}`)); } } else lines.push(row(th.fg("dim", "No cached tools."))); lines.push(row("")); lines.push(row(th.fg("dim", "N edit display name · O edit personal note"))); }
|
|
432
|
+
lines.push(row(th.fg("dim", "Read-only plugin cache · Esc / ← back")));
|
|
433
|
+
} else {
|
|
434
|
+
lines.push(row(th.fg("muted", this.browserPath || "Choose a drive"))); if (this.browserPath) lines.push(row(` ${th.fg("accent", "S")} set this folder as Workspace`)); lines.push(row("")); this.renderItems(lines, row, marker, this.browserEntries); lines.push(row("")); lines.push(row(th.fg("dim", this.browserPath ? "Enter / → folder · S select · Esc / ← up" : "Enter / → drive · Esc / ← back")));
|
|
435
|
+
}
|
|
436
|
+
lines.push(th.fg("borderAccent", `╰${"─".repeat(inner)}╯`)); return lines;
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
private renderItems(lines: string[], row: (text: string) => string, marker: (index: number) => string, values: FileItem[]): void {
|
|
440
|
+
if (!values.length) { lines.push(row(this.theme.fg("dim", " No readable folders here."))); return; }
|
|
441
|
+
const start = Math.floor(this.selected / LIST_PAGE_SIZE) * LIST_PAGE_SIZE;
|
|
442
|
+
const end = Math.min(start + LIST_PAGE_SIZE, values.length);
|
|
443
|
+
for (let i = start; i < end; i++) { const item = values[i]!; lines.push(row(` ${marker(i)} ${this.theme.fg(i === this.selected ? "text" : "muted", `${item.name}${item.directory && !item.name.endsWith("\\") ? "/" : ""}`)}`)); }
|
|
444
|
+
if (values.length > LIST_PAGE_SIZE) lines.push(row(this.theme.fg("dim", `Page ${Math.floor(start / LIST_PAGE_SIZE) + 1} / ${Math.ceil(values.length / LIST_PAGE_SIZE)} · ↑ ↓ to browse`)));
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
invalidate(): void {}
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
export default function workspaceDrawer(pi: ExtensionAPI) {
|
|
451
|
+
let workspace: Workspace | undefined;
|
|
452
|
+
const active = (ctx: ExtensionContext): Workspace => workspace || restoredWorkspace(ctx.sessionManager.getBranch(), ctx.cwd);
|
|
453
|
+
const restore = (ctx: ExtensionContext) => { workspace = restoredWorkspace(ctx.sessionManager.getBranch(), ctx.cwd); };
|
|
454
|
+
pi.on("session_start", async (_event, ctx) => restore(ctx));
|
|
455
|
+
pi.on("session_tree", async (_event, ctx) => restore(ctx));
|
|
456
|
+
pi.on("before_agent_start", async (event, ctx) => {
|
|
457
|
+
const root = active(ctx);
|
|
458
|
+
return { 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.\n` };
|
|
459
|
+
});
|
|
460
|
+
const open = async (ctx: ExtensionCommandContext): Promise<void> => {
|
|
461
|
+
if (ctx.mode !== "tui") return;
|
|
462
|
+
const current = active(ctx);
|
|
463
|
+
const result = await ctx.ui.custom<Result>((tui, theme, _keybindings, done) => new WorkspaceDrawer(ctx, current, configuredWorkspaces(ctx.cwd), theme, done, tui), {
|
|
464
|
+
overlay: true,
|
|
465
|
+
overlayOptions: { anchor: "right-center", width: 54, maxHeight: "100%", margin: { top: 1, right: 1, bottom: 1 } },
|
|
466
|
+
});
|
|
467
|
+
if (result?.type === "workspace") { workspace = result.workspace; pi.appendEntry(STATE_TYPE, workspace); ctx.ui.notify(`Workspace: ${workspace.name}`, "info"); }
|
|
468
|
+
else if (result?.type === "sessions") await openSessionLibrary(pi, ctx);
|
|
469
|
+
else if (result?.type === "organize-skills") { await organizeSkillFolders(ctx); await open(ctx); }
|
|
470
|
+
else if (result?.type === "use-skill") { ctx.ui.setEditorText(`/skill:${result.canonicalName} `); ctx.ui.notify("Skill command is ready in the editor. Add details, then submit.", "info"); }
|
|
471
|
+
else if (result?.type === "toggle-skill-folder") {
|
|
472
|
+
const action = result.enabled ? "Disable" : "Enable";
|
|
473
|
+
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.`);
|
|
474
|
+
if (approved) { 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"); } catch (error) { ctx.ui.notify(error instanceof Error ? error.message : "Could not move skill folder.", "error"); } }
|
|
475
|
+
await open(ctx);
|
|
476
|
+
}
|
|
477
|
+
else if (result?.type === "edit-label") {
|
|
478
|
+
const current = labelsFor(result.kind, result.key)[result.field] || "";
|
|
479
|
+
const next = result.field === "displayName" ? await ctx.ui.input(`Personal ${result.kind === "mcp" ? "MCP" : "skill"} display name`, current || result.fallback) : await ctx.ui.editor(`Personal note for ${result.fallback}`, current);
|
|
480
|
+
if (next !== undefined) { const data = resourceMetadata(); const collection = data[result.kind] || {}; const labels = { ...collection[result.key], [result.field]: next.trim() }; if (!labels.displayName && !labels.note) delete collection[result.key]; else collection[result.key] = labels; data[result.kind] = collection; saveResourceMetadata(data); ctx.ui.notify("Personal label saved. It is not sent to the model.", "info"); }
|
|
481
|
+
}
|
|
482
|
+
else if (result?.type === "view-diagram") {
|
|
483
|
+
const url = await openMermaidViewer(current.path, result.diagram);
|
|
484
|
+
ctx.ui.notify(url ? `Opened Mermaid Viewer: ${result.diagram.title}` : "This entry does not have a readable registered .mmd Mermaid source.", url ? "info" : "error");
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
};
|
|
488
|
+
pi.registerCommand("workspace", { description: "Open Terra Workspace Drawer", handler: async (_args, ctx) => await open(ctx) });
|
|
489
|
+
pi.registerShortcut(Key.alt("w"), { description: "Open Terra Workspace Drawer", handler: async (ctx) => await open(ctx as ExtensionCommandContext) });
|
|
490
|
+
}
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
import { existsSync, rmSync } from "node:fs";
|
|
2
|
+
import { SessionManager, type ExtensionAPI, type ExtensionCommandContext, type SessionInfo } from "@earendil-works/pi-coding-agent";
|
|
3
|
+
|
|
4
|
+
export const SESSION_DESCRIPTION_TYPE = "terra-session-description-v1";
|
|
5
|
+
export type SessionDescription = { text: string };
|
|
6
|
+
export type SessionStats = { user: number; assistant: number; toolCalls: number; toolResults: number; input: number; cacheRead: number; cacheWrite: number; output: number; hasUsage: boolean };
|
|
7
|
+
|
|
8
|
+
export function relativeTime(date: Date): string {
|
|
9
|
+
const seconds = Math.max(0, Math.floor((Date.now() - date.getTime()) / 1000));
|
|
10
|
+
if (seconds < 60) return "just now";
|
|
11
|
+
if (seconds < 3600) return `${Math.floor(seconds / 60)}m ago`;
|
|
12
|
+
if (seconds < 86400) return `${Math.floor(seconds / 3600)}h ago`;
|
|
13
|
+
return `${Math.floor(seconds / 86400)}d ago`;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export function sessionTitle(session: SessionInfo): string {
|
|
17
|
+
return session.name?.trim() || session.firstMessage.trim().replace(/\s+/g, " ").slice(0, 56) || "Untitled session";
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function formatTokens(value: number): string {
|
|
21
|
+
return new Intl.NumberFormat("en-US").format(value);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export async function listSessions(): Promise<SessionInfo[]> {
|
|
25
|
+
return (await SessionManager.listAll()).sort((a, b) => b.modified.getTime() - a.modified.getTime());
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function descriptionOf(path: string): string {
|
|
29
|
+
try {
|
|
30
|
+
const entries = SessionManager.open(path).getEntries();
|
|
31
|
+
for (let i = entries.length - 1; i >= 0; i--) {
|
|
32
|
+
const entry = entries[i];
|
|
33
|
+
if (entry?.type !== "custom" || entry.customType !== SESSION_DESCRIPTION_TYPE) continue;
|
|
34
|
+
const data = entry.data as SessionDescription | undefined;
|
|
35
|
+
if (typeof data?.text === "string") return data.text;
|
|
36
|
+
}
|
|
37
|
+
} catch { /* A damaged historical session must not block the library. */ }
|
|
38
|
+
return "";
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function statisticsOf(path: string): SessionStats {
|
|
42
|
+
const stats: SessionStats = { user: 0, assistant: 0, toolCalls: 0, toolResults: 0, input: 0, cacheRead: 0, cacheWrite: 0, output: 0, hasUsage: false };
|
|
43
|
+
try {
|
|
44
|
+
for (const entry of SessionManager.open(path).getEntries()) {
|
|
45
|
+
if (entry.type !== "message") continue;
|
|
46
|
+
const message = entry.message;
|
|
47
|
+
if (message.role === "user") stats.user++;
|
|
48
|
+
else if (message.role === "toolResult") stats.toolResults++;
|
|
49
|
+
else if (message.role === "assistant") {
|
|
50
|
+
stats.assistant++;
|
|
51
|
+
stats.toolCalls += message.content.filter((part) => part.type === "toolCall").length;
|
|
52
|
+
const usage = message.usage;
|
|
53
|
+
if (usage) {
|
|
54
|
+
stats.hasUsage = true;
|
|
55
|
+
stats.input += usage.input || 0;
|
|
56
|
+
stats.cacheRead += usage.cacheRead || 0;
|
|
57
|
+
stats.cacheWrite += usage.cacheWrite || 0;
|
|
58
|
+
stats.output += usage.output || 0;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
} catch { /* Zeroes communicate that unreadable historical data has no usable stats. */ }
|
|
63
|
+
return stats;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export function setSessionName(pi: ExtensionAPI, ctx: ExtensionCommandContext, path: string, current: boolean, name: string): void {
|
|
67
|
+
if (current) pi.setSessionName(name);
|
|
68
|
+
else SessionManager.open(path).appendSessionInfo(name);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export function setSessionDescription(pi: ExtensionAPI, ctx: ExtensionCommandContext, path: string, current: boolean, text: string): void {
|
|
72
|
+
const data = { text } satisfies SessionDescription;
|
|
73
|
+
if (current) pi.appendEntry(SESSION_DESCRIPTION_TYPE, data);
|
|
74
|
+
else SessionManager.open(path).appendCustomEntry(SESSION_DESCRIPTION_TYPE, data);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export function deleteSession(path: string, activePath: string | undefined): boolean {
|
|
78
|
+
if (path === activePath || !path.endsWith(".jsonl") || !existsSync(path)) return false;
|
|
79
|
+
rmSync(path);
|
|
80
|
+
return true;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function detailTitle(session: SessionInfo, current: boolean, description: string, stats: SessionStats): string {
|
|
84
|
+
const totalMessages = stats.user + stats.assistant + stats.toolResults;
|
|
85
|
+
const totalInput = stats.input + stats.cacheRead;
|
|
86
|
+
const totalTokens = totalInput + stats.output;
|
|
87
|
+
const cacheRate = totalInput ? ` (${((stats.cacheRead / totalInput) * 100).toFixed(1)}%)` : "";
|
|
88
|
+
const tokens = stats.hasUsage
|
|
89
|
+
? [`Input: ${formatTokens(totalInput)}`, ` Cached: ${formatTokens(stats.cacheRead)}${cacheRate}`, ` Uncached: ${formatTokens(stats.input)} (${formatTokens(stats.cacheWrite)} written to cache)`, `Output: ${formatTokens(stats.output)}`, `Total: ${formatTokens(totalTokens)}`]
|
|
90
|
+
: ["Usage data: —"];
|
|
91
|
+
return [current ? "Current session" : "Historical session", `Name: ${sessionTitle(session)}`, `Description: ${description || "—"}`, `Updated: ${relativeTime(session.modified)}`, `Workspace: ${session.cwd || "—"}`, "", "Messages", `Total: ${formatTokens(totalMessages)}`, `User: ${formatTokens(stats.user)}`, `Assistant: ${formatTokens(stats.assistant)}`, `Tools: ${formatTokens(stats.toolCalls)} calls, ${formatTokens(stats.toolResults)} results`, "", "Tokens", ...tokens].join("\n");
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export async function openSessionLibrary(pi: ExtensionAPI, ctx: ExtensionCommandContext): Promise<void> {
|
|
95
|
+
if (ctx.mode !== "tui") return;
|
|
96
|
+
while (true) {
|
|
97
|
+
const currentPath = ctx.sessionManager.getSessionFile();
|
|
98
|
+
const available = await listSessions();
|
|
99
|
+
if (!available.length) { ctx.ui.notify("No persisted Pi sessions found.", "info"); return; }
|
|
100
|
+
const options = available.map((session) => `${sessionTitle(session)} — ${relativeTime(session.modified)} · ${session.messageCount} messages${session.path === currentPath ? " ● current" : ""}`);
|
|
101
|
+
const choice = await ctx.ui.select("Session Library", [...options, "Cancel"]);
|
|
102
|
+
if (!choice || choice === "Cancel") return;
|
|
103
|
+
const session = available[options.indexOf(choice)];
|
|
104
|
+
if (!session) continue;
|
|
105
|
+
if (await manageSession(pi, ctx, session, currentPath) === "switch") return;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
async function manageSession(pi: ExtensionAPI, ctx: ExtensionCommandContext, initial: SessionInfo, currentPath: string | undefined): Promise<"back" | "switch"> {
|
|
110
|
+
let session = initial;
|
|
111
|
+
while (true) {
|
|
112
|
+
const current = session.path === currentPath;
|
|
113
|
+
const description = descriptionOf(session.path);
|
|
114
|
+
const stats = statisticsOf(session.path);
|
|
115
|
+
const actions = current ? ["Edit name", "Edit description", "Back"] : ["Reload in this window", "Edit name", "Edit description", "Delete session", "Back"];
|
|
116
|
+
const selected = await ctx.ui.select(detailTitle(session, current, description, stats), actions);
|
|
117
|
+
if (!selected || selected === "Back") return "back";
|
|
118
|
+
if (selected === "Edit name") {
|
|
119
|
+
const next = await ctx.ui.input("Session name", session.name || sessionTitle(session));
|
|
120
|
+
if (next?.trim()) { setSessionName(pi, ctx, session.path, current, next.trim()); ctx.ui.notify("Session name saved.", "info"); session = (await listSessions()).find((item) => item.path === session.path) || session; }
|
|
121
|
+
continue;
|
|
122
|
+
}
|
|
123
|
+
if (selected === "Edit description") {
|
|
124
|
+
const next = await ctx.ui.editor("Session description", description);
|
|
125
|
+
if (next !== undefined) { setSessionDescription(pi, ctx, session.path, current, next.trim()); ctx.ui.notify("Session description saved.", "info"); }
|
|
126
|
+
continue;
|
|
127
|
+
}
|
|
128
|
+
if (selected === "Reload in this window") {
|
|
129
|
+
await ctx.waitForIdle();
|
|
130
|
+
const result = await ctx.switchSession(session.path, { withSession: async (replacement) => replacement.ui.notify(`Reloaded: ${sessionTitle(session)}`, "info") });
|
|
131
|
+
return result.cancelled ? "back" : "switch";
|
|
132
|
+
}
|
|
133
|
+
if (selected === "Delete session") {
|
|
134
|
+
if (session.path === ctx.sessionManager.getSessionFile()) { ctx.ui.notify("The active session cannot be deleted.", "warning"); continue; }
|
|
135
|
+
const approved = await ctx.ui.confirm("Delete session?", `Permanently delete “${sessionTitle(session)}”? This cannot be undone.`);
|
|
136
|
+
if (!approved) continue;
|
|
137
|
+
if (!deleteSession(session.path, ctx.sessionManager.getSessionFile())) { ctx.ui.notify("The active or unavailable session cannot be deleted.", "warning"); continue; }
|
|
138
|
+
ctx.ui.notify("Session deleted.", "info");
|
|
139
|
+
return "back";
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "pi-arsenal",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "A polished workspace for Pi: sessions, skills, MCP, tasks, themes, and splash.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"keywords": [
|
|
8
|
+
"pi-package",
|
|
9
|
+
"pi",
|
|
10
|
+
"pi-coding-agent",
|
|
11
|
+
"tui",
|
|
12
|
+
"workspace",
|
|
13
|
+
"skills",
|
|
14
|
+
"sessions"
|
|
15
|
+
],
|
|
16
|
+
"files": [
|
|
17
|
+
"extensions",
|
|
18
|
+
"lib",
|
|
19
|
+
"themes",
|
|
20
|
+
"README.md",
|
|
21
|
+
"LICENSE"
|
|
22
|
+
],
|
|
23
|
+
"peerDependencies": {
|
|
24
|
+
"@earendil-works/pi-ai": "*",
|
|
25
|
+
"@earendil-works/pi-coding-agent": "*",
|
|
26
|
+
"@earendil-works/pi-tui": "*"
|
|
27
|
+
},
|
|
28
|
+
"pi": {
|
|
29
|
+
"extensions": ["./extensions"],
|
|
30
|
+
"themes": ["./themes"]
|
|
31
|
+
},
|
|
32
|
+
"repository": {
|
|
33
|
+
"type": "git",
|
|
34
|
+
"url": "git+https://github.com/SeiyunSky/Pi-Arsenal.git"
|
|
35
|
+
}
|
|
36
|
+
}
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "https://raw.githubusercontent.com/earendil-works/pi/main/packages/coding-agent/src/modes/interactive/theme/theme-schema.json",
|
|
3
|
+
"name": "tokyo-night-terra",
|
|
4
|
+
"vars": {
|
|
5
|
+
"bg": "#1a1b2e",
|
|
6
|
+
"surface": "#24283b",
|
|
7
|
+
"surfaceRaised": "#2f354f",
|
|
8
|
+
"selection": "#33467c",
|
|
9
|
+
"border": "#3b4261",
|
|
10
|
+
"muted": "#7a83a6",
|
|
11
|
+
"dim": "#565f89",
|
|
12
|
+
"text": "#c0caf5",
|
|
13
|
+
"terra": "#bb9af7",
|
|
14
|
+
"blue": "#7aa2f7",
|
|
15
|
+
"cyan": "#7dcfff",
|
|
16
|
+
"teal": "#73daca",
|
|
17
|
+
"green": "#9ece6a",
|
|
18
|
+
"yellow": "#e0af68",
|
|
19
|
+
"orange": "#ff9e64",
|
|
20
|
+
"red": "#f7768e",
|
|
21
|
+
"magenta": "#c099ff"
|
|
22
|
+
},
|
|
23
|
+
"colors": {
|
|
24
|
+
"accent": "terra",
|
|
25
|
+
"border": "border",
|
|
26
|
+
"borderAccent": "terra",
|
|
27
|
+
"borderMuted": "dim",
|
|
28
|
+
"success": "green",
|
|
29
|
+
"error": "red",
|
|
30
|
+
"warning": "yellow",
|
|
31
|
+
"muted": "muted",
|
|
32
|
+
"dim": "dim",
|
|
33
|
+
"text": "text",
|
|
34
|
+
"thinkingText": "muted",
|
|
35
|
+
"selectedBg": "selection",
|
|
36
|
+
"scrollbarTrack": "surface",
|
|
37
|
+
"scrollbarThumb": "blue",
|
|
38
|
+
"searchMatchBg": "yellow",
|
|
39
|
+
"searchMatchText": "bg",
|
|
40
|
+
"userMessageBg": "#20243a",
|
|
41
|
+
"userMessageText": "text",
|
|
42
|
+
"customMessageBg": "#28243d",
|
|
43
|
+
"customMessageText": "text",
|
|
44
|
+
"customMessageLabel": "terra",
|
|
45
|
+
"toolPendingBg": "#20273d",
|
|
46
|
+
"toolSuccessBg": "#1f302f",
|
|
47
|
+
"toolErrorBg": "#382536",
|
|
48
|
+
"toolTitle": "cyan",
|
|
49
|
+
"toolOutput": "muted",
|
|
50
|
+
"mdHeading": "terra",
|
|
51
|
+
"mdLink": "blue",
|
|
52
|
+
"mdLinkUrl": "dim",
|
|
53
|
+
"mdCode": "teal",
|
|
54
|
+
"mdCodeBlock": "text",
|
|
55
|
+
"mdCodeBlockBorder": "border",
|
|
56
|
+
"mdQuote": "muted",
|
|
57
|
+
"mdQuoteBorder": "blue",
|
|
58
|
+
"mdHr": "border",
|
|
59
|
+
"mdListBullet": "cyan",
|
|
60
|
+
"toolDiffAdded": "green",
|
|
61
|
+
"toolDiffRemoved": "red",
|
|
62
|
+
"toolDiffContext": "muted",
|
|
63
|
+
"syntaxComment": "dim",
|
|
64
|
+
"syntaxKeyword": "terra",
|
|
65
|
+
"syntaxFunction": "blue",
|
|
66
|
+
"syntaxVariable": "text",
|
|
67
|
+
"syntaxString": "green",
|
|
68
|
+
"syntaxNumber": "orange",
|
|
69
|
+
"syntaxType": "cyan",
|
|
70
|
+
"syntaxOperator": "teal",
|
|
71
|
+
"syntaxPunctuation": "muted",
|
|
72
|
+
"thinkingOff": "dim",
|
|
73
|
+
"thinkingMinimal": "muted",
|
|
74
|
+
"thinkingLow": "blue",
|
|
75
|
+
"thinkingMedium": "cyan",
|
|
76
|
+
"thinkingHigh": "terra",
|
|
77
|
+
"thinkingXhigh": "magenta",
|
|
78
|
+
"thinkingMax": "red",
|
|
79
|
+
"bashMode": "green"
|
|
80
|
+
},
|
|
81
|
+
"export": {
|
|
82
|
+
"pageBg": "#1a1b2e",
|
|
83
|
+
"cardBg": "#24283b",
|
|
84
|
+
"infoBg": "#2f2a42"
|
|
85
|
+
}
|
|
86
|
+
}
|