standardnotes-mcp 0.0.0-stage → 3.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.
Files changed (86) hide show
  1. package/CHANGELOG.md +165 -0
  2. package/LICENSE +22 -0
  3. package/README.md +320 -3
  4. package/SECURITY.md +56 -0
  5. package/dist/cli/install.js +187 -0
  6. package/dist/cli/install.js.map +1 -0
  7. package/dist/cli/login.js +126 -0
  8. package/dist/cli/login.js.map +1 -0
  9. package/dist/cli/logout.js +22 -0
  10. package/dist/cli/logout.js.map +1 -0
  11. package/dist/cli/setup.js +200 -0
  12. package/dist/cli/setup.js.map +1 -0
  13. package/dist/config.js +60 -0
  14. package/dist/config.js.map +1 -0
  15. package/dist/index.js +10 -0
  16. package/dist/index.js.map +1 -0
  17. package/dist/security/errors.js +20 -0
  18. package/dist/security/errors.js.map +1 -0
  19. package/dist/security/logger.js +17 -0
  20. package/dist/security/logger.js.map +1 -0
  21. package/dist/security/redact.js +31 -0
  22. package/dist/security/redact.js.map +1 -0
  23. package/dist/security/regex.js +27 -0
  24. package/dist/security/regex.js.map +1 -0
  25. package/dist/server.js +327 -0
  26. package/dist/server.js.map +1 -0
  27. package/dist/sn/cache.js +53 -0
  28. package/dist/sn/cache.js.map +1 -0
  29. package/dist/sn/client.js +1999 -0
  30. package/dist/sn/client.js.map +1 -0
  31. package/dist/sn/crypto.js +63 -0
  32. package/dist/sn/crypto.js.map +1 -0
  33. package/dist/sn/dates.js +157 -0
  34. package/dist/sn/dates.js.map +1 -0
  35. package/dist/sn/entitlement.js +75 -0
  36. package/dist/sn/entitlement.js.map +1 -0
  37. package/dist/sn/frontmatter.js +171 -0
  38. package/dist/sn/frontmatter.js.map +1 -0
  39. package/dist/sn/governance.js +40 -0
  40. package/dist/sn/governance.js.map +1 -0
  41. package/dist/sn/http.js +289 -0
  42. package/dist/sn/http.js.map +1 -0
  43. package/dist/sn/links.js +78 -0
  44. package/dist/sn/links.js.map +1 -0
  45. package/dist/sn/markdownSections.js +141 -0
  46. package/dist/sn/markdownSections.js.map +1 -0
  47. package/dist/sn/predicates.js +135 -0
  48. package/dist/sn/predicates.js.map +1 -0
  49. package/dist/sn/protocol004.js +401 -0
  50. package/dist/sn/protocol004.js.map +1 -0
  51. package/dist/sn/scope.js +68 -0
  52. package/dist/sn/scope.js.map +1 -0
  53. package/dist/sn/search.js +260 -0
  54. package/dist/sn/search.js.map +1 -0
  55. package/dist/sn/session.js +55 -0
  56. package/dist/sn/session.js.map +1 -0
  57. package/dist/sn/tagHierarchy.js +105 -0
  58. package/dist/sn/tagHierarchy.js.map +1 -0
  59. package/dist/sn/tasks.js +32 -0
  60. package/dist/sn/tasks.js.map +1 -0
  61. package/dist/sn/templates.js +23 -0
  62. package/dist/sn/templates.js.map +1 -0
  63. package/dist/sn/types.js +12 -0
  64. package/dist/sn/types.js.map +1 -0
  65. package/dist/tools/daily.js +126 -0
  66. package/dist/tools/daily.js.map +1 -0
  67. package/dist/tools/export.js +96 -0
  68. package/dist/tools/export.js.map +1 -0
  69. package/dist/tools/history.js +41 -0
  70. package/dist/tools/history.js.map +1 -0
  71. package/dist/tools/links.js +51 -0
  72. package/dist/tools/links.js.map +1 -0
  73. package/dist/tools/notes.js +404 -0
  74. package/dist/tools/notes.js.map +1 -0
  75. package/dist/tools/smartviews.js +52 -0
  76. package/dist/tools/smartviews.js.map +1 -0
  77. package/dist/tools/tags.js +82 -0
  78. package/dist/tools/tags.js.map +1 -0
  79. package/dist/tools/tasks.js +43 -0
  80. package/dist/tools/tasks.js.map +1 -0
  81. package/dist/tools/templates.js +145 -0
  82. package/dist/tools/templates.js.map +1 -0
  83. package/docs/protocol-004.md +72 -0
  84. package/docs/self-hosted.md +123 -0
  85. package/docs/troubleshooting.md +89 -0
  86. package/package.json +85 -6
