@narumitw/pi-notes 0.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/menu.ts ADDED
@@ -0,0 +1,179 @@
1
+ import type { ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
2
+ import { type MenuDefinition, runMenu, sanitizeTerminalText } from "@narumitw/pi-tui-kit";
3
+ import type { DiscoveryResult, MarkdownEntry, NotesStorage } from "./storage.js";
4
+
5
+ interface NotesMenuState {
6
+ notes: DiscoveryResult;
7
+ templates: DiscoveryResult;
8
+ }
9
+
10
+ type NotesScreen = "notes" | "templates" | "path";
11
+ type NotesAction = "chooseNote" | "chooseTemplate" | "createNote";
12
+
13
+ export interface NotesManagerResult {
14
+ kind: "open" | "closed";
15
+ notePath?: string;
16
+ }
17
+
18
+ export function createNotesMenu(storage: NotesStorage) {
19
+ let selectedTemplate: string | undefined;
20
+ let selectedNote: string | undefined;
21
+
22
+ const getState = async ({ signal }: { signal: AbortSignal }): Promise<NotesMenuState> => {
23
+ const notes = await storage.discoverNotes(signal);
24
+ if (signal.aborted) throw signal.reason;
25
+ const templates = await storage.discoverTemplates(signal);
26
+ return { notes, templates };
27
+ };
28
+
29
+ const menu: MenuDefinition<NotesMenuState, NotesScreen, NotesAction> = {
30
+ start: "notes",
31
+ screens: {
32
+ notes: ({ state }) => ({
33
+ kind: "choice",
34
+ title: `Pi Notes · ${state.notes.entries.length} note${state.notes.entries.length === 1 ? "" : "s"}`,
35
+ lines: discoveryLines(state.notes, "note"),
36
+ items: [
37
+ {
38
+ id: "create",
39
+ label: "Create a note…",
40
+ description: "Start blank or copy a user template.",
41
+ searchText: "new create blank template",
42
+ },
43
+ ...state.notes.entries.map((note, index) => ({
44
+ id: `note:${index}`,
45
+ label: note.displayPath,
46
+ description: `${note.size} bytes`,
47
+ searchText: note.displayPath,
48
+ })),
49
+ ],
50
+ action: "chooseNote",
51
+ enableSearch: state.notes.entries.length > 8,
52
+ viewportSize: 12,
53
+ hint: "close",
54
+ }),
55
+ templates: ({ state }) => ({
56
+ kind: "choice",
57
+ title: "Choose initial content",
58
+ lines: discoveryLines(state.templates, "template"),
59
+ items: [
60
+ {
61
+ id: "blank",
62
+ label: "Blank",
63
+ description: "Create an empty Markdown note.",
64
+ },
65
+ ...state.templates.entries.map((template, index) => ({
66
+ id: `template:${index}`,
67
+ label: template.displayPath,
68
+ description: `${template.size} bytes`,
69
+ searchText: template.displayPath,
70
+ })),
71
+ ],
72
+ action: "chooseTemplate",
73
+ enableSearch: state.templates.entries.length > 8,
74
+ viewportSize: 12,
75
+ hint: "back",
76
+ }),
77
+ path: () => ({
78
+ kind: "input",
79
+ title: "New note path",
80
+ lines: [
81
+ "Enter a relative Markdown path below pi-notes/notes.",
82
+ selectedTemplate ? `Template: ${sanitizeTerminalText(selectedTemplate)}` : "Template: Blank",
83
+ ],
84
+ placeholder: "topic.md or folder/topic.md",
85
+ action: "createNote",
86
+ hint: "back",
87
+ }),
88
+ },
89
+ actions: {
90
+ chooseNote: ({ state, itemId }) => {
91
+ if (itemId === "create") return { kind: "to", screen: "templates" };
92
+ const note = indexedEntry(state.notes.entries, itemId, "note:");
93
+ if (!note) return { kind: "rejected", error: new Error("The selected note is no longer available") };
94
+ selectedNote = note.relativePath;
95
+ return { kind: "close" };
96
+ },
97
+ chooseTemplate: ({ state, itemId }) => {
98
+ if (itemId === "blank") {
99
+ selectedTemplate = undefined;
100
+ return { kind: "to", screen: "path" };
101
+ }
102
+ const template = indexedEntry(state.templates.entries, itemId, "template:");
103
+ if (!template) {
104
+ return { kind: "rejected", error: new Error("The selected template is no longer available") };
105
+ }
106
+ selectedTemplate = template.relativePath;
107
+ return { kind: "to", screen: "path" };
108
+ },
109
+ createNote: async ({ value, signal }) => {
110
+ if (typeof value !== "string") return { kind: "rejected", error: new Error("Note path is required") };
111
+ const note = await storage.createNote(value, { templatePath: selectedTemplate, signal });
112
+ if (signal.aborted) return { kind: "close" };
113
+ selectedNote = note.relativePath;
114
+ return { kind: "close" };
115
+ },
116
+ },
117
+ };
118
+
119
+ return {
120
+ menu,
121
+ getState,
122
+ getSelectedNote: () => selectedNote,
123
+ };
124
+ }
125
+
126
+ export async function showNotesManager(
127
+ ctx: ExtensionCommandContext,
128
+ storage: NotesStorage,
129
+ ownership: { signal: AbortSignal; isCurrent(): boolean },
130
+ ): Promise<NotesManagerResult> {
131
+ const controller = createNotesMenu(storage);
132
+ const result = await runMenu(ctx, controller.menu, {
133
+ getState: controller.getState,
134
+ signal: ownership.signal,
135
+ isCurrent: ownership.isCurrent,
136
+ onError: (currentCtx, error) => {
137
+ if (!ownership.signal.aborted && ownership.isCurrent()) {
138
+ safeNotify(currentCtx, `Pi Notes failed: ${safeErrorMessage(error)}`, "error");
139
+ }
140
+ },
141
+ });
142
+ if (result.kind === "error") throw result.error;
143
+ const selected = controller.getSelectedNote();
144
+ return selected && ownership.isCurrent() && !ownership.signal.aborted
145
+ ? { kind: "open", notePath: selected }
146
+ : { kind: "closed" };
147
+ }
148
+
149
+ function indexedEntry(entries: readonly MarkdownEntry[], itemId: string, prefix: string): MarkdownEntry | undefined {
150
+ if (!itemId.startsWith(prefix)) return undefined;
151
+ const index = Number.parseInt(itemId.slice(prefix.length), 10);
152
+ return Number.isSafeInteger(index) && index >= 0 ? entries[index] : undefined;
153
+ }
154
+
155
+ function discoveryLines(result: DiscoveryResult, noun: string): string[] | undefined {
156
+ if (result.errors.length === 0 && !result.limited) {
157
+ return result.entries.length === 0 ? [`No ${noun}s found.`] : undefined;
158
+ }
159
+ const lines = result.errors.slice(0, 3).map((error) => {
160
+ const path = error.relativePath ? `${sanitizeTerminalText(error.relativePath)}: ` : "";
161
+ return `${path}${sanitizeTerminalText(error.message)}`;
162
+ });
163
+ if (result.errors.length > lines.length)
164
+ lines.push(`${result.errors.length - lines.length} more issue(s) not shown.`);
165
+ if (result.limited) lines.push("Discovery reached a safety limit; some entries are not shown.");
166
+ return lines;
167
+ }
168
+
169
+ function safeNotify(ctx: ExtensionCommandContext, message: string, level: "info" | "warning" | "error"): void {
170
+ try {
171
+ ctx.ui.notify(sanitizeTerminalText(message), level);
172
+ } catch {
173
+ // A replaced parent session must not keep an obsolete command continuation alive.
174
+ }
175
+ }
176
+
177
+ function safeErrorMessage(error: unknown): string {
178
+ return sanitizeTerminalText(error instanceof Error ? error.message : String(error));
179
+ }
@@ -0,0 +1,134 @@
1
+ import {
2
+ type ExtensionAPI,
3
+ type ExtensionCommandContext,
4
+ type ExtensionContext,
5
+ getAgentDir,
6
+ } from "@earendil-works/pi-coding-agent";
7
+ import type { NotesManagerResult } from "./menu.js";
8
+ import { NotesStorage } from "./storage.js";
9
+ import type { OpenNotesWorkspaceOptions } from "./workspace.js";
10
+
11
+ interface NotesExtensionDependencies {
12
+ getAgentDir(): string;
13
+ createStorage(agentDir: string): NotesStorage;
14
+ showManager(
15
+ ctx: ExtensionCommandContext,
16
+ storage: NotesStorage,
17
+ ownership: { signal: AbortSignal; isCurrent(): boolean },
18
+ ): Promise<NotesManagerResult>;
19
+ openWorkspace(options: OpenNotesWorkspaceOptions): Promise<void>;
20
+ }
21
+
22
+ export function createNotesExtension(
23
+ dependencies: Partial<NotesExtensionDependencies> = {},
24
+ ): (pi: ExtensionAPI) => void {
25
+ const deps: NotesExtensionDependencies = {
26
+ getAgentDir: dependencies.getAgentDir ?? getAgentDir,
27
+ createStorage: dependencies.createStorage ?? ((agentDir) => new NotesStorage(agentDir)),
28
+ showManager:
29
+ dependencies.showManager ??
30
+ (async (ctx, storage, ownership) => {
31
+ const { showNotesManager } = await import("./menu.js");
32
+ if (ownership.signal.aborted || !ownership.isCurrent()) return { kind: "closed" };
33
+ return showNotesManager(ctx, storage, ownership);
34
+ }),
35
+ openWorkspace:
36
+ dependencies.openWorkspace ??
37
+ (async (options) => {
38
+ const { openNotesWorkspace } = await import("./workspace.js");
39
+ if (options.signal.aborted || !options.isCurrent()) return;
40
+ await openNotesWorkspace(options);
41
+ }),
42
+ };
43
+
44
+ return function notesExtension(pi: ExtensionAPI): void {
45
+ let generation = 0;
46
+ let activeSessionManager: unknown;
47
+ let sessionController = new AbortController();
48
+ const activeCommands = new Set<Promise<void>>();
49
+
50
+ const replaceOwner = (sessionManager: unknown, reason: string) => {
51
+ sessionController.abort(new DOMException(reason, "AbortError"));
52
+ sessionController = new AbortController();
53
+ activeSessionManager = sessionManager;
54
+ generation += 1;
55
+ };
56
+
57
+ const runCommand = async (args: string, ctx: ExtensionCommandContext): Promise<void> => {
58
+ if (args.trim()) {
59
+ rejectCommand(ctx, "Usage: /notes");
60
+ return;
61
+ }
62
+ if (ctx.mode !== "tui" || !ctx.hasUI) throw new Error("/notes requires Pi TUI mode.");
63
+ if (activeSessionManager === undefined) replaceOwner(ctx.sessionManager, "Pi Notes initialized a session owner");
64
+ const owner = ctx.sessionManager;
65
+ const ownerGeneration = generation;
66
+ const ownerController = sessionController;
67
+ const signal = ctx.signal ? AbortSignal.any([ctx.signal, ownerController.signal]) : ownerController.signal;
68
+ const isCurrent = () =>
69
+ activeSessionManager === owner && generation === ownerGeneration && !ownerController.signal.aborted;
70
+ if (!isCurrent()) throw new Error("Pi Notes session is no longer active.");
71
+
72
+ const agentDir = deps.getAgentDir();
73
+ const storage = deps.createStorage(agentDir);
74
+ await storage.initialize(signal);
75
+ if (!isCurrent() || signal.aborted) return;
76
+ const selected = await deps.showManager(ctx, storage, { signal, isCurrent });
77
+ if (!isCurrent() || signal.aborted || selected.kind !== "open" || !selected.notePath) return;
78
+ const thinkingLevel = pi.getThinkingLevel();
79
+ if (!isCurrent() || signal.aborted) return;
80
+ await deps.openWorkspace({
81
+ ctx,
82
+ agentDir,
83
+ storage,
84
+ notePath: selected.notePath,
85
+ thinkingLevel,
86
+ signal,
87
+ isCurrent,
88
+ });
89
+ };
90
+
91
+ pi.registerCommand("notes", {
92
+ description: "Browse and edit global Markdown notes with an isolated agent",
93
+ handler: async (args, ctx) => {
94
+ const task = runCommand(args, ctx);
95
+ activeCommands.add(task);
96
+ try {
97
+ await task;
98
+ } finally {
99
+ activeCommands.delete(task);
100
+ }
101
+ },
102
+ });
103
+
104
+ pi.on("session_start", async (_event, ctx) => {
105
+ if (activeSessionManager !== undefined) {
106
+ sessionController.abort(new DOMException("Pi Notes parent session replaced or reloaded", "AbortError"));
107
+ await Promise.allSettled([...activeCommands]);
108
+ }
109
+ replaceOwner(ctx.sessionManager, "Pi Notes session started");
110
+ });
111
+
112
+ pi.on("session_shutdown", async (_event, ctx) => {
113
+ if (ctx.sessionManager !== activeSessionManager) return;
114
+ sessionController.abort(new DOMException("Pi Notes session shut down", "AbortError"));
115
+ activeSessionManager = undefined;
116
+ generation += 1;
117
+ await Promise.allSettled([...activeCommands]);
118
+ });
119
+ };
120
+ }
121
+
122
+ function rejectCommand(ctx: ExtensionContext, message: string): void {
123
+ if (ctx.hasUI) {
124
+ try {
125
+ ctx.ui.notify(message, "warning");
126
+ } catch {
127
+ // A replaced session can invalidate the old UI immediately.
128
+ }
129
+ return;
130
+ }
131
+ throw new Error(message);
132
+ }
133
+
134
+ export default createNotesExtension();