@narumitw/pi-notes 0.1.0 → 0.2.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/README.md CHANGED
@@ -10,7 +10,7 @@
10
10
  - Discovers notes and user-managed templates dynamically under Pi's configured agent directory.
11
11
  - Creates a blank or templated note immediately under a collision-safe temporary name without asking for a filename.
12
12
  - Lets the embedded agent proactively rename the current note when its purpose becomes clear.
13
- - Opens notes directly or inserts a selected note's canonical absolute path into the parent editor without replacing its draft.
13
+ - Opens notes directly, deletes a highlighted note after confirmation, or inserts its canonical absolute path into the parent editor without replacing the draft.
14
14
  - Edits existing templates with cancellation and stale-write protection.
15
15
  - Shows a fullscreen split Chat/Preview workspace on wide terminals and fullscreen tabs on narrow terminals.
16
16
  - Gives the embedded agent only tools scoped to the currently open note.
@@ -49,7 +49,7 @@ Run Pi in TUI mode, then open the manager:
49
49
  /notes
50
50
  ```
51
51
 
52
- Choose **Open a note…**, **Create a note…**, **Paste a note path…**, or **Manage templates…**. Existing note names appear only after opening the dedicated note list. New notes can be blank or copy a Markdown template found at `${getAgentDir()}/pi-notes/templates/`; the extension opens the note immediately as `untitled.md`, an available numbered variant, or a generated fallback, then the embedded agent renames it when the note's purpose is clear. The extension does not seed templates.
52
+ Choose **Open a note…**, **Create a note…**, **Paste a note path…**, or **Manage templates…**. Existing note names appear only after opening the dedicated note list. In that list, Enter opens the highlighted note and the configured `app.session.delete` binding (`Ctrl+D` by default) asks to delete it. New notes can be blank or copy a Markdown template found at `${getAgentDir()}/pi-notes/templates/`; the extension opens the note immediately as `untitled.md`, an available numbered variant, or a generated fallback, then the embedded agent renames it when the note's purpose is clear. The extension does not seed templates.
53
53
 
54
54
  ## 🧭 How it works
55
55
 
@@ -57,6 +57,7 @@ Choose **Open a note…**, **Create a note…**, **Paste a note path…**, or **
57
57
  flowchart LR
58
58
  P[Parent Pi session] -->|/notes| M[Notes manager]
59
59
  M --> W[Temporary notes workspace]
60
+ M --> D[Confirm and delete note]
60
61
  M --> I[Paste canonical path into parent draft]
61
62
  M --> E[Edit existing template]
62
63
  W --> C[Isolated child AgentSession]
@@ -85,7 +86,9 @@ New managed directories use mode `0700` and newly created notes use `0600` where
85
86
 
86
87
  `/notes` opens the browse/create manager and accepts no arguments. It requires Pi TUI mode and rejects RPC, print, and JSON modes.
87
88
 
88
- The manager rescans notes and templates when each screen opens. Its first level contains actions only; **Open a note…** shows the current note list on a separate screen. **Paste a note path…** resolves the selected regular file again, closes the manager, and inserts its canonical absolute path at the parent editor's current cursor without replacing the existing draft. Paths containing terminal or display-direction controls are rejected because Pi's paste handling cannot preserve them safely.
89
+ The manager rescans notes and templates when each screen opens. Its first level contains actions only; **Open a note…** shows the current note list on a separate screen. Enter opens the highlighted note. The effective `app.session.delete` binding (`Ctrl+D` by default) shows the exact relative path in quoted, terminal-safe escaped form and its byte size before deletion. Cancelling leaves the note unchanged. A confirmed deletion succeeds only while the selected file still has the reviewed revision, then refreshes the list and highlights a neighboring note. It removes the Markdown file but preserves its path-keyed child conversation under `pi-notes/sessions/`.
90
+
91
+ **Paste a note path…** resolves the selected regular file again, closes the manager, and inserts its canonical absolute path at the parent editor's current cursor without replacing the existing draft. Paths containing terminal or display-direction controls are rejected because Pi's paste handling cannot preserve them safely.
89
92
 
90
93
  **Manage templates…** opens an existing template in a Pi-style multiline editor. The editor preserves leading and trailing whitespace and hides terminal controls as spaces without changing their raw values. It rejects pasted text containing an ambiguous bracketed-paste terminator rather than silently reordering it. Because terminal paste framing cannot represent a literal terminator unambiguously, the first save after a paste asks you to review the content and press save again. Cancelling or submitting unchanged content returns to the manager without writing. A changed template is published atomically only if its revision is still current; if another process changed it, Pi Notes preserves that external content, reports the conflict, and refreshes the manager.
91
94
 
@@ -110,9 +113,9 @@ The content tools accept no path, and the rename tool accepts no source path. A
110
113
  - Model and credential configuration is read from Pi's configured agent directory. A provider registered only in another extension's in-memory runtime is not inherited.
111
114
  - Child history remains on disk under `pi-notes/sessions/` until the user removes it.
112
115
  - Note and template operations reject absolute paths, traversal, special files, and symlinked managed paths. Rename refuses an existing destination and paths deeper than the discovery limit so renamed notes remain available in menus. Same-directory temporary files and atomic publication preserve the previous content when a managed write fails.
113
- - Revision checks detect stale writes and renames, but another process can still change a file immediately around publication; this extension does not provide cross-process locking or an OS sandbox.
116
+ - Revision checks detect stale writes, renames, and deletions, but another process can still change a file immediately around publication; this extension does not provide cross-process locking or an OS sandbox.
114
117
  - Note paths and content are treated as untrusted terminal text and sanitized only for display; raw Markdown content and valid raw file identities remain unchanged on disk.
115
- - The extension has no delete operation. Removing or disabling the package leaves `getAgentDir()/pi-notes/` untouched.
118
+ - Deleting a note does not delete its child-session history. Removing or disabling the package leaves all data under `getAgentDir()/pi-notes/` untouched.
116
119
 
117
120
  ## 🚧 Limitations
118
121
 
@@ -121,7 +124,7 @@ The content tools accept no path, and the rename tool accepts no source path. A
121
124
  - Each note path supports at most 100 saved child-session files. The visible transcript is bounded to the latest 200 messages and 50,000 characters.
122
125
  - A rename keeps the currently open child conversation, but reopening the renamed note starts a separate child conversation unless the new path already has history. Renaming a note outside the extension has the same path-associated behavior.
123
126
  - Parent-only dynamic providers and runtime-only provider state are unavailable to the child; use a provider reconstructable from Pi's normal model and credential files.
124
- - There is no manual rename UI, delete operation, tags, backlinks, full-text index, direct `/notes <path>` route, template language, settings, or bundled skill.
127
+ - There is no manual rename UI, child-history deletion UI, tags, backlinks, full-text index, direct `/notes <path>` route, template language, settings, or bundled skill.
125
128
  - Template management edits existing files only; create, rename, delete, agent-assisted template work, and Pi's external-editor shortcut are not supported.
126
129
  - Cross-process locking, large notes, rich-text editing, attachments, synchronization, and collaborative editing are not supported.
127
130
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@narumitw/pi-notes",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Pi extension for managing global Markdown notes with an isolated embedded agent.",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/src/menu.ts CHANGED
@@ -1,14 +1,15 @@
1
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";
2
+ import { type MenuDefinition, runCustomInteraction, runMenu, sanitizeTerminalText } from "@narumitw/pi-tui-kit";
3
+ import { NotePicker, type NotePickerResult } from "./note-picker.js";
4
+ import type { DiscoveryResult, MarkdownEntry, NoteSnapshot, NotesStorage } from "./storage.js";
4
5
 
5
6
  interface NotesMenuState {
6
7
  notes: DiscoveryResult;
7
8
  templates: DiscoveryResult;
8
9
  }
9
10
 
10
- type NotesScreen = "notes" | "openNote" | "templates" | "pastePath" | "manageTemplates";
11
- type NotesAction = "chooseRoute" | "chooseNote" | "chooseTemplate" | "pastePath" | "editTemplate";
11
+ type NotesScreen = "notes" | "templates" | "pastePath" | "manageTemplates";
12
+ type NotesAction = "chooseRoute" | "chooseTemplate" | "pastePath" | "editTemplate";
12
13
 
13
14
  export type NotesManagerResult =
14
15
  | { kind: "open"; notePath: string }
@@ -16,7 +17,7 @@ export type NotesManagerResult =
16
17
  | { kind: "editTemplate"; templatePath: string }
17
18
  | { kind: "closed" };
18
19
 
19
- export function createNotesMenu(storage: NotesStorage) {
20
+ export function createNotesMenu(storage: NotesStorage, ownership: { isCurrent?: () => boolean } = {}) {
20
21
  let result: Exclude<NotesManagerResult, { kind: "closed" }> | undefined;
21
22
 
22
23
  const getState = async ({ signal }: { signal: AbortSignal }): Promise<NotesMenuState> => {
@@ -64,21 +65,6 @@ export function createNotesMenu(storage: NotesStorage) {
64
65
  viewportSize: 12,
65
66
  hint: "close",
66
67
  }),
67
- openNote: ({ state }) => ({
68
- kind: "choice",
69
- title: "Open a note",
70
- lines: discoveryLines(state.notes, "note"),
71
- items: state.notes.entries.map((note, index) => ({
72
- id: `note:${index}`,
73
- label: note.displayPath,
74
- description: `${note.size} bytes`,
75
- searchText: note.displayPath,
76
- })),
77
- action: "chooseNote",
78
- enableSearch: state.notes.entries.length > 8,
79
- viewportSize: 12,
80
- hint: "back",
81
- }),
82
68
  templates: ({ state }) => ({
83
69
  kind: "choice",
84
70
  title: "Choose initial content",
@@ -133,19 +119,20 @@ export function createNotesMenu(storage: NotesStorage) {
133
119
  }),
134
120
  },
135
121
  actions: {
136
- chooseRoute: ({ itemId }) => {
137
- if (itemId === "open") return { kind: "to", screen: "openNote" };
122
+ chooseRoute: async ({ ctx, itemId, signal }) => {
123
+ if (itemId === "open") {
124
+ const selected = await chooseOpenNote(ctx, storage, signal, ownership);
125
+ if (selected.kind === "open") {
126
+ result = selected;
127
+ return { kind: "close" };
128
+ }
129
+ return { kind: selected.kind === "close" ? "close" : "stay" };
130
+ }
138
131
  if (itemId === "create") return { kind: "to", screen: "templates" };
139
132
  if (itemId === "paste-path") return { kind: "to", screen: "pastePath" };
140
133
  if (itemId === "manage-templates") return { kind: "to", screen: "manageTemplates" };
141
134
  return { kind: "rejected", error: new Error("The selected notes action is no longer available") };
142
135
  },
143
- chooseNote: ({ state, itemId }) => {
144
- const note = indexedEntry(state.notes.entries, itemId, "note:");
145
- if (!note) return { kind: "rejected", error: new Error("The selected note is no longer available") };
146
- result = { kind: "open", notePath: note.relativePath };
147
- return { kind: "close" };
148
- },
149
136
  chooseTemplate: async ({ state, itemId, signal }) => {
150
137
  const templatePath =
151
138
  itemId === "blank" ? undefined : indexedEntry(state.templates.entries, itemId, "template:")?.relativePath;
@@ -186,7 +173,7 @@ export async function showNotesManager(
186
173
  storage: NotesStorage,
187
174
  ownership: { signal: AbortSignal; isCurrent(): boolean },
188
175
  ): Promise<NotesManagerResult> {
189
- const controller = createNotesMenu(storage);
176
+ const controller = createNotesMenu(storage, ownership);
190
177
  const result = await runMenu(ctx, controller.menu, {
191
178
  getState: controller.getState,
192
179
  signal: ownership.signal,
@@ -202,6 +189,122 @@ export async function showNotesManager(
202
189
  return selected && ownership.isCurrent() && !ownership.signal.aborted ? selected : { kind: "closed" };
203
190
  }
204
191
 
192
+ async function chooseOpenNote(
193
+ ctx: ExtensionCommandContext,
194
+ storage: NotesStorage,
195
+ signal: AbortSignal,
196
+ ownership: { isCurrent?: () => boolean },
197
+ ): Promise<{ kind: "open"; notePath: string } | { kind: "back" | "close" }> {
198
+ let selectedPath: string | undefined;
199
+ let query = "";
200
+ const isCurrent = () => ownership.isCurrent?.() ?? true;
201
+
202
+ while (!signal.aborted && isCurrent()) {
203
+ const notes = await storage.discoverNotes(signal);
204
+ if (signal.aborted || !isCurrent()) return { kind: "close" };
205
+ const interaction = await runCustomInteraction<NotePickerResult>(ctx, {
206
+ signal,
207
+ isCurrent,
208
+ onError: (currentCtx, error) => {
209
+ if (!signal.aborted && isCurrent()) {
210
+ safeNotify(currentCtx, `Pi Notes picker failed: ${safeErrorMessage(error)}`, "error");
211
+ }
212
+ },
213
+ create: ({ tui, theme, keybindings, complete }) =>
214
+ new NotePicker({
215
+ tui,
216
+ theme,
217
+ keybindings,
218
+ notes: notes.entries,
219
+ lines: discoveryLines(notes, "note"),
220
+ initialSelectedPath: selectedPath,
221
+ initialQuery: query,
222
+ complete,
223
+ }),
224
+ });
225
+ if (signal.aborted || !isCurrent() || interaction.kind === "stale") return { kind: "close" };
226
+ if (interaction.kind !== "completed") return { kind: "close" };
227
+
228
+ const choice = interaction.value;
229
+ if ("query" in choice && choice.query !== undefined) query = choice.query;
230
+ if ("selectedPath" in choice) selectedPath = choice.selectedPath;
231
+ if (choice.kind === "back" || choice.kind === "close") return { kind: choice.kind };
232
+ if (choice.kind === "open") return { kind: "open", notePath: choice.notePath };
233
+
234
+ selectedPath = choice.nextSelectedPath;
235
+ const selected = notes.entries.find(({ relativePath }) => relativePath === choice.notePath);
236
+ if (!selected) {
237
+ safeNotify(ctx, "The selected note is no longer available; refreshed the note list.", "warning");
238
+ continue;
239
+ }
240
+
241
+ let snapshot: NoteSnapshot;
242
+ try {
243
+ snapshot = await storage.readNote(selected.relativePath, signal);
244
+ } catch (error) {
245
+ if (signal.aborted || !isCurrent()) return { kind: "close" };
246
+ safeNotify(ctx, `Pi Notes failed to read the selected note: ${safeErrorMessage(error)}`, "error");
247
+ continue;
248
+ }
249
+ if (signal.aborted || !isCurrent()) return { kind: "close" };
250
+
251
+ let confirmed: boolean;
252
+ try {
253
+ confirmed = await ctx.ui.confirm("Delete note?", deleteConfirmationMessage(selected, snapshot.size), {
254
+ signal,
255
+ });
256
+ } catch (error) {
257
+ if (signal.aborted || !isCurrent()) return { kind: "close" };
258
+ throw error;
259
+ }
260
+ if (signal.aborted || !isCurrent()) return { kind: "close" };
261
+ if (!confirmed) {
262
+ selectedPath = selected.relativePath;
263
+ continue;
264
+ }
265
+
266
+ try {
267
+ await storage.deleteNote(snapshot.relativePath, snapshot.revision, signal);
268
+ } catch (error) {
269
+ if (signal.aborted || !isCurrent()) return { kind: "close" };
270
+ safeNotify(ctx, `Pi Notes failed to delete the selected note: ${safeErrorMessage(error)}`, "error");
271
+ selectedPath = selected.relativePath;
272
+ continue;
273
+ }
274
+ if (signal.aborted || !isCurrent()) return { kind: "close" };
275
+ safeNotify(ctx, `Deleted note: ${displayNotePath(selected)}`, "info");
276
+ }
277
+
278
+ return { kind: "close" };
279
+ }
280
+
281
+ function deleteConfirmationMessage(note: MarkdownEntry, size: number): string {
282
+ return [
283
+ `Note: ${displayNotePath(note)}`,
284
+ `Size: ${size} bytes`,
285
+ "",
286
+ "Delete this Markdown note? This cannot be undone.",
287
+ "Its saved child conversation will remain under pi-notes/sessions/.",
288
+ ].join("\n");
289
+ }
290
+
291
+ function displayNotePath(note: MarkdownEntry): string {
292
+ let display = '"';
293
+ for (const character of note.relativePath) {
294
+ if (character === '"' || character === "\\") {
295
+ display += `\\${character}`;
296
+ continue;
297
+ }
298
+ if (sanitizeTerminalText(character) !== character) {
299
+ const codePoint = character.codePointAt(0) ?? 0;
300
+ display += codePoint <= 0xff ? `\\x${codePoint.toString(16).padStart(2, "0")}` : `\\u{${codePoint.toString(16)}}`;
301
+ continue;
302
+ }
303
+ display += character;
304
+ }
305
+ return `${display}"`;
306
+ }
307
+
205
308
  function indexedEntry(entries: readonly MarkdownEntry[], itemId: string, prefix: string): MarkdownEntry | undefined {
206
309
  if (!itemId.startsWith(prefix)) return undefined;
207
310
  const index = Number.parseInt(itemId.slice(prefix.length), 10);
@@ -0,0 +1,735 @@
1
+ import type { KeybindingsManager, Theme } from "@earendil-works/pi-coding-agent";
2
+ import {
3
+ type Component,
4
+ decodeKittyPrintable,
5
+ type Focusable,
6
+ fuzzyFilter,
7
+ Input,
8
+ isKittyProtocolActive,
9
+ Key,
10
+ type KeyId,
11
+ matchesKey,
12
+ type TUI,
13
+ type TuiMouseEvent,
14
+ type TuiMouseEventResult,
15
+ truncateToWidth,
16
+ visibleWidth,
17
+ wrapTextWithAnsi,
18
+ } from "@earendil-works/pi-tui";
19
+ import { formatInteractionHints, HorizontalRule, renderBoundedFrame, sanitizeTerminalText } from "@narumitw/pi-tui-kit";
20
+ import type { MarkdownEntry } from "./storage.js";
21
+
22
+ const BRACKETED_PASTE_START = "\u001b[200~";
23
+ const BRACKETED_PASTE_END = "\u001b[201~";
24
+ const INPUT_PREFIX_TIMEOUT_MS = 10;
25
+ const MAX_SEARCH_QUERY_LENGTH = 256;
26
+ const MAX_VISIBLE_NOTES = 12;
27
+
28
+ type KeyboardProtocolTerminal = TUI["terminal"] & {
29
+ readonly modifyOtherKeysActive?: boolean;
30
+ };
31
+
32
+ interface NotePickerHintKeys {
33
+ navigation: readonly KeyId[];
34
+ confirm: readonly KeyId[];
35
+ back: readonly KeyId[];
36
+ }
37
+
38
+ const PICKER_BINDINGS = [
39
+ "tui.select.up",
40
+ "tui.select.down",
41
+ "tui.select.pageUp",
42
+ "tui.select.pageDown",
43
+ "tui.select.confirm",
44
+ "tui.select.cancel",
45
+ ] as const;
46
+ // These are the configurable actions Pi Input consumes before printable insertion.
47
+ const SEARCH_INPUT_BINDINGS = [
48
+ "tui.editor.undo",
49
+ "tui.input.submit",
50
+ "tui.editor.deleteCharBackward",
51
+ "tui.editor.deleteCharForward",
52
+ "tui.editor.deleteWordBackward",
53
+ "tui.editor.deleteWordForward",
54
+ "tui.editor.deleteToLineStart",
55
+ "tui.editor.deleteToLineEnd",
56
+ "tui.editor.yank",
57
+ "tui.editor.yankPop",
58
+ "tui.editor.cursorLeft",
59
+ "tui.editor.cursorRight",
60
+ "tui.editor.cursorLineStart",
61
+ "tui.editor.cursorLineEnd",
62
+ "tui.editor.cursorWordLeft",
63
+ "tui.editor.cursorWordRight",
64
+ ] as const;
65
+
66
+ const MODIFIERS = ["shift", "alt", "ctrl", "super"] as const;
67
+ const SYMBOLS = "`-=[]\\;',./!@#$%^&*()_|~{}:<>?";
68
+ const SPECIAL_KEYS = new Set([
69
+ "escape",
70
+ "enter",
71
+ "tab",
72
+ "space",
73
+ "backspace",
74
+ "insert",
75
+ "delete",
76
+ "clear",
77
+ "home",
78
+ "end",
79
+ "pageup",
80
+ "pagedown",
81
+ "left",
82
+ "right",
83
+ "up",
84
+ "down",
85
+ ]);
86
+ const FUNCTION_INPUTS = ["OP", "OQ", "OR", "OS", "[15~", "[17~", "[18~", "[19~", "[20~", "[21~", "[23~", "[24~"];
87
+ const LEGACY_INPUTS = [
88
+ ...Array.from({ length: 128 }, (_, code) => String.fromCharCode(code)),
89
+ ...Array.from({ length: 128 }, (_, code) => `\u001b${String.fromCharCode(code)}`),
90
+ "\u001b[Z",
91
+ "\u001bOM",
92
+ "\u001b[E",
93
+ "\u001b[e",
94
+ "\u001bOe",
95
+ ...FUNCTION_INPUTS.map((suffix) => `\u001b${suffix}`),
96
+ ];
97
+ const SPECIAL_CODEPOINTS: Record<string, number> = {
98
+ escape: 27,
99
+ tab: 9,
100
+ enter: 13,
101
+ space: 32,
102
+ backspace: 127,
103
+ insert: 57425,
104
+ delete: 57426,
105
+ home: 57423,
106
+ end: 57424,
107
+ pageup: 57421,
108
+ pagedown: 57422,
109
+ left: 57417,
110
+ right: 57418,
111
+ up: 57419,
112
+ down: 57420,
113
+ };
114
+
115
+ export type NotePickerResult =
116
+ | { kind: "open"; notePath: string; query?: string }
117
+ | { kind: "delete"; notePath: string; nextSelectedPath?: string; query?: string }
118
+ | { kind: "back"; selectedPath?: string; query?: string }
119
+ | { kind: "close"; selectedPath?: string; query?: string };
120
+
121
+ interface NotePickerOptions {
122
+ tui: TUI;
123
+ theme: Theme;
124
+ keybindings: KeybindingsManager;
125
+ notes: readonly MarkdownEntry[];
126
+ lines?: readonly string[];
127
+ initialSelectedPath?: string;
128
+ initialQuery?: string;
129
+ complete(result: NotePickerResult): void;
130
+ }
131
+
132
+ interface MouseLayout {
133
+ width: number;
134
+ inputFrameRow?: number;
135
+ noteByFrameRow: ReadonlyMap<number, number>;
136
+ }
137
+
138
+ export class NotePicker implements Component, Focusable {
139
+ private readonly searchInput = new Input();
140
+ private readonly searchEnabled: boolean;
141
+ private filteredNotes: MarkdownEntry[];
142
+ private selectedPath: string | undefined;
143
+ private restoreSelectedPath: string | undefined;
144
+ private scrollOffset = 0;
145
+ private pasteStartBuffer = "";
146
+ private pasteBuffer: string | undefined;
147
+ private pasteStartTimer: ReturnType<typeof setTimeout> | undefined;
148
+ private mousePressedIndex: number | undefined;
149
+ private mouseLayout: MouseLayout | undefined;
150
+ private disposed = false;
151
+ private completed = false;
152
+ private isFocused = false;
153
+
154
+ constructor(private readonly options: NotePickerOptions) {
155
+ this.searchEnabled = options.notes.length > 8;
156
+ initializeSearchInput(this.searchInput, sanitizeTerminalText(options.initialQuery ?? ""));
157
+ this.searchInput.focused = false;
158
+ this.filteredNotes = this.filterNotes();
159
+ this.selectedPath = this.filteredNotes.some(({ relativePath }) => relativePath === options.initialSelectedPath)
160
+ ? options.initialSelectedPath
161
+ : this.filteredNotes[0]?.relativePath;
162
+ }
163
+
164
+ get focused(): boolean {
165
+ return this.isFocused;
166
+ }
167
+
168
+ set focused(value: boolean) {
169
+ this.isFocused = value;
170
+ this.searchInput.focused = value && this.searchEnabled && !this.disposed;
171
+ }
172
+
173
+ render(width: number): string[] {
174
+ const safeWidth = Math.max(1, Math.floor(width));
175
+ const viewportSize = this.viewportSize();
176
+ this.keepSelectionVisible(viewportSize);
177
+ const visible = this.filteredNotes.slice(this.scrollOffset, this.scrollOffset + viewportSize);
178
+ const rows = visible.map((note) => this.renderNote(note, note.relativePath === this.selectedPath, safeWidth));
179
+ const content: string[] = [];
180
+ let selectedContentIndex: number | undefined;
181
+
182
+ if (this.searchEnabled) {
183
+ content.push(this.renderSearch(safeWidth), "");
184
+ }
185
+ const listStart = content.length;
186
+ if (rows.length > 0) {
187
+ content.push(...rows);
188
+ const selectedVisibleIndex = visible.findIndex(({ relativePath }) => relativePath === this.selectedPath);
189
+ if (selectedVisibleIndex >= 0) selectedContentIndex = listStart + selectedVisibleIndex;
190
+ } else {
191
+ content.push(
192
+ this.options.theme.fg(
193
+ this.queryTooLong() ? "error" : "dim",
194
+ this.queryTooLong()
195
+ ? ` Search query is too long (maximum ${MAX_SEARCH_QUERY_LENGTH} characters)`
196
+ : this.options.notes.length === 0
197
+ ? " No notes found."
198
+ : " No matching notes.",
199
+ ),
200
+ );
201
+ selectedContentIndex = content.length - 1;
202
+ }
203
+ if (this.filteredNotes.length > viewportSize) {
204
+ const selectedIndex = this.selectedIndex();
205
+ content.push(this.options.theme.fg("dim", ` (${selectedIndex + 1}/${this.filteredNotes.length})`));
206
+ }
207
+ if (this.searchEnabled) content.push(this.options.theme.fg("dim", "Type to search"));
208
+
209
+ const hint = this.interactionHint();
210
+ const hintRows = wrapTextWithAnsi(this.options.theme.fg("dim", hint), safeWidth);
211
+ const title = this.options.theme.fg("accent", this.options.theme.bold("Open a note"));
212
+ const context = (this.options.lines ?? []).map((line) =>
213
+ this.options.theme.fg("muted", sanitizeTerminalText(line)),
214
+ );
215
+ const rule =
216
+ new HorizontalRule({ ruleStyle: (text) => this.options.theme.fg("border", text) }).render(safeWidth)[0] ?? "";
217
+ const priorities = [
218
+ ...(this.searchEnabled ? [0] : []),
219
+ ...(selectedContentIndex === undefined ? [] : [selectedContentIndex]),
220
+ ];
221
+ const maxRows = Math.max(1, Math.floor(this.options.tui.terminal.rows) - 3);
222
+ const frame = renderBoundedFrame({
223
+ width: safeWidth,
224
+ maxRows,
225
+ rule,
226
+ title: [title],
227
+ context,
228
+ content,
229
+ hints: hintRows,
230
+ compactHint: truncateToWidth(this.options.theme.fg("dim", hint), safeWidth, ""),
231
+ priorityRows: priorities,
232
+ focusedRow: selectedContentIndex,
233
+ });
234
+ const fullFrameRows = context.length + content.length + hintRows.length + 4;
235
+ // Kit's compact frame does not expose public pointer-row metadata. Disable pointer routing there rather than
236
+ // risk opening a different raw note identity; keyboard navigation remains available at every height.
237
+ if (fullFrameRows <= maxRows) {
238
+ const contentFrameStart = context.length + 3;
239
+ this.mouseLayout = {
240
+ width: safeWidth,
241
+ ...(this.searchEnabled ? { inputFrameRow: contentFrameStart } : {}),
242
+ noteByFrameRow: new Map(
243
+ visible.map((_, index) => [contentFrameStart + listStart + index, this.scrollOffset + index]),
244
+ ),
245
+ };
246
+ } else this.mouseLayout = undefined;
247
+ return frame;
248
+ }
249
+
250
+ handleInput(data: string): void {
251
+ if (this.disposed || this.completed) return;
252
+ this.routeInput(data);
253
+ }
254
+
255
+ handleMouse(event: TuiMouseEvent): TuiMouseEventResult | undefined {
256
+ if (this.disposed || this.completed || !this.mouseLayout || event.width !== this.mouseLayout.width) {
257
+ return undefined;
258
+ }
259
+ if (event.y === this.mouseLayout.inputFrameRow) {
260
+ const labelWidth = visibleWidth("Search: ");
261
+ const inputWidth = Math.max(1, event.width - labelWidth);
262
+ if (event.x < labelWidth || event.x >= labelWidth + inputWidth) return undefined;
263
+ return this.searchInput.handleMouse({
264
+ ...event,
265
+ x: event.x - labelWidth,
266
+ y: 0,
267
+ width: inputWidth,
268
+ height: 1,
269
+ });
270
+ }
271
+ const mappedIndex = this.mouseLayout.noteByFrameRow.get(event.y);
272
+ if (mappedIndex === undefined) return undefined;
273
+ const noteIndex = event.type === "click" ? (this.mousePressedIndex ?? mappedIndex) : mappedIndex;
274
+ if (noteIndex < 0 || noteIndex >= this.filteredNotes.length) return undefined;
275
+ if (event.type === "wheel" && event.wheelDelta) {
276
+ const next = Math.max(
277
+ 0,
278
+ Math.min(this.filteredNotes.length - 1, this.selectedIndex() + (event.wheelDelta < 0 ? -1 : 1)),
279
+ );
280
+ const changed = next !== this.selectedIndex();
281
+ if (changed) this.selectAt(next);
282
+ return { handled: true, render: changed };
283
+ }
284
+ if (event.type === "move") return { handled: true };
285
+ if (event.button !== "left") return undefined;
286
+ if (event.type === "press") {
287
+ this.mousePressedIndex = noteIndex;
288
+ const changed = this.selectedIndex() !== noteIndex;
289
+ if (changed) this.selectAt(noteIndex);
290
+ return { handled: true, focus: true, render: changed };
291
+ }
292
+ if (event.type === "click") {
293
+ this.mousePressedIndex = undefined;
294
+ if (this.selectedIndex() !== noteIndex) this.selectAt(noteIndex);
295
+ this.openSelected();
296
+ return { handled: true };
297
+ }
298
+ return undefined;
299
+ }
300
+
301
+ invalidate(): void {
302
+ this.mouseLayout = undefined;
303
+ this.searchInput.invalidate();
304
+ }
305
+
306
+ dispose(): void {
307
+ this.disposed = true;
308
+ this.clearPasteStartTimer();
309
+ this.pasteStartBuffer = "";
310
+ this.pasteBuffer = undefined;
311
+ this.mousePressedIndex = undefined;
312
+ this.mouseLayout = undefined;
313
+ this.isFocused = false;
314
+ this.searchInput.focused = false;
315
+ }
316
+
317
+ private renderSearch(width: number): string {
318
+ const label = this.options.theme.fg("muted", "Search: ");
319
+ const inputWidth = Math.max(1, width - visibleWidth(label));
320
+ return truncateToWidth(`${label}${this.searchInput.render(inputWidth)[0] ?? ""}`, width, "");
321
+ }
322
+
323
+ private renderNote(note: MarkdownEntry, selected: boolean, width: number): string {
324
+ const prefix = selected ? this.options.theme.fg("accent", "→ ") : " ";
325
+ const description = `${note.size} bytes`;
326
+ const availableLabelWidth = Math.max(1, width - visibleWidth(prefix) - visibleWidth(description) - 2);
327
+ const label = truncateToWidth(sanitizeTerminalText(note.displayPath), availableLabelWidth, "…");
328
+ const spacing = " ".repeat(
329
+ Math.max(1, width - visibleWidth(prefix) - visibleWidth(label) - visibleWidth(description)),
330
+ );
331
+ const line = truncateToWidth(
332
+ `${prefix}${label}${this.options.theme.fg("muted", `${spacing}${description}`)}`,
333
+ width,
334
+ "",
335
+ );
336
+ return selected ? this.options.theme.bold(line) : line;
337
+ }
338
+
339
+ private interactionHint(): string {
340
+ const hintKeys = resolveNotePickerHintKeys(this.options.keybindings, this.searchEnabled, this.options.tui.terminal);
341
+ const deleteKey = resolveNoteDeleteKey(this.options.keybindings, this.searchEnabled, this.options.tui.terminal);
342
+ return formatInteractionHints(this.options.keybindings, [
343
+ { keys: hintKeys.navigation, label: "navigate" },
344
+ { keys: hintKeys.confirm, label: "open" },
345
+ ...(deleteKey ? [{ keys: [deleteKey], label: "delete" }] : []),
346
+ { keys: hintKeys.back, label: "back" },
347
+ { keys: ["ctrl+c"], label: "close" },
348
+ ]);
349
+ }
350
+
351
+ private viewportSize(): number {
352
+ const fixedRows = this.searchEnabled ? 9 : 6;
353
+ return Math.max(1, Math.min(MAX_VISIBLE_NOTES, Math.floor(this.options.tui.terminal.rows) - fixedRows));
354
+ }
355
+
356
+ private query(): string {
357
+ return this.searchEnabled ? this.searchInput.getValue() : "";
358
+ }
359
+
360
+ private queryTooLong(): boolean {
361
+ return this.query().length > MAX_SEARCH_QUERY_LENGTH;
362
+ }
363
+
364
+ private filterNotes(): MarkdownEntry[] {
365
+ const query = this.searchInput.getValue();
366
+ if (!this.searchEnabled || !query.trim()) return [...this.options.notes];
367
+ if (query.length > MAX_SEARCH_QUERY_LENGTH) return [];
368
+ return fuzzyFilter([...this.options.notes], query, ({ displayPath }) => sanitizeTerminalText(displayPath));
369
+ }
370
+
371
+ private applySearchInput(data: string): void {
372
+ const previousQuery = this.searchInput.getValue();
373
+ this.searchInput.handleInput(data);
374
+ const safeQuery = sanitizeTerminalText(this.searchInput.getValue());
375
+ if (safeQuery !== this.searchInput.getValue()) this.searchInput.setValue(safeQuery);
376
+ if (safeQuery === previousQuery) return;
377
+ const previousSelection = this.selectedPath;
378
+ this.filteredNotes = this.filterNotes();
379
+ const restored = this.filteredNotes.find(({ relativePath }) => relativePath === this.restoreSelectedPath);
380
+ const retained = this.filteredNotes.find(({ relativePath }) => relativePath === previousSelection);
381
+ if (restored) {
382
+ this.selectedPath = restored.relativePath;
383
+ this.restoreSelectedPath = undefined;
384
+ } else if (retained) this.selectedPath = retained.relativePath;
385
+ else {
386
+ if (previousSelection) this.restoreSelectedPath ??= previousSelection;
387
+ this.selectedPath = this.filteredNotes[0]?.relativePath;
388
+ }
389
+ this.scrollOffset = 0;
390
+ }
391
+
392
+ private routeInput(data: string): void {
393
+ this.clearPasteStartTimer();
394
+ if (this.pasteBuffer !== undefined) {
395
+ this.pasteBuffer += data;
396
+ this.flushPasteBuffer();
397
+ return;
398
+ }
399
+
400
+ const combined = this.pasteStartBuffer + data;
401
+ this.pasteStartBuffer = "";
402
+ const pasteStart = combined.indexOf(BRACKETED_PASTE_START);
403
+ if (pasteStart >= 0) {
404
+ if (pasteStart > 0) this.handleNonPasteInput(combined.slice(0, pasteStart));
405
+ if (this.disposed || this.completed) return;
406
+ this.pasteBuffer = combined.slice(pasteStart + BRACKETED_PASTE_START.length);
407
+ this.flushPasteBuffer();
408
+ return;
409
+ }
410
+
411
+ const prefixLength = trailingMarkerPrefixLength(combined, BRACKETED_PASTE_START);
412
+ const outsidePaste = combined.slice(0, combined.length - prefixLength);
413
+ if (outsidePaste) this.handleNonPasteInput(outsidePaste);
414
+ if (this.disposed || this.completed) return;
415
+ const prefix = combined.slice(combined.length - prefixLength);
416
+ if (!prefix) return;
417
+ this.pasteStartBuffer = prefix;
418
+ this.pasteStartTimer = setTimeout(() => {
419
+ this.pasteStartTimer = undefined;
420
+ const pending = this.pasteStartBuffer;
421
+ this.pasteStartBuffer = "";
422
+ if (!this.disposed && !this.completed && pending) this.handleNonPasteInput(pending);
423
+ }, INPUT_PREFIX_TIMEOUT_MS);
424
+ }
425
+
426
+ private flushPasteBuffer(): void {
427
+ if (this.pasteBuffer === undefined) return;
428
+ const pasteEnd = this.pasteBuffer.indexOf(BRACKETED_PASTE_END);
429
+ if (pasteEnd < 0) return;
430
+ const pasted = this.pasteBuffer.slice(0, pasteEnd);
431
+ const remaining = this.pasteBuffer.slice(pasteEnd + BRACKETED_PASTE_END.length);
432
+ this.pasteBuffer = undefined;
433
+ if (this.searchEnabled) {
434
+ const safePaste = sanitizePastedSearchText(pasted);
435
+ this.applySearchInput(`${BRACKETED_PASTE_START}${safePaste}${BRACKETED_PASTE_END}`);
436
+ this.options.tui.requestRender();
437
+ }
438
+ if (remaining && !this.disposed && !this.completed) this.routeInput(remaining);
439
+ }
440
+
441
+ private clearPasteStartTimer(): void {
442
+ if (!this.pasteStartTimer) return;
443
+ clearTimeout(this.pasteStartTimer);
444
+ this.pasteStartTimer = undefined;
445
+ }
446
+
447
+ private handleNonPasteInput(data: string): void {
448
+ if (this.disposed || this.completed) return;
449
+ this.mousePressedIndex = undefined;
450
+ this.mouseLayout = undefined;
451
+ if (matchesKey(data, Key.ctrl("c"))) {
452
+ this.finish({ kind: "close", ...this.pickerState() });
453
+ return;
454
+ }
455
+ if (matchesKey(data, Key.escape) || this.options.keybindings.matches(data, "tui.select.cancel")) {
456
+ this.finish({ kind: "back", ...this.pickerState() });
457
+ return;
458
+ }
459
+ if (this.options.keybindings.matches(data, "tui.select.up")) this.move(-1);
460
+ else if (this.options.keybindings.matches(data, "tui.select.down")) this.move(1);
461
+ else if (this.options.keybindings.matches(data, "tui.select.pageUp")) this.move(-this.viewportSize(), false);
462
+ else if (this.options.keybindings.matches(data, "tui.select.pageDown")) this.move(this.viewportSize(), false);
463
+ else if (!this.searchEnabled && matchesKey(data, Key.home)) this.selectAt(0);
464
+ else if (!this.searchEnabled && matchesKey(data, Key.end)) this.selectAt(this.filteredNotes.length - 1);
465
+ else if (this.options.keybindings.matches(data, "tui.select.confirm")) this.openSelected();
466
+ else {
467
+ const deleteKey = resolveNoteDeleteKey(this.options.keybindings, this.searchEnabled, this.options.tui.terminal);
468
+ if (deleteKey && matchesKey(data, deleteKey)) this.deleteSelected();
469
+ else if (this.searchEnabled) {
470
+ const safeInput = sanitizeInsertableSearchInput(data, this.options.keybindings);
471
+ if (safeInput !== undefined) this.applySearchInput(safeInput);
472
+ }
473
+ }
474
+ if (!this.completed) this.options.tui.requestRender();
475
+ }
476
+
477
+ private selectedIndex(): number {
478
+ return Math.max(
479
+ 0,
480
+ this.filteredNotes.findIndex(({ relativePath }) => relativePath === this.selectedPath),
481
+ );
482
+ }
483
+
484
+ private move(delta: number, wrap = true): void {
485
+ if (this.filteredNotes.length === 0) return;
486
+ const current = this.selectedIndex();
487
+ const next = wrap
488
+ ? (current + delta + this.filteredNotes.length) % this.filteredNotes.length
489
+ : Math.max(0, Math.min(this.filteredNotes.length - 1, current + delta));
490
+ this.selectAt(next);
491
+ }
492
+
493
+ private selectAt(index: number): void {
494
+ if (this.filteredNotes.length === 0) return;
495
+ const bounded = Math.max(0, Math.min(this.filteredNotes.length - 1, index));
496
+ this.selectedPath = this.filteredNotes[bounded]?.relativePath;
497
+ this.restoreSelectedPath = undefined;
498
+ }
499
+
500
+ private keepSelectionVisible(height: number): void {
501
+ if (this.filteredNotes.length === 0) {
502
+ this.scrollOffset = 0;
503
+ return;
504
+ }
505
+ const index = this.selectedIndex();
506
+ if (index < this.scrollOffset) this.scrollOffset = index;
507
+ if (index >= this.scrollOffset + height) this.scrollOffset = index - height + 1;
508
+ this.scrollOffset = Math.max(0, Math.min(this.scrollOffset, this.filteredNotes.length - height));
509
+ }
510
+
511
+ private openSelected(): void {
512
+ if (!this.selectedPath) return;
513
+ this.finish({ kind: "open", notePath: this.selectedPath, query: this.query() });
514
+ }
515
+
516
+ private deleteSelected(): void {
517
+ if (!this.selectedPath) return;
518
+ const selectedIndex = this.selectedIndex();
519
+ const nextSelectedPath =
520
+ this.filteredNotes[selectedIndex + 1]?.relativePath ?? this.filteredNotes[selectedIndex - 1]?.relativePath;
521
+ this.finish({
522
+ kind: "delete",
523
+ notePath: this.selectedPath,
524
+ ...(nextSelectedPath ? { nextSelectedPath } : {}),
525
+ query: this.query(),
526
+ });
527
+ }
528
+
529
+ private pickerState(): { selectedPath?: string; query?: string } {
530
+ return {
531
+ ...(this.selectedPath ? { selectedPath: this.selectedPath } : {}),
532
+ ...(this.searchEnabled ? { query: this.query() } : {}),
533
+ };
534
+ }
535
+
536
+ private finish(result: NotePickerResult): void {
537
+ if (this.completed) return;
538
+ this.completed = true;
539
+ this.clearPasteStartTimer();
540
+ this.pasteStartBuffer = "";
541
+ this.pasteBuffer = undefined;
542
+ this.options.complete(result);
543
+ }
544
+ }
545
+
546
+ function sanitizePastedSearchText(value: string): string {
547
+ const singleLine = value
548
+ .replace(/\r\n/gu, "")
549
+ .replace(/[\r\n]/gu, "")
550
+ .replace(/\t/gu, " ");
551
+ return sanitizeTerminalText(singleLine);
552
+ }
553
+
554
+ function sanitizeInsertableSearchInput(
555
+ data: string,
556
+ keybindings: Pick<KeybindingsManager, "matches">,
557
+ ): string | undefined {
558
+ if (data === "\n" || SEARCH_INPUT_BINDINGS.some((binding) => keybindings.matches(data, binding))) return data;
559
+ const printable = decodeKittyPrintable(data) ?? decodeModifyOtherKeysPrintable(data);
560
+ if (printable !== undefined) return sanitizeTerminalText(printable) || undefined;
561
+ const hasControlCharacters = [...data].some((character) => {
562
+ const codePoint = character.codePointAt(0) ?? 0;
563
+ return codePoint < 0x20 || (codePoint >= 0x7f && codePoint <= 0x9f);
564
+ });
565
+ if (hasControlCharacters) return data;
566
+ return sanitizeTerminalText(data) || undefined;
567
+ }
568
+
569
+ function decodeModifyOtherKeysPrintable(data: string): string | undefined {
570
+ // Pi exposes the Kitty decoder from its root; mirror Editor's xterm modifyOtherKeys fallback.
571
+ const prefix = "\u001b[27;";
572
+ if (!data.startsWith(prefix)) return undefined;
573
+ const match = data.slice(prefix.length).match(/^(\d+);(\d+)~$/u);
574
+ if (!match) return undefined;
575
+ const modifier = (Number.parseInt(match[1] ?? "", 10) - 1) & ~(64 | 128);
576
+ const codePoint = Number.parseInt(match[2] ?? "", 10);
577
+ if ((modifier & ~1) !== 0 || !Number.isFinite(codePoint) || codePoint < 32) return undefined;
578
+ try {
579
+ return String.fromCodePoint(codePoint);
580
+ } catch {
581
+ return undefined;
582
+ }
583
+ }
584
+
585
+ function initializeSearchInput(input: Input, value: string): void {
586
+ input.setValue(value);
587
+ // Input.setValue() preserves its cursor, so use its public mouse contract to place a fresh cursor at the end.
588
+ const x = visibleWidth(value) + 2;
589
+ input.handleMouse({
590
+ type: "press",
591
+ button: "left",
592
+ x,
593
+ y: 0,
594
+ screenX: x,
595
+ screenY: 0,
596
+ width: x + 1,
597
+ height: 1,
598
+ shift: false,
599
+ alt: false,
600
+ ctrl: false,
601
+ });
602
+ }
603
+
604
+ function resolveNotePickerHintKeys(
605
+ keybindings: Pick<KeybindingsManager, "getKeys">,
606
+ searchEnabled: boolean,
607
+ terminal?: KeyboardProtocolTerminal,
608
+ ): NotePickerHintKeys {
609
+ const disambiguatedKeyProtocol = usesDisambiguatedKeyProtocol(terminal);
610
+ const claimed = ["ctrl+c"];
611
+ const claim = (candidates: readonly unknown[]): KeyId[] => {
612
+ const available: KeyId[] = [];
613
+ for (const candidate of candidates) {
614
+ const normalized = normalizeKey(candidate);
615
+ if (!normalized || !keyRoutesAsSingleInput(normalized, disambiguatedKeyProtocol)) continue;
616
+ if (claimed.some((other) => keysOverlap(normalized, other, disambiguatedKeyProtocol))) continue;
617
+ claimed.push(normalized);
618
+ available.push(normalized as KeyId);
619
+ }
620
+ return available;
621
+ };
622
+
623
+ // Match handleNonPasteInput() branch order so every displayed key reaches its labeled action.
624
+ const back = claim([...keybindings.getKeys("tui.select.cancel"), "escape"]);
625
+ const up = claim(keybindings.getKeys("tui.select.up"));
626
+ const down = claim(keybindings.getKeys("tui.select.down"));
627
+ claim(keybindings.getKeys("tui.select.pageUp"));
628
+ claim(keybindings.getKeys("tui.select.pageDown"));
629
+ if (!searchEnabled) {
630
+ claim(["home"]);
631
+ claim(["end"]);
632
+ }
633
+ const confirm = claim(keybindings.getKeys("tui.select.confirm"));
634
+ return { navigation: [...up, ...down], confirm, back };
635
+ }
636
+
637
+ /** Resolve the first effective delete binding that remains reachable in this picker. */
638
+ export function resolveNoteDeleteKey(
639
+ keybindings: Pick<KeybindingsManager, "getKeys">,
640
+ searchEnabled: boolean,
641
+ terminal?: KeyboardProtocolTerminal,
642
+ ): KeyId | undefined {
643
+ const activeBindings = [...PICKER_BINDINGS, ...(searchEnabled ? SEARCH_INPUT_BINDINGS : [])];
644
+ const disambiguatedKeyProtocol = usesDisambiguatedKeyProtocol(terminal);
645
+ const reserved = [
646
+ "ctrl+c",
647
+ "escape",
648
+ ...(!searchEnabled ? ["home", "end"] : []),
649
+ ...(searchEnabled && !disambiguatedKeyProtocol ? ["ctrl+j"] : []),
650
+ ...activeBindings.flatMap((binding) => {
651
+ if (binding === "tui.editor.deleteCharForward") {
652
+ return keybindings.getKeys(binding).filter((key) => normalizeKey(key) !== "ctrl+d");
653
+ }
654
+ return keybindings.getKeys(binding);
655
+ }),
656
+ ];
657
+ for (const candidate of keybindings.getKeys("app.session.delete")) {
658
+ const normalized = normalizeKey(candidate);
659
+ if (!normalized || (searchEnabled && isTextKey(normalized))) continue;
660
+ if (disambiguatedKeyProtocol) {
661
+ if (reserved.some((other) => normalizeKey(other) === normalized)) continue;
662
+ return normalized as KeyId;
663
+ }
664
+ const inputs = inputsFor(normalized);
665
+ if (inputs.length === 0 || inputs.some((input) => !routesAsSingleNonPasteInput(input))) continue;
666
+ if (reserved.some((other) => inputs.some((input) => matchesKey(input, other as KeyId)))) continue;
667
+ return normalized as KeyId;
668
+ }
669
+ return undefined;
670
+ }
671
+
672
+ function normalizeKey(value: unknown): string | undefined {
673
+ if (typeof value !== "string" || value.length > 80 || /[\s\p{Cc}]/u.test(value)) return undefined;
674
+ const parts = value.toLowerCase().split("+");
675
+ let base = parts.pop();
676
+ if (!base) return undefined;
677
+ if (base === "esc") base = "escape";
678
+ if (base === "return") base = "enter";
679
+ if (new Set(parts).size !== parts.length || parts.some((part) => !MODIFIERS.includes(part as never)))
680
+ return undefined;
681
+ if (
682
+ !SPECIAL_KEYS.has(base) &&
683
+ !/^f(?:[1-9]|1[0-2])$/u.test(base) &&
684
+ !(base.length === 1 && (/^[a-z0-9]$/u.test(base) || SYMBOLS.includes(base)))
685
+ )
686
+ return undefined;
687
+ if ((base === "escape" || /^f(?:[1-9]|1[0-2])$/u.test(base)) && parts.length > 0) return undefined;
688
+ if (base === "clear" && (parts.length > 1 || (parts.length === 1 && !["ctrl", "shift"].includes(parts[0] ?? ""))))
689
+ return undefined;
690
+ return [...MODIFIERS.filter((modifier) => parts.includes(modifier)), base].join("+");
691
+ }
692
+
693
+ function inputsFor(key: string): string[] {
694
+ const parts = key.split("+");
695
+ const base = parts.pop() ?? "";
696
+ const modifier = MODIFIERS.reduce((mask, part, bit) => mask | (parts.includes(part) ? 1 << bit : 0), 0);
697
+ const code = SPECIAL_CODEPOINTS[base] ?? (base.length === 1 ? base.charCodeAt(0) : undefined);
698
+ const inputs = code === undefined ? LEGACY_INPUTS : [...LEGACY_INPUTS, `\u001b[${code};${modifier + 1}u`];
699
+ return inputs.filter((input) => matchesKey(input, key as KeyId));
700
+ }
701
+
702
+ function usesDisambiguatedKeyProtocol(terminal?: KeyboardProtocolTerminal): boolean {
703
+ return isKittyProtocolActive() || terminal?.kittyProtocolActive === true || terminal?.modifyOtherKeysActive === true;
704
+ }
705
+
706
+ function keysOverlap(first: string, second: string, disambiguatedKeyProtocol: boolean): boolean {
707
+ if (disambiguatedKeyProtocol) return first === second;
708
+ return inputsFor(first).some((input) => matchesKey(input, second as KeyId));
709
+ }
710
+
711
+ function keyRoutesAsSingleInput(key: string, disambiguatedKeyProtocol: boolean): boolean {
712
+ if (disambiguatedKeyProtocol) return true;
713
+ const inputs = inputsFor(key);
714
+ return inputs.length > 0 && inputs.every(routesAsSingleNonPasteInput);
715
+ }
716
+
717
+ function routesAsSingleNonPasteInput(input: string): boolean {
718
+ if (input.includes(BRACKETED_PASTE_START)) return false;
719
+ const prefixLength = trailingMarkerPrefixLength(input, BRACKETED_PASTE_START);
720
+ return prefixLength === 0 || prefixLength === input.length;
721
+ }
722
+
723
+ function trailingMarkerPrefixLength(value: string, marker: string): number {
724
+ const maximum = Math.min(value.length, marker.length - 1);
725
+ for (let length = maximum; length > 0; length -= 1) {
726
+ if (value.endsWith(marker.slice(0, length))) return length;
727
+ }
728
+ return 0;
729
+ }
730
+
731
+ function isTextKey(key: string): boolean {
732
+ const parts = key.split("+");
733
+ const base = parts.at(-1) ?? "";
734
+ return (base.length === 1 || base === "space") && !parts.some((part) => ["ctrl", "alt", "super"].includes(part));
735
+ }
package/src/storage.ts CHANGED
@@ -104,6 +104,32 @@ export class NotesStorage {
104
104
  return (await resolveExistingMarkdown(this.paths.notes, relativePath, "Note", signal)).absolutePath;
105
105
  }
106
106
 
107
+ async deleteNote(relativePath: string, expectedRevision: string, signal?: AbortSignal): Promise<void> {
108
+ const normalized = normalizeExistingMarkdownPath(relativePath);
109
+ const root = await canonicalDirectory(this.paths.notes, signal);
110
+ const target = resolve(root, ...normalized.split("/"));
111
+ assertContained(root, target);
112
+ await withFileMutationQueue(root, async () => {
113
+ throwIfAborted(signal);
114
+ const resolved = await resolveExistingMarkdown(root, normalized, "Note", signal);
115
+ const current = await readBoundedMarkdown(resolved.absolutePath, "Note", signal);
116
+ if (revisionFor(current) !== expectedRevision) {
117
+ throw new Error("Note revision is stale; read the current note before deleting it");
118
+ }
119
+ throwIfAborted(signal);
120
+ const latest = await resolveExistingMarkdown(root, normalized, "Note", signal);
121
+ if (latest.absolutePath !== resolved.absolutePath) {
122
+ throw new Error("Note path changed before deletion; read it again");
123
+ }
124
+ const latestContent = await readBoundedMarkdown(latest.absolutePath, "Note", signal);
125
+ if (revisionFor(latestContent) !== expectedRevision) {
126
+ throw new Error("Note changed before deletion; read it again");
127
+ }
128
+ throwIfAborted(signal);
129
+ await unlink(latest.absolutePath);
130
+ });
131
+ }
132
+
107
133
  async readTemplate(relativePath: string, signal?: AbortSignal): Promise<TemplateSnapshot> {
108
134
  const resolved = await resolveExistingMarkdown(this.paths.templates, relativePath, "Template", signal);
109
135
  const content = await readBoundedMarkdown(resolved.absolutePath, "Template", signal);