pi-arsenal 0.3.0 → 0.4.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.
@@ -0,0 +1,74 @@
1
+ import { spawn } from "node:child_process";
2
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
3
+ import { Type } from "typebox";
4
+
5
+ // ─── Toast via WinRT ──────────────────────────────────────────────────────────
6
+ // Uses Windows.UI.Notifications WinRT API (available on Windows 10/11).
7
+ // Falls back to a simple `msg %USERNAME%` if WinRT fails.
8
+
9
+ const APP_ID = "Pi Arsenal";
10
+
11
+ function escapeXml(s: string): string {
12
+ return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
13
+ }
14
+
15
+ function sendToast(title: string, body: string, urgency: "info" | "warning" | "error"): Promise<void> {
16
+ const scenario = urgency === "error" ? "urgent" : urgency === "warning" ? "reminder" : "default";
17
+ // WinRT XML template
18
+ const xml = `<toast scenario="${scenario}"><visual><binding template="ToastGeneric"><text>${escapeXml(title)}</text><text>${escapeXml(body)}</text></binding></visual></toast>`;
19
+ const ps = `
20
+ $xml = '${xml.replace(/'/g, "''")}';
21
+ $dom = New-Object Windows.Data.Xml.Dom.XmlDocument;
22
+ $dom.LoadXml($xml);
23
+ [Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType=WindowsRuntime] | Out-Null;
24
+ [Windows.Data.Xml.Dom.XmlDocument, Windows.Data.Xml.Dom, ContentType=WindowsRuntime] | Out-Null;
25
+ $toast = [Windows.UI.Notifications.ToastNotification]::new($dom);
26
+ $notifier = [Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier('${APP_ID.replace(/'/g, "''")}');
27
+ $notifier.Show($toast);
28
+ `;
29
+ return new Promise((resolve) => {
30
+ const proc = spawn("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", ps], { stdio: "ignore" });
31
+ proc.on("close", (code) => {
32
+ if (code !== 0) sendFallback(title, body).then(resolve);
33
+ else resolve();
34
+ });
35
+ proc.on("error", () => sendFallback(title, body).then(resolve));
36
+ });
37
+ }
38
+
39
+ function sendFallback(title: string, body: string): Promise<void> {
40
+ // msg.exe: works on all Windows versions, shows a dialog to the current user session.
41
+ return new Promise((resolve) => {
42
+ const text = `${title}\n\n${body}`;
43
+ const proc = spawn("msg.exe", ["%USERNAME%", text], { stdio: "ignore" });
44
+ proc.on("close", () => resolve());
45
+ proc.on("error", () => resolve()); // silent fail — notification is best-effort
46
+ });
47
+ }
48
+
49
+ // ─── Extension ────────────────────────────────────────────────────────────────
50
+
51
+ export default function piNotify(pi: ExtensionAPI) {
52
+ pi.registerTool({
53
+ name: "pi_notify",
54
+ description:
55
+ "Send a desktop notification to the user via the Windows notification system. " +
56
+ "Use this after completing a long-running task (build, install, test run, file generation) " +
57
+ "so the user is informed even if they stepped away. " +
58
+ "Keep title short (≤ 48 chars) and body concise (≤ 120 chars). " +
59
+ "Do NOT use for every message — only for genuinely async completions or important alerts.",
60
+ parameters: Type.Object({
61
+ title: Type.String({ description: "Short notification title, e.g. 'Build complete' or 'Tests failed'." }),
62
+ body: Type.String({ description: "One or two sentence summary of what happened and what to do next." }),
63
+ urgency: Type.Union(
64
+ [Type.Literal("info"), Type.Literal("warning"), Type.Literal("error")],
65
+ { description: "info = task done normally; warning = completed with issues; error = failed." }
66
+ ),
67
+ }),
68
+ async execute(_id, input, _signal, _onUpdate, _ctx) {
69
+ const { title, body, urgency } = input as { title: string; body: string; urgency: "info" | "warning" | "error" };
70
+ await sendToast(title.slice(0, 128), body.slice(0, 256), urgency);
71
+ return { content: [{ type: "text" as const, text: `Notification sent: "${title}"` }] };
72
+ },
73
+ });
74
+ }
@@ -0,0 +1,165 @@
1
+ import type { ExtensionAPI, ExtensionCommandContext, Theme } from "@earendil-works/pi-coding-agent";
2
+ import { Key, matchesKey, truncateToWidth, visibleWidth, type Focusable } from "@earendil-works/pi-tui";
3
+
4
+ // ─── Bridge ───────────────────────────────────────────────────────────────────
5
+
6
+ const TASK_BRIDGE_KEY = Symbol.for("pi-arsenal.task-panel.bridge.v1");
7
+
8
+ type PlanStatus = "pending" | "in_progress" | "completed";
9
+ type PlanStep = { id: string; goal: string; status: PlanStatus };
10
+ type TaskBridge = { getSteps(): PlanStep[]; cancelPlan(): void };
11
+
12
+ function getTaskBridge(): TaskBridge | undefined {
13
+ return (globalThis as Record<symbol, unknown>)[TASK_BRIDGE_KEY] as TaskBridge | undefined;
14
+ }
15
+
16
+ // ─── Layout ───────────────────────────────────────────────────────────────────
17
+
18
+ const WIDTH = 56;
19
+ const INNER = WIDTH - 2;
20
+
21
+ // ─── Overlay component ────────────────────────────────────────────────────────
22
+
23
+ class TaskOverlay implements Focusable {
24
+ readonly width = WIDTH;
25
+ focused = false;
26
+
27
+ private scrollTop = 0; // first visible step index
28
+ private readonly pageSize = 14;
29
+
30
+ constructor(
31
+ private readonly steps: PlanStep[],
32
+ private readonly theme: Theme,
33
+ private readonly done: (cancelled: boolean) => void,
34
+ ) {}
35
+
36
+ private get completed(): number { return this.steps.filter((s) => s.status === "completed").length; }
37
+ private get active(): PlanStep | undefined { return this.steps.find((s) => s.status === "in_progress"); }
38
+ private get hasActive(): boolean { return this.steps.some((s) => s.status !== "completed"); }
39
+
40
+ handleInput(data: string): void {
41
+ if (matchesKey(data, Key.escape) || matchesKey(data, "q")) { this.done(false); return; }
42
+
43
+ // Scroll
44
+ if (matchesKey(data, Key.up) || matchesKey(data, "k")) {
45
+ this.scrollTop = Math.max(0, this.scrollTop - 1); return;
46
+ }
47
+ if (matchesKey(data, Key.down) || matchesKey(data, "j")) {
48
+ this.scrollTop = Math.min(Math.max(0, this.steps.length - this.pageSize), this.scrollTop + 1); return;
49
+ }
50
+ // Cancel plan
51
+ if ((matchesKey(data, Key.enter) || matchesKey(data, "c")) && this.hasActive) {
52
+ this.done(true); return;
53
+ }
54
+ }
55
+
56
+ render(_width: number): string[] {
57
+ const th = this.theme;
58
+ const row = (text: string): string =>
59
+ th.fg("border", "│") + text + " ".repeat(Math.max(0, INNER - visibleWidth(text))) + th.fg("border", "│");
60
+
61
+ const completed = this.completed;
62
+ const total = this.steps.length;
63
+ const pct = total ? Math.round((completed / total) * 100) : 0;
64
+
65
+ // Progress bar
66
+ const barWidth = INNER - 14;
67
+ const filled = Math.round((completed / Math.max(1, total)) * barWidth);
68
+ const bar = th.fg("success", "█".repeat(filled)) + th.fg("dim", "░".repeat(barWidth - filled));
69
+
70
+ // Header
71
+ const headerText = `Tasks ${completed}/${total} ${pct}%`;
72
+ const lines: string[] = [
73
+ th.fg("borderAccent", `╭─ ${th.bold(headerText)} ${"─".repeat(Math.max(0, INNER - visibleWidth(headerText) - 3))}╮`),
74
+ row(""),
75
+ row(` ${bar}`),
76
+ row(""),
77
+ ];
78
+
79
+ // Active step callout
80
+ const act = this.active;
81
+ if (act) {
82
+ lines.push(row(` ${th.fg("warning", "▶")} ${th.fg("warning", th.bold(truncateToWidth(act.goal, INNER - 4)))}`));
83
+ lines.push(row(` ${th.fg("dim", " currently in progress")}`));
84
+ lines.push(row(""));
85
+ }
86
+
87
+ // Step list (paginated)
88
+ const visible = this.steps.slice(this.scrollTop, this.scrollTop + this.pageSize);
89
+ for (let i = 0; i < visible.length; i++) {
90
+ const step = visible[i]!;
91
+ const absIdx = this.scrollTop + i;
92
+ const isActive = step.status === "in_progress";
93
+ const icon =
94
+ step.status === "completed" ? th.fg("success", "✓") :
95
+ isActive ? th.fg("warning", "●") :
96
+ th.fg("dim", "○");
97
+ const num = th.fg("dim", `${String(absIdx + 1).padStart(2)}.`);
98
+ const goal = isActive
99
+ ? th.fg("warning", th.bold(truncateToWidth(step.goal, INNER - 7)))
100
+ : step.status === "completed"
101
+ ? th.fg("muted", truncateToWidth(step.goal, INNER - 7))
102
+ : th.fg("text", truncateToWidth(step.goal, INNER - 7));
103
+ lines.push(row(` ${num} ${icon} ${goal}`));
104
+ }
105
+
106
+ // Scroll indicator
107
+ if (this.steps.length > this.pageSize) {
108
+ const page = Math.floor(this.scrollTop / this.pageSize) + 1;
109
+ const totalPages = Math.ceil(this.steps.length / this.pageSize);
110
+ lines.push(row(""));
111
+ lines.push(row(th.fg("dim", ` Page ${page} / ${totalPages} ↑ ↓ scroll`)));
112
+ }
113
+
114
+ // Footer
115
+ lines.push(row(""));
116
+ if (this.hasActive) {
117
+ lines.push(row(th.fg("dim", " C / Enter cancel plan · Q / Esc close")));
118
+ } else {
119
+ lines.push(row(th.fg("success", " Plan complete — all steps done")));
120
+ lines.push(row(th.fg("dim", " Q / Esc close")));
121
+ }
122
+
123
+ lines.push(th.fg("borderAccent", `╰${"─".repeat(INNER)}╯`));
124
+ return lines;
125
+ }
126
+
127
+ invalidate(): void {}
128
+ }
129
+
130
+ // ─── Extension ────────────────────────────────────────────────────────────────
131
+
132
+ async function openOverlay(ctx: ExtensionCommandContext): Promise<void> {
133
+ if (ctx.mode !== "tui") return;
134
+ const bridge = getTaskBridge();
135
+ const steps = bridge?.getSteps() ?? [];
136
+
137
+ if (!steps.length) { ctx.ui.notify("No active plan.", "info"); return; }
138
+
139
+ const cancelled = await ctx.ui.custom<boolean>(
140
+ (_tui, theme, _kb, done) => new TaskOverlay(steps, theme, done),
141
+ { overlay: true, overlayOptions: { anchor: "right-center", width: WIDTH + 2, maxHeight: "100%", margin: { top: 1, right: 1, bottom: 1 } } },
142
+ );
143
+
144
+ if (cancelled && bridge) {
145
+ const confirmed = await ctx.ui.confirm(
146
+ "Cancel plan?",
147
+ "Mark all remaining steps completed so the model is free to start a new plan.",
148
+ );
149
+ if (confirmed) {
150
+ bridge.cancelPlan();
151
+ ctx.ui.notify("Plan cancelled. The model may now start a new plan.", "info");
152
+ }
153
+ }
154
+ }
155
+
156
+ export default function taskOverlay(pi: ExtensionAPI) {
157
+ pi.registerCommand("task-overlay", {
158
+ description: "Show full task plan in an overlay panel",
159
+ handler: async (_args, ctx) => openOverlay(ctx),
160
+ });
161
+ pi.registerShortcut(Key.alt("t"), {
162
+ description: "Show task plan overlay (Alt+T)",
163
+ handler: async (ctx) => openOverlay(ctx as ExtensionCommandContext),
164
+ });
165
+ }
@@ -87,6 +87,9 @@ function approvalFromChoices(event: { toolName: string; content: Array<{ type: s
87
87
  }
88
88
  }
89
89
 
90
+ const TASK_BRIDGE_KEY = Symbol.for("pi-arsenal.task-panel.bridge.v1");
91
+ type TaskBridge = { getSteps(): PlanStep[]; cancelPlan(): void };
92
+
90
93
  export default function taskPanel(pi: ExtensionAPI) {
91
94
  let steps: PlanStep[] = [];
92
95
  let planChangeAuthorized = false;
@@ -120,6 +123,15 @@ export default function taskPanel(pi: ExtensionAPI) {
120
123
 
121
124
  pi.on("session_start", async (_event, ctx) => restore(ctx));
122
125
  pi.on("session_tree", async (_event, ctx) => restore(ctx));
126
+
127
+ // Publish bridge so task-overlay can read steps without import coupling.
128
+ const bridge: TaskBridge = {
129
+ getSteps: () => steps,
130
+ cancelPlan: () => {
131
+ steps = steps.map((s) => ({ ...s, status: "completed" as const }));
132
+ },
133
+ };
134
+ (globalThis as Record<symbol, unknown>)[TASK_BRIDGE_KEY] = bridge;
123
135
  pi.on("before_agent_start", async (event) => {
124
136
  if (!isActivePlan(steps)) return;
125
137
  event.systemPromptOptions.customInstructions = [event.systemPromptOptions.customInstructions, TASK_DISCIPLINE].filter(Boolean).join("\n\n");