standardnotes-mcp 3.0.0 → 3.1.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.
Files changed (71) hide show
  1. package/CHANGELOG.md +55 -0
  2. package/README.md +118 -55
  3. package/SECURITY.md +2 -1
  4. package/dist/cli/clients.js +124 -0
  5. package/dist/cli/folders.js +63 -0
  6. package/dist/cli/install.js +60 -18
  7. package/dist/cli/isMain.js +21 -0
  8. package/dist/cli/login.js +15 -12
  9. package/dist/cli/logout.js +1 -1
  10. package/dist/cli/setup.js +168 -72
  11. package/dist/config.js +30 -2
  12. package/dist/confirmDelete.js +88 -0
  13. package/dist/server.js +79 -86
  14. package/dist/slimTools.js +78 -0
  15. package/dist/sn/client.js +189 -44
  16. package/dist/sn/entitlement.js +25 -6
  17. package/dist/sn/frontmatter.js +15 -4
  18. package/dist/sn/markdownSections.js +16 -1
  19. package/dist/sn/protocol004.js +11 -8
  20. package/dist/sn/scope.js +34 -0
  21. package/dist/sn/session.js +22 -4
  22. package/dist/tools/daily.js +7 -19
  23. package/dist/tools/history.js +1 -1
  24. package/dist/tools/links.js +2 -9
  25. package/dist/tools/notes.js +142 -42
  26. package/dist/tools/smartviews.js +5 -5
  27. package/dist/tools/tags.js +1 -1
  28. package/dist/tools/templates.js +42 -32
  29. package/dist/version.js +12 -0
  30. package/docs/self-hosted.md +7 -10
  31. package/docs/troubleshooting.md +97 -89
  32. package/package.json +6 -5
  33. package/dist/cli/install.js.map +0 -1
  34. package/dist/cli/login.js.map +0 -1
  35. package/dist/cli/logout.js.map +0 -1
  36. package/dist/cli/setup.js.map +0 -1
  37. package/dist/config.js.map +0 -1
  38. package/dist/index.js.map +0 -1
  39. package/dist/security/errors.js.map +0 -1
  40. package/dist/security/logger.js.map +0 -1
  41. package/dist/security/redact.js.map +0 -1
  42. package/dist/security/regex.js.map +0 -1
  43. package/dist/server.js.map +0 -1
  44. package/dist/sn/cache.js.map +0 -1
  45. package/dist/sn/client.js.map +0 -1
  46. package/dist/sn/crypto.js.map +0 -1
  47. package/dist/sn/dates.js.map +0 -1
  48. package/dist/sn/entitlement.js.map +0 -1
  49. package/dist/sn/frontmatter.js.map +0 -1
  50. package/dist/sn/governance.js.map +0 -1
  51. package/dist/sn/http.js.map +0 -1
  52. package/dist/sn/links.js.map +0 -1
  53. package/dist/sn/markdownSections.js.map +0 -1
  54. package/dist/sn/predicates.js.map +0 -1
  55. package/dist/sn/protocol004.js.map +0 -1
  56. package/dist/sn/scope.js.map +0 -1
  57. package/dist/sn/search.js.map +0 -1
  58. package/dist/sn/session.js.map +0 -1
  59. package/dist/sn/tagHierarchy.js.map +0 -1
  60. package/dist/sn/tasks.js.map +0 -1
  61. package/dist/sn/templates.js.map +0 -1
  62. package/dist/sn/types.js.map +0 -1
  63. package/dist/tools/daily.js.map +0 -1
  64. package/dist/tools/export.js.map +0 -1
  65. package/dist/tools/history.js.map +0 -1
  66. package/dist/tools/links.js.map +0 -1
  67. package/dist/tools/notes.js.map +0 -1
  68. package/dist/tools/smartviews.js.map +0 -1
  69. package/dist/tools/tags.js.map +0 -1
  70. package/dist/tools/tasks.js.map +0 -1
  71. package/dist/tools/templates.js.map +0 -1
package/dist/sn/client.js CHANGED
@@ -6,10 +6,10 @@ import { cacheTtlMs, ensureFresh } from "./cache.js";
6
6
  import { makeParentRef, parentUuidOf, stripParentRefs, subtreeTagUuids, wouldCreateCycle, } from "./tagHierarchy.js";
7
7
  import { ToolError } from "../security/errors.js";
8
8
  import { assertSafeRegex } from "../security/regex.js";
9
- import { getSectionBody, insertIntoSection, outline } from "./markdownSections.js";
9
+ import { continuesBlock, getSectionBody, insertIntoSection, outline } from "./markdownSections.js";
10
10
  import { searchDecryptedNotes } from "./search.js";
11
11
  import { evaluatePredicate, isPredicateJson, notePredicateTarget, summarizePredicate, } from "./predicates.js";
12
- import { resolveScope, scopeAllows, } from "./scope.js";
12
+ import { resolveScope, scopeAllows, scopeReport, } from "./scope.js";
13
13
  import { aiPolicyOf } from "./governance.js";
