@cad0p/pi-napkin 0.6.6 → 0.7.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
@@ -151,7 +151,7 @@ Both extensions use napkin's built-in vault resolution. The resolution order is:
151
151
 
152
152
  1. **Local project vault** — walk up from cwd looking for `.napkin/` (or `.obsidian/.napkin/`)
153
153
  2. **Global fallback** — read `$XDG_CONFIG_HOME/napkin/config.json` (defaults to `~/.config/napkin/config.json`)
154
- 3. **Bare vault** — create a new vault at cwd as a last resort
154
+ 3. **Error** — if neither exists, napkin >= 0.14 fails with `VaultNotFoundError` (exit code 4) and an actionable message; it **never** creates a vault implicitly (older versions still auto-create a bare vault at cwd).
155
155
 
156
156
  ```json
157
157
  // ~/.config/napkin/config.json
@@ -160,7 +160,7 @@ Both extensions use napkin's built-in vault resolution. The resolution order is:
160
160
  }
161
161
  ```
162
162
 
163
- Local project vaults take priority when present.
163
+ Local project vaults take priority when present. No vault yet? Run `napkin init` in the directory you want as the vault root (see `napkin init --list` for templates) — the napkin-context extension surfaces a no-vault guidance message on session start when no vault resolves (no local project vault and no global fallback), so a fresh setup is self-documenting.
164
164
 
165
165
  ### Migrating from `~/.pi/agent/napkin.json`
166
166
 
@@ -12,6 +12,7 @@ import type {
12
12
  } from "@earendil-works/pi-coding-agent";
13
13
  import { SessionManager } from "@earendil-works/pi-coding-agent";
14
14
  import type { AutocompleteItem } from "@earendil-works/pi-tui";
