@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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 narumiruna
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,131 @@
1
+ # πŸ“ Pi Notes β€” Global Agent-Assisted Markdown Notes
2
+
3
+ [![npm](https://img.shields.io/npm/v/@narumitw/pi-notes)](https://www.npmjs.com/package/@narumitw/pi-notes) [![Pi extension](https://img.shields.io/badge/Pi-extension-blue)](https://pi.dev) [![License: MIT](https://img.shields.io/badge/license-MIT-green.svg)](./LICENSE)
4
+
5
+ `@narumitw/pi-notes` is a Pi extension for browsing and editing user-owned Markdown notes across projects, folders, and worktrees. Each note opens in a focused workspace with an isolated embedded agent and a live Markdown preview.
6
+
7
+ ## ✨ Features
8
+
9
+ - Keeps every managed item as an equal Markdown note without built-in note types.
10
+ - Discovers notes and user-managed templates dynamically under Pi's configured agent directory.
11
+ - Shows a responsive split Chat/Preview workspace on wide terminals and tabs on narrow terminals.
12
+ - Gives the embedded agent only pathless tools for the currently open note.
13
+ - Persists a separate child conversation for each normalized note path without replacing the parent Pi session.
14
+ - Creates and updates notes with traversal, symlink, stale-revision, and same-process race checks.
15
+
16
+ ## πŸ“¦ Install
17
+
18
+ Install the extension permanently:
19
+
20
+ ```bash
21
+ pi install npm:@narumitw/pi-notes
22
+ ```
23
+
24
+ Try it without installing permanently:
25
+
26
+ ```bash
27
+ pi -e npm:@narumitw/pi-notes
28
+ ```
29
+
30
+ From this repository, install dependencies, build Pi TUI Kit, and load the local package:
31
+
32
+ ```bash
33
+ npm install
34
+ npm run build --workspace @narumitw/pi-tui-kit
35
+ pi --no-extensions --no-skills -e ./packages/pi-notes
36
+ ```
37
+
38
+ Pi extensions execute with the same filesystem and process permissions as Pi. Review the package before enabling it; the embedded tool allowlist is a model capability boundary, not an operating-system sandbox.
39
+
40
+ ## πŸš€ Quick start
41
+
42
+ Run Pi in TUI mode, then open the manager:
43
+
44
+ ```text
45
+ /notes
46
+ ```
47
+
48
+ Choose an existing note or **Create a note…**. New notes can be blank or copy a Markdown template found at `${getAgentDir()}/pi-notes/templates/`; the extension does not seed templates.
49
+
50
+ ## 🧭 How it works
51
+
52
+ ```mermaid
53
+ flowchart LR
54
+ P[Parent Pi session] -->|/notes| M[Notes manager]
55
+ M --> W[Temporary notes workspace]
56
+ W --> C[Isolated child AgentSession]
57
+ W --> V[Markdown preview]
58
+ C --> N[Current note only]
59
+ T[User templates] -->|Initial content| N
60
+ C --> S[Per-note child history]
61
+ ```
62
+
63
+ Opening a note temporarily gives terminal input to the notes workspace. Closing it aborts child work, disposes the child session, and returns to the unchanged parent conversation and editor.
64
+
65
+ All data is below `getAgentDir()`, which honors `PI_CODING_AGENT_DIR`:
66
+
67
+ ```text
68
+ ${getAgentDir()}/pi-notes/
69
+ β”œβ”€β”€ notes/ # Markdown notes
70
+ β”œβ”€β”€ templates/ # User-managed initial content
71
+ └── sessions/ # Per-note embedded-agent history
72
+ ```
73
+
74
+ New managed directories use mode `0700` and newly created notes use `0600` where the platform supports Unix modes. Existing permissions and files are not changed.
75
+
76
+ ## πŸ’¬ Commands
77
+
78
+ `/notes` opens the browse/create manager and accepts no arguments. It requires Pi TUI mode and rejects RPC, print, and JSON modes.
79
+
80
+ The manager rescans notes and templates when each screen opens. Creating a note copies the selected template exactly once; later template changes do not classify or alter that note.
81
+
82
+ ## Embedded assistant
83
+
84
+ The child session inherits the parent's selected model and thinking level when that model is available through a separate Pi model runtime. It loads no discovered extensions, skills, prompt templates, themes, context files, shell, or general filesystem tools.
85
+
86
+ The child receives only these tools:
87
+
88
+ - `read_current_note` reads the open note and returns its revision.
89
+ - `edit_current_note` replaces one unique exact fragment using the latest revision.
90
+ - `replace_current_note` replaces the complete open note using the latest revision.
91
+
92
+ These tools accept no path. Templates affect initial note content only and never become skills, prompt instructions, persistent types, or durable template associations.
93
+
94
+ ## πŸ”’ Security and privacy
95
+
96
+ - The managed notes-root path, note content, child prompts, tool results, and relevant child conversation history are sent to the selected model provider when the embedded agent runs.
97
+ - 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.
98
+ - Child history remains on disk under `pi-notes/sessions/` until the user removes it.
99
+ - Note operations reject absolute paths, traversal, special files, and symlinked managed paths. Same-directory temporary files and atomic publication preserve the previous note when a managed write fails.
100
+ - Revision checks detect stale writes, but another process can still change a file immediately around publication; this extension does not provide cross-process locking or an OS sandbox.
101
+ - 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.
102
+ - The extension has no delete operation. Removing or disabling the package leaves `getAgentDir()/pi-notes/` untouched.
103
+
104
+ ## 🚧 Limitations
105
+
106
+ - Notes and templates must be regular `.md` files no larger than 45,000 UTF-8 bytes or 1,800 lines.
107
+ - Discovery shows at most 1,000 files, descends at most 16 directories, and reports at most 100 scan issues per pass.
108
+ - 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.
109
+ - Renaming a note outside the extension keeps the Markdown usable but starts a new path-associated child conversation.
110
+ - 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.
111
+ - The first release has no rename, delete, tags, backlinks, full-text index, direct `/notes <path>` route, template language, settings, bundled skill, or template-management UI.
112
+ - Cross-process locking, large notes, rich-text editing, attachments, synchronization, and collaborative editing are not supported.
113
+
114
+ ## πŸ—‚οΈ Package layout
115
+
116
+ ```text
117
+ packages/pi-notes/
118
+ β”œβ”€β”€ src/ # Extension, storage, child session, manager, and workspace
119
+ β”‚ └── index.ts # Thin Pi entrypoint
120
+ β”œβ”€β”€ test/ # Storage, isolation, command, lifecycle, and TUI coverage
121
+ β”œβ”€β”€ README.md
122
+ └── LICENSE
123
+ ```
124
+
125
+ ## πŸ”Ž Keywords
126
+
127
+ pi, pi-extension, notes, markdown, embedded-agent, tui
128
+
129
+ ## πŸ“„ License
130
+
131
+ [MIT](./LICENSE) Β© narumiruna
package/package.json ADDED
@@ -0,0 +1,50 @@
1
+ {
2
+ "name": "@narumitw/pi-notes",
3
+ "version": "0.0.0",
4
+ "description": "Pi extension for managing global Markdown notes with an isolated embedded agent.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "private": false,
8
+ "keywords": [
9
+ "pi-package",
10
+ "pi-extension",
11
+ "pi",
12
+ "notes",
13
+ "markdown",
14
+ "agent"
15
+ ],
16
+ "files": [
17
+ "src",
18
+ "README.md",
19
+ "LICENSE"
20
+ ],
21
+ "pi": {
22
+ "extensions": [
23
+ "./src/index.ts"
24
+ ]
25
+ },
26
+ "scripts": {
27
+ "check": "biome check . && npm run typecheck",
28
+ "format": "biome check --write .",
29
+ "typecheck": "tsc --noEmit"
30
+ },
31
+ "dependencies": {
32
+ "@narumitw/pi-tui-kit": "^0.65.1"
33
+ },
34
+ "peerDependencies": {
35
+ "@earendil-works/pi-ai": "*",
36
+ "@earendil-works/pi-coding-agent": "*",
37
+ "@earendil-works/pi-tui": "*"
38
+ },
39
+ "devDependencies": {
40
+ "@earendil-works/pi-ai": "0.86.0",
41
+ "@earendil-works/pi-coding-agent": "0.86.0",
42
+ "@earendil-works/pi-tui": "0.86.0",
43
+ "typescript": "7.0.2"
44
+ },
45
+ "repository": {
46
+ "type": "git",
47
+ "url": "https://github.com/narumiruna/pi-extensions",
48
+ "directory": "packages/pi-notes"
49
+ }
50
+ }
@@ -0,0 +1,353 @@
1
+ import { createHash } from "node:crypto";
2
+ import type { Dir } from "node:fs";
3
+ import { lstat, mkdir, opendir, realpath } from "node:fs/promises";
4
+ import { isAbsolute, join, relative, sep } from "node:path";
5
+ import { type Api, type Model, Type } from "@earendil-works/pi-ai";
6
+ import {
7
+ type AgentSession,
8
+ type CreateAgentSessionOptions,
9
+ createAgentSession,
10
+ DefaultResourceLoader,
11
+ defineTool,
12
+ ModelRuntime,
13
+ SessionManager,
14
+ SettingsManager,
15
+ } from "@earendil-works/pi-coding-agent";
16
+ import { sanitizeTerminalText } from "@narumitw/pi-tui-kit/terminal-text";
17
+ import { CHILD_TOOL_NAMES, MAX_SESSION_FILES_PER_NOTE, NOTES_SYSTEM_PROMPT } from "./constants.js";
18
+ import type { NoteSnapshot, NotesStorage } from "./storage.js";
19
+
20
+ export interface CreateNotesChildSessionOptions {
21
+ agentDir: string;
22
+ storage: NotesStorage;
23
+ notePath: string;
24
+ parentModel: Model<Api> | undefined;
25
+ thinkingLevel: NonNullable<CreateAgentSessionOptions["thinkingLevel"]>;
26
+ signal?: AbortSignal;
27
+ onNoteChanged?(snapshot: NoteSnapshot): void;
28
+ }
29
+
30
+ export interface NotesChildSession {
31
+ session: AgentSession;
32
+ resumed: boolean;
33
+ recoveryWarning?: string;
34
+ modelFallbackMessage?: string;
35
+ }
36
+
37
+ export interface NotesChildSessionDependencies {
38
+ createModelRuntime(options: Parameters<typeof ModelRuntime.create>[0]): Promise<ModelRuntime>;
39
+ }
40
+
41
+ export async function createNotesChildSession(
42
+ options: CreateNotesChildSessionOptions,
43
+ dependencies: Partial<NotesChildSessionDependencies> = {},
44
+ ): Promise<NotesChildSession> {
45
+ throwIfAborted(options.signal);
46
+ if (!options.parentModel) throw new Error("Select a model in the parent Pi session before opening a note");
47
+
48
+ const createModelRuntime = dependencies.createModelRuntime ?? ModelRuntime.create;
49
+ const modelRuntime = await createModelRuntime({
50
+ authPath: join(options.agentDir, "auth.json"),
51
+ modelsPath: join(options.agentDir, "models.json"),
52
+ modelsStorePath: join(options.agentDir, "models-store.json"),
53
+ signal: options.signal,
54
+ });
55
+ throwIfAborted(options.signal);
56
+ const model = modelRuntime.getModel(options.parentModel.provider, options.parentModel.id);
57
+ if (!model) {
58
+ throw new Error(
59
+ `The selected model ${options.parentModel.provider}/${options.parentModel.id} is not available to the embedded notes runtime. Providers registered only by another extension are not inherited.`,
60
+ );
61
+ }
62
+
63
+ const settingsManager = SettingsManager.inMemory({
64
+ compaction: { enabled: true },
65
+ retry: { enabled: true },
66
+ });
67
+ const resourceLoader = new DefaultResourceLoader({
68
+ cwd: options.storage.paths.notes,
69
+ agentDir: options.agentDir,
70
+ settingsManager,
71
+ noExtensions: true,
72
+ noSkills: true,
73
+ noPromptTemplates: true,
74
+ noThemes: true,
75
+ noContextFiles: true,
76
+ systemPrompt: NOTES_SYSTEM_PROMPT,
77
+ });
78
+ await resourceLoader.reload();
79
+ throwIfAborted(options.signal);
80
+
81
+ const selectedSession = await selectNoteSessionManager(
82
+ options.storage.paths.notes,
83
+ options.storage.paths.sessions,
84
+ options.notePath,
85
+ options.signal,
86
+ );
87
+ throwIfAborted(options.signal);
88
+ if (!selectedSession.manager.getSessionName()) {
89
+ selectedSession.manager.appendSessionInfo(sanitizeTerminalText(options.notePath));
90
+ }
91
+
92
+ const tools = createCurrentNoteTools(options.storage, options.notePath, options.onNoteChanged);
93
+ const sessionModelRuntime = options.signal ? withCancellableAuth(modelRuntime, options.signal) : modelRuntime;
94
+ const result = await createAgentSession({
95
+ cwd: options.storage.paths.notes,
96
+ agentDir: options.agentDir,
97
+ modelRuntime: sessionModelRuntime,
98
+ model,
99
+ thinkingLevel: options.thinkingLevel,
100
+ tools: [...CHILD_TOOL_NAMES],
101
+ customTools: tools,
102
+ resourceLoader,
103
+ sessionManager: selectedSession.manager,
104
+ settingsManager,
105
+ });
106
+ if (options.signal?.aborted) {
107
+ result.session.dispose();
108
+ throwIfAborted(options.signal);
109
+ }
110
+ if (result.extensionsResult.extensions.length > 0 || result.extensionsResult.errors.length > 0) {
111
+ result.session.dispose();
112
+ throw new Error("The embedded notes runtime did not remain resource-isolated");
113
+ }
114
+ const activeTools = result.session.getActiveToolNames();
115
+ if (
116
+ activeTools.length !== CHILD_TOOL_NAMES.length ||
117
+ activeTools.some((toolName, index) => toolName !== CHILD_TOOL_NAMES[index])
118
+ ) {
119
+ result.session.dispose();
120
+ throw new Error(`Unexpected embedded notes tool set: ${activeTools.join(", ") || "none"}`);
121
+ }
122
+
123
+ return {
124
+ session: result.session,
125
+ resumed: selectedSession.resumed,
126
+ ...(selectedSession.recoveryWarning ? { recoveryWarning: selectedSession.recoveryWarning } : {}),
127
+ ...(result.modelFallbackMessage ? { modelFallbackMessage: result.modelFallbackMessage } : {}),
128
+ };
129
+ }
130
+
131
+ export function createCurrentNoteTools(
132
+ storage: NotesStorage,
133
+ notePath: string,
134
+ onNoteChanged?: (snapshot: NoteSnapshot) => void,
135
+ ) {
136
+ const readTool = defineTool({
137
+ name: "read_current_note",
138
+ label: "Read current note",
139
+ description: "Read the complete current Markdown note and return its revision. This tool never accepts a path.",
140
+ parameters: Type.Object({}),
141
+ async execute(_toolCallId, _params, signal) {
142
+ const note = await storage.readNote(notePath, signal);
143
+ return {
144
+ content: [
145
+ {
146
+ type: "text" as const,
147
+ text: `Revision: ${note.revision}\nBytes: ${note.size}\n\n${note.content}`,
148
+ },
149
+ ],
150
+ details: { revision: note.revision, size: note.size },
151
+ };
152
+ },
153
+ });
154
+
155
+ const editTool = defineTool({
156
+ name: "edit_current_note",
157
+ label: "Edit current note",
158
+ description:
159
+ "Replace one unique exact text fragment in the current Markdown note. This tool never accepts a path and rejects stale revisions.",
160
+ parameters: Type.Object({
161
+ revision: Type.String({ description: "Latest revision returned by a current-note tool" }),
162
+ oldText: Type.String({ minLength: 1, description: "Unique exact text to replace" }),
163
+ newText: Type.String({ description: "Replacement text" }),
164
+ }),
165
+ async execute(_toolCallId, params, signal) {
166
+ const note = await storage.editNote(notePath, params.revision, params.oldText, params.newText, signal);
167
+ notifyNoteChanged(onNoteChanged, note);
168
+ return mutationResult(note);
169
+ },
170
+ });
171
+
172
+ const replaceTool = defineTool({
173
+ name: "replace_current_note",
174
+ label: "Replace current note",
175
+ description:
176
+ "Replace the complete current Markdown note. Use only when a precise edit is unsuitable. This tool never accepts a path and rejects stale revisions.",
177
+ parameters: Type.Object({
178
+ revision: Type.String({ description: "Latest revision returned by a current-note tool" }),
179
+ content: Type.String({ description: "Complete replacement Markdown" }),
180
+ }),
181
+ async execute(_toolCallId, params, signal) {
182
+ const note = await storage.replaceNote(notePath, params.revision, params.content, signal);
183
+ notifyNoteChanged(onNoteChanged, note);
184
+ return mutationResult(note);
185
+ },
186
+ });
187
+
188
+ return [readTool, editTool, replaceTool];
189
+ }
190
+
191
+ export function noteSessionKey(notePath: string): string {
192
+ return createHash("sha256").update(notePath).digest("hex");
193
+ }
194
+
195
+ async function selectNoteSessionManager(
196
+ notesRoot: string,
197
+ sessionsRoot: string,
198
+ notePath: string,
199
+ signal?: AbortSignal,
200
+ ): Promise<{ manager: SessionManager; resumed: boolean; recoveryWarning?: string }> {
201
+ throwIfAborted(signal);
202
+ const rootInfo = await lstat(sessionsRoot);
203
+ throwIfAborted(signal);
204
+ if (rootInfo.isSymbolicLink() || !rootInfo.isDirectory()) {
205
+ throw new Error(`Invalid note sessions root: ${sessionsRoot}`);
206
+ }
207
+ const root = await realpath(sessionsRoot);
208
+ throwIfAborted(signal);
209
+ const sessionDirectory = join(root, noteSessionKey(notePath));
210
+ assertContained(root, sessionDirectory);
211
+ try {
212
+ await mkdir(sessionDirectory, { mode: 0o700 });
213
+ } catch (error) {
214
+ if (!isNodeError(error, "EEXIST")) throw error;
215
+ }
216
+ throwIfAborted(signal);
217
+ const sessionInfo = await lstat(sessionDirectory);
218
+ throwIfAborted(signal);
219
+ if (sessionInfo.isSymbolicLink() || !sessionInfo.isDirectory()) {
220
+ throw new Error(`Invalid note session directory: ${sessionDirectory}`);
221
+ }
222
+ const canonicalDirectory = await realpath(sessionDirectory);
223
+ throwIfAborted(signal);
224
+ assertContained(root, canonicalDirectory);
225
+ if (canonicalDirectory !== sessionDirectory) throw new Error("Note session directory is not canonical");
226
+
227
+ const candidates: string[] = [];
228
+ let directory: Dir | undefined;
229
+ try {
230
+ directory = await opendir(canonicalDirectory);
231
+ throwIfAborted(signal);
232
+ for await (const entry of directory) {
233
+ throwIfAborted(signal);
234
+ if (entry.isSymbolicLink() || !entry.isFile() || !entry.name.endsWith(".jsonl")) continue;
235
+ candidates.push(entry.name);
236
+ if (candidates.length > MAX_SESSION_FILES_PER_NOTE) {
237
+ throw new Error(`A note may have at most ${MAX_SESSION_FILES_PER_NOTE} saved sessions`);
238
+ }
239
+ }
240
+ throwIfAborted(signal);
241
+ } finally {
242
+ await directory?.close().catch(() => undefined);
243
+ }
244
+ throwIfAborted(signal);
245
+ candidates.sort((first, second) => second.localeCompare(first));
246
+
247
+ let invalidSessions = 0;
248
+ for (const name of candidates) {
249
+ const file = join(canonicalDirectory, name);
250
+ try {
251
+ const info = await lstat(file);
252
+ throwIfAborted(signal);
253
+ if (info.isSymbolicLink() || !info.isFile()) continue;
254
+ const manager = SessionManager.open(file, canonicalDirectory, notesRoot);
255
+ return {
256
+ manager,
257
+ resumed: true,
258
+ ...(invalidSessions > 0
259
+ ? {
260
+ recoveryWarning: `Ignored ${invalidSessions} invalid newer note session${invalidSessions === 1 ? "" : "s"}.`,
261
+ }
262
+ : {}),
263
+ };
264
+ } catch {
265
+ throwIfAborted(signal);
266
+ invalidSessions += 1;
267
+ }
268
+ }
269
+
270
+ return {
271
+ manager: SessionManager.create(notesRoot, canonicalDirectory),
272
+ resumed: false,
273
+ ...(invalidSessions > 0
274
+ ? {
275
+ recoveryWarning: `Started a new conversation after ${invalidSessions} saved note session${invalidSessions === 1 ? "" : "s"} could not be loaded.`,
276
+ }
277
+ : {}),
278
+ };
279
+ }
280
+
281
+ function withCancellableAuth(modelRuntime: ModelRuntime, lifetime: AbortSignal): ModelRuntime {
282
+ // AgentSession.prompt does not forward caller cancellation to its authentication check.
283
+ const checkAuth: ModelRuntime["checkAuth"] = (providerId, options) => {
284
+ const signal = options?.signal ? AbortSignal.any([lifetime, options.signal]) : lifetime;
285
+ throwIfAborted(signal);
286
+ return settleOnAbort(modelRuntime.checkAuth(providerId, { ...options, signal }), signal);
287
+ };
288
+ return new Proxy(modelRuntime, {
289
+ get(target, property) {
290
+ if (property === "checkAuth") return checkAuth;
291
+ const value = Reflect.get(target, property, target) as unknown;
292
+ return typeof value === "function" ? value.bind(target) : value;
293
+ },
294
+ });
295
+ }
296
+
297
+ function settleOnAbort<T>(operation: Promise<T>, signal: AbortSignal): Promise<T> {
298
+ if (signal.aborted) return Promise.reject(abortReason(signal));
299
+ return new Promise<T>((resolve, reject) => {
300
+ const abort = () => reject(abortReason(signal));
301
+ signal.addEventListener("abort", abort, { once: true });
302
+ void operation.then(
303
+ (value) => {
304
+ signal.removeEventListener("abort", abort);
305
+ if (signal.aborted) reject(abortReason(signal));
306
+ else resolve(value);
307
+ },
308
+ (error: unknown) => {
309
+ signal.removeEventListener("abort", abort);
310
+ reject(error);
311
+ },
312
+ );
313
+ });
314
+ }
315
+
316
+ function abortReason(signal: AbortSignal): Error {
317
+ return signal.reason instanceof Error ? signal.reason : new DOMException("Operation aborted", "AbortError");
318
+ }
319
+
320
+ function notifyNoteChanged(callback: ((snapshot: NoteSnapshot) => void) | undefined, note: NoteSnapshot): void {
321
+ try {
322
+ callback?.(note);
323
+ } catch {
324
+ // The note is already published; a rendering callback must not turn success into a tool failure.
325
+ }
326
+ }
327
+
328
+ function mutationResult(note: NoteSnapshot) {
329
+ return {
330
+ content: [
331
+ {
332
+ type: "text" as const,
333
+ text: `Updated the current note.\nRevision: ${note.revision}\nBytes: ${note.size}`,
334
+ },
335
+ ],
336
+ details: { revision: note.revision, size: note.size },
337
+ };
338
+ }
339
+
340
+ function assertContained(root: string, candidate: string): void {
341
+ const nested = relative(root, candidate);
342
+ if (nested === "" || (!nested.startsWith(`..${sep}`) && nested !== ".." && !isAbsolute(nested))) return;
343
+ throw new Error("Session path escapes the managed sessions directory");
344
+ }
345
+
346
+ function isNodeError(error: unknown, code: string): error is NodeJS.ErrnoException {
347
+ return error instanceof Error && "code" in error && error.code === code;
348
+ }
349
+
350
+ function throwIfAborted(signal?: AbortSignal): void {
351
+ if (!signal?.aborted) return;
352
+ throw signal.reason instanceof Error ? signal.reason : new DOMException("Operation aborted", "AbortError");
353
+ }
@@ -0,0 +1,22 @@
1
+ export const NOTES_DIRECTORY = "notes";
2
+ export const TEMPLATES_DIRECTORY = "templates";
3
+ export const SESSIONS_DIRECTORY = "sessions";
4
+
5
+ /** Keep a complete note plus tool metadata below Pi's 50 KB model-output ceiling. */
6
+ export const MAX_MARKDOWN_BYTES = 45_000;
7
+ export const MAX_MARKDOWN_LINES = 1_800;
8
+ export const MAX_DISCOVERED_FILES = 1_000;
9
+ export const MAX_SCAN_DEPTH = 16;
10
+ export const MAX_SCAN_ERRORS = 100;
11
+ export const MAX_SESSION_FILES_PER_NOTE = 100;
12
+ export const MAX_TRANSCRIPT_MESSAGES = 200;
13
+ export const MAX_TRANSCRIPT_CHARS = 50_000;
14
+ export const WIDE_WORKSPACE_COLUMNS = 100;
15
+
16
+ export const CHILD_TOOL_NAMES = ["read_current_note", "edit_current_note", "replace_current_note"] as const;
17
+
18
+ export const NOTES_SYSTEM_PROMPT = `You are the assistant for one Markdown note.
19
+
20
+ Work only on the current note. Read it before editing. Use edit_current_note for precise changes and replace_current_note only when a full replacement is necessary. Every mutation requires the latest revision returned by read_current_note or a successful mutation. If a revision is stale, read again before retrying.
21
+
22
+ You have no access to other notes, templates, sessions, project files, or a shell. Do not claim that you changed content unless a mutation tool succeeded. Keep the note valid Markdown and preserve unrelated content.`;
package/src/index.ts ADDED
@@ -0,0 +1 @@
1
+ export { default } from "./notes-extension.js";