14
14
  import { extractTasks, setTaskState } from "./tasks.js";
15
15
  import { deleteFrontmatterKey, parseFrontmatter, setFrontmatterKey, } from "./frontmatter.js";
@@ -38,7 +38,7 @@ export async function createClientFromLogin(config, password, mfaPrompt) {
38
38
  }
39
39
  if (!mfaPrompt) {
40
40
  throw new Error("Two-factor authentication is enabled on this account. " +
41
- "Run `npm run login` interactively (it wires the MFA prompt).");
41
+ "Run `standardnotes-mcp-login` interactively (it wires the MFA prompt).");
42
42
  }
43
43
  const mfaKey = err.payload?.mfa_key ?? "";
44
44
  if (!mfaKey) {
@@ -79,6 +79,7 @@ export async function createClientFromLogin(config, password, mfaPrompt) {
79
79
  scope: config.scope ?? { readTags: null, denyTags: [] },
80
80
  governance: config.governance ?? true,
81
81
  clientName: config.clientName ?? (() => null),
82
+ newNoteEditor: config.newNoteEditor ?? null,
82
83
  roles: null,
83
84
  };
84
85
  await saveSession(config.email, {
@@ -98,10 +99,10 @@ export async function createClientFromLogin(config, password, mfaPrompt) {
98
99
  export async function createClientFromSession(config) {
99
100
  const stored = await loadSession(config.email);
100
101
  if (!stored) {
101
- throw new Error("No session found. Run `npm run login` to authenticate first.");
102
+ throw new Error("No session found. Run `standardnotes-mcp-login` to authenticate first.");
102
103
  }
103
104
  if (!stored.masterKeyHex || !/^[0-9a-f]{64}$/i.test(stored.masterKeyHex)) {
104
- throw new Error("Stored session is missing a valid masterKey; run `npm run login` again.");
105
+ throw new Error("Stored session is missing a valid masterKey; run `standardnotes-mcp-login` again.");
105
106
  }
106
107
  const keyParams = stored.keyParams;
107
108
  const rootKey = {
@@ -133,6 +134,7 @@ export async function createClientFromSession(config) {
133
134
  scope: config.scope ?? { readTags: null, denyTags: [] },
134
135
  governance: config.governance ?? true,
135
136
  clientName: config.clientName ?? (() => null),
137
+ newNoteEditor: config.newNoteEditor ?? null,
136
138
  roles: null,
137
139
  };
138
140
  await fullSync(state);
@@ -159,7 +161,7 @@ async function refreshTokens(state) {
159
161
  fresh = await http.refreshSession({ serverUrl: state.serverUrl }, state.authToken, state.refreshToken);
160
162
  }
161
163
  catch (refreshErr) {
162
- throw new Error("Session refresh failed; run `npm run login` to re-authenticate. " +
164
+ throw new Error("Session refresh failed; run `standardnotes-mcp-login` to re-authenticate. " +
163
165
  (refreshErr instanceof Error ? refreshErr.message : String(refreshErr)));
164
166
  }
165
167
  state.authToken = fresh.access_token;
@@ -205,10 +207,29 @@ async function authedCall(state, fn) {
205
207
  return await fn(cfg());
206
208
  }
207
209
  }
210
+ const pendingDecrypts = new WeakMap();
211
+ function pendingFor(state) {
212
+ let p = pendingDecrypts.get(state);
213
+ if (!p) {
214
+ p = { full: true, uuids: new Set() };
215
+ pendingDecrypts.set(state, p);
216
+ }
217
+ return p;
218
+ }
219
+ /** Stores a raw item from the server and queues it for decryption. */
220
+ function storeRaw(state, item) {
221
+ state.encryptedItemsRaw.set(item.uuid, item);
222
+ const p = pendingFor(state);
223
+ p.uuids.add(item.uuid);
224
+ if (item.content_type === "SN|ItemsKey")
225
+ p.full = true;
226
+ }
208
227
  /** Folds items the server sent back into the raw cache; deletions drop out of every cache. */
209
228
  function applyRetrieved(state, items) {
210
229
  for (const item of items) {
211
230
  if (item.deleted) {
231
+ if (state.itemsKeys.has(item.uuid))
232
+ pendingFor(state).full = true;
212
233
  state.encryptedItemsRaw.delete(item.uuid);
213
234
  state.notesCache.delete(item.uuid);
214
235
  state.tagsCache.delete(item.uuid);
@@ -216,14 +237,10 @@ function applyRetrieved(state, items) {
216
237
  state.itemsKeys.delete(item.uuid);
217
238
  continue;
218
239
  }
219
- state.encryptedItemsRaw.set(item.uuid, item);
240
+ storeRaw(state, item);
220
241
  }
221
242
  }
222
243
  async function fullSync(state) {
223
- // Reset the failure counters at the top so a fix upstream (e.g. an
224
- // items_key that arrives on a later page) doesn't leave stale entries.
225
- state.decryptFailedNotes.clear();
226
- state.decryptFailedTags.clear();
227
244
  let cursorToken;
228
245
  let syncToken = state.syncToken ?? undefined;
229
246
  // eslint-disable-next-line no-constant-condition
@@ -236,35 +253,64 @@ async function fullSync(state) {
236
253
  break;
237
254
  }
238
255
  state.syncToken = syncToken ?? null;
239
- // First pass: decrypt items_keys
240
- let mostRecentTs = -Infinity;
241
- for (const item of state.encryptedItemsRaw.values()) {
242
- if (item.content_type !== "SN|ItemsKey")
243
- continue;
244
- try {
245
- const k = await decryptItemsKey(item, state.rootKey);
246
- state.itemsKeys.set(k.uuid, k);
247
- const ts = item.updated_at_timestamp ?? 0;
248
- if (ts >= mostRecentTs) {
249
- mostRecentTs = ts;
250
- state.defaultItemsKeyUuid = k.uuid;
256
+ const pending = pendingFor(state);
257
+ const full = pending.full || state.itemsKeys.size === 0;
258
+ if (full) {
259
+ // Everything is decrypted again, so start the failure lists over.
260
+ state.decryptFailedNotes.clear();
261
+ state.decryptFailedTags.clear();
262
+ // First pass: decrypt items_keys
263
+ let mostRecentTs = -Infinity;
264
+ for (const item of state.encryptedItemsRaw.values()) {
265
+ if (item.content_type !== "SN|ItemsKey")
266
+ continue;
267
+ try {
268
+ const k = await decryptItemsKey(item, state.rootKey);
269
+ state.itemsKeys.set(k.uuid, k);
270
+ const ts = item.updated_at_timestamp ?? 0;
271
+ if (ts >= mostRecentTs) {
272
+ mostRecentTs = ts;
273
+ state.defaultItemsKeyUuid = k.uuid;
274
+ }
275
+ }
276
+ catch (err) {
277
+ logger.warn(`Failed to decrypt items_key ${item.uuid}`, {
278
+ message: err instanceof Error ? err.message : String(err),
279
+ });
251
280
  }
252
281
  }
253
- catch (err) {
254
- logger.warn(`Failed to decrypt items_key ${item.uuid}`, {
255
- message: err instanceof Error ? err.message : String(err),
256
- });
282
+ if (state.itemsKeys.size === 0) {
283
+ throw new Error("No items_key decrypted — likely wrong password or account not on protocol 004.");
257
284
  }
258
285
  }
259
- if (state.itemsKeys.size === 0) {
260
- throw new Error("No items_key decrypted — likely wrong password or account not on protocol 004.");
261
- }
262
286
  const itemsKeyBytesByUuid = new Map();
263
287
  for (const [u, k] of state.itemsKeys.entries()) {
264
288
  itemsKeyBytesByUuid.set(u, k.itemsKey);
265
289
  }
290
+ // Which items to decrypt: all of them on a full pass; otherwise only those
291
+ // the server sent since the last sync, plus earlier failures (an items key
292
+ // that arrived since may fix them).
293
+ let toDecrypt;
294
+ if (full) {
295
+ toDecrypt = [...state.encryptedItemsRaw.values()];
296
+ }
297
+ else {
298
+ const uuids = new Set([
299
+ ...pending.uuids,
300
+ ...state.decryptFailedNotes,
301
+ ...state.decryptFailedTags,
302
+ ]);
303
+ state.decryptFailedNotes.clear();
304
+ state.decryptFailedTags.clear();
305
+ toDecrypt = [];
306
+ for (const u of uuids) {
307
+ const item = state.encryptedItemsRaw.get(u);
308
+ if (item)
309
+ toDecrypt.push(item);
310
+ }
311
+ }
266
312
  // Second pass: decrypt notes
267
- for (const item of state.encryptedItemsRaw.values()) {
313
+ for (const item of toDecrypt) {
268
314
  if (item.content_type !== "Note")
269
315
  continue;
270
316
  try {
@@ -279,7 +325,7 @@ async function fullSync(state) {
279
325
  }
280
326
  }
281
327
  // Third pass: decrypt tags
282
- for (const item of state.encryptedItemsRaw.values()) {
328
+ for (const item of toDecrypt) {
283
329
  if (item.content_type !== "Tag")
284
330
  continue;
285
331
  try {
@@ -295,7 +341,7 @@ async function fullSync(state) {
295
341
  }
296
342
  // Fourth pass: decrypt smart views (saved searches). Non-fatal on failure —
297
343
  // a broken view shouldn't block vault access.
298
- for (const item of state.encryptedItemsRaw.values()) {
344
+ for (const item of toDecrypt) {
299
345
  if (item.content_type !== "SN|SmartView")
300
346
  continue;
301
347
  try {
@@ -308,8 +354,11 @@ async function fullSync(state) {
308
354
  });
309
355
  }
310
356
  }
357
+ pending.full = false;
358
+ pending.uuids.clear();
311
359
  state.lastSyncAt = Date.now();
312
360
  logger.info("Sync complete", {
361
+ decrypted: full ? "all" : toDecrypt.length,
313
362
  notes: state.notesCache.size,
314
363
  tags: state.tagsCache.size,
315
364
  itemsKeys: state.itemsKeys.size,
@@ -325,12 +374,15 @@ async function fullSync(state) {
325
374
  });
326
375
  }
327
376
  }
377
+ /** Characters of body text in list and search summaries (kept short: every
378
+ * listed note costs the AI context window). */
379
+ const PREVIEW_CHARS = 120;
328
380
  function toSummary(n) {
329
381
  return {
330
382
  uuid: n.uuid,
331
383
  title: n.title,
332
384
  updatedAt: n.updatedAt,
333
- preview: n.text.slice(0, 200),
385
+ preview: n.text.slice(0, PREVIEW_CHARS),
334
386
  trashed: n.trashed,
335
387
  protected: n.protected,
336
388
  locked: n.locked,
@@ -408,7 +460,7 @@ function buildClient(state) {
408
460
  const retrieved = res.retrieved_items ?? [];
409
461
  applyRetrieved(state, retrieved);
410
462
  for (const saved of res.saved_items) {
411
- state.encryptedItemsRaw.set(saved.uuid, saved);
463
+ storeRaw(state, saved);
412
464
  }
413
465
  if (retrieved.length > 0)
414
466
  state.lastSyncAt = 0;
@@ -453,7 +505,7 @@ function buildClient(state) {
453
505
  const cc = conflict;
454
506
  if (cc.type === "sync_conflict" && cc.server_item && attempt < 1) {
455
507
  logger.info(`sync_conflict on note ${uuid} — refreshing and retrying`);
456
- state.encryptedItemsRaw.set(uuid, cc.server_item);
508
+ storeRaw(state, cc.server_item);
457
509
  return submitNoteUpdate(uuid, merged, attempt + 1);
458
510
  }
459
511
  throw new Error(`Conflict on note ${uuid} (type=${cc.type ?? "unknown"}, attempts=${attempt + 1}). Run the sync tool and retry.`);
@@ -537,7 +589,14 @@ function buildClient(state) {
537
589
  throw new Error(`Tag ${uuid} not found`);
538
590
  }
539
591
  }
592
+ // Replacing tags only touches tags this client can see: a scoped client
593
+ // must not strip tags outside its scope that it doesn't know exist.
594
+ const sc = currentScope();
540
595
  for (const tag of state.tagsCache.values()) {
596
+ if (sc !== null &&
597
+ (sc.hiddenTags.has(tag.uuid) || (sc.allowTags !== null && !sc.allowTags.has(tag.uuid)))) {
598
+ continue;
599
+ }
541
600
  const hasRef = tag.references.some((r) => r.uuid === noteUuid);
542
601
  if (desired.has(tag.uuid) && !hasRef) {
543
602
  await attachTagInternal(noteUuid, tag.uuid);
@@ -661,6 +720,21 @@ function buildClient(state) {
661
720
  ? "markdown"
662
721
  : "plain-text"
663
722
  : decideNoteType(requested, ent()).noteType;
723
+ // Type and editor for a new note. Without an explicit type, a configured
724
+ // SN_NEW_NOTE_EDITOR opens it in that editor (paid accounts: free accounts
725
+ // can't install custom plugins); SN marks notes in custom editors with
726
+ // noteType "unknown".
727
+ const createShape = (requested) => requested === undefined && state.newNoteEditor && isPaid(ent())
728
+ ? { noteType: "unknown", extra: { editorIdentifier: state.newNoteEditor } }
729
+ : { noteType: noteTypeForCreate(requested), extra: {} };
730
+ // A deliberate type change also drops the old editor, so the note opens in
731
+ // the new type's editor; otherwise the note keeps its editor.
732
+ const extraForType = (existing, nextType) => {
733
+ if (nextType === existing.noteType || !("editorIdentifier" in existing.extra))
734
+ return existing.extra;
735
+ const { editorIdentifier: _dropped, ...rest } = existing.extra;
736
+ return rest;
737
+ };
664
738
  // Updates keep a note's existing type; only an explicit change is gated.
665
739
  const noteTypeForUpdate = (requested, existing) => requested === undefined || requested === existing
666
740
  ? existing
@@ -674,10 +748,37 @@ function buildClient(state) {
674
748
  };
675
749
  const assertCanNestTags = () => {
676
750
  if (!isPaid(ent())) {
677
- throw paidFeatureError("Nested folders", ent(), "Create the folder at the top level instead (omit `parent`).");
751
+ throw paidFeatureError("Nested tags", ent(), "Create the tag at the top level instead (omit `parent`).");
678
752
  }
679
753
  };
680
754
  const currentScope = () => resolveScope(state.tagsCache, state.scope);
755
+ /**
756
+ * Notes under the templates folder (see listTemplateNotes), or null when
757
+ * no non-denied folder matches `tag`. `shared` lifts only the
758
+ * SN_READ_TAGS allowlist: SN_DENY_TAGS, governance and trash still apply.
759
+ */
760
+ const templateSet = (tag, shared) => {
761
+ const sc = currentScope();
762
+ const byUuid = state.tagsCache.get(tag);
763
+ const roots = (byUuid
764
+ ? [byUuid]
765
+ : [...state.tagsCache.values()].filter((t) => t.title.toLowerCase() === tag.toLowerCase())).filter((t) => sc === null || !sc.hiddenTags.has(t.uuid));
766
+ if (roots.length === 0)
767
+ return null;
768
+ const noteUuids = new Set();
769
+ for (const root of roots) {
770
+ for (const tu of subtreeTagUuids(state.tagsCache, root.uuid)) {
771
+ if (sc !== null && sc.hiddenTags.has(tu))
772
+ continue;
773
+ for (const r of state.tagsCache.get(tu)?.references ?? []) {
774
+ if (r.content_type === "Note")
775
+ noteUuids.add(r.uuid);
776
+ }
777
+ }
778
+ }
779
+ const visible = (uuid) => shared ? sc === null || !sc.deny.has(uuid) : scopeAllows(sc, uuid);
780
+ return [...state.notesCache.values()].filter((n) => noteUuids.has(n.uuid) && !n.trashed && visible(n.uuid) && aiReadable(n));
781
+ };
681
782
  const noteNotFound = (uuid) => new ToolError("note_not_found", `Note ${uuid} not found`, "Run notes_search or notes_list to find the note's uuid.");
682
783
  // Frontmatter AI governance (see src/sn/governance.ts). `ai: no-access`
683
784
  // notes are invisible; `ai: read-only` notes reject every write path.
@@ -946,7 +1047,8 @@ function buildClient(state) {
946
1047
  async createNote({ title, text, noteType, tags }) {
947
1048
  assertTagsWithinScope(currentScope(), tags);
948
1049
  const uuid = crypto.randomUUID();
949
- const resolvedType = noteTypeForCreate(noteType);
1050
+ const shape = createShape(noteType);
1051
+ const resolvedType = shape.noteType;
950
1052
  const resolvedText = resolvedType === "super" ? normalizeSuperText(text) : text;
951
1053
  const encrypted = await encryptNote({
952
1054
  uuid,
@@ -954,6 +1056,7 @@ function buildClient(state) {
954
1056
  text: resolvedText,
955
1057
  trashed: false,
956
1058
  noteType: resolvedType,
1059
+ extra: shape.extra,
957
1060
  }, { uuid: defaultItemsKey().uuid, itemsKey: defaultItemsKey().itemsKey });
958
1061
  const nowIso = new Date().toISOString();
959
1062
  const res = await pushItems([
@@ -991,7 +1094,7 @@ function buildClient(state) {
991
1094
  created_at_timestamp: saved.created_at_timestamp ?? 0,
992
1095
  updated_at_timestamp: saved.updated_at_timestamp ?? 0,
993
1096
  references: [],
994
- extra: {},
1097
+ extra: shape.extra,
995
1098
  });
996
1099
  if (tags && tags.length > 0) {
997
1100
  for (const tagUuid of tags) {
@@ -1010,7 +1113,8 @@ function buildClient(state) {
1010
1113
  }
1011
1114
  const nowIso = new Date().toISOString();
1012
1115
  const prepared = inputs.map((input) => {
1013
- const resolvedType = noteTypeForCreate(input.noteType);
1116
+ const shape = createShape(input.noteType);
1117
+ const resolvedType = shape.noteType;
1014
1118
  const resolvedText = resolvedType === "super"
1015
1119
  ? normalizeSuperText(input.text)
1016
1120
  : input.text;
@@ -1019,6 +1123,7 @@ function buildClient(state) {
1019
1123
  title: input.title,
1020
1124
  text: resolvedText,
1021
1125
  noteType: resolvedType,
1126
+ extra: shape.extra,
1022
1127
  tags: input.tags ?? [],
1023
1128
  };
1024
1129
  });
@@ -1029,6 +1134,7 @@ function buildClient(state) {
1029
1134
  text: p.text,
1030
1135
  trashed: false,
1031
1136
  noteType: p.noteType,
1137
+ extra: p.extra,
1032
1138
  }, {
1033
1139
  uuid: defaultItemsKey().uuid,
1034
1140
  itemsKey: defaultItemsKey().itemsKey,
@@ -1070,7 +1176,7 @@ function buildClient(state) {
1070
1176
  created_at_timestamp: saved.created_at_timestamp ?? 0,
1071
1177
  updated_at_timestamp: saved.updated_at_timestamp ?? 0,
1072
1178
  references: [],
1073
- extra: {},
1179
+ extra: p.extra,
1074
1180
  });
1075
1181
  }
1076
1182
  if (failed.length > 0) {
@@ -1148,7 +1254,7 @@ function buildClient(state) {
1148
1254
  pinned: input.pinned ?? existing.pinned,
1149
1255
  noteType: nextType,
1150
1256
  references: existing.references,
1151
- extra: existing.extra,
1257
+ extra: extraForType(existing, nextType),
1152
1258
  };
1153
1259
  const encrypted = await encryptNote(merged, {
1154
1260
  uuid: defaultItemsKey().uuid,
@@ -1335,7 +1441,7 @@ function buildClient(state) {
1335
1441
  pinned: pinned ?? existing.pinned,
1336
1442
  noteType: nextType,
1337
1443
  references: existing.references,
1338
- extra: existing.extra,
1444
+ extra: extraForType(existing, nextType),
1339
1445
  };
1340
1446
  const saved = await submitNoteUpdate(uuid, merged, 0);
1341
1447
  state.notesCache.set(uuid, {
@@ -1366,6 +1472,12 @@ function buildClient(state) {
1366
1472
  return content;
1367
1473
  if (position === "prepend")
1368
1474
  return content + eol + eol + text;
1475
+ // Rows appended to a note that ends in a table join the table
1476
+ // directly; a blank line between them would split it in two.
1477
+ const trimmed = text.replace(/(\r?\n)+$/, "");
1478
+ const lastLine = trimmed.split(/\r?\n/).pop();
1479
+ if (continuesBlock(lastLine, content))
1480
+ return trimmed + eol + content;
1369
1481
  const sep = text.endsWith("\n") ? eol : eol + eol;
1370
1482
  return text + sep + content;
1371
1483
  });
@@ -1763,7 +1875,7 @@ function buildClient(state) {
1763
1875
  pinned: existing.pinned,
1764
1876
  noteType: rev.noteType,
1765
1877
  references: existing.references,
1766
- extra: existing.extra,
1878
+ extra: extraForType(existing, rev.noteType),
1767
1879
  };
1768
1880
  const saved = await submitNoteUpdate(noteUuid, merged, 0);
1769
1881
  state.notesCache.set(noteUuid, {
@@ -1840,6 +1952,39 @@ function buildClient(state) {
1840
1952
  (sc.allowTags === null || sc.allowTags.has(t.uuid)))))
1841
1953
  .map((t) => t.uuid);
1842
1954
  },
1955
+ async listTemplateNotes(tag, opts) {
1956
+ await ensureFresh(state, cacheTtlMs(), () => fullSync(state));
1957
+ const set = templateSet(tag, opts?.shared === true);
1958
+ if (set === null)
1959
+ return null;
1960
+ return set
1961
+ .sort((a, b) => a.title.localeCompare(b.title))
1962
+ .slice(0, 200)
1963
+ .map(toSummary);
1964
+ },
1965
+ async getTemplate(tag, uuid, opts) {
1966
+ await ensureFresh(state, cacheTtlMs(), () => fullSync(state));
1967
+ const n = templateSet(tag, opts?.shared === true)?.find((t) => t.uuid === uuid);
1968
+ if (!n)
1969
+ return null;
1970
+ const sc = currentScope();
1971
+ // Only folders this client could see anyway: a shared template's
1972
+ // out-of-scope folders are never revealed or copied onto new notes.
1973
+ const visibleTagUuids = [...state.tagsCache.values()]
1974
+ .filter((t) => t.references.some((r) => r.uuid === uuid && r.content_type === "Note") &&
1975
+ (sc === null ||
1976
+ (!sc.hiddenTags.has(t.uuid) &&
1977
+ (sc.allowTags === null || sc.allowTags.has(t.uuid)))))
1978
+ .map((t) => t.uuid);
1979
+ return { uuid: n.uuid, title: n.title, text: n.text, noteType: n.noteType, visibleTagUuids };
1980
+ },
1981
+ scopeRootUuids() {
1982
+ const sc = currentScope();
1983
+ return sc?.allowRoots !== null && sc?.allowRoots !== undefined ? [...sc.allowRoots] : null;
1984
+ },
1985
+ scopeReport() {
1986
+ return scopeReport(state.tagsCache, state.scope);
1987
+ },
1843
1988
  async getLinks(uuid) {
1844
1989
  await ensureFresh(state, cacheTtlMs(), () => fullSync(state));
1845
1990
  const sc = currentScope();
@@ -35,10 +35,10 @@ export function canViewRevision(requiredRole, e) {
35
35
  const FREE_NOTE_TYPES = new Set(["plain-text"]);
36
36
  export const PAID_FEATURE_REASON = "paid_feature";
37
37
  export function paidFeatureError(feature, e, alternative) {
38
- const why = e.plan === "unknown"
39
- ? "this server could not confirm the account's Standard Notes plan"
40
- : "this account is on the free plan";
41
- return new ToolError(PAID_FEATURE_REASON, `${feature} is a paid Standard Notes feature (Productivity or Professional plan), and ${why}.`, alternative);
38
+ const message = e.plan === "unknown"
39
+ ? `${feature} isn't available: this account's Standard Notes plan couldn't be confirmed.`
40
+ : `${feature} isn't available on this account's Standard Notes plan.`;
41
+ return new ToolError(PAID_FEATURE_REASON, message, alternative);
42
42
  }
43
43
  /**
44
44
  * Decide the note type for a write that explicitly requests `requested`.
@@ -57,16 +57,35 @@ export function decideNoteType(requested, e) {
57
57
  }
58
58
  return {
59
59
  noteType: "plain-text",
60
- notice: `Saved as a plain-text note: the ${requested} editor is a paid Standard Notes feature. The text is unchanged, so markdown syntax still reads fine.`,
60
+ notice: `Saved as a plain-text note (this account uses the plain-text editor). The text is unchanged.`,
61
61
  };
62
62
  }
63
+ const shownNotices = new WeakMap();
64
+ /**
65
+ * Returns the notice the first time it is shown for this client (one
66
+ * session), then undefined: free-plan fallbacks are explained once, not on
67
+ * every note.
68
+ */
69
+ export function noticeOnce(owner, notice) {
70
+ if (notice === undefined)
71
+ return undefined;
72
+ let seen = shownNotices.get(owner);
73
+ if (!seen) {
74
+ seen = new Set();
75
+ shownNotices.set(owner, seen);
76
+ }
77
+ if (seen.has(notice))
78
+ return undefined;
79
+ seen.add(notice);
80
+ return notice;
81
+ }
63
82
  /** Human-readable list of what is degraded for this account. */
64
83
  export function degradedFeatures(e) {
65
84
  if (isPaid(e))
66
85
  return [];
67
86
  return [
68
87
  "Super and other non-plain editors: new notes are saved as plain text",
69
- "Nested folders: folders can only be created at the top level",
88
+ "Nested tags: tags can only be created at the top level",
70
89
  "Smart Views: existing views can be read; use notes_query for new filters",
71
90
  "Native note links: [[wikilinks]] in note text are used instead",
72
91
  "Note history: only recent revisions are available",
@@ -132,7 +132,10 @@ export function setFrontmatterKey(text, key, value) {
132
132
  const parsed = parseFrontmatter(text);
133
133
  const newLine = `${key}: ${serializeScalar(value)}`;
134
134
  if (parsed.blockStart === null || parsed.blockEnd === null) {
135
- return ["---", newLine, "---", "", ...parsed.lines].join(parsed.eol);
135
+ // The blank line before the closing fence matters: without it, editors
136
+ // that render markdown (Standard Notes included) read "key: value"
137
+ // followed by "---" as a setext H2 heading.
138
+ return ["---", newLine, "", "---", "", ...parsed.lines].join(parsed.eol);
136
139
  }
137
140
  const lines = [...parsed.lines];
138
141
  const range = keyRange(parsed, key);
@@ -140,7 +143,14 @@ export function setFrontmatterKey(text, key, value) {
140
143
  lines.splice(range.start, range.end - range.start, newLine);
141
144
  }
142
145
  else {
143
- lines.splice(parsed.blockEnd, 0, newLine);
146
+ // Insert above any blank lines that sit just before the closing fence,
147
+ // so a block written with that blank separator keeps it.
148
+ let insertAt = parsed.blockEnd;
149
+ while (insertAt - 1 > parsed.blockStart &&
150
+ (lines[insertAt - 1] ?? "").trim() === "") {
151
+ insertAt--;
152
+ }
153
+ lines.splice(insertAt, 0, newLine);
144
154
  }
145
155
  return lines.join(parsed.eol);
146
156
  }
@@ -160,8 +170,9 @@ export function deleteFrontmatterKey(text, key) {
160
170
  .slice(parsed.blockStart + 1, closingFence)
161
171
  .filter((l) => l.trim() !== "");
162
172
  if (remaining.length === 0) {
163
- // Both fences, plus the blank separator line after the block if present.
164
- let removeCount = 2;
173
+ // Both fences and any blank lines between them, plus the blank
174
+ // separator line after the block if present.
175
+ let removeCount = closingFence - parsed.blockStart + 1;
165
176
  if ((lines[closingFence + 1] ?? "") === "")
166
177
  removeCount++;
167
178
  lines.splice(parsed.blockStart, removeCount);
@@ -1,4 +1,16 @@
1
1
  import { ToolError } from "../security/errors.js";
2
+ /** True for a markdown table line ("| a | b |" or "|---|---|"). */
3
+ function isTableRow(line) {
4
+ return line !== undefined && line.trimStart().startsWith("|");
5
+ }
6
+ /**
7
+ * Whether appended content continues the block that ends on `prevLine`
8
+ * and so must NOT be separated from it by a blank line. Today that means
9
+ * table rows: a blank line in the middle of a table splits it in two.
10
+ */
11
+ export function continuesBlock(prevLine, content) {
12
+ return isTableRow(prevLine) && isTableRow(content.split(/\r?\n/)[0]);
13
+ }
2
14
  function parse(text) {
3
15
  const eol = text.includes("\r\n") ? "\r\n" : "\n";
4
16
  const lines = text.split(/\r?\n/);
@@ -124,7 +136,10 @@ export function insertIntoSection(text, sectionPath, content, position) {
124
136
  insertAt--;
125
137
  }
126
138
  const insertion = [];
127
- if (insertAt - 1 >= heading.line + 1 && lines[insertAt - 1] !== "") {
139
+ if (continuesBlock(lines[insertAt - 1], content) && insertAt - 1 > heading.line) {
140
+ // Appending rows to a table that ends the section: no separator.
141
+ }
142
+ else if (insertAt - 1 >= heading.line + 1 && lines[insertAt - 1] !== "") {
128
143
  insertion.push("");
129
144
  }
130
145
  else if (insertAt - 1 === heading.line) {
@@ -152,7 +152,6 @@ const MANAGED_NOTE_KEYS = new Set([
152
152
  "trashed",
153
153
  "archived",
154
154
  "pinned",
155
- "editorIdentifier",
156
155
  "preview_plain",
157
156
  "preview_html",
158
157
  ]);
@@ -214,13 +213,17 @@ export async function encryptNote(note, itemsKey) {
214
213
  // Including it here causes the SN app to fail AEAD verification and drop the note.
215
214
  const aad = { u: note.uuid, v: "004" };
216
215
  const resolvedType = note.noteType ?? "plain-text";
217
- // Editor identifier is a hint for legacy SN clients that route by editor
218
- // rather than by `noteType`. Modern SN routes by `noteType` alone, so we
219
- // only set this for editors with a stable, well-known identifier. For
220
- // `rich-text` / `task` / `spreadsheet` / `authentication` we omit it
221
- // intentionally — `noteType` is sufficient and a wrong identifier would
222
- // mask the type.
223
- const editorIdentifier = EDITOR_IDENTIFIERS[resolvedType];
216
+ // The editor that opens the note. An existing editorIdentifier (kept in
217
+ // `extra`) always wins, so edits never switch a note away from the editor
218
+ // the user chose: custom plugins (noteType "unknown"), Markdown Visual,
219
+ // checklists. Callers drop it from `extra` when the note type is changed
220
+ // on purpose. Otherwise the well-known editor for the type is used; for
221
+ // `rich-text` / `task` / `spreadsheet` / `authentication` none is set,
222
+ // since `noteType` is enough and a wrong identifier would mask the type.
223
+ const extraEditor = (note.extra ?? {}).editorIdentifier;
224
+ const editorIdentifier = typeof extraEditor === "string" && extraEditor !== ""
225
+ ? extraEditor
226
+ : EDITOR_IDENTIFIERS[resolvedType];
224
227
  const previewPlain = resolvedType === "plain-text" || resolvedType === "markdown"
225
228
  ? note.text.slice(0, 160)
226
229
  : undefined;
package/dist/sn/scope.js CHANGED
@@ -56,6 +56,40 @@ export function resolveScope(tags, scope) {
56
56
  allowRoots,
57
57
  };
58
58
  }
59
+ /**
60
+ * Per-entry resolution of the configured scope, for server_status and the
61
+ * startup instructions. Unmatched entries are skipped by resolveScope (a
62
+ * renamed tag shouldn't brick the server), which fails closed for reads but
63
+ * is invisible from the AI side: a client whose only read entry is
64
+ * misspelled just sees an empty vault. This makes that diagnosable.
65
+ * Entries come from the operator's config, so echoing them leaks nothing
66
+ * from the vault. null when no scope is configured.
67
+ */
68
+ export function scopeReport(tags, scope) {
69
+ if (scope.readTags === null && scope.denyTags.length === 0)
70
+ return null;
71
+ const status = (entry) => ({
72
+ entry,
73
+ matched: resolveTag(tags, entry) !== null,
74
+ });
75
+ const readTags = scope.readTags !== null ? scope.readTags.map(status) : null;
76
+ const denyTags = scope.denyTags.map(status);
77
+ const warnings = [];
78
+ if (readTags !== null) {
79
+ const missing = readTags.filter((s) => !s.matched).map((s) => s.entry);
80
+ if (missing.length > 0 && missing.length === readTags.length) {
81
+ warnings.push(`No SN_READ_TAGS entry matches a tag in this vault (${missing.join(", ")}), so no notes are visible. Check the spelling against the tag names in Standard Notes.`);
82
+ }
83
+ else if (missing.length > 0) {
84
+ warnings.push(`SN_READ_TAGS entries that match no tag are ignored: ${missing.join(", ")}.`);
85
+ }
86
+ }
87
+ const missingDeny = denyTags.filter((s) => !s.matched).map((s) => s.entry);
88
+ if (missingDeny.length > 0) {
89
+ warnings.push(`SN_DENY_TAGS entries that match no tag hide nothing: ${missingDeny.join(", ")}.`);
90
+ }
91
+ return { readTags, denyTags, warnings };
92
+ }
59
93
  export function scopeAllows(scope, noteUuid) {
60
94
  if (scope === null)
61
95
  return true;