@@ -0,0 +1,1999 @@
1
+ import { logger } from "../security/logger.js";
2
+ import * as http from "./http.js";
3
+ import { decryptItemsKey, decryptNote, decryptSmartView, decryptTag, deriveRootKey, encryptNote, encryptTag, normalizeSuperText, } from "./protocol004.js";
4
+ import { loadSession, saveSession } from "./session.js";
5
+ import { cacheTtlMs, ensureFresh } from "./cache.js";
6
+ import { makeParentRef, parentUuidOf, stripParentRefs, subtreeTagUuids, wouldCreateCycle, } from "./tagHierarchy.js";
7
+ import { ToolError } from "../security/errors.js";
8
+ import { assertSafeRegex } from "../security/regex.js";
9
+ import { getSectionBody, insertIntoSection, outline } from "./markdownSections.js";
10
+ import { searchDecryptedNotes } from "./search.js";
11
+ import { evaluatePredicate, isPredicateJson, notePredicateTarget, summarizePredicate, } from "./predicates.js";
12
+ import { resolveScope, scopeAllows, } from "./scope.js";
13
+ import { aiPolicyOf } from "./governance.js";
14
+ import { extractTasks, setTaskState } from "./tasks.js";
15
+ import { deleteFrontmatterKey, parseFrontmatter, setFrontmatterKey, } from "./frontmatter.js";
16
+ import { fromHex, toHex } from "./crypto.js";
17
+ import { snTimestampToMs } from "./dates.js";
18
+ import { hasWikilinkTo, nativeLinkUuids, parseWikilinks, titleKey } from "./links.js";
19
+ import { decideNoteType, entitlementFromRoles, canViewRevision, isPaid, paidFeatureError, } from "./entitlement.js";
20
+ // Cache TTL policy lives in ./cache.ts so the ensureFresh helper can be
21
+ // unit-tested without spinning up the full crypto+http stack.
22
+ export async function createClientFromLogin(config, password, mfaPrompt) {
23
+ if (!password)
24
+ throw new Error("password required");
25
+ const codeVerifier = http.generateCodeVerifier();
26
+ const codeChallenge = http.computeCodeChallenge(codeVerifier);
27
+ // Standard Notes verifies MFA inside the /v2/login-params handler — when 2FA
28
+ // is enabled, this first call fails with `mfa-required` and we must re-call
29
+ // login-params with `{ [mfa_key]: code }`. The /v2/login endpoint itself does
30
+ // NOT recheck MFA, so the prompt belongs around this call, not around login().
31
+ let params;
32
+ try {
33
+ params = await http.getLoginParams({ serverUrl: config.serverUrl }, config.email, codeChallenge);
34
+ }
35
+ catch (err) {
36
+ if (!(err instanceof http.SnApiError) || err.tag !== "mfa-required") {
37
+ throw err;
38
+ }
39
+ if (!mfaPrompt) {
40
+ throw new Error("Two-factor authentication is enabled on this account. " +
41
+ "Run `npm run login` interactively (it wires the MFA prompt).");
42
+ }
43
+ const mfaKey = err.payload?.mfa_key ?? "";
44
+ if (!mfaKey) {
45
+ throw new Error("Server requested 2FA but did not return an mfa_key field. " +
46
+ "This is likely a server bug or a non-standard MFA flow.");
47
+ }
48
+ const code = (await mfaPrompt()).trim();
49
+ if (!code) {
50
+ throw new Error("Empty 2FA code; aborting login.");
51
+ }
52
+ params = await http.getLoginParams({ serverUrl: config.serverUrl }, config.email, codeChallenge, { [mfaKey]: code });
53
+ }
54
+ const keyParams = {
55
+ version: "004",
56
+ identifier: params.identifier,
57
+ pw_nonce: params.pw_nonce,
58
+ origination: params.origination,
59
+ created: params.created,
60
+ };
61
+ const rootKey = await deriveRootKey(password, keyParams);
62
+ const loginRes = await http.login({ serverUrl: config.serverUrl }, config.email, rootKey.serverPassword, codeVerifier);
63
+ const state = {
64
+ serverUrl: config.serverUrl,
65
+ email: config.email,
66
+ authToken: loginRes.session.access_token,
67
+ refreshToken: loginRes.session.refresh_token,
68
+ rootKey,
69
+ itemsKeys: new Map(),
70
+ defaultItemsKeyUuid: null,
71
+ notesCache: new Map(),
72
+ tagsCache: new Map(),
73
+ smartViewsCache: new Map(),
74
+ encryptedItemsRaw: new Map(),
75
+ syncToken: null,
76
+ lastSyncAt: 0,
77
+ decryptFailedNotes: new Set(),
78
+ decryptFailedTags: new Set(),
79
+ scope: config.scope ?? { readTags: null, denyTags: [] },
80
+ governance: config.governance ?? true,
81
+ clientName: config.clientName ?? (() => null),
82
+ roles: null,
83
+ };
84
+ await saveSession(config.email, {
85
+ serverUrl: config.serverUrl,
86
+ email: config.email,
87
+ sessionPayload: {
88
+ access_token: loginRes.session.access_token,
89
+ refresh_token: loginRes.session.refresh_token,
90
+ },
91
+ masterKeyHex: await toHex(rootKey.masterKey),
92
+ keyParams: loginRes.key_params ?? keyParams,
93
+ savedAt: new Date().toISOString(),
94
+ });
95
+ await fullSync(state);
96
+ return buildClient(state);
97
+ }
98
+ export async function createClientFromSession(config) {
99
+ const stored = await loadSession(config.email);
100
+ if (!stored) {
101
+ throw new Error("No session found. Run `npm run login` to authenticate first.");
102
+ }
103
+ 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
+ }
106
+ const keyParams = stored.keyParams;
107
+ const rootKey = {
108
+ masterKey: await fromHex(stored.masterKeyHex),
109
+ serverPassword: "",
110
+ keyParams,
111
+ };
112
+ const state = {
113
+ serverUrl: stored.serverUrl,
114
+ email: stored.email,
115
+ authToken: stored.sessionPayload.access_token,
116
+ refreshToken: stored.sessionPayload.refresh_token,
117
+ rootKey,
118
+ itemsKeys: new Map(),
119
+ defaultItemsKeyUuid: null,
120
+ notesCache: new Map(),
121
+ tagsCache: new Map(),
122
+ smartViewsCache: new Map(),
123
+ encryptedItemsRaw: new Map(),
124
+ // Always start with a null syncToken on cold boot — incremental sync
125
+ // skips items_keys (they rarely change), and we have nothing in
126
+ // encryptedItemsRaw to fall back on after a fresh process. The
127
+ // stored syncToken remains in the persisted session for future
128
+ // reuse if we ever start caching the encrypted vault snapshot too.
129
+ syncToken: null,
130
+ lastSyncAt: 0,
131
+ decryptFailedNotes: new Set(),
132
+ decryptFailedTags: new Set(),
133
+ scope: config.scope ?? { readTags: null, denyTags: [] },
134
+ governance: config.governance ?? true,
135
+ clientName: config.clientName ?? (() => null),
136
+ roles: null,
137
+ };
138
+ await fullSync(state);
139
+ return buildClient(state);
140
+ }
141
+ async function persistSession(state) {
142
+ await saveSession(state.email, {
143
+ serverUrl: state.serverUrl,
144
+ email: state.email,
145
+ sessionPayload: {
146
+ access_token: state.authToken,
147
+ refresh_token: state.refreshToken,
148
+ },
149
+ masterKeyHex: await toHex(state.rootKey.masterKey),
150
+ keyParams: state.rootKey.keyParams,
151
+ syncToken: state.syncToken,
152
+ savedAt: new Date().toISOString(),
153
+ });
154
+ }
155
+ async function refreshTokens(state) {
156
+ logger.info("Access token rejected (401); refreshing");
157
+ let fresh;
158
+ try {
159
+ fresh = await http.refreshSession({ serverUrl: state.serverUrl }, state.authToken, state.refreshToken);
160
+ }
161
+ catch (refreshErr) {
162
+ throw new Error("Session refresh failed; run `npm run login` to re-authenticate. " +
163
+ (refreshErr instanceof Error ? refreshErr.message : String(refreshErr)));
164
+ }
165
+ state.authToken = fresh.access_token;
166
+ state.refreshToken = fresh.refresh_token;
167
+ await persistSession(state);
168
+ }
169
+ async function callSync(state, params) {
170
+ const record = (res) => {
171
+ const roles = res.meta?.auth?.roles;
172
+ if (roles)
173
+ state.roles = roles.map((r) => r.name);
174
+ return res;
175
+ };
176
+ try {
177
+ return record(await http.sync({ serverUrl: state.serverUrl, authToken: state.authToken }, params));
178
+ }
179
+ catch (err) {
180
+ if (!(err instanceof http.SnApiError) ||
181
+ err.status !== 401 ||
182
+ !state.refreshToken) {
183
+ throw err;
184
+ }
185
+ await refreshTokens(state);
186
+ return record(await http.sync({ serverUrl: state.serverUrl, authToken: state.authToken }, params));
187
+ }
188
+ }
189
+ /** Authenticated GET with the same 401-refresh-retry behavior as callSync. */
190
+ async function authedCall(state, fn) {
191
+ const cfg = () => ({
192
+ serverUrl: state.serverUrl,
193
+ authToken: state.authToken,
194
+ });
195
+ try {
196
+ return await fn(cfg());
197
+ }
198
+ catch (err) {
199
+ if (!(err instanceof http.SnApiError) ||
200
+ err.status !== 401 ||
201
+ !state.refreshToken) {
202
+ throw err;
203
+ }
204
+ await refreshTokens(state);
205
+ return await fn(cfg());
206
+ }
207
+ }
208
+ /** Folds items the server sent back into the raw cache; deletions drop out of every cache. */
209
+ function applyRetrieved(state, items) {
210
+ for (const item of items) {
211
+ if (item.deleted) {
212
+ state.encryptedItemsRaw.delete(item.uuid);
213
+ state.notesCache.delete(item.uuid);
214
+ state.tagsCache.delete(item.uuid);
215
+ state.smartViewsCache.delete(item.uuid);
216
+ state.itemsKeys.delete(item.uuid);
217
+ continue;
218
+ }
219
+ state.encryptedItemsRaw.set(item.uuid, item);
220
+ }
221
+ }
222
+ 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
+ let cursorToken;
228
+ let syncToken = state.syncToken ?? undefined;
229
+ // eslint-disable-next-line no-constant-condition
230
+ while (true) {
231
+ const res = await callSync(state, { syncToken, cursorToken, limit: 150 });
232
+ applyRetrieved(state, res.retrieved_items);
233
+ syncToken = res.sync_token;
234
+ cursorToken = res.cursor_token;
235
+ if (!cursorToken)
236
+ break;
237
+ }
238
+ 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;
251
+ }
252
+ }
253
+ catch (err) {
254
+ logger.warn(`Failed to decrypt items_key ${item.uuid}`, {
255
+ message: err instanceof Error ? err.message : String(err),
256
+ });
257
+ }
258
+ }
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
+ const itemsKeyBytesByUuid = new Map();
263
+ for (const [u, k] of state.itemsKeys.entries()) {
264
+ itemsKeyBytesByUuid.set(u, k.itemsKey);
265
+ }
266
+ // Second pass: decrypt notes
267
+ for (const item of state.encryptedItemsRaw.values()) {
268
+ if (item.content_type !== "Note")
269
+ continue;
270
+ try {
271
+ const note = await decryptNote(item, itemsKeyBytesByUuid);
272
+ state.notesCache.set(note.uuid, note);
273
+ }
274
+ catch (err) {
275
+ state.decryptFailedNotes.add(item.uuid);
276
+ logger.warn(`Failed to decrypt note ${item.uuid}`, {
277
+ message: err instanceof Error ? err.message : String(err),
278
+ });
279
+ }
280
+ }
281
+ // Third pass: decrypt tags
282
+ for (const item of state.encryptedItemsRaw.values()) {
283
+ if (item.content_type !== "Tag")
284
+ continue;
285
+ try {
286
+ const tag = await decryptTag(item, itemsKeyBytesByUuid);
287
+ state.tagsCache.set(tag.uuid, tag);
288
+ }
289
+ catch (err) {
290
+ state.decryptFailedTags.add(item.uuid);
291
+ logger.warn(`Failed to decrypt tag ${item.uuid}`, {
292
+ message: err instanceof Error ? err.message : String(err),
293
+ });
294
+ }
295
+ }
296
+ // Fourth pass: decrypt smart views (saved searches). Non-fatal on failure —
297
+ // a broken view shouldn't block vault access.
298
+ for (const item of state.encryptedItemsRaw.values()) {
299
+ if (item.content_type !== "SN|SmartView")
300
+ continue;
301
+ try {
302
+ const view = await decryptSmartView(item, itemsKeyBytesByUuid);
303
+ state.smartViewsCache.set(view.uuid, view);
304
+ }
305
+ catch (err) {
306
+ logger.warn(`Failed to decrypt smart view ${item.uuid}`, {
307
+ message: err instanceof Error ? err.message : String(err),
308
+ });
309
+ }
310
+ }
311
+ state.lastSyncAt = Date.now();
312
+ logger.info("Sync complete", {
313
+ notes: state.notesCache.size,
314
+ tags: state.tagsCache.size,
315
+ itemsKeys: state.itemsKeys.size,
316
+ decryptFailedNotes: state.decryptFailedNotes.size,
317
+ decryptFailedTags: state.decryptFailedTags.size,
318
+ });
319
+ try {
320
+ await persistSession(state);
321
+ }
322
+ catch (err) {
323
+ logger.warn("Failed to persist sync_token to keychain", {
324
+ message: err instanceof Error ? err.message : String(err),
325
+ });
326
+ }
327
+ }
328
+ function toSummary(n) {
329
+ return {
330
+ uuid: n.uuid,
331
+ title: n.title,
332
+ updatedAt: n.updatedAt,
333
+ preview: n.text.slice(0, 200),
334
+ trashed: n.trashed,
335
+ protected: n.protected,
336
+ locked: n.locked,
337
+ archived: n.archived,
338
+ pinned: n.pinned,
339
+ noteType: n.noteType,
340
+ };
341
+ }
342
+ function tagsForNote(noteUuid, tagsCache) {
343
+ const titles = [];
344
+ for (const tag of tagsCache.values()) {
345
+ if (tag.references.some((r) => r.uuid === noteUuid)) {
346
+ titles.push(tag.title);
347
+ }
348
+ }
349
+ return titles.sort((a, b) => a.localeCompare(b));
350
+ }
351
+ function toFullNote(n, tagsCache) {
352
+ return {
353
+ uuid: n.uuid,
354
+ title: n.title,
355
+ text: n.text,
356
+ createdAt: n.createdAt,
357
+ updatedAt: n.updatedAt,
358
+ trashed: n.trashed,
359
+ protected: n.protected,
360
+ locked: n.locked,
361
+ archived: n.archived,
362
+ pinned: n.pinned,
363
+ tags: tagsForNote(n.uuid, tagsCache),
364
+ noteType: n.noteType,
365
+ };
366
+ }
367
+ function toTagSummary(t) {
368
+ return {
369
+ uuid: t.uuid,
370
+ title: t.title,
371
+ updatedAt: t.updatedAt,
372
+ noteCount: t.references.filter((r) => r.content_type === "Note").length,
373
+ parentUuid: parentUuidOf(t),
374
+ };
375
+ }
376
+ function toFullTag(t) {
377
+ return {
378
+ uuid: t.uuid,
379
+ title: t.title,
380
+ createdAt: t.createdAt,
381
+ updatedAt: t.updatedAt,
382
+ noteUuids: t.references
383
+ .filter((r) => r.content_type === "Note")
384
+ .map((r) => r.uuid),
385
+ parentUuid: parentUuidOf(t),
386
+ };
387
+ }
388
+ function buildClient(state) {
389
+ const defaultItemsKey = () => {
390
+ const uuid = state.defaultItemsKeyUuid;
391
+ if (!uuid)
392
+ throw new Error("No default items_key available");
393
+ const k = state.itemsKeys.get(uuid);
394
+ if (!k)
395
+ throw new Error(`Default items_key ${uuid} missing from state`);
396
+ return k;
397
+ };
398
+ const pushItems = async (items) => {
399
+ const res = await callSync(state, {
400
+ syncToken: state.syncToken ?? undefined,
401
+ items,
402
+ limit: 150,
403
+ });
404
+ // A push response also carries changes made elsewhere since our last
405
+ // sync token (edits and deletions in the SN app). Dropping them while
406
+ // advancing the token loses them for good, so fold them in and mark
407
+ // the decrypted caches stale; the next read re-decrypts.
408
+ const retrieved = res.retrieved_items ?? [];
409
+ applyRetrieved(state, retrieved);
410
+ for (const saved of res.saved_items) {
411
+ state.encryptedItemsRaw.set(saved.uuid, saved);
412
+ }
413
+ if (retrieved.length > 0)
414
+ state.lastSyncAt = 0;
415
+ // More pages pending: keep the old token so the next fullSync
416
+ // re-fetches them instead of skipping past.
417
+ if (res.cursor_token) {
418
+ state.lastSyncAt = 0;
419
+ }
420
+ else {
421
+ state.syncToken = res.sync_token ?? state.syncToken;
422
+ }
423
+ return res;
424
+ };
425
+ const submitNoteUpdate = async (uuid, merged, attempt) => {
426
+ const raw = state.encryptedItemsRaw.get(uuid);
427
+ if (!raw)
428
+ throw new Error(`Note ${uuid} has no encrypted record`);
429
+ const encrypted = await encryptNote(merged, {
430
+ uuid: defaultItemsKey().uuid,
431
+ itemsKey: defaultItemsKey().itemsKey,
432
+ });
433
+ const res = await pushItems([
434
+ {
435
+ ...raw,
436
+ content: encrypted.content,
437
+ enc_item_key: encrypted.enc_item_key,
438
+ items_key_id: encrypted.items_key_id,
439
+ updated_at: new Date().toISOString(),
440
+ updated_at_timestamp: raw.updated_at_timestamp,
441
+ },
442
+ ]);
443
+ const saved = res.saved_items.find((i) => i.uuid === uuid);
444
+ if (saved)
445
+ return saved;
446
+ const conflict = res.conflicts.find((c) => {
447
+ const cc = c;
448
+ return (cc.server_item?.uuid === uuid || cc.unsaved_item?.uuid === uuid);
449
+ });
450
+ if (!conflict) {
451
+ throw new Error(`Server did not save note ${uuid} and reported no conflict`);
452
+ }
453
+ const cc = conflict;
454
+ if (cc.type === "sync_conflict" && cc.server_item && attempt < 1) {
455
+ logger.info(`sync_conflict on note ${uuid} — refreshing and retrying`);
456
+ state.encryptedItemsRaw.set(uuid, cc.server_item);
457
+ return submitNoteUpdate(uuid, merged, attempt + 1);
458
+ }
459
+ throw new Error(`Conflict on note ${uuid} (type=${cc.type ?? "unknown"}, attempts=${attempt + 1}). Run the sync tool and retry.`);
460
+ };
461
+ const pushTag = async (existing, next) => {
462
+ const raw = state.encryptedItemsRaw.get(next.uuid);
463
+ const encrypted = await encryptTag(next, {
464
+ uuid: defaultItemsKey().uuid,
465
+ itemsKey: defaultItemsKey().itemsKey,
466
+ });
467
+ const nowIso = new Date().toISOString();
468
+ const item = raw
469
+ ? {
470
+ ...raw,
471
+ content: encrypted.content,
472
+ enc_item_key: encrypted.enc_item_key,
473
+ items_key_id: encrypted.items_key_id,
474
+ updated_at: nowIso,
475
+ updated_at_timestamp: raw.updated_at_timestamp,
476
+ }
477
+ : {
478
+ uuid: next.uuid,
479
+ content_type: "Tag",
480
+ content: encrypted.content,
481
+ enc_item_key: encrypted.enc_item_key,
482
+ items_key_id: encrypted.items_key_id,
483
+ created_at: nowIso,
484
+ updated_at: nowIso,
485
+ created_at_timestamp: 0,
486
+ updated_at_timestamp: 0,
487
+ deleted: false,
488
+ };
489
+ const res = await pushItems([item]);
490
+ const saved = res.saved_items.find((i) => i.uuid === next.uuid);
491
+ if (!saved) {
492
+ const conflict = res.conflicts.find((c) => c.unsaved_item?.uuid ===
493
+ next.uuid);
494
+ throw new Error(`Server did not save tag ${next.uuid}` +
495
+ (conflict ? ` (conflict: ${JSON.stringify(conflict)})` : ""));
496
+ }
497
+ const stored = {
498
+ uuid: next.uuid,
499
+ title: next.title,
500
+ references: next.references,
501
+ createdAt: saved.created_at ?? existing?.createdAt ?? nowIso,
502
+ updatedAt: saved.updated_at ?? nowIso,
503
+ created_at_timestamp: saved.created_at_timestamp ?? existing?.created_at_timestamp ?? 0,
504
+ updated_at_timestamp: saved.updated_at_timestamp ?? existing?.updated_at_timestamp ?? 0,
505
+ };
506
+ state.tagsCache.set(next.uuid, stored);
507
+ return stored;
508
+ };
509
+ const attachTagInternal = async (noteUuid, tagUuid) => {
510
+ if (!state.notesCache.has(noteUuid)) {
511
+ throw new Error(`Note ${noteUuid} not found`);
512
+ }
513
+ const tag = state.tagsCache.get(tagUuid);
514
+ if (!tag)
515
+ throw new Error(`Tag ${tagUuid} not found`);
516
+ if (tag.references.some((r) => r.uuid === noteUuid))
517
+ return;
518
+ const nextRefs = [
519
+ ...tag.references,
520
+ { uuid: noteUuid, content_type: "Note" },
521
+ ];
522
+ await pushTag(tag, { uuid: tag.uuid, title: tag.title, references: nextRefs });
523
+ };
524
+ const detachTagInternal = async (noteUuid, tagUuid) => {
525
+ const tag = state.tagsCache.get(tagUuid);
526
+ if (!tag)
527
+ throw new Error(`Tag ${tagUuid} not found`);
528
+ if (!tag.references.some((r) => r.uuid === noteUuid))
529
+ return;
530
+ const nextRefs = tag.references.filter((r) => r.uuid !== noteUuid);
531
+ await pushTag(tag, { uuid: tag.uuid, title: tag.title, references: nextRefs });
532
+ };
533
+ const syncTagsToNote = async (noteUuid, tagUuids) => {
534
+ const desired = new Set(tagUuids);
535
+ for (const uuid of desired) {
536
+ if (!state.tagsCache.has(uuid)) {
537
+ throw new Error(`Tag ${uuid} not found`);
538
+ }
539
+ }
540
+ for (const tag of state.tagsCache.values()) {
541
+ const hasRef = tag.references.some((r) => r.uuid === noteUuid);
542
+ if (desired.has(tag.uuid) && !hasRef) {
543
+ await attachTagInternal(noteUuid, tag.uuid);
544
+ }
545
+ else if (!desired.has(tag.uuid) && hasRef) {
546
+ await detachTagInternal(noteUuid, tag.uuid);
547
+ }
548
+ }
549
+ };
550
+ const escapeRegExp = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
551
+ const applyOneReplacement = (text, r) => {
552
+ if (r.useRegex)
553
+ assertSafeRegex(r.find);
554
+ const source = r.useRegex ? r.find : escapeRegExp(r.find);
555
+ const flags = (r.replaceAll ? "g" : "") + (r.caseSensitive ? "" : "i");
556
+ const re = new RegExp(source, flags);
557
+ let count = 0;
558
+ const out = text.replace(re, () => {
559
+ count++;
560
+ return r.replace;
561
+ });
562
+ return { text: out, count };
563
+ };
564
+ // Shared write path for the surgical text edits (append / replace_in).
565
+ // Mirrors updateNote's invariants: unconditional sync first, super notes
566
+ // refused (their body is rich-text JSON — line surgery would corrupt it),
567
+ // conflict-retried push via submitNoteUpdate.
568
+ const applyTextEdit = async (uuid, transform) => {
569
+ await ensureFresh(state, 0, () => fullSync(state));
570
+ if (!scopeAllows(currentScope(), uuid))
571
+ throw noteNotFound(uuid);
572
+ const existing = state.notesCache.get(uuid);
573
+ if (!existing) {
574
+ throw new ToolError("note_not_found", `Note ${uuid} not found`, "Run notes_search or notes_list to find the note's uuid.");
575
+ }
576
+ assertAiWritable(existing);
577
+ if (existing.noteType === "super") {
578
+ throw new ToolError("unsupported_note_type", `Note ${uuid} is a super (rich-text) note; section append and search-replace only work on plain-text/markdown bodies.`, "Use notes_update to replace the whole body instead.");
579
+ }
580
+ const raw = state.encryptedItemsRaw.get(uuid);
581
+ if (!raw)
582
+ throw new Error(`Note ${uuid} has no encrypted record`);
583
+ const nextText = transform(existing.text);
584
+ const merged = {
585
+ uuid,
586
+ title: existing.title,
587
+ text: nextText,
588
+ trashed: existing.trashed,
589
+ archived: existing.archived,
590
+ pinned: existing.pinned,
591
+ noteType: existing.noteType,
592
+ references: existing.references,
593
+ extra: existing.extra,
594
+ };
595
+ const saved = await submitNoteUpdate(uuid, merged, 0);
596
+ state.notesCache.set(uuid, {
597
+ ...existing,
598
+ text: nextText,
599
+ createdAt: saved.created_at ?? existing.createdAt,
600
+ updatedAt: saved.updated_at ?? existing.updatedAt,
601
+ created_at_timestamp: saved.created_at_timestamp ?? existing.created_at_timestamp,
602
+ updated_at_timestamp: saved.updated_at_timestamp ?? existing.updated_at_timestamp,
603
+ });
604
+ return {
605
+ previousSizeInBytes: Buffer.byteLength(existing.text, "utf8"),
606
+ currentSizeInBytes: Buffer.byteLength(nextText, "utf8"),
607
+ };
608
+ };
609
+ // Resolve a tag filter (UUID or case-insensitive title) to the set of
610
+ // note UUIDs it covers, optionally walking the whole subtree (SN sidebar
611
+ // folder behavior). Shared by listNotes and searchNotes.
612
+ const resolveTagFilter = (tag, includeDescendants) => {
613
+ const matched = state.tagsCache.get(tag) ??
614
+ [...state.tagsCache.values()].find((t) => t.title.toLowerCase() === tag.toLowerCase());
615
+ const scf = currentScope();
616
+ if (!matched ||
617
+ (scf !== null && scf.hiddenTags.has(matched.uuid)) ||
618
+ (scf !== null && scf.allowTags !== null && !scf.allowTags.has(matched.uuid))) {
619
+ throw new ToolError("tag_not_found", `Tag not found: ${tag}`, "Run tags_list to see the available tags and their uuids.");
620
+ }
621
+ const tagUuids = includeDescendants
622
+ ? subtreeTagUuids(state.tagsCache, matched.uuid)
623
+ : new Set([matched.uuid]);
624
+ const allowed = new Set();
625
+ for (const uuid of tagUuids) {
626
+ const t = state.tagsCache.get(uuid);
627
+ if (!t)
628
+ continue;
629
+ for (const r of t.references) {
630
+ if (r.content_type === "Note")
631
+ allowed.add(r.uuid);
632
+ }
633
+ }
634
+ return allowed;
635
+ };
636
+ const decodeCursor = (cursor) => {
637
+ if (cursor === undefined || cursor === "")
638
+ return 0;
639
+ try {
640
+ const parsed = JSON.parse(Buffer.from(cursor, "base64url").toString("utf8"));
641
+ if (typeof parsed.o === "number" && parsed.o >= 0)
642
+ return parsed.o;
643
+ }
644
+ catch {
645
+ // fall through
646
+ }
647
+ throw new ToolError("cursor_invalid", "The search cursor is not valid.", "Restart the search without a cursor and page using the returned nextCursor values.");
648
+ };
649
+ const encodeCursor = (offset) => Buffer.from(JSON.stringify({ o: offset }), "utf8").toString("base64url");
650
+ // Read scope (SN_READ_TAGS / SN_DENY_TAGS), re-resolved per call because
651
+ // tag membership changes with every sync. Out-of-scope notes are treated
652
+ // as nonexistent — "not found" rather than "forbidden" so the scope's
653
+ // contents can't be probed.
654
+ // ----- SN plan gating (see ./entitlement.ts) -----
655
+ const ent = () => entitlementFromRoles(state.roles);
656
+ // New notes default to markdown on paid accounts (the historical default)
657
+ // and plain-text on free ones; an explicit type goes through
658
+ // decideNoteType (paid editors → plain-text, super → refused).
659
+ const noteTypeForCreate = (requested) => requested === undefined
660
+ ? isPaid(ent())
661
+ ? "markdown"
662
+ : "plain-text"
663
+ : decideNoteType(requested, ent()).noteType;
664
+ // Updates keep a note's existing type; only an explicit change is gated.
665
+ const noteTypeForUpdate = (requested, existing) => requested === undefined || requested === existing
666
+ ? existing
667
+ : decideNoteType(requested, ent()).noteType;
668
+ // Free accounts can view Super notes in the SN app but not edit them;
669
+ // mirror that rather than editing their content on the account's behalf.
670
+ const assertCanEditContent = (n, textChanging) => {
671
+ if (textChanging && n.noteType === "super" && !isPaid(ent())) {
672
+ throw paidFeatureError("Editing Super notes", ent(), "Super notes stay readable; create a plain-text note for new content.");
673
+ }
674
+ };
675
+ const assertCanNestTags = () => {
676
+ if (!isPaid(ent())) {
677
+ throw paidFeatureError("Nested folders", ent(), "Create the folder at the top level instead (omit `parent`).");
678
+ }
679
+ };
680
+ const currentScope = () => resolveScope(state.tagsCache, state.scope);
681
+ 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
+ // Frontmatter AI governance (see src/sn/governance.ts). `ai: no-access`
683
+ // notes are invisible; `ai: read-only` notes reject every write path.
684
+ const aiPolicy = (n) => state.governance ? aiPolicyOf(n.text, state.clientName()) : "ok";
685
+ // A note the user protected in the SN app (re-auth required to open it)
686
+ // is invisible to the AI, exactly like `ai: no-access`: no title, body,
687
+ // dates, tags, counts, search ranking or "it's protected" error — it is
688
+ // indistinguishable from a note that doesn't exist. Applies even with
689
+ // governance off, since protection is the user's own SN setting.
690
+ const aiReadable = (n) => !n.protected && aiPolicy(n) !== "no-access";
691
+ /** A note uuid that exists, is in scope and may be seen by the AI. */
692
+ const noteVisible = (sc, uuid) => {
693
+ const n = state.notesCache.get(uuid);
694
+ return n !== undefined && scopeAllows(sc, uuid) && aiReadable(n);
695
+ };
696
+ const assertAiWritable = (n) => {
697
+ if (n.protected)
698
+ throw noteNotFound(n.uuid);
699
+ const p = aiPolicy(n);
700
+ if (p === "no-access")
701
+ throw noteNotFound(n.uuid);
702
+ if (p === "read-only") {
703
+ throw new ToolError("governance_read_only", `Note ${n.uuid} has frontmatter "ai: read-only" — the user has marked it as not editable by AI.`, "Do not retry. If the user explicitly wants it edited, they can change or remove the `ai` frontmatter key.");
704
+ }
705
+ };
706
+ // Under an allowlist scope (SN_READ_TAGS), creates and retags must keep
707
+ // the note inside the scope: at least one in-scope tag, never a denied
708
+ // (hidden) tag. Without this a scoped client could mint notes it cannot
709
+ // see or clean up, or untag existing notes out of its own scope.
710
+ const assertTagsWithinScope = (sc, tags) => {
711
+ if (sc === null)
712
+ return;
713
+ const provided = tags ?? [];
714
+ for (const t of provided) {
715
+ if (sc.hiddenTags.has(t)) {
716
+ throw new ToolError("tag_not_found", `Tag ${t} not found`, "Run tags_list to see the available tags and their uuids.");
717
+ }
718
+ }
719
+ const allowTags = sc.allowTags;
720
+ if (allowTags !== null && !provided.some((t) => allowTags.has(t))) {
721
+ throw new ToolError("scope_create_denied", "Your config scope (SN_READ_TAGS) requires notes you create or retag to stay filed under an in-scope tag; none of the provided tags qualify.", "Run tags_list to get an in-scope tag uuid and include it in `tags`.");
722
+ }
723
+ };
724
+ const tagNotFoundErr = (tagUuid) => new ToolError("tag_not_found", `Tag ${tagUuid} not found`, "Run tags_list to see the available tags and their uuids.");
725
+ // Tag visibility under scope: a scoped client only sees tags inside its
726
+ // allowlist (and never denied tags). Without this, tag titles outside the
727
+ // scope leak via tags_list — and tag writes become a read-escalation:
728
+ // moving an out-of-scope tag under an allowed one would expose every
729
+ // note in it.
730
+ const assertTagVisible = (sc, tagUuid) => {
731
+ if (sc === null)
732
+ return;
733
+ if (sc.hiddenTags.has(tagUuid))
734
+ throw tagNotFoundErr(tagUuid);
735
+ if (sc.allowTags !== null && !sc.allowTags.has(tagUuid)) {
736
+ throw tagNotFoundErr(tagUuid);
737
+ }
738
+ };
739
+ // Scope roots (the tags named in SN_READ_TAGS) are V's structure: a
740
+ // scoped client may work inside them but never rename/move/delete them.
741
+ const assertTagMutable = (sc, tagUuid) => {
742
+ assertTagVisible(sc, tagUuid);
743
+ if (sc !== null && sc.allowRoots !== null && sc.allowRoots.has(tagUuid)) {
744
+ throw new ToolError("scope_tag_root", `Tag ${tagUuid} is a scope root and cannot be renamed, moved, or deleted by this client.`, "Ask V to restructure scope roots from the Standard Notes app.");
745
+ }
746
+ };
747
+ const tagsCountFor = (noteUuid) => {
748
+ let count = 0;
749
+ for (const tag of state.tagsCache.values()) {
750
+ if (tag.references.some((r) => r.uuid === noteUuid && r.content_type === "Note")) {
751
+ count++;
752
+ }
753
+ }
754
+ return count;
755
+ };
756
+ // Shared evaluation for smart views and ad-hoc predicate queries:
757
+ // scope-filtered, predicate-matched, sorted by recency, paginated.
758
+ const runPredicate = (predicate, { limit, offset }) => {
759
+ const sc = currentScope();
760
+ const matched = [...state.notesCache.values()]
761
+ .filter((n) => scopeAllows(sc, n.uuid))
762
+ .filter((n) => aiReadable(n))
763
+ .filter((n) => evaluatePredicate(predicate, notePredicateTarget(n, tagsCountFor(n.uuid))))
764
+ .sort((a, b) => b.updated_at_timestamp - a.updated_at_timestamp);
765
+ return {
766
+ notes: matched.slice(offset, offset + limit).map(toSummary),
767
+ totalCount: matched.length,
768
+ };
769
+ };
770
+ // Fetch + decrypt one revision. AAD of the stored payload is the NOTE's
771
+ // uuid, not the revision's — decrypt with item_uuid as the item identity.
772
+ const revisionsRefused = (err) => err instanceof http.SnApiError && err.status === 403
773
+ ? paidFeatureError("Note history", ent(), "Use the Standard Notes app's built-in note history.")
774
+ : err;
775
+ const fetchRevision = async (noteUuid, revisionUuid) => {
776
+ // Respect the plan's history window before fetching any content: the
777
+ // revision's required_role comes from the listing (see canViewRevision).
778
+ const listing = await authedCall(state, (cfg) => http.listRevisions(cfg, noteUuid)).catch((err) => {
779
+ throw revisionsRefused(err);
780
+ });
781
+ const meta = listing.find((r) => r.uuid === revisionUuid);
782
+ if (!meta) {
783
+ throw new ToolError("revision_not_found", `Revision ${revisionUuid} not found for this note.`, "List the available revisions with notes_history.");
784
+ }
785
+ if (!canViewRevision(meta.required_role, ent())) {
786
+ throw paidFeatureError("Older note history", ent(), "Pick a more recent revision from notes_history.");
787
+ }
788
+ const rev = await authedCall(state, (cfg) => http.getRevision(cfg, noteUuid, revisionUuid));
789
+ if (!rev.content || !rev.enc_item_key) {
790
+ throw new ToolError("revision_empty", `Revision ${revisionUuid} has no content payload.`, "Pick another revision from notes_history.");
791
+ }
792
+ const itemsKeyBytes = new Map();
793
+ for (const [u, k] of state.itemsKeys.entries()) {
794
+ itemsKeyBytes.set(u, k.itemsKey);
795
+ }
796
+ const decrypted = await decryptNote({
797
+ uuid: rev.item_uuid,
798
+ content_type: "Note",
799
+ content: rev.content,
800
+ enc_item_key: rev.enc_item_key,
801
+ items_key_id: rev.items_key_id,
802
+ created_at: rev.created_at,
803
+ updated_at: rev.updated_at,
804
+ }, itemsKeyBytes);
805
+ return {
806
+ revisionUuid: rev.uuid,
807
+ noteUuid,
808
+ title: decrypted.title,
809
+ text: decrypted.text,
810
+ noteType: decrypted.noteType,
811
+ revisionCreatedAt: rev.created_at,
812
+ };
813
+ };
814
+ return {
815
+ async listNotes({ limit, offset, includeTrashed, tag, includeDescendants }) {
816
+ await ensureFresh(state, cacheTtlMs(), () => fullSync(state));
817
+ const sc = currentScope();
818
+ let allowedNoteUuids = null;
819
+ if (tag !== undefined && tag !== "") {
820
+ // With includeDescendants, walk the sub-tree from the matched tag
821
+ // and union the note refs of every tag inside it. Mirrors the SN
822
+ // sidebar: clicking a parent folder shows every note filed under
823
+ // any child, grandchild, etc.
824
+ allowedNoteUuids = resolveTagFilter(tag, includeDescendants ?? false);
825
+ }
826
+ const all = [...state.notesCache.values()]
827
+ .filter((n) => includeTrashed || !n.trashed)
828
+ .filter((n) => scopeAllows(sc, n.uuid))
829
+ .filter((n) => aiReadable(n))
830
+ .filter((n) => !allowedNoteUuids || allowedNoteUuids.has(n.uuid))
831
+ .sort((a, b) => b.updated_at_timestamp - a.updated_at_timestamp);
832
+ return all.slice(offset, offset + limit).map(toSummary);
833
+ },
834
+ async stats() {
835
+ await ensureFresh(state, cacheTtlMs(), () => fullSync(state));
836
+ const sc = currentScope();
837
+ // Same visibility as every other read: scope AND governance. Without
838
+ // aiReadable an `ai: no-access` note could surface by title as the
839
+ // largest/oldest/newest note and inflate the counts.
840
+ const notes = [...state.notesCache.values()]
841
+ .filter((n) => scopeAllows(sc, n.uuid))
842
+ .filter((n) => aiReadable(n));
843
+ const visibleTagCount = [...state.tagsCache.values()]
844
+ .filter((t) => sc === null || !sc.hiddenTags.has(t.uuid))
845
+ .filter((t) => sc === null || sc.allowTags === null || sc.allowTags.has(t.uuid)).length;
846
+ const active = notes.filter((n) => !n.trashed);
847
+ const byNoteType = {};
848
+ let totalTextBytes = 0;
849
+ let largest = null;
850
+ let oldestTs = Infinity;
851
+ let oldest = null;
852
+ let newestTs = -Infinity;
853
+ let newest = null;
854
+ for (const n of active) {
855
+ byNoteType[n.noteType] = (byNoteType[n.noteType] ?? 0) + 1;
856
+ const bytes = Buffer.byteLength(n.text, "utf8");
857
+ totalTextBytes += bytes;
858
+ if (!largest || bytes > largest.bytes) {
859
+ largest = { uuid: n.uuid, title: n.title, bytes };
860
+ }
861
+ if (n.created_at_timestamp > 0 && n.created_at_timestamp < oldestTs) {
862
+ oldestTs = n.created_at_timestamp;
863
+ oldest = { uuid: n.uuid, title: n.title, createdAt: n.createdAt };
864
+ }
865
+ if (n.updated_at_timestamp > newestTs) {
866
+ newestTs = n.updated_at_timestamp;
867
+ newest = { uuid: n.uuid, title: n.title, updatedAt: n.updatedAt };
868
+ }
869
+ }
870
+ return {
871
+ notes: {
872
+ total: notes.length,
873
+ active: active.length,
874
+ trashed: notes.length - active.length,
875
+ },
876
+ tags: visibleTagCount,
877
+ byNoteType,
878
+ totalTextBytes,
879
+ averageTextBytes: active.length === 0 ? 0 : Math.round(totalTextBytes / active.length),
880
+ largest,
881
+ oldest,
882
+ newest,
883
+ syncedAt: new Date(state.lastSyncAt).toISOString(),
884
+ cacheAgeMs: Date.now() - state.lastSyncAt,
885
+ // Vault-wide diagnostics; withheld from scoped clients, for whom
886
+ // they'd describe items outside their scope.
887
+ decryptFailures: sc === null
888
+ ? {
889
+ notes: state.decryptFailedNotes.size,
890
+ tags: state.decryptFailedTags.size,
891
+ }
892
+ : { notes: 0, tags: 0 },
893
+ };
894
+ },
895
+ async searchNotes(opts) {
896
+ await ensureFresh(state, cacheTtlMs(), () => fullSync(state));
897
+ const sc = currentScope();
898
+ let tagFilter = null;
899
+ if (opts.tag !== undefined && opts.tag !== "") {
900
+ tagFilter = resolveTagFilter(opts.tag, opts.includeDescendants);
901
+ }
902
+ const offset = decodeCursor(opts.cursor);
903
+ const { hits, totalCount } = searchDecryptedNotes(state.notesCache.values(), {
904
+ query: opts.query,
905
+ mode: opts.mode,
906
+ contextLength: opts.contextLength,
907
+ maxMatchesPerHit: opts.maxMatchesPerHit,
908
+ includeTrashed: opts.includeTrashed,
909
+ noteType: opts.noteType,
910
+ updatedAfter: opts.updatedAfter,
911
+ updatedBefore: opts.updatedBefore,
912
+ sort: opts.sort,
913
+ fuzzy: opts.fuzzy,
914
+ isAllowed: (uuid) => {
915
+ if (!scopeAllows(sc, uuid))
916
+ return false;
917
+ if (tagFilter !== null && !tagFilter.has(uuid))
918
+ return false;
919
+ const n = state.notesCache.get(uuid);
920
+ return n !== undefined && aiReadable(n);
921
+ },
922
+ });
923
+ const page = hits.slice(offset, offset + opts.limit);
924
+ const nextOffset = offset + page.length;
925
+ return {
926
+ hits: page.map((h) => ({
927
+ ...toSummary(h.note),
928
+ matches: h.matches,
929
+ totalMatches: h.totalMatches,
930
+ truncated: h.truncated,
931
+ fuzzy: h.fuzzy,
932
+ })),
933
+ totalCount,
934
+ nextCursor: nextOffset < hits.length ? encodeCursor(nextOffset) : null,
935
+ };
936
+ },
937
+ async getNote(uuid) {
938
+ await ensureFresh(state, cacheTtlMs(), () => fullSync(state));
939
+ if (!scopeAllows(currentScope(), uuid))
940
+ return null;
941
+ const n = state.notesCache.get(uuid);
942
+ if (!n || !aiReadable(n))
943
+ return null;
944
+ return toFullNote(n, state.tagsCache);
945
+ },
946
+ async createNote({ title, text, noteType, tags }) {
947
+ assertTagsWithinScope(currentScope(), tags);
948
+ const uuid = crypto.randomUUID();
949
+ const resolvedType = noteTypeForCreate(noteType);
950
+ const resolvedText = resolvedType === "super" ? normalizeSuperText(text) : text;
951
+ const encrypted = await encryptNote({
952
+ uuid,
953
+ title,
954
+ text: resolvedText,
955
+ trashed: false,
956
+ noteType: resolvedType,
957
+ }, { uuid: defaultItemsKey().uuid, itemsKey: defaultItemsKey().itemsKey });
958
+ const nowIso = new Date().toISOString();
959
+ const res = await pushItems([
960
+ {
961
+ uuid,
962
+ content_type: "Note",
963
+ content: encrypted.content,
964
+ enc_item_key: encrypted.enc_item_key,
965
+ items_key_id: encrypted.items_key_id,
966
+ created_at: nowIso,
967
+ updated_at: nowIso,
968
+ created_at_timestamp: 0,
969
+ updated_at_timestamp: 0,
970
+ deleted: false,
971
+ },
972
+ ]);
973
+ const saved = res.saved_items.find((i) => i.uuid === uuid);
974
+ if (!saved) {
975
+ const conflict = res.conflicts.find((c) => c.unsaved_item?.uuid === uuid);
976
+ throw new Error(`Server did not save note ${uuid}` +
977
+ (conflict ? ` (conflict: ${JSON.stringify(conflict)})` : ""));
978
+ }
979
+ state.notesCache.set(uuid, {
980
+ uuid,
981
+ title,
982
+ text: resolvedText,
983
+ trashed: false,
984
+ protected: false,
985
+ locked: false,
986
+ archived: false,
987
+ pinned: false,
988
+ noteType: resolvedType,
989
+ createdAt: saved.created_at ?? nowIso,
990
+ updatedAt: saved.updated_at ?? nowIso,
991
+ created_at_timestamp: saved.created_at_timestamp ?? 0,
992
+ updated_at_timestamp: saved.updated_at_timestamp ?? 0,
993
+ references: [],
994
+ extra: {},
995
+ });
996
+ if (tags && tags.length > 0) {
997
+ for (const tagUuid of tags) {
998
+ await attachTagInternal(uuid, tagUuid);
999
+ }
1000
+ }
1001
+ return uuid;
1002
+ },
1003
+ async createNotesBatch(inputs) {
1004
+ if (inputs.length === 0)
1005
+ return [];
1006
+ const scCreate = currentScope();
1007
+ for (const input of inputs) {
1008
+ assertTagsWithinScope(scCreate, input.tags);
1009
+ noteTypeForCreate(input.noteType); // refuse paid-only types up front
1010
+ }
1011
+ const nowIso = new Date().toISOString();
1012
+ const prepared = inputs.map((input) => {
1013
+ const resolvedType = noteTypeForCreate(input.noteType);
1014
+ const resolvedText = resolvedType === "super"
1015
+ ? normalizeSuperText(input.text)
1016
+ : input.text;
1017
+ return {
1018
+ uuid: crypto.randomUUID(),
1019
+ title: input.title,
1020
+ text: resolvedText,
1021
+ noteType: resolvedType,
1022
+ tags: input.tags ?? [],
1023
+ };
1024
+ });
1025
+ const items = await Promise.all(prepared.map(async (p) => {
1026
+ const encrypted = await encryptNote({
1027
+ uuid: p.uuid,
1028
+ title: p.title,
1029
+ text: p.text,
1030
+ trashed: false,
1031
+ noteType: p.noteType,
1032
+ }, {
1033
+ uuid: defaultItemsKey().uuid,
1034
+ itemsKey: defaultItemsKey().itemsKey,
1035
+ });
1036
+ return {
1037
+ uuid: p.uuid,
1038
+ content_type: "Note",
1039
+ content: encrypted.content,
1040
+ enc_item_key: encrypted.enc_item_key,
1041
+ items_key_id: encrypted.items_key_id,
1042
+ created_at: nowIso,
1043
+ updated_at: nowIso,
1044
+ created_at_timestamp: 0,
1045
+ updated_at_timestamp: 0,
1046
+ deleted: false,
1047
+ };
1048
+ }));
1049
+ const res = await pushItems(items);
1050
+ const savedByUuid = new Map(res.saved_items.map((i) => [i.uuid, i]));
1051
+ const failed = [];
1052
+ for (const p of prepared) {
1053
+ const saved = savedByUuid.get(p.uuid);
1054
+ if (!saved) {
1055
+ failed.push(p.uuid);
1056
+ continue;
1057
+ }
1058
+ state.notesCache.set(p.uuid, {
1059
+ uuid: p.uuid,
1060
+ title: p.title,
1061
+ text: p.text,
1062
+ trashed: false,
1063
+ protected: false,
1064
+ locked: false,
1065
+ archived: false,
1066
+ pinned: false,
1067
+ noteType: p.noteType,
1068
+ createdAt: saved.created_at ?? nowIso,
1069
+ updatedAt: saved.updated_at ?? nowIso,
1070
+ created_at_timestamp: saved.created_at_timestamp ?? 0,
1071
+ updated_at_timestamp: saved.updated_at_timestamp ?? 0,
1072
+ references: [],
1073
+ extra: {},
1074
+ });
1075
+ }
1076
+ if (failed.length > 0) {
1077
+ throw new Error(`Server did not save ${failed.length} note(s) in batch: ${failed.join(", ")}`);
1078
+ }
1079
+ for (const p of prepared) {
1080
+ for (const tagUuid of p.tags) {
1081
+ await attachTagInternal(p.uuid, tagUuid);
1082
+ }
1083
+ }
1084
+ return prepared.map((p) => ({ uuid: p.uuid, title: p.title }));
1085
+ },
1086
+ async updateNotesBatch(inputs) {
1087
+ // One sync + one push for the whole batch; per-note failures are
1088
+ // collected instead of aborting the rest.
1089
+ await ensureFresh(state, 0, () => fullSync(state));
1090
+ const sc = currentScope();
1091
+ const failed = [];
1092
+ const prepared = [];
1093
+ for (const input of inputs) {
1094
+ const existing = state.notesCache.get(input.uuid);
1095
+ // Visibility first: a protected or no-access note reports "not
1096
+ // found", never anything that confirms it exists.
1097
+ if (!existing || !scopeAllows(sc, input.uuid) || !aiReadable(existing)) {
1098
+ failed.push({ uuid: input.uuid, error: "not found" });
1099
+ continue;
1100
+ }
1101
+ if (existing.locked) {
1102
+ failed.push({ uuid: input.uuid, error: "edit-locked" });
1103
+ continue;
1104
+ }
1105
+ if (aiPolicy(existing) === "read-only") {
1106
+ failed.push({ uuid: input.uuid, error: "governance: ai read-only" });
1107
+ continue;
1108
+ }
1109
+ const raw = state.encryptedItemsRaw.get(input.uuid);
1110
+ if (!raw) {
1111
+ failed.push({ uuid: input.uuid, error: "no encrypted record" });
1112
+ continue;
1113
+ }
1114
+ if (input.tags !== undefined) {
1115
+ try {
1116
+ assertTagsWithinScope(sc, input.tags);
1117
+ }
1118
+ catch (err) {
1119
+ failed.push({
1120
+ uuid: input.uuid,
1121
+ error: err instanceof Error ? err.message : String(err),
1122
+ });
1123
+ continue;
1124
+ }
1125
+ }
1126
+ let nextType;
1127
+ try {
1128
+ assertCanEditContent(existing, input.text !== undefined);
1129
+ nextType = noteTypeForUpdate(input.noteType, existing.noteType);
1130
+ }
1131
+ catch (err) {
1132
+ failed.push({
1133
+ uuid: input.uuid,
1134
+ error: err instanceof Error ? err.message : String(err),
1135
+ });
1136
+ continue;
1137
+ }
1138
+ const nextTextRaw = input.text ?? existing.text;
1139
+ const nextText = nextType === "super" && input.text !== undefined
1140
+ ? normalizeSuperText(input.text)
1141
+ : nextTextRaw;
1142
+ const merged = {
1143
+ uuid: input.uuid,
1144
+ title: input.title ?? existing.title,
1145
+ text: nextText,
1146
+ trashed: input.trashed ?? existing.trashed,
1147
+ archived: input.archived ?? existing.archived,
1148
+ pinned: input.pinned ?? existing.pinned,
1149
+ noteType: nextType,
1150
+ references: existing.references,
1151
+ extra: existing.extra,
1152
+ };
1153
+ const encrypted = await encryptNote(merged, {
1154
+ uuid: defaultItemsKey().uuid,
1155
+ itemsKey: defaultItemsKey().itemsKey,
1156
+ });
1157
+ prepared.push({
1158
+ uuid: input.uuid,
1159
+ merged,
1160
+ existing,
1161
+ tags: input.tags,
1162
+ item: {
1163
+ ...raw,
1164
+ content: encrypted.content,
1165
+ enc_item_key: encrypted.enc_item_key,
1166
+ items_key_id: encrypted.items_key_id,
1167
+ updated_at: new Date().toISOString(),
1168
+ updated_at_timestamp: raw.updated_at_timestamp,
1169
+ },
1170
+ });
1171
+ }
1172
+ if (prepared.length > 0) {
1173
+ const res = await pushItems(prepared.map((p) => p.item));
1174
+ const savedByUuid = new Map(res.saved_items.map((i) => [i.uuid, i]));
1175
+ for (const p of prepared) {
1176
+ const saved = savedByUuid.get(p.uuid);
1177
+ if (!saved) {
1178
+ failed.push({ uuid: p.uuid, error: "server did not save" });
1179
+ continue;
1180
+ }
1181
+ state.notesCache.set(p.uuid, {
1182
+ ...p.existing,
1183
+ ...p.merged,
1184
+ createdAt: saved.created_at ?? p.existing.createdAt,
1185
+ updatedAt: saved.updated_at ?? p.existing.updatedAt,
1186
+ created_at_timestamp: saved.created_at_timestamp ?? p.existing.created_at_timestamp,
1187
+ updated_at_timestamp: saved.updated_at_timestamp ?? p.existing.updated_at_timestamp,
1188
+ });
1189
+ }
1190
+ }
1191
+ // Tag changes ride on the tag items, not the note push — apply after.
1192
+ for (const p of prepared) {
1193
+ if (p.tags !== undefined && state.notesCache.has(p.uuid)) {
1194
+ try {
1195
+ await syncTagsToNote(p.uuid, p.tags);
1196
+ }
1197
+ catch (err) {
1198
+ failed.push({
1199
+ uuid: p.uuid,
1200
+ error: `note saved but tags failed: ${err instanceof Error ? err.message : String(err)}`,
1201
+ });
1202
+ }
1203
+ }
1204
+ }
1205
+ const failedUuids = new Set(failed.map((f) => f.uuid));
1206
+ return {
1207
+ updated: prepared.map((p) => p.uuid).filter((u) => !failedUuids.has(u)),
1208
+ failed,
1209
+ };
1210
+ },
1211
+ async deleteNotesBatch(uuids, permanent) {
1212
+ await ensureFresh(state, 0, () => fullSync(state));
1213
+ const sc = currentScope();
1214
+ const failed = [];
1215
+ const items = [];
1216
+ const trashing = [];
1217
+ for (const uuid of uuids) {
1218
+ const raw = state.encryptedItemsRaw.get(uuid);
1219
+ const existing = state.notesCache.get(uuid);
1220
+ if (!raw || !existing || !scopeAllows(sc, uuid) || !aiReadable(existing)) {
1221
+ failed.push({ uuid, error: "not found" });
1222
+ continue;
1223
+ }
1224
+ if (existing.locked) {
1225
+ failed.push({ uuid, error: "edit-locked" });
1226
+ continue;
1227
+ }
1228
+ if (aiPolicy(existing) === "read-only") {
1229
+ failed.push({ uuid, error: "governance: ai read-only" });
1230
+ continue;
1231
+ }
1232
+ if (permanent) {
1233
+ items.push({
1234
+ uuid,
1235
+ content_type: "Note",
1236
+ deleted: true,
1237
+ content: "",
1238
+ enc_item_key: "",
1239
+ updated_at_timestamp: raw.updated_at_timestamp,
1240
+ });
1241
+ }
1242
+ else {
1243
+ const encrypted = await encryptNote({
1244
+ uuid,
1245
+ title: existing.title,
1246
+ text: existing.text,
1247
+ trashed: true,
1248
+ archived: existing.archived,
1249
+ pinned: existing.pinned,
1250
+ noteType: existing.noteType,
1251
+ references: existing.references,
1252
+ extra: existing.extra,
1253
+ }, {
1254
+ uuid: defaultItemsKey().uuid,
1255
+ itemsKey: defaultItemsKey().itemsKey,
1256
+ });
1257
+ items.push({
1258
+ ...raw,
1259
+ content: encrypted.content,
1260
+ enc_item_key: encrypted.enc_item_key,
1261
+ items_key_id: encrypted.items_key_id,
1262
+ updated_at: new Date().toISOString(),
1263
+ updated_at_timestamp: raw.updated_at_timestamp,
1264
+ });
1265
+ trashing.push({ uuid, existing });
1266
+ }
1267
+ }
1268
+ if (items.length > 0) {
1269
+ const res = await pushItems(items);
1270
+ const savedByUuid = new Map(res.saved_items.map((i) => [i.uuid, i]));
1271
+ for (const uuid of uuids) {
1272
+ if (failed.some((f) => f.uuid === uuid))
1273
+ continue;
1274
+ if (permanent) {
1275
+ state.notesCache.delete(uuid);
1276
+ state.encryptedItemsRaw.delete(uuid);
1277
+ }
1278
+ else {
1279
+ const t = trashing.find((x) => x.uuid === uuid);
1280
+ const saved = savedByUuid.get(uuid);
1281
+ if (t) {
1282
+ state.notesCache.set(uuid, {
1283
+ ...t.existing,
1284
+ trashed: true,
1285
+ updatedAt: saved?.updated_at ?? t.existing.updatedAt,
1286
+ updated_at_timestamp: saved?.updated_at_timestamp ??
1287
+ t.existing.updated_at_timestamp,
1288
+ });
1289
+ }
1290
+ }
1291
+ }
1292
+ }
1293
+ const failedUuids = new Set(failed.map((f) => f.uuid));
1294
+ return {
1295
+ deleted: uuids.filter((u) => !failedUuids.has(u)),
1296
+ failed,
1297
+ };
1298
+ },
1299
+ async updateNote({ uuid, title, text, noteType, tags, trashed, archived, pinned }) {
1300
+ // Sync inconditionnel avant mutation : sinon on peut écraser une
1301
+ // révision plus récente produite par une autre instance du serveur
1302
+ // (cf. intakes/mcp-standardnotes-cache-staleness.md).
1303
+ await ensureFresh(state, 0, () => fullSync(state));
1304
+ if (!scopeAllows(currentScope(), uuid))
1305
+ throw noteNotFound(uuid);
1306
+ const existing = state.notesCache.get(uuid);
1307
+ if (!existing) {
1308
+ throw new ToolError("note_not_found", `Note ${uuid} not found`, "Run notes_search or notes_list to find the note's uuid.");
1309
+ }
1310
+ const raw = state.encryptedItemsRaw.get(uuid);
1311
+ if (!raw)
1312
+ throw new Error(`Note ${uuid} has no encrypted record`);
1313
+ assertAiWritable(existing);
1314
+ assertCanEditContent(existing, text !== undefined);
1315
+ const contentChanged = title !== undefined ||
1316
+ text !== undefined ||
1317
+ noteType !== undefined ||
1318
+ (archived !== undefined && archived !== existing.archived) ||
1319
+ (pinned !== undefined && pinned !== existing.pinned);
1320
+ const trashChanged = trashed !== undefined && trashed !== existing.trashed;
1321
+ let nextText = existing.text;
1322
+ if (contentChanged || trashChanged) {
1323
+ const nextType = noteTypeForUpdate(noteType, existing.noteType);
1324
+ const nextTextRaw = text ?? existing.text;
1325
+ nextText =
1326
+ nextType === "super" && text !== undefined
1327
+ ? normalizeSuperText(text)
1328
+ : nextTextRaw;
1329
+ const merged = {
1330
+ uuid,
1331
+ title: title ?? existing.title,
1332
+ text: nextText,
1333
+ trashed: trashed ?? existing.trashed,
1334
+ archived: archived ?? existing.archived,
1335
+ pinned: pinned ?? existing.pinned,
1336
+ noteType: nextType,
1337
+ references: existing.references,
1338
+ extra: existing.extra,
1339
+ };
1340
+ const saved = await submitNoteUpdate(uuid, merged, 0);
1341
+ state.notesCache.set(uuid, {
1342
+ ...existing,
1343
+ ...merged,
1344
+ createdAt: saved.created_at ?? existing.createdAt,
1345
+ updatedAt: saved.updated_at ?? existing.updatedAt,
1346
+ created_at_timestamp: saved.created_at_timestamp ?? existing.created_at_timestamp,
1347
+ updated_at_timestamp: saved.updated_at_timestamp ?? existing.updated_at_timestamp,
1348
+ });
1349
+ }
1350
+ if (tags !== undefined) {
1351
+ assertTagsWithinScope(currentScope(), tags);
1352
+ await syncTagsToNote(uuid, tags);
1353
+ }
1354
+ return {
1355
+ previousSizeInBytes: Buffer.byteLength(existing.text, "utf8"),
1356
+ currentSizeInBytes: Buffer.byteLength(nextText, "utf8"),
1357
+ };
1358
+ },
1359
+ async appendNote({ uuid, content, position, section }) {
1360
+ return applyTextEdit(uuid, (text) => {
1361
+ if (section !== undefined && section !== "") {
1362
+ return insertIntoSection(text, section, content, position);
1363
+ }
1364
+ const eol = text.includes("\r\n") ? "\r\n" : "\n";
1365
+ if (text === "")
1366
+ return content;
1367
+ if (position === "prepend")
1368
+ return content + eol + eol + text;
1369
+ const sep = text.endsWith("\n") ? eol : eol + eol;
1370
+ return text + sep + content;
1371
+ });
1372
+ },
1373
+ async replaceInNote({ uuid, replacements }) {
1374
+ const perReplacement = [];
1375
+ const delta = await applyTextEdit(uuid, (text) => {
1376
+ let out = text;
1377
+ for (const r of replacements) {
1378
+ const res = applyOneReplacement(out, r);
1379
+ out = res.text;
1380
+ perReplacement.push({ find: r.find, count: res.count });
1381
+ }
1382
+ return out;
1383
+ });
1384
+ return {
1385
+ ...delta,
1386
+ totalReplacements: perReplacement.reduce((n, p) => n + p.count, 0),
1387
+ perReplacement,
1388
+ };
1389
+ },
1390
+ async getSection(noteUuid, sectionPath) {
1391
+ await ensureFresh(state, cacheTtlMs(), () => fullSync(state));
1392
+ if (!scopeAllows(currentScope(), noteUuid))
1393
+ throw noteNotFound(noteUuid);
1394
+ const n = state.notesCache.get(noteUuid);
1395
+ if (!n || !aiReadable(n))
1396
+ throw noteNotFound(noteUuid);
1397
+ return getSectionBody(n.text, sectionPath);
1398
+ },
1399
+ async getOutline(noteUuid) {
1400
+ await ensureFresh(state, cacheTtlMs(), () => fullSync(state));
1401
+ if (!scopeAllows(currentScope(), noteUuid))
1402
+ throw noteNotFound(noteUuid);
1403
+ const n = state.notesCache.get(noteUuid);
1404
+ if (!n || !aiReadable(n))
1405
+ throw noteNotFound(noteUuid);
1406
+ return outline(n.text).map((h) => ({
1407
+ level: h.level,
1408
+ title: h.title,
1409
+ path: h.path,
1410
+ }));
1411
+ },
1412
+ async deleteNote(uuid, permanent) {
1413
+ await ensureFresh(state, 0, () => fullSync(state));
1414
+ if (!scopeAllows(currentScope(), uuid))
1415
+ throw noteNotFound(uuid);
1416
+ const existingForPolicy = state.notesCache.get(uuid);
1417
+ if (existingForPolicy)
1418
+ assertAiWritable(existingForPolicy);
1419
+ const raw = state.encryptedItemsRaw.get(uuid);
1420
+ if (!raw)
1421
+ throw new Error(`Note ${uuid} not found`);
1422
+ if (permanent) {
1423
+ await pushItems([
1424
+ {
1425
+ uuid,
1426
+ content_type: "Note",
1427
+ deleted: true,
1428
+ content: "",
1429
+ enc_item_key: "",
1430
+ updated_at_timestamp: raw.updated_at_timestamp,
1431
+ },
1432
+ ]);
1433
+ state.notesCache.delete(uuid);
1434
+ state.encryptedItemsRaw.delete(uuid);
1435
+ }
1436
+ else {
1437
+ const existing = state.notesCache.get(uuid);
1438
+ if (!existing)
1439
+ throw new Error(`Note ${uuid} not found in cache`);
1440
+ const merged = { ...existing, trashed: true };
1441
+ const encrypted = await encryptNote({
1442
+ uuid,
1443
+ title: merged.title,
1444
+ text: merged.text,
1445
+ trashed: true,
1446
+ archived: merged.archived,
1447
+ pinned: merged.pinned,
1448
+ noteType: merged.noteType,
1449
+ references: existing.references,
1450
+ extra: existing.extra,
1451
+ }, {
1452
+ uuid: defaultItemsKey().uuid,
1453
+ itemsKey: defaultItemsKey().itemsKey,
1454
+ });
1455
+ const res = await pushItems([
1456
+ {
1457
+ ...raw,
1458
+ content: encrypted.content,
1459
+ enc_item_key: encrypted.enc_item_key,
1460
+ items_key_id: encrypted.items_key_id,
1461
+ updated_at: new Date().toISOString(),
1462
+ updated_at_timestamp: raw.updated_at_timestamp,
1463
+ },
1464
+ ]);
1465
+ const saved = res.saved_items.find((i) => i.uuid === uuid);
1466
+ state.notesCache.set(uuid, {
1467
+ ...merged,
1468
+ updatedAt: saved?.updated_at ?? existing.updatedAt,
1469
+ updated_at_timestamp: saved?.updated_at_timestamp ?? existing.updated_at_timestamp,
1470
+ });
1471
+ }
1472
+ },
1473
+ async listTags() {
1474
+ await ensureFresh(state, cacheTtlMs(), () => fullSync(state));
1475
+ const sc = currentScope();
1476
+ return [...state.tagsCache.values()]
1477
+ .filter((t) => sc === null || !sc.hiddenTags.has(t.uuid))
1478
+ .filter((t) => sc === null || sc.allowTags === null || sc.allowTags.has(t.uuid))
1479
+ .sort((a, b) => a.title.localeCompare(b.title))
1480
+ .map((t) => {
1481
+ const summary = toTagSummary(t);
1482
+ // Count only notes the AI may see (no protected / no-access /
1483
+ // out-of-scope notes, which a raw count would reveal).
1484
+ summary.noteCount = t.references.filter((r) => r.content_type === "Note" && noteVisible(sc, r.uuid)).length;
1485
+ return summary;
1486
+ });
1487
+ },
1488
+ async getTag(uuid) {
1489
+ await ensureFresh(state, cacheTtlMs(), () => fullSync(state));
1490
+ const sc = currentScope();
1491
+ if (sc !== null && sc.hiddenTags.has(uuid))
1492
+ return null;
1493
+ if (sc !== null && sc.allowTags !== null && !sc.allowTags.has(uuid)) {
1494
+ return null;
1495
+ }
1496
+ const t = state.tagsCache.get(uuid);
1497
+ if (!t)
1498
+ return null;
1499
+ const full = toFullTag(t);
1500
+ full.noteUuids = full.noteUuids.filter((id) => noteVisible(sc, id));
1501
+ return full;
1502
+ },
1503
+ async createTag({ title, parent }) {
1504
+ // Sync forcé : le duplicate-title-under-same-parent check ne vaut
1505
+ // rien sur un cache périmé.
1506
+ await ensureFresh(state, 0, () => fullSync(state));
1507
+ const scCreateTag = currentScope();
1508
+ if (scCreateTag !== null && scCreateTag.allowTags !== null && parent === undefined) {
1509
+ throw new ToolError("scope_create_denied", "Your config scope (SN_READ_TAGS) requires new tags to be nested under an in-scope tag.", "Pass `parent` with an in-scope tag uuid (run tags_list).");
1510
+ }
1511
+ if (parent !== undefined) {
1512
+ assertCanNestTags();
1513
+ assertTagVisible(scCreateTag, parent);
1514
+ if (!state.tagsCache.has(parent)) {
1515
+ throw new Error(`Parent tag ${parent} not found`);
1516
+ }
1517
+ }
1518
+ // SN allows same-title tags under different parents (like folders), so
1519
+ // scope the duplicate check to actual siblings, not the whole vault.
1520
+ const sibling = [...state.tagsCache.values()].find((t) => t.title === title && parentUuidOf(t) === (parent ?? null));
1521
+ if (sibling) {
1522
+ throw new Error(`Tag with title "${title}" already exists under the same parent (uuid=${sibling.uuid})`);
1523
+ }
1524
+ const uuid = crypto.randomUUID();
1525
+ const references = parent !== undefined ? [makeParentRef(parent)] : [];
1526
+ await pushTag(null, { uuid, title, references });
1527
+ return uuid;
1528
+ },
1529
+ async updateTag({ uuid, title, parent }) {
1530
+ await ensureFresh(state, 0, () => fullSync(state));
1531
+ const scUpdateTag = currentScope();
1532
+ assertTagMutable(scUpdateTag, uuid);
1533
+ if (parent === null &&
1534
+ scUpdateTag !== null &&
1535
+ scUpdateTag.allowTags !== null) {
1536
+ throw new ToolError("scope_move_denied", "Moving a tag to the top level would take it (and its notes) outside your config scope.", "Re-parent within your scope, or ask V to move it from the Standard Notes app.");
1537
+ }
1538
+ if (parent !== undefined && parent !== null) {
1539
+ assertCanNestTags();
1540
+ assertTagVisible(scUpdateTag, parent);
1541
+ }
1542
+ const existing = state.tagsCache.get(uuid);
1543
+ if (!existing)
1544
+ throw new Error(`Tag ${uuid} not found`);
1545
+ if (title === undefined && parent === undefined) {
1546
+ throw new Error(`updateTag on ${uuid}: provide at least one of { title, parent }`);
1547
+ }
1548
+ let references = existing.references;
1549
+ if (parent !== undefined) {
1550
+ if (parent !== null) {
1551
+ if (!state.tagsCache.has(parent)) {
1552
+ throw new Error(`Parent tag ${parent} not found`);
1553
+ }
1554
+ if (wouldCreateCycle(state.tagsCache, uuid, parent)) {
1555
+ throw new Error(`Cannot make tag ${uuid} a child of ${parent}: would create a cycle`);
1556
+ }
1557
+ }
1558
+ references = stripParentRefs(references);
1559
+ if (parent !== null)
1560
+ references = [...references, makeParentRef(parent)];
1561
+ }
1562
+ const nextTitle = title ?? existing.title;
1563
+ // Same sibling-uniqueness check as createTag, using whatever parent the
1564
+ // tag will end up with after this update.
1565
+ const nextParent = parent !== undefined ? parent : parentUuidOf(existing);
1566
+ const sibling = [...state.tagsCache.values()].find((t) => t.uuid !== uuid &&
1567
+ t.title === nextTitle &&
1568
+ parentUuidOf(t) === (nextParent ?? null));
1569
+ if (sibling) {
1570
+ throw new Error(`Tag with title "${nextTitle}" already exists under the same parent (uuid=${sibling.uuid})`);
1571
+ }
1572
+ await pushTag(existing, {
1573
+ uuid,
1574
+ title: nextTitle,
1575
+ references,
1576
+ });
1577
+ },
1578
+ async deleteTag(uuid) {
1579
+ await ensureFresh(state, 0, () => fullSync(state));
1580
+ const scDelete = currentScope();
1581
+ assertTagMutable(scDelete, uuid);
1582
+ // Under an allowlist, deleting a tag can orphan more than notes:
1583
+ // child tags lose their parent link and fall out of scope, taking
1584
+ // their notes with them. Refuse while either is at stake.
1585
+ if (scDelete !== null && scDelete.allowTags !== null) {
1586
+ const allowTags = scDelete.allowTags;
1587
+ const childTags = [...state.tagsCache.values()].filter((t) => parentUuidOf(t) === uuid && allowTags.has(t.uuid));
1588
+ if (childTags.length > 0) {
1589
+ throw new ToolError("scope_orphan", `Tag ${uuid} has ${childTags.length} child tag(s); deleting it would drop them (and their notes) outside your config scope.`, "Move the child tags to another in-scope parent first (tags_update), then delete.");
1590
+ }
1591
+ const tag = state.tagsCache.get(uuid);
1592
+ const orphanedNotes = (tag?.references ?? []).filter((r) => {
1593
+ if (r.content_type !== "Note")
1594
+ return false;
1595
+ return ![...state.tagsCache.values()].some((t) => t.uuid !== uuid &&
1596
+ allowTags.has(t.uuid) &&
1597
+ t.references.some((x) => x.uuid === r.uuid && x.content_type === "Note"));
1598
+ });
1599
+ if (orphanedNotes.length > 0) {
1600
+ throw new ToolError("scope_orphan", `Deleting this tag would leave ${orphanedNotes.length} note(s) with no in-scope tag — they would immediately fall outside your config scope.`, "Re-file those notes under another in-scope tag first (tags_attach), then delete.");
1601
+ }
1602
+ }
1603
+ const raw = state.encryptedItemsRaw.get(uuid);
1604
+ if (!raw)
1605
+ throw new Error(`Tag ${uuid} not found`);
1606
+ await pushItems([
1607
+ {
1608
+ uuid,
1609
+ content_type: "Tag",
1610
+ deleted: true,
1611
+ content: "",
1612
+ enc_item_key: "",
1613
+ updated_at_timestamp: raw.updated_at_timestamp,
1614
+ },
1615
+ ]);
1616
+ state.tagsCache.delete(uuid);
1617
+ state.encryptedItemsRaw.delete(uuid);
1618
+ },
1619
+ async attachTag(noteUuid, tagUuid) {
1620
+ await ensureFresh(state, 0, () => fullSync(state));
1621
+ // Scope escape guard: without this, a tag-scoped client could attach
1622
+ // an invisible note to an allowed tag and then read it.
1623
+ const sc = currentScope();
1624
+ const n = state.notesCache.get(noteUuid);
1625
+ if (!n || !scopeAllows(sc, noteUuid) || !aiReadable(n)) {
1626
+ throw noteNotFound(noteUuid);
1627
+ }
1628
+ assertAiWritable(n);
1629
+ assertTagVisible(sc, tagUuid);
1630
+ await attachTagInternal(noteUuid, tagUuid);
1631
+ },
1632
+ async detachTag(noteUuid, tagUuid) {
1633
+ await ensureFresh(state, 0, () => fullSync(state));
1634
+ const sc = currentScope();
1635
+ const n = state.notesCache.get(noteUuid);
1636
+ if (!n || !scopeAllows(sc, noteUuid) || !aiReadable(n)) {
1637
+ throw noteNotFound(noteUuid);
1638
+ }
1639
+ assertAiWritable(n);
1640
+ assertTagVisible(sc, tagUuid);
1641
+ // Under an allowlist, detaching the note's LAST in-scope tag would
1642
+ // orphan it: visible now, unreachable the moment the detach lands.
1643
+ if (sc !== null && sc.allowTags !== null) {
1644
+ const allowTags = sc.allowTags;
1645
+ const remaining = [...state.tagsCache.values()].filter((t) => t.uuid !== tagUuid &&
1646
+ allowTags.has(t.uuid) &&
1647
+ t.references.some((r) => r.uuid === noteUuid && r.content_type === "Note"));
1648
+ if (remaining.length === 0) {
1649
+ throw new ToolError("scope_orphan", "Detaching this tag would leave the note with no in-scope tag — it would immediately fall outside your config scope.", "Attach another in-scope tag first (tags_attach), then detach this one.");
1650
+ }
1651
+ }
1652
+ await detachTagInternal(noteUuid, tagUuid);
1653
+ },
1654
+ async updateFrontmatter({ uuid, operation, key, value }) {
1655
+ let frontmatter = {};
1656
+ const delta = await applyTextEdit(uuid, (text) => {
1657
+ const next = operation === "set"
1658
+ ? setFrontmatterKey(text, key, value)
1659
+ : deleteFrontmatterKey(text, key);
1660
+ frontmatter = parseFrontmatter(next).data;
1661
+ return next;
1662
+ });
1663
+ return { ...delta, frontmatter };
1664
+ },
1665
+ async listNotesCreatedBetween(startMs, endMs) {
1666
+ await ensureFresh(state, cacheTtlMs(), () => fullSync(state));
1667
+ const sc = currentScope();
1668
+ const createdTs = (n) => n.created_at_timestamp > 0
1669
+ ? snTimestampToMs(n.created_at_timestamp)
1670
+ : (Date.parse(n.createdAt) || 0);
1671
+ return [...state.notesCache.values()]
1672
+ .filter((n) => !n.trashed)
1673
+ .filter((n) => scopeAllows(sc, n.uuid))
1674
+ .filter((n) => aiReadable(n))
1675
+ .filter((n) => {
1676
+ const ts = createdTs(n);
1677
+ return ts >= startMs && ts <= endMs;
1678
+ })
1679
+ .sort((a, b) => createdTs(a) - createdTs(b))
1680
+ .map(toSummary);
1681
+ },
1682
+ async listTasks({ includeDone, tag, noteUuid, limit }) {
1683
+ await ensureFresh(state, cacheTtlMs(), () => fullSync(state));
1684
+ const sc = currentScope();
1685
+ let tagFilter = null;
1686
+ if (tag !== undefined && tag !== "") {
1687
+ tagFilter = resolveTagFilter(tag, true);
1688
+ }
1689
+ const tasks = [];
1690
+ for (const n of state.notesCache.values()) {
1691
+ if (tasks.length >= limit)
1692
+ break;
1693
+ if (n.trashed || n.noteType === "super")
1694
+ continue;
1695
+ if (noteUuid !== undefined && n.uuid !== noteUuid)
1696
+ continue;
1697
+ if (!scopeAllows(sc, n.uuid) || !aiReadable(n))
1698
+ continue;
1699
+ if (tagFilter !== null && !tagFilter.has(n.uuid))
1700
+ continue;
1701
+ for (const t of extractTasks(n.text)) {
1702
+ if (!includeDone && t.done)
1703
+ continue;
1704
+ tasks.push({
1705
+ noteUuid: n.uuid,
1706
+ noteTitle: n.title,
1707
+ line: t.line,
1708
+ text: t.text,
1709
+ done: t.done,
1710
+ });
1711
+ if (tasks.length >= limit)
1712
+ break;
1713
+ }
1714
+ }
1715
+ return tasks;
1716
+ },
1717
+ async toggleTask(noteUuid, line, done) {
1718
+ return applyTextEdit(noteUuid, (text) => setTaskState(text, line, done));
1719
+ },
1720
+ async listNoteRevisions(noteUuid) {
1721
+ await ensureFresh(state, cacheTtlMs(), () => fullSync(state));
1722
+ const n = state.notesCache.get(noteUuid);
1723
+ if (!n || !scopeAllows(currentScope(), noteUuid) || !aiReadable(n)) {
1724
+ throw noteNotFound(noteUuid);
1725
+ }
1726
+ try {
1727
+ const revisions = await authedCall(state, (cfg) => http.listRevisions(cfg, noteUuid));
1728
+ return revisions
1729
+ .filter((r) => canViewRevision(r.required_role, ent()))
1730
+ .map((r) => ({
1731
+ uuid: r.uuid,
1732
+ createdAt: r.created_at,
1733
+ updatedAt: r.updated_at,
1734
+ requiredRole: r.required_role,
1735
+ }));
1736
+ }
1737
+ catch (err) {
1738
+ throw revisionsRefused(err);
1739
+ }
1740
+ },
1741
+ async getNoteRevision(noteUuid, revisionUuid) {
1742
+ await ensureFresh(state, cacheTtlMs(), () => fullSync(state));
1743
+ const n = state.notesCache.get(noteUuid);
1744
+ if (!n || !scopeAllows(currentScope(), noteUuid) || !aiReadable(n)) {
1745
+ throw noteNotFound(noteUuid);
1746
+ }
1747
+ return fetchRevision(noteUuid, revisionUuid);
1748
+ },
1749
+ async restoreNoteRevision(noteUuid, revisionUuid) {
1750
+ await ensureFresh(state, 0, () => fullSync(state));
1751
+ const existing = state.notesCache.get(noteUuid);
1752
+ if (!existing || !scopeAllows(currentScope(), noteUuid)) {
1753
+ throw noteNotFound(noteUuid);
1754
+ }
1755
+ assertAiWritable(existing);
1756
+ const rev = await fetchRevision(noteUuid, revisionUuid);
1757
+ const merged = {
1758
+ uuid: noteUuid,
1759
+ title: rev.title,
1760
+ text: rev.text,
1761
+ trashed: existing.trashed,
1762
+ archived: existing.archived,
1763
+ pinned: existing.pinned,
1764
+ noteType: rev.noteType,
1765
+ references: existing.references,
1766
+ extra: existing.extra,
1767
+ };
1768
+ const saved = await submitNoteUpdate(noteUuid, merged, 0);
1769
+ state.notesCache.set(noteUuid, {
1770
+ ...existing,
1771
+ ...merged,
1772
+ createdAt: saved.created_at ?? existing.createdAt,
1773
+ updatedAt: saved.updated_at ?? existing.updatedAt,
1774
+ created_at_timestamp: saved.created_at_timestamp ?? existing.created_at_timestamp,
1775
+ updated_at_timestamp: saved.updated_at_timestamp ?? existing.updated_at_timestamp,
1776
+ });
1777
+ return {
1778
+ previousSizeInBytes: Buffer.byteLength(existing.text, "utf8"),
1779
+ currentSizeInBytes: Buffer.byteLength(rev.text, "utf8"),
1780
+ };
1781
+ },
1782
+ async listSmartViews() {
1783
+ await ensureFresh(state, cacheTtlMs(), () => fullSync(state));
1784
+ return [...state.smartViewsCache.values()]
1785
+ .sort((a, b) => a.title.localeCompare(b.title))
1786
+ .map((v) => ({
1787
+ uuid: v.uuid,
1788
+ title: v.title,
1789
+ predicateSummary: summarizePredicate(v.predicate),
1790
+ updatedAt: v.updatedAt,
1791
+ }));
1792
+ },
1793
+ async runSmartView(idOrTitle, { limit, offset }) {
1794
+ await ensureFresh(state, cacheTtlMs(), () => fullSync(state));
1795
+ const view = state.smartViewsCache.get(idOrTitle) ??
1796
+ [...state.smartViewsCache.values()].find((v) => v.title.toLowerCase() === idOrTitle.toLowerCase());
1797
+ if (!view) {
1798
+ const available = [...state.smartViewsCache.values()]
1799
+ .map((v) => v.title)
1800
+ .join(", ");
1801
+ throw new ToolError("smartview_not_found", `No smart view matches "${idOrTitle}".` +
1802
+ (available ? ` Available: ${available}.` : " No smart views exist."), "Run smartviews_list to see the saved views, or use notes_query for an ad-hoc predicate.");
1803
+ }
1804
+ if (!isPredicateJson(view.predicate)) {
1805
+ throw new ToolError("predicate_invalid", `Smart view "${view.title}" has no usable predicate.`, "The view may have been created by an unsupported client. Use notes_query with an explicit predicate instead.");
1806
+ }
1807
+ const result = runPredicate(view.predicate, { limit, offset });
1808
+ return { view: { uuid: view.uuid, title: view.title }, ...result };
1809
+ },
1810
+ async runPredicateQuery(predicate, { limit, offset }) {
1811
+ await ensureFresh(state, cacheTtlMs(), () => fullSync(state));
1812
+ if (!isPredicateJson(predicate)) {
1813
+ throw new ToolError("predicate_invalid", "The predicate must be an object with an `operator` field (leaf: {keypath, operator, value}; compound: {operator: \"and\"|\"or\", value: [...]}).", 'Example: {"operator":"and","value":[{"keypath":"trashed","operator":"=","value":false},{"keypath":"title","operator":"startsWith","value":"Weekly"}]}');
1814
+ }
1815
+ return { view: null, ...runPredicate(predicate, { limit, offset }) };
1816
+ },
1817
+ async sync() {
1818
+ await fullSync(state);
1819
+ // Counts reflect what this client may see, not the whole vault.
1820
+ const sc = currentScope();
1821
+ const notes = [...state.notesCache.values()].filter((n) => scopeAllows(sc, n.uuid) && aiReadable(n)).length;
1822
+ const tags = [...state.tagsCache.values()].filter((t) => sc === null ||
1823
+ (!sc.hiddenTags.has(t.uuid) &&
1824
+ (sc.allowTags === null || sc.allowTags.has(t.uuid)))).length;
1825
+ return { notes, tags, syncedAt: new Date().toISOString() };
1826
+ },
1827
+ entitlement() {
1828
+ return ent();
1829
+ },
1830
+ async getNoteTagUuids(uuid) {
1831
+ await ensureFresh(state, cacheTtlMs(), () => fullSync(state));
1832
+ const sc = currentScope();
1833
+ const n = state.notesCache.get(uuid);
1834
+ if (!n || !scopeAllows(sc, uuid) || !aiReadable(n))
1835
+ throw noteNotFound(uuid);
1836
+ return [...state.tagsCache.values()]
1837
+ .filter((t) => t.references.some((r) => r.uuid === uuid && r.content_type === "Note") &&
1838
+ (sc === null ||
1839
+ (!sc.hiddenTags.has(t.uuid) &&
1840
+ (sc.allowTags === null || sc.allowTags.has(t.uuid)))))
1841
+ .map((t) => t.uuid);
1842
+ },
1843
+ async getLinks(uuid) {
1844
+ await ensureFresh(state, cacheTtlMs(), () => fullSync(state));
1845
+ const sc = currentScope();
1846
+ // One visibility rule for source, targets and backlinkers: in scope,
1847
+ // AI-readable, not trashed. A hidden note is indistinguishable from a
1848
+ // missing one — never listed, never counted, never "resolved".
1849
+ const visible = (n) => n !== undefined && !n.trashed && scopeAllows(sc, n.uuid) && aiReadable(n);
1850
+ const source = state.notesCache.get(uuid);
1851
+ if (!visible(source))
1852
+ throw noteNotFound(uuid);
1853
+ const visibleNotes = [...state.notesCache.values()].filter(visible);
1854
+ const byTitle = new Map();
1855
+ for (const n of visibleNotes) {
1856
+ const k = titleKey(n.title);
1857
+ if (k === "")
1858
+ continue;
1859
+ const list = byTitle.get(k);
1860
+ if (list)
1861
+ list.push(n);
1862
+ else
1863
+ byTitle.set(k, [n]);
1864
+ }
1865
+ const ref = (n, via) => ({
1866
+ uuid: n.uuid,
1867
+ title: n.title,
1868
+ protected: n.protected,
1869
+ via,
1870
+ });
1871
+ const addVia = (m, n, v) => {
1872
+ const cur = m.get(n.uuid);
1873
+ if (!cur)
1874
+ m.set(n.uuid, ref(n, [v]));
1875
+ else if (!cur.via.includes(v))
1876
+ cur.via.push(v);
1877
+ };
1878
+ const outgoing = new Map();
1879
+ const unresolved = [];
1880
+ const ambiguous = [];
1881
+ if (source.noteType !== "super") {
1882
+ for (const link of parseWikilinks(source.text)) {
1883
+ const matches = (byTitle.get(titleKey(link.target)) ?? []).filter((n) => n.uuid !== source.uuid);
1884
+ if (matches.length === 0)
1885
+ unresolved.push(link.target);
1886
+ else if (matches.length === 1)
1887
+ addVia(outgoing, matches[0], "wikilink");
1888
+ else
1889
+ ambiguous.push({ target: link.target, candidates: matches.map((n) => ref(n, ["wikilink"])) });
1890
+ }
1891
+ }
1892
+ for (const target of nativeLinkUuids(source)) {
1893
+ const n = state.notesCache.get(target);
1894
+ if (visible(n) && n.uuid !== source.uuid)
1895
+ addVia(outgoing, n, "native");
1896
+ }
1897
+ const backlinks = new Map();
1898
+ const sourceKey = titleKey(source.title);
1899
+ for (const n of visibleNotes) {
1900
+ if (n.uuid === source.uuid)
1901
+ continue;
1902
+ if (sourceKey !== "" &&
1903
+ n.noteType !== "super" &&
1904
+ parseWikilinks(n.text).some((l) => titleKey(l.target) === sourceKey)) {
1905
+ addVia(backlinks, n, "wikilink");
1906
+ }
1907
+ if (nativeLinkUuids(n).includes(source.uuid))
1908
+ addVia(backlinks, n, "native");
1909
+ }
1910
+ return {
1911
+ uuid: source.uuid,
1912
+ title: source.title,
1913
+ outgoing: [...outgoing.values()],
1914
+ backlinks: [...backlinks.values()],
1915
+ unresolved,
1916
+ ambiguous,
1917
+ };
1918
+ },
1919
+ async linkNotes({ uuid, target, section }) {
1920
+ await ensureFresh(state, 0, () => fullSync(state));
1921
+ const sc = currentScope();
1922
+ const visible = (n) => n !== undefined && !n.trashed && scopeAllows(sc, n.uuid) && aiReadable(n);
1923
+ const source = state.notesCache.get(uuid);
1924
+ if (!visible(source))
1925
+ throw noteNotFound(uuid);
1926
+ const dest = state.notesCache.get(target);
1927
+ if (!visible(dest))
1928
+ throw noteNotFound(target);
1929
+ if (source.uuid === dest.uuid) {
1930
+ throw new ToolError("link_self", "A note cannot link to itself.");
1931
+ }
1932
+ assertAiWritable(source);
1933
+ const paid = isPaid(ent());
1934
+ const canWikilink = source.noteType !== "super" && !/[[\]|#\r\n]/.test(dest.title) && dest.title.trim() !== "";
1935
+ if (!canWikilink && !paid) {
1936
+ throw source.noteType === "super"
1937
+ ? paidFeatureError("Linking from Super notes", ent(), "Link from a plain-text note instead.")
1938
+ : new ToolError("link_title_unsupported", `"${dest.title}" can't be written as a [[wikilink]] (empty, or contains [ ] | # or a line break).`, "Rename the target note, then link again.");
1939
+ }
1940
+ let nextText = source.text;
1941
+ let wikilinkAdded = false;
1942
+ if (canWikilink && !hasWikilinkTo(source.text, dest.title)) {
1943
+ const link = `[[${dest.title.trim()}]]`;
1944
+ if (section !== undefined && section !== "") {
1945
+ nextText = insertIntoSection(source.text, section, link, "append");
1946
+ }
1947
+ else {
1948
+ const eol = source.text.includes("\r\n") ? "\r\n" : "\n";
1949
+ nextText =
1950
+ source.text === ""
1951
+ ? link
1952
+ : source.text + (source.text.endsWith("\n") ? eol : eol + eol) + link;
1953
+ }
1954
+ wikilinkAdded = true;
1955
+ }
1956
+ let nextRefs = source.references;
1957
+ let nativeLinkAdded = false;
1958
+ // Native links are a paid SN feature: written only for paid accounts.
1959
+ if (paid &&
1960
+ !source.references.some((r) => r.uuid === dest.uuid && r.reference_type === "NoteToNote")) {
1961
+ nextRefs = [
1962
+ ...source.references,
1963
+ { uuid: dest.uuid, content_type: "Note", reference_type: "NoteToNote" },
1964
+ ];
1965
+ nativeLinkAdded = true;
1966
+ }
1967
+ const previousSizeInBytes = Buffer.byteLength(source.text, "utf8");
1968
+ if (!wikilinkAdded && !nativeLinkAdded) {
1969
+ return { previousSizeInBytes, currentSizeInBytes: previousSizeInBytes, wikilinkAdded, nativeLinkAdded };
1970
+ }
1971
+ const merged = {
1972
+ uuid: source.uuid,
1973
+ title: source.title,
1974
+ text: nextText,
1975
+ trashed: source.trashed,
1976
+ archived: source.archived,
1977
+ pinned: source.pinned,
1978
+ noteType: source.noteType,
1979
+ references: nextRefs,
1980
+ extra: source.extra,
1981
+ };
1982
+ const saved = await submitNoteUpdate(source.uuid, merged, 0);
1983
+ state.notesCache.set(source.uuid, {
1984
+ ...source,
1985
+ text: nextText,
1986
+ references: nextRefs,
1987
+ updatedAt: saved.updated_at ?? source.updatedAt,
1988
+ updated_at_timestamp: saved.updated_at_timestamp ?? source.updated_at_timestamp,
1989
+ });
1990
+ return {
1991
+ previousSizeInBytes,
1992
+ currentSizeInBytes: Buffer.byteLength(nextText, "utf8"),
1993
+ wikilinkAdded,
1994
+ nativeLinkAdded,
1995
+ };
1996
+ },
1997
+ };
1998
+ }
1999
+ //# sourceMappingURL=client.js.map