15
+ import { sendCustomMessageWithFallback } from "../shared/custom-message";
15
16
  import {
16
17
  countTrackedFiles,
17
18
  ensureVaultReadyForDistill,
@@ -966,8 +967,10 @@ export default function (pi: ExtensionAPI) {
966
967
  * `lastDistillCompletionMessageCursor` to current end and extract
967
968
  * write-class file ops (reuses `extractFileOpsFromMessage` via a
968
969
  * slice-bounded `SessionEntriesSource` adapter).
969
- * 3. Intersect. If non-empty, post an `appendCustomMessageEntry`
970
- * with `customType: "napkin-distill-overlap"`.
970
+ * 3. Intersect. If non-empty, post a custom message with
971
+ * `customType: "napkin-distill-overlap"` via the shared
972
+ * `sendCustomMessageWithFallback` helper (see
973
+ * extensions/shared/custom-message.ts).
971
974
  * 4. Update `lastDistillCompletionMessageCursor` to the current end
972
975
  * of the entries array — even when overlap is empty — so the
973
976
  * next completion only walks new entries.
@@ -980,7 +983,7 @@ export default function (pi: ExtensionAPI) {
980
983
  * `appendSystemPrompt` mechanism.
981
984
  *
982
985
  * Failure modes are all silent (best-effort): vault resolution fail,
983
- * git fail, missing startSha, missing SessionManager mutation method.
986
+ * git fail, missing startSha, sendMessage API unavailable.
984
987
  * Completion bookkeeping must never block the next distill.
985
988
  */
986
989
  function postOverlapNoticeOnCompletion(
@@ -1020,23 +1023,20 @@ export default function (pi: ExtensionAPI) {
1020
1023
 
1021
1024
  if (overlap.length === 0) return;
1022
1025
 
1023
- // Post the notice. SessionManager's mutation methods are not on the
1024
- // public ReadonlySessionManager type that pi exposes via
1025
- // ExtensionContext, so we cast through Partial<SessionManager> the
1026
- // same way `napkin-context` does — graceful degradation if pi ever
1027
- // tightens the readonly contract at runtime.
1028
- const sm = ctx.sessionManager as Partial<SessionManager>;
1029
- if (typeof sm.appendCustomMessageEntry === "function") {
1030
- try {
1031
- sm.appendCustomMessageEntry(
1032
- "napkin-distill-overlap",
1033
- formatOverlapNotice(overlap),
1034
- true, // display: surface in TUI so the user sees what happened
1035
- );
1036
- } catch {
1037
- // best-effort; cursor was already advanced above
1038
- }
1039
- }
1026
+ // Post the notice via the shared sendCustomMessageWithFallback helper
1027
+ // (pi.sendMessage primary, direct-append fallback) so the TUI renders it
1028
+ // live. See extensions/shared/custom-message.ts for the streaming
1029
+ // steer divergence (deferred render/append after the cursor advanced)
1030
+ // and the invalidated-runtime fallback (e.g. /new mid-distill).
1031
+ // (Verified empirically 2026-08-11: direct mid-session append invisible
1032
+ // in TUI, sendMessage renders immediately.)
1033
+ sendCustomMessageWithFallback({
1034
+ poster: pi,
1035
+ sm: ctx.sessionManager as Partial<SessionManager>,
1036
+ customType: "napkin-distill-overlap",
1037
+ content: formatOverlapNotice(overlap),
1038
+ display: true, // display: surface in TUI so the user sees what happened
1039
+ });
1040
1040
  }
1041
1041
 
1042
1042
  /**
@@ -1936,7 +1936,7 @@ export function formatOutcomeNotification(args: {
1936
1936
  * 1. Persist the new cursor (`newCursor`) into closure state, even
1937
1937
  * when overlap is empty — otherwise the next completion re-walks
1938
1938
  * the same window.
1939
- * 2. If overlap is non-empty, post it via `appendCustomMessageEntry`
1939
+ * 2. If overlap is non-empty, post it via `pi.sendMessage`
1940
1940
  * (or otherwise notify the agent).
1941
1941
  *
1942
1942
  * The session walk is bounded to `entries.slice(cursor)` so each
@@ -11,6 +11,7 @@ import {
11
11
  } from "@earendil-works/pi-coding-agent";
12
12
  import { Markdown, Text } from "@earendil-works/pi-tui";
13
13
  import { Type } from "@sinclair/typebox";
14
+ import { sendCustomMessageWithFallback } from "../shared/custom-message";
14
15
 
15
16
  function loadShowStatus(vaultPath: string): boolean {
16
17
  const configPath = path.join(vaultPath, "config.json");
@@ -169,7 +170,17 @@ function getNapkin(cwd: string): Napkin {
169
170
  return new Napkin(cwd);
170
171
  }
171
172
 
172
- function getOverview(n: Napkin): string | null {
173
+ function hasInjectedContext(sm: Pick<SessionManager, "getEntries">): boolean {
174
+ return sm
175
+ .getEntries()
176
+ .some(
177
+ (e) =>
178
+ e.type === "custom_message" &&
179
+ (e as { customType?: string }).customType === "napkin-context",
180
+ );
181
+ }
182
+
183
+ function getOverview(n: Napkin): { text: string; root: string } | null {
173
184
  try {
174
185
  // napkin >= 0.12.3 ships the fork's defaults (collapseDepth 2, maxRows
175
186
  // 100) in DEFAULT_CONFIG, so the extension must not diverge from napkin —
@@ -201,7 +212,7 @@ function getOverview(n: Napkin): string | null {
201
212
  }
202
213
  const body = text.trim();
203
214
  if (!body) return null;
204
- return `Vault root: ${overview.root} (napkin vault --json | jq -r .path)\n\n${body}`;
215
+ return { text: body, root: overview.root };
205
216
  } catch {
206
217
  return null;
207
218
  }
@@ -209,6 +220,7 @@ function getOverview(n: Napkin): string | null {
209
220
 
210
221
  export default function (pi: ExtensionAPI) {
211
222
  let hasVault = false;
223
+ let vaultRoot: string | null = null;
212
224
 
213
225
  pi.registerMessageRenderer(
214
226
  "napkin-context",
@@ -260,47 +272,73 @@ export default function (pi: ExtensionAPI) {
260
272
  let n: Napkin;
261
273
  try {
262
274
  n = getNapkin(ctx.cwd);
263
- } catch {
275
+ } catch (e) {
276
+ // No usable vault (none found, or a refused legacy-layout vault).
277
+ // Surface napkin's own actionable error to BOTH the user (TUI) and the
278
+ // agent (context), so the first session is self-documenting: without
279
+ // this, the kb_* tools are the only discovery path, and a session
280
+ // that never calls them never learns a vault is expected or how to
281
+ // create/configure one.
282
+ if (e instanceof Error && e.name === "VaultNotFoundError") {
283
+ if (!hasInjectedContext(ctx.sessionManager)) {
284
+ sendCustomMessageWithFallback({
285
+ poster: pi,
286
+ sm: ctx.sessionManager as Partial<SessionManager>,
287
+ customType: "napkin-context",
288
+ content: e.message,
289
+ onFallbackFailure: (err) => {
290
+ if (ctx.hasUI) {
291
+ ctx.ui.notify(
292
+ `napkin-context: could not surface no-vault guidance (${
293
+ err instanceof Error ? err.message : String(err)
294
+ })`,
295
+ "warning",
296
+ );
297
+ }
298
+ },
299
+ });
300
+ }
301
+ if (ctx.hasUI) {
302
+ // Unconditional on purpose — unlike the success path it cannot
303
+ // consult loadShowStatus(): no vault exists, so there is no vault
304
+ // config.json to read. The hint must render even when the user
305
+ // never configured showStatus, or nothing explains why no vault
306
+ // context was injected.
307
+ ctx.ui.setStatus(
308
+ "napkin",
309
+ ctx.ui.theme.fg("dim", "napkin: no vault"),
310
+ );
311
+ }
312
+ }
264
313
  return;
265
314
  }
266
315
 
267
316
  const overview = getOverview(n);
268
317
  hasVault = !!overview;
318
+ vaultRoot = overview?.root ?? null;
269
319
 
270
320
  if (overview) {
271
321
  // Check if we already injected context in this session
272
- const alreadyInjected = ctx.sessionManager
273
- .getEntries()
274
- .some(
275
- (e) =>
276
- e.type === "custom_message" &&
277
- (e as { customType?: string }).customType === "napkin-context",
278
- );
322
+ const alreadyInjected = hasInjectedContext(ctx.sessionManager);
279
323
 
280
324
  if (!alreadyInjected) {
281
- // pi's ExtensionContext narrows sessionManager to
282
- // ReadonlySessionManager, which omits mutation methods. At runtime
283
- // it's always the full SessionManager, but if pi ever wraps the
284
- // instance in a genuine readonly proxy the mutation method will
285
- // either be absent or throw. Guard both the duck-type and the
286
- // call so the worst-case is a degraded (no context injection)
287
- // session, not a fatal extension error. (R2-2)
288
- const sm = ctx.sessionManager as Partial<SessionManager>;
289
- if (typeof sm.appendCustomMessageEntry === "function") {
290
- try {
291
- sm.appendCustomMessageEntry(
292
- "napkin-context",
293
- "## Napkin vault context\n" +
294
- "You have access to a napkin vault (Obsidian-compatible knowledge base). " +
295
- "Here is the vault overview. Use the kb_search tool to find specific content, " +
296
- "kb_read to read files, and kb_outline to see file structure.\n\n" +
297
- overview,
298
- true,
299
- );
300
- } catch (err) {
301
- // Graceful degradation: pi may have tightened the readonly
302
- // contract at runtime. Surface once, then proceed without
303
- // context injection.
325
+ // Send via the public message event path (message_start) so the TUI
326
+ // renders the custom message live. A direct sessionManager append is
327
+ // only picked up by the next full chat rebuild — on /new the chat is
328
+ // rebuilt BEFORE session_start handlers run, so a direct append would
329
+ // leave the vault overview invisible in the new session's chat (the
330
+ // stale line survives as terminal pixels until the next repaint).
331
+ // pi.sendMessage is fire-and-forget (void). In the idle path it
332
+ // appends the entry to the session manager synchronously AND pushes
333
+ // the message into agent state — the overview participates in LLM
334
+ // context by design, even where the TUI event is not subscribed yet
335
+ // (startup path).
336
+ sendCustomMessageWithFallback({
337
+ poster: pi,
338
+ sm: ctx.sessionManager as Partial<SessionManager>,
339
+ customType: "napkin-context",
340
+ content: overview.text,
341
+ onFallbackFailure: (err) => {
304
342
  if (ctx.hasUI) {
305
343
  ctx.ui.notify(
306
344
  `napkin-context: could not inject vault overview (${
@@ -309,8 +347,8 @@ export default function (pi: ExtensionAPI) {
309
347
  "warning",
310
348
  );
311
349
  }
312
- }
313
- }
350
+ },
351
+ });
314
352
  }
315
353
  }
316
354
 
@@ -324,6 +362,15 @@ export default function (pi: ExtensionAPI) {
324
362
  }
325
363
  });
326
364
 
365
+ pi.on("before_agent_start", async (event) => {
366
+ if (!hasVault || !vaultRoot) return {};
367
+ return {
368
+ systemPrompt:
369
+ event.systemPrompt +
370
+ `\n\nA napkin obsidian vault with the user context is available at ${vaultRoot}. Before answering, you must consult it via kb_search.`,
371
+ };
372
+ });
373
+
327
374
  // ── Tools ───────────────────────────────────────────────────────
328
375
 
329
376
  pi.registerTool({
@@ -0,0 +1,79 @@
1
+ import type {
2
+ ExtensionAPI,
3
+ SessionManager,
4
+ } from "@earendil-works/pi-coding-agent";
5
+
6
+ export interface SendCustomMessageWithFallbackOptions {
7
+ /** The extension API whose `sendMessage` is fire-and-forget (void). */
8
+ poster: Pick<ExtensionAPI, "sendMessage">;
9
+ /**
10
+ * The captured session manager for the fallback append. pi narrows the
11
+ * ExtensionContext type to `ReadonlySessionManager` at compile time, so
12
+ * callers pass `ctx.sessionManager as Partial<SessionManager>` — the
13
+ * runtime object is the full SessionManager.
14
+ */
15
+ sm: Partial<SessionManager> | undefined;
16
+ customType: string;
17
+ content: string;
18
+ /** Defaults to `true` (surface in the TUI). */
19
+ display?: boolean;
20
+ /**
21
+ * Invoked when the fallback append itself throws (e.g. a genuinely
22
+ * readonly manager at runtime). Lets callers surface a warning;
23
+ * omitted = silent best-effort.
24
+ */
25
+ onFallbackFailure?: (err: unknown) => void;
26
+ }
27
+
28
+ /**
29
+ * Deliver an extension custom message so the TUI renders it live, with a
30
+ * graceful fallback. Never throws.
31
+ *
32
+ * Primary path: `pi.sendMessage` (public extension API, fire-and-forget /
33
+ * void). In the idle case `sendCustomMessage` appends the entry to the
34
+ * session manager synchronously AND emits `message_start`, so the TUI
35
+ * renders the message immediately. A direct `sessionManager.append`
36
+ * is only picked up by the next full chat rebuild (e.g. /reload): on
37
+ * `/new` the chat is rebuilt BEFORE `session_start` handlers run, so a
38
+ * direct append never becomes a TUI component in the new session (the
39
+ * stale line survives as terminal pixels until the next repaint), and
40
+ * mid-session appends stay invisible until a rebuild. (Verified
41
+ * empirically 2026-08-11: direct mid-session append invisible in TUI,
42
+ * sendMessage renders immediately.)
43
+ *
44
+ * Fallback: when `sendMessage` throws — e.g. the spawning session's
45
+ * runtime was invalidated by a session switch (e.g. /new) while the
46
+ * call was in flight: `assertActive()` throws synchronously — append
47
+ * directly on the captured session manager, which keeps working and
48
+ * surfaces on the next rebuild (e.g. resume).
49
+ *
50
+ * Known divergences of the primary path (best-effort by design; no
51
+ * extension-visible `isStreaming` exists):
52
+ * - While the parent agent is streaming, `sendMessage` routes to
53
+ * `agent.steer()`: the message is drained into the running turn, the
54
+ * agent runs an extra assistant response, and the TUI render + session
55
+ * append are deferred until drain.
56
+ */
57
+ export function sendCustomMessageWithFallback(
58
+ options: SendCustomMessageWithFallbackOptions,
59
+ ): void {
60
+ const {
61
+ poster,
62
+ sm,
63
+ customType,
64
+ content,
65
+ display = true,
66
+ onFallbackFailure,
67
+ } = options;
68
+ try {
69
+ poster.sendMessage({ customType, content, display });
70
+ } catch {
71
+ if (sm && typeof sm.appendCustomMessageEntry === "function") {
72
+ try {
73
+ sm.appendCustomMessageEntry(customType, content, display);
74
+ } catch (err) {
75
+ onFallbackFailure?.(err);
76
+ }
77
+ }
78
+ }
79
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cad0p/pi-napkin",
3
- "version": "0.6.6",
3
+ "version": "0.7.0",
4
4
  "description": "📜 Napkin integration for pi — vault context, knowledge tools, and automatic distillation with git-worktree concurrency safety",
5
5
  "type": "module",
6
6
  "publishConfig": {
@@ -64,7 +64,7 @@
64
64
  "vitest": "^2.1.0"
65
65
  },
66
66
  "dependencies": {
67
- "@cad0p/napkin": "^0.13.2"
67
+ "@cad0p/napkin": "^0.13.2 || ^0.14.0"
68
68
  },
69
69
  "peerDependencies": {
70
70
  "@earendil-works/pi-coding-agent": ">=0.74.0",
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: napkin
3
- description: Read, create, search, and manage notes in Obsidian vaults using the napkin CLI. Works directly on markdown files and canvas files — no Obsidian app required. Use when the user asks to interact with their Obsidian vault, manage notes, search vault content, work with tasks, tags, properties, daily notes, templates, bases, bookmarks, aliases, or canvas files from the command line.
3
+ description: Read, create, search, and manage notes in Obsidian vaults using the napkin CLI. Works directly on markdown files and canvas files — no Obsidian app required. Use when the user asks to interact with their Obsidian vault, set up or initialize a knowledge base / note vault (napkin init), configure the default vault, or manage notes, search vault content, work with tasks, tags, properties, daily notes, templates, bases, bookmarks, aliases, or canvas files from the command line.
4
4
  ---
5
5
 
6
6
  # napkin
@@ -9,7 +9,7 @@ CLI for Obsidian vaults. Operates directly on markdown files — no Obsidian app
9
9
 
10
10
  See: **[README.md](../../README.md)** for full documentation — install, config, auto-distill, concurrency, commands, tools, agent visibility, vault setup, and troubleshooting.
11
11
 
12
- The single piece of agent-critical operational info we keep in the SKILL itself is vault resolution, since misresolution silently creates a bare vault (which is a data-loss hazard).
12
+ The single piece of agent-critical operational info we keep in the SKILL itself is vault resolution, since misresolution used to silently create a bare vault (a data-loss hazard) — that footgun is gone, but knowing where a command points remains essential.
13
13
 
14
14
  ## Vault Resolution
15
15
 
@@ -18,13 +18,11 @@ Before any command runs, napkin picks a vault in this order:
18
18
  1. **`--vault <path>`** flag, if supplied.
19
19
  2. **Nearest ancestor with `.napkin/`** (or `.obsidian/.napkin/`) walking up from cwd.
20
20
  3. **Global fallback** — `vault` field in `$XDG_CONFIG_HOME/napkin/config.json` (defaults to `~/.config/napkin/config.json`).
21
- 4. **Bare vault auto-created at cwd** — last resort. napkin silently creates `.napkin/` + `NAPKIN.md` + `.obsidian/` in the current directory with no prompt.
22
-
23
- > **Warning:** Step 4 is a footgun at first setup. Running `napkin vault` (or any command that resolves the vault) from a random directory with no ancestor `.napkin/` and no global config will silently create an empty vault there. Always confirm the resolved vault before running commands that might trigger this fallback.
21
+ 4. **Error** — if none of the above exists, napkin >= 0.14 commands fail with `VaultNotFoundError` (exit code 4) and an actionable message: napkin **never** creates a vault implicitly (older versions still auto-create a bare vault as a last resort).
24
22
 
25
23
  ### First-time setup
26
24
 
27
- Configure the global fallback so commands never accidentally create bare vaults:
25
+ When the user has no vault yet, run `napkin init` in the directory they want as the vault root (optionally with `--template personal|coding|research|company|product`), or set up a global vault so commands work from any directory:
28
26
 
29
27
  ```json
30
28
  // ~/.config/napkin/config.json
@@ -41,4 +39,4 @@ Confirm resolution before first use:
41
39
  napkin vault --json | jq -r .path # Should print the expected vault path
42
40
  ```
43
41
 
44
- If it prints a path that shouldn't be a vault (e.g. your cwd or `$HOME`), napkin just created a bare vault there — either delete the stray `.napkin/`/`NAPKIN.md`/`.obsidian/` it generated and configure the global fallback, or re-run with `--vault <path>`.
42
+ If it errors with `No napkin vault found`, either run `napkin init` in a directory you want as a vault, or configure the global fallback above and re